Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: ERROR: operator does not exist: integer = character varying

Here i am trying to create view as shown below in example:

Example:

 create view view1
 as 
 select table1.col1,table2.col1,table3.col3
 from table1 
 inner join
 table2 
 inner join 
 table3
 on 
 table1.col4 = table2.col5 
 /* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
 /* ERROR: operator does not exist: integer = character varying */
 ....;

Note: The same query executed in sql server but getting the above error in postgreSQL.

like image 963
Sarfaraz Makandar Avatar asked May 13 '14 04:05

Sarfaraz Makandar


People also ask

What is character varying [] in Postgres?

Character varying is the official type of SQL ANSI standard. It will support all SQL compliances. Character varying is most useful and important data type in PostgreSQL used without a length specifier.


1 Answers

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

like image 107
Timusan Avatar answered Oct 13 '22 22:10

Timusan