Function Reference

CAST

Converts a value to the specified data type.

MySQL 8.1
CAST(value AS type)

Parameters

value
Value to convert
typekeyword
Target data type, some types take a size in parentheses
Values:BINARYCHARDATEDATETIMEDECIMALDOUBLEFLOATJSONNCHARREALSIGNEDTIMEUNSIGNEDYEAR

Return value

A value of the given type; a failed conversion gives 0 or NULL with a warning, not an error

Examples

DECIMAL with and without scale

MySQL 8.1
SELECT CAST(12005.6 AS DECIMAL) AS rounded,
	CAST(12005.6 AS DECIMAL(10, 2)) AS with_scale;
roundedwith_scale
1200612005.6

Average with two decimals

MySQL 8.1
SELECT family_member,
	CAST(AVG(unit_price) AS DECIMAL(10, 2)) AS avg_price
FROM Payments
GROUP BY family_member;
family_memberavg_price
11542.5
210575.43
3505.8
4250
5179.33

Strings to an integer

MySQL 8.1
SELECT CAST('12abc' AS SIGNED) AS number_prefix,
	CAST('abc' AS SIGNED) AS no_number;
number_prefixno_number
120

Details

The list of target types in MySQL is shorter than the list of column types: an integer is written as SIGNED or UNSIGNED, and CAST(1 AS INT) is a syntax error. A string is CHAR, not VARCHAR.

TypeResult
DATEA date in the YYYY-MM-DD format.
DATETIMEA datetime in the YYYY-MM-DD HH:MM:SS format.
TIMEA time in the HH:MM:SS format.
DECIMAL[(M[,D])]A fixed-point number: M is the total number of digits (10 by default), D is the number of digits after the decimal point (0 by default, so without it the fractional part is rounded).
DOUBLEA double-precision floating-point number.
FLOAT[(p)]A single-precision floating-point number; with p greater than 24 — double precision, like DOUBLE.
REALThe same as DOUBLE (unless the REAL_AS_FLOAT mode is on).
CHAR[(N)]A string; if N is given, it is cut to N characters.
NCHAR[(N)]Like CHAR, but in the national character set (utf8mb3).
JSONA JSON value; the string must be valid JSON, otherwise an error.
SIGNEDA signed integer (BIGINT). A fractional number is rounded, and a string is read up to the first non-digit character.
UNSIGNEDAn unsigned integer (BIGINT UNSIGNED). A negative number turns into a very large positive one.
BINARY[(N)]A binary string: comparisons with it are byte by byte and case sensitive.
YEARA year; a two-digit number is expanded to four digits: 23 becomes 2023, and 70 becomes 1970.

See also

Where to learn