Full answer
sql
SELECT CAST('12abc' AS INTEGER) AS prefix, CAST('abc' AS INTEGER) AS none, CAST('3.9' AS INTEGER) AS truncated;| prefix | none | truncated |
|---|---|---|
| 12 | 0 | 3 |
sql
SELECT CAST('12abc' AS INTEGER); -- error on purposetext
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;| x | clean |
|---|---|
| 007 | 0 |
| 12 | 1 |
| 12abc | 0 |
| abc | 0 |
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