Simple Postgres Type Cast

I recently did a select similar to the following, where a subquery grabs some ids, and then a main query uses them:

select * from attributes
where id in (
 select id from documents
 where owner = 'sam'
);

But I got the following error:

ERROR:  operator does not exist:
integer = text
HINT:  No operator matches the given
name and argument type(s). You might
need to add explicit type casts.

The reason for this is that the sub-query ‘select id from documents…’ is returning text, but the attributes table is expecting an integer id.  The two tables were created with the ids as ‘text’ in one and as ‘integers’ in the other.  The way to fix this is to cast the text as integer in the sub-query by adding the text “::int” as follows:

select * from attributes
where id in (
 select id::int from documents
 where owner = 'sam'
);

See also:

http://www.depesz.com/index.php/2008/05/05/error-operator-does-not-exist-integer-text-how-to-fix-it/

This entry was posted in Software Development and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">