CAST()
Converts a value from one data type to another, such as a number to text or text to a number.
Description
CAST converts a value from one data type into another. Common uses
include turning a number into text so it can be concatenated with other
strings, turning text into a number so it can be used in math, or turning
text into a proper date.
Syntax
CAST(expression AS type)Parameters
| Name | Description | Optional |
|---|---|---|
| expression | The value or column being converted. | No |
| type | The data type to convert into, for example VARCHAR, INTEGER, DOUBLE, or DATE. | No |
Return Type
CAST returns a value of whatever type is specified after AS. The
"return type" is determined entirely by the target type you choose.
Examples
Loading database engine...
Loading database engine...
CAST is essential before concatenating numbers
Some databases automatically convert numbers to text when you use CONCAT
or ||, but others don't. Explicitly using CAST(price AS VARCHAR) makes
your query work reliably across different database engines.
Common Mistakes
- Casting text that isn't actually a valid number or date.
CAST('abc' AS INTEGER)fails because'abc'can't be interpreted as a number. - Forgetting that
CASTcan lose precision. Casting aDOUBLElike19.99toINTEGERtruncates it to19, which may not be the rounding behavior you wanted; useROUNDfirst if you need to round rather than truncate. - Casting when it isn't needed. Many databases implicitly convert
compatible types (like comparing an integer column to a numeric literal),
so an explicit
CASTis only required when types genuinely don't match.
Related Functions
See also: COALESCE, ROUND.