SQL
5 min read
BEGINNER
CAST and coercion
Quick AnswerCAST(value AS type) requests an explicit type conversion. Coercion is conversion performed automatically by the engine in a particular context.
Core idea
CAST(value AS type) requests an explicit type conversion. Coercion is conversion performed automatically by the engine in a particular context.
Minimal example
sql
SELECT CAST('42' AS INTEGER), CAST(7.9 AS INTEGER);Expected SQLite rows:
text
42 | 7How it works
Conversion may lose fractional digits, fail, or produce unexpected values. SQLite casts invalid integer text to zero in this example; PostgreSQL rejects that input. Do not rely on successful CAST as validation across engines. PostgreSQL also supports :: syntax, but CAST is more portable. In applications validate input and bind parameters.
Practical example
sql
SELECT CAST('not-a-number' AS INTEGER), typeof(CAST('42' AS INTEGER));Expected SQLite rows:
text
0 | integerCommon mistake and practice
Predict the result of casting 7.9 to INTEGER in SQLite. Do not assume PostgreSQL numeric-to-integer conversion uses the same rounding behavior.