Coding⏱️ 2 min read📅 2026-06-03

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

PostgreSQL cast string to integer with default value

Quick Answer: Use the TRY_CAST function or COALESCE with TRY_CAST to return 0 in case of error.

The error 'invalid input syntax for integer: ''

💡 Why You Are Getting This Error

  • When casting a varchar column to an integer in PostgreSQL, if the column contains non-numeric values like empty strings, it results in this error. This affects users who rely on accurate numeric data from the table.
  • This error can be frustrating when trying to analyze or manipulate numeric data in PostgreSQL.

🔧 Proven Troubleshooting Steps

Using TRY_CAST

  1. Step 1: To cast a varchar column to an integer while handling errors, use the TRY_CAST function instead of CAST. The TRY_CAST function attempts to cast the value and returns NULL if it fails.
  2. Step 2: The query should look like this: SELECT TRY_CAST(myfield AS INTEGER) FROM mytable
  3. Step 3: This method is preferred over CAST because it allows you to specify a default value when the cast fails, in this case 0.

Using COALESCE

  1. Step 1: Another approach is to use the COALESCE function along with TRY_CAST. This will return NULL if the cast fails and then you can apply a default value.
  2. Step 2: The query should look like this: SELECT COALESCE(TRY_CAST(myfield AS INTEGER), 0) FROM mytable

✨ Wrapping Up

By using either of these methods, you can effectively handle errors when casting varchar columns to integers in PostgreSQL and get the desired result with a default value of 0.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions