CAST is a type-conversion function defined in the SQL standard that creates a value of a specified data type from a given expression. Unlike implicit type coercion performed automatically by the database, CAST is explicit, making queries self-documenting and less error-prone. It can be used in SELECT lists, WHERE clauses, JOIN conditions, INSERT statements, and anywhere an expression is valid. If the requested conversion is not supported (for example, casting a non-numeric string to INTEGER), the statement fails at runtime with a conversion error. Some dialects allow synonym functions such as CONVERT or the :: operator (PostgreSQL). Precision and scale attributes (e.g., DECIMAL(10,2)) or character length (VARCHAR(50)) can be supplied. Casting never mutates stored data; it only affects the value returned in the result set or inserted into another column.
expression
- Any valid SQL expression to be convertedtarget_data_type
- The destination type, optionally with precision/scale or length (e.g., DECIMAL(10,2), VARCHAR(100))SQL-92 standard
Implicit conversion is done automatically by the database, which can hide errors. CAST requires you to state the desired type, making code clearer and safer.
Yes. For example, CAST(total AS DECIMAL(10,2)) converts a value to a decimal with 10 digits in total and 2 after the decimal point.
Validate or clean the data first, or use SAFE_CAST/TRY_CAST variants available in some dialects to return NULL instead of throwing an error.
CAST is defined in the SQL standard and works in all major systems, but supported data types and default precisions can differ, so always test.