Full answer
sql
SELECT CAST(3.9 AS INTEGER) AS a, CAST(-3.9 AS INTEGER) AS b, CAST('12abc' AS INTEGER) AS c, CAST('abc' AS INTEGER) AS d;| a | b | c | d |
|---|---|---|---|
| 3 | -3 | 12 | 0 |
Truncation drops the fractional part, which moves negative numbers up towards zero, so -3.9 becomes -3 rather than -4. Text conversion is lenient: '12abc' starts with the digits 12, so the cast yields 12, and 'abc' has no numeric prefix, so it yields 0. That leniency hides bad data, because a typo becomes a plausible number. PostgreSQL rejects both strings with an invalid input error and rounds 3.9 to 4 when casting to integer (PostgreSQL behaviour stated, not run here). Validate input with a pattern check or typeof() before relying on SQLite casts.
sql
SELECT CAST(3.9 AS INTEGER) AS a, CAST(-3.9 AS INTEGER) AS b, CAST('12abc' AS INTEGER) AS c, CAST('abc' AS INTEGER) AS d;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- CAST to INTEGER truncates toward zero in SQLite
- Text casts use the numeric prefix
- No numeric prefix gives 0, not an error
- PostgreSQL raises errors and rounds
Common mistakes
- Trusting CAST to reject malformed numbers
Follow-ups
- How would you find rows whose text is not a valid integer?
- How would you floor negative numbers?
Tips
- Watch negatives and prefixes