SQL CAST converts a value from one data type to another at query time. Use CAST when you need a precise, ANSI-standard way to change types—like turning text into dates or decimals—so functions, comparisons, and joins work correctly.
SQL CAST converts a value from one data type to another at runtime, letting you align mismatched columns or format literals so operations succeed.
CAST is ANSI-SQL compliant and portable across most databases, while CONVERT is vendor-specific; choose CAST for cross-platform code.
Use CAST(expression AS target_type)
; the database returns the value in the new type or raises an error if conversion fails.
Wrap the numeric column or literal in CAST(... AS VARCHAR)
to produce a textual representation you can concatenate or store.
Ensure the string contains only numeric characters, then apply CAST(text_col AS INTEGER)
or AS DECIMAL(10,2)
for precise math.
Pass an ISO-8601 compliant string like '2024-05-31'
to CAST(text_col AS DATE)
; non-standard formats may need CONVERT
or TO_DATE
.
Yes—CAST works in any expression context, letting you align join keys or filter criteria without altering the underlying table schema.
Avoid CAST on large tables in tight loops; casting prevents index use on the converted column, potentially causing full scans.
Prefer explicit length/precision, validate data before casting, cast the smaller dataset in joins, and document why the cast is required.
CAST offers portable, explicit type conversion but can impact performance and fail on bad data, so use it deliberately and validate inputs.
Most relational engines—including PostgreSQL, SQL Server, MySQL, Snowflake, and BigQuery—support ANSI CAST, though exact type names can vary.
value::type
is PostgreSQL’s shorthand for CAST. Both compile to the same operation, so choose the style that matches team conventions.
Use vendor-specific safe functions like TRY_CAST
, SAFE_CAST
, or wrap CAST in CASE WHEN
checks to return NULL on failure.
Yes, but avoid unnecessary layers. A single precise cast is clearer and usually faster than chaining multiple conversions.