Skip to content
SQLSimplified
conversion

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

NameDescriptionOptional
expressionThe value or column being converted.No
typeThe 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

Store (Customers/Orders/Products)

Loading database engine...

Store (Customers/Orders/Products)

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 CAST can lose precision. Casting a DOUBLE like 19.99 to INTEGER truncates it to 19, which may not be the rounding behavior you wanted; use ROUND first 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 CAST is only required when types genuinely don't match.

See also: COALESCE, ROUND.

Search

Search lessons, functions, examples, and practice problems