How to compare character varying (varcar) to UUID in PostgreSQL? - postgresql

Operator does not exist: character varying = uuid
Client id is UUId and should be why it is not working.
Where I am wrong, since I have tried almost everything I imagined.
SELECT * FROM "cobranca_assinatura"
INNER JOIN "cadastro_cliente" ON ("cobranca_assinatura"."cliente_id" = "cadastro_cliente"."id")
WHERE "cadastro_cliente"."nome" LIKE marcelo% ESCAPE '\'
[2019-03-21 14:40:34] [42883] ERROR: operator does not exist:
character varying = uuid [2019-03-21 14:40:34]
Dica: No operator
matches the given name and argument type(s). You might need to add
explicit type casts.

uuid is a specific datatype. To you it looks like text, but it's not. You cannot compare uuid using string functions (uuid like "abc%"), or compare it with text.
As Tamer suggests, you can cast it first, if you need to compare.
SELECT *
FROM (SELECT 'A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'::uuid as my_uuid) foo
WHERE my_uuid::text like 'a%'
For example, above I create a uuid by casting a string to uuid type. (You'll fail if you attempt to cast just any old string to uuid because 'abc' cannot be a uuid).
Then with a uuid item called 'my_uuid', I cast to back to a string to use string comparison. (Note the 'A' becomes 'a'!)

In java -> spring boot for JDBC template. I got the same issue. This is type-mismatch error, it's expecting UUID datatype but supplying String.
So, I converted UUID from String using UUID.fromString() and using UUID type in prepared statement (SQL)
Example:
String testSelectQry = "SELECT * from facility_announcements where id=:announcementID";
SqlParameterSource params = new MapSqlParameterSource("announcementID", UUID.fromString("094b76da-4140-11eb-b139-0242ac11000f"));
namedParameterJdbcTemplate.query(testSelectQry, params, new FacilityAnnouncementMapper());

Related

How to insert value into uuid column in Postgres?

I have a table with a uuid column, and some of the rows are missing the data. I need to insert data into this uuid column. The data is entered manually, so we are suffixing with other column data to differentiate, but it gives me an error.
UPDATE schema.table
SET uuid_column = CONCAT ('f7949f56-8840-5afa-8c6d-3b0f6e7f93e9', '-', id_column)
WHERE id_column = '1234';
Error: [42804] ERROR: column "uuid_column" is of type uuid but expression is of type text
Hint: You will need to rewrite or cast the expression.
Position: 45
I also tried
UPDATE schema.table
SET uuid_column = CONCAT ('f7949f56-8840-5afa-8c6d-3b0f6e7f93e9', '-', id_column)::uuid
WHERE id_column = '1234';
Error: [22P02] ERROR: invalid input syntax for uuid: "f7949f56-8840-5afa-8c6d-3b0f6e7f93e9-1234"
An UUID consists of 16 bytes, which you see displayed in hexadecimal notation.
You cannot have a UUID with fewer or more bytes.
I recommend using the type bytea if you really need to do such a thing.

How to use comparison where operator for JSON

I get this error when querying with a json column:
(psycopg2.ProgrammingError) operator does not exist: json = text
The column is defined as JSON with SQLAlchemy:
json_data = db.Column(db.JSON, nullable=False)
How do you compare with Postgres?
There is no equality (or inequality) operator for the data type json. If you need to test the value as a whole, you might cast to jsonb:
... WHERE json_data::jsonb = jsonb '{}';
Or cast to text for simple cases:
... WHERE json_data::text = '{}';
But there are many valid text representations for the same json value - which is the reason why Postgres does not implement equality / inequality operators for the type.
See:
How to query a json column for empty objects?

Explicit type conversion in postgreSQL

I am joining the two tables using the query below:
update campaign_items
set last_modified = evt.event_time
from (
select max(event_time) event_time
,result
from events
where request = '/campaignitem/add'
group by result
) evt
where evt.result = campaign_items.id
where the result column is of character varying type and the id is of integer type
But the data in the result column contains digits(i.e. 12345)
How would I run this query with converting the type of the result(character) into id
(integer)
Well you don't need to because postgresql will do implicit type conversion in this situation. For example, you can try
select ' 12 ' = 12
You will see that it returns true even though there is extra whitespace in the string version. Nevertheless, if you need explicit conversion.
where evt.result::int = campaign_items.id
According to your comment you have values like convRepeatDelay, these obviously cannot be converted to int. What you should then do is convert your int to char!!
where evt.result = campaign_items.id::char
There are several solutions. You can use the cast operator :: to cast a value from a given type into another type:
WHERE evt.result::int = campaign_items.id
You can also use the CAST function, which is more portable:
WHERE CAST(evt.result AS int) = campaign_items.id
Note that to improve performances, you can add an index on the casting operation (note the mandatory double parentheses), but then you have to use GROUP BY result::int instead of GROUP BY result to take advantage of the index:
CREATE INDEX i_events_result ON events_items ((result::int));
By the way the best option is maybe to change the result column type to int if you know that it will only contain integers ;-)

Postgres: ERROR: operator does not exist: character varying = bigint

My query is something like this. I try to get a status for a list of ids.
select order_number, order_status_name
from data.order_fact s
join data.order_status_dim l
on s.order_status_key = l.order_status_key
where
order_number in (1512011196169,1512011760019,1512011898493,1512011972111)
I get an error though that says:
ERROR: operator does not exist: character varying = bigint
LINE 6: order_number in (1512011196169,1512011760019,1512011898493,1...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Do you have any clue on how I should reform the ids to get it work?
Thanks a lot!
Your order_number is a varchar, you can't compare that to a number (123 is a number in SQL, '123' is a string constant)
You need to use string literals:
order_number in ('1512011196169','1512011760019','1512011898493','1512011972111')
More details in the manual:
http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
If you can't change the type of numbers within in, you could use cast:
select * from numbers_as_string
where cast(my_numbers_as_string as int) in (1,2,3)
This happen too when you are using native query in sprinboot and you are passing a parameter as string but that field is a (integer or long) in your model/entity, also when you are comparing a string with a integer due that param is used like string without casting.
so you should cast it as integer in the native query like this
x\:\:integer
for example:
#Query(value="
......
.....
inner join tablex t on t.x\\:\\:integer = pv.id \n"+
....
....
")
List<Object> getMyQuery(#Param("x") String x)

How to update a text[] field with a string

I have a table with a field called tags which can contain any number of strings:
Table "public.page"
Column | Type | Modifiers
----------------------+--------------------------+----------------------------------
tags | text[] | not null default ARRAY[]::text[]
I want to add a string to the tags field - but I can't seem to get the concat function to work for me. I've tried:
update page set tags=concat('My New String',tags);
ERROR: function concat(unknown, text[]) does not exist
LINE 1: update page set tags=concat('My New String',tags) where ...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
and
update page set tags=('My New String'||tags);
ERROR: operator is not unique: unknown || text[]
LINE 1: update page set tags = ('My New String' || tags) where w...
^
HINT: Could not choose a best candidate operator. You might need to add explicit type casts.
Any ideas?
In PostgreSQL's type system, the literal 'My New String' is not a varchar or text value, but a literal of type unknown, which can be processed as any type. (For instance, the literal for a date could be '2013-08-29'; this would not be processed as a varchar and then converted to date, it would be interpreted as a "date literal" at a very low level.)
Often, PostgreSQL can deduce the type automatically, but when it can't, you need to use one of the following to tell it that you want the literal to be treated as text:
text 'My New String' (SQL standard literal syntax)
Cast('My New String' as text) (SQL standard cast syntax, but not really a cast in this context)
'My New String'::text (PostgreSQL non-standard cast syntax, but quite readable)
In your case , the error message operator is not unique: unknown || text[] is saying that there are multiple types that Postgres could interpret the literal as, each with their own definition of the || operator.
You therefore need something like this (I've removed the unnecessary parentheses):
update page set tags = 'My New String'::text || tags;
Did you try || to concatenate?
select array['abc','def']::text[] || 'qwerty'::text;
http://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-OPERATORS-TABLE
Note: this answer was in response to the OP's original (unedited) question. Other answers contain more detail relevant to the updated question.