How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

Posted by silviot on Stack Overflow See other posts from Stack Overflow or by silviot
Published on 2010-01-17T21:17:29Z Indexed on 2010/05/24 3:10 UTC
Read the original article Hit count: 283

Filed under:
|
|

In postgres I have a table with a varchar column. The data is supposed to be integers and I need it in iteger type in a query. Some values are empty strings. The following:

SELECT myfield::integer FROM mytable

yields ERROR: invalid input syntax for integer: ""

How can I query a cast and have 0 in case of error during the cast in postgres?

© Stack Overflow or respective owner

Related posts about sql

Related posts about postgresql