Function or operator · Text, numbers and dates

CAST

CAST converts a value to another data type within an expression. It does not change the type of the stored column.

CAST example

The text '18' needs to take part in a numeric sum. The conversion makes that intent clear:

SQL
SELECT CAST('18' AS INTEGER) + 7 AS total;

What to look for: The result of CAST('18' AS INTEGER) + 7 is 25. Conversion is for when you need a number to calculate with; do not use it to paper over badly formatted data without checking where it came from.

Check the result with small data

The first value is numeric text and the second is a decimal number.

Self-contained query · SQLite
SELECT CAST('18' AS INTEGER) + 7 AS sum_value,
       CAST(2.75 AS INTEGER) AS without_decimals;
Query result
sum_valuewithout_decimals
252

CAST lets you ask for a different type: «18» becomes an integer so it can be added, while converting 2.75 to INTEGER truncates the decimal part in SQLite.

Check your understanding: Why should CAST not be confused with ROUND?

Show answer

CAST changes the type of the value and, when converting to INTEGER in SQLite, truncates: 2.75 becomes 2. ROUND keeps a number and rounds to the nearest value: ROUND(2.75) returns 3.

Common mix-ups with CAST

Assuming an invalid conversion fails the same way on every engine

Problem query
SELECT CAST('eighteen' AS INTEGER) AS age;

This input is not a valid integer. PostgreSQL rejects the conversion; SQLite may return 0 because of its type affinity rules; SQL Server offers alternatives such as TRY_CAST that return NULL when the conversion fails. Do not build portable logic around any one of those outcomes: validate the format before converting.

Converting a type is not the same as validating the data

A conversion is about how to represent a value as another type; validation decides whether that value belongs to the accepted domain. A field imported as text can contain «12», «12 pounds», an empty string and a null. Do not assume all of those inputs raise an error: SQLite allows conversions that other engines reject and may read only the numeric part of the text.

Preview the original and converted values side by side before overwriting the column. If a code such as «0012» is a text identifier, converting it to an integer drops the leading zeros and can make it indistinguishable from «12». If a measurement has decimals, converting it to an integer changes the precision and calls for a rule, not just a choice of syntax.

Test valid, invalid and edge cases on the target engine. An expression that returns a number in SQLite does not guarantee the same result in PostgreSQL or SQL Server. Nor does converting a column inside a filter guarantee better performance: it can change the comparison and how indexes are used. Keep the original type when it represents the entity correctly, and convert only when the purpose is clear.

Technical questions: SQLite: expressions and type conversions (opens in a new tab).