MySQL CAST() Function
MySQL CAST() Function
The MySQL CAST() function converts a value from one data type into another explicit SQL type inside a query. Use it when sorting numeric strings, parsing ISO date strings, or formatting decimals cleanly.
Syntax
CAST(expr AS type [ARRAY])
expr: The column, literal, or expression you want to convert.type: Target SQL type, such asCHAR,SIGNED,UNSIGNED,DECIMAL(M, D),DATE,DATETIME,TIME,FLOAT,DOUBLE,BINARY, orJSON(MySQL 5.7+).
CAST() follows the ANSI SQL standard, making queries easier to port than MySQL's CONVERT(expr, type) syntax.
Practical Example
Suppose demo_products.sku_rank stores numeric rankings as VARCHAR strings, which sort alphabetically ('10' before '2'). Casting sku_rank to UNSIGNED restores true numeric order.
SELECT
product_id,
product_name,
sku_rank,
CAST(sku_rank AS UNSIGNED) AS numeric_rank,
CAST(unit_price AS DECIMAL(10, 2)) AS formatted_price
FROM demo_products
ORDER BY numeric_rank ASC;
| product_id | product_name | sku_rank | numeric_rank | formatted_price |
|---|---|---|---|---|
| 11 | Mechanical Keyboard | 2 | 2 | 129.00 |
| 12 | USB-C Hub | 10 | 10 | 49.50 |
| 13 | Laptop Stand | NULL | NULL | 35.00 |
Common Mistakes & NULL Behavior
- NULL handling:
CAST(NULL AS <type>)always returnsNULL. - Invalid date or JSON casts: Casting a malformed string such as
CAST('2026-02-30' AS DATE)returnsNULL(with a warning in non-strict mode, or an error in strict mode depending on context), whereasCAST('not-json' AS JSON)throws a runtime error immediately. - Invalid numeric strings:
CAST('abc' AS SIGNED)returns0with a truncation warning rather thanNULL. Always validate input text if'0'is a meaningful domain value. - Unsigned underflow: Casting a negative number like
CAST(-5 AS UNSIGNED)wraps around to18446744073709551611(BIGINT UNSIGNEDmax minus 4) or raises an out-of-range error in strict mode. UseSIGNEDwhen negative values are possible.
Frequently Asked Questions
What is the difference between CAST() and CONVERT() in MySQL?
For data type conversion, CAST(expr AS type) and CONVERT(expr, type) behave identically. CAST() is ANSI-standard SQL, while CONVERT() also supports CONVERT(expr USING charset).
Why cannot I use CAST(x AS INT) in older MySQL?
MySQL expects SIGNED or UNSIGNED (not INT or INTEGER) inside CAST(). For example, write CAST('42' AS SIGNED).
Does CAST() affect index usage in WHERE clauses?
Yes. Wrapping an indexed column inside CAST(col AS ...) disables standard B-tree index lookups on col unless you define a matching functional index.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.