← Back to SQL, page 21

sql-0411 · Medium mid

What do CAST(3.9 AS INTEGER), CAST(-3.9 AS INTEGER), CAST('12abc' AS INTEGER) and CAST('abc' AS INTEGER) return in SQLite?

They return 3, -3, 12 and 0. CAST to INTEGER truncates reals toward zero, and for text SQLite reads the longest numeric prefix, returning 0 when there is none, instead of raising an error.

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;
abcd
3-3120

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