← Back to SQL, page 9

sql-0167 · Medium mid

What does CAST('12abc' AS INTEGER) return in SQLite and in PostgreSQL?

SQLite reads the longest numeric prefix and returns 12; for text with no numeric prefix it returns 0. PostgreSQL raises an error for invalid integer input. Validate before casting, because SQLite's lenient cast can turn bad data into plausible numbers.

Full answer
sql
SELECT CAST('12abc' AS INTEGER) AS prefix, CAST('abc' AS INTEGER) AS none, CAST('3.9' AS INTEGER) AS truncated;
prefixnonetruncated
1203
sql
SELECT CAST('12abc' AS INTEGER);  -- error on purpose
text
Error: invalid input syntax for type integer: "12abc"

SQLite never fails a CAST to INTEGER; it extracts what it can. That means a typo such as '1O0' (letter O) becomes 1, silently.

To find values that would not convert cleanly in SQLite, compare the cast back to the original:

sql
WITH v(x) AS (VALUES ('12'), ('12abc'), ('007'), ('abc'))
SELECT x, CAST(CAST(x AS INTEGER) AS TEXT) = x AS clean
FROM v ORDER BY x;
xclean
0070
121
12abc0
abc0

The value '007' fails the check too, because the cast drops the leading zeros. Whether that counts as bad data depends on the column: for a quantity it is fine, for a code it is not.

PostgreSQL 16 added pg_input_is_valid('12abc', 'integer') for the same check without raising an error (not run here).

sql
SELECT CAST('12abc' AS INTEGER) AS prefix, CAST('abc' AS INTEGER) AS none, CAST('3.9' AS INTEGER) AS truncated;

WITH v(x) AS (VALUES ('12'), ('12abc'), ('007'), ('abc'))
SELECT x, CAST(CAST(x AS INTEGER) AS TEXT) = x AS clean
FROM v ORDER BY x;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • SQLite CAST takes the numeric prefix
  • Non-numeric text casts to 0 in SQLite
  • PostgreSQL errors on invalid input
  • Compare the cast back to the original to detect bad values

Common mistakes

  • Trusting SQLite casts to validate input
  • Importing data into PostgreSQL without cleaning it first

Follow-ups

  • How would you count invalid numeric strings in a column?
  • What does CAST('3.9' AS INTEGER) return?

Tips

  • Show the silent conversion risk