Cast and conversion functions
CAST, CONVERT and BINARY: converting a value to another type.
Conversions between types happen in two places: implicitly, when an operator or a column needs another type (see Type conversion), and explicitly with CAST and CONVERT.
A conversion that finds nothing to convert gives NULL for a date type (CAST('abc' AS DATE)) and 0 for a number type. CAST(x AS YEAR) and CAST(x AS FLOAT(p)) are not supported.
Differences from MySQL: CAST(-5 AS UNSIGNED) is 0 here (MySQL gives 18446744073709551611); CAST(x AS CHAR(n)) cuts the text to n characters; CAST(x AS TIME) keeps the time part of a text without checking it; CAST(x AS DECIMAL(p,s)) rounds to s places and does not check p.
Summary of functions#
| Function | What it does | Dialect |
|---|---|---|
BINARY | Accepted in front of an expression so that MySQL scripts parse, but it changes nothing: the value is the same and the comparison still ignores case (real MySQL gives 0 for BINARY 'a' = 'A'). | MySQL and MariaDB |
CAST | Converts expr to type: SIGNED [INTEGER], UNSIGNED [INTEGER], CHAR[(n)], NCHAR[(n)], BINARY[(n)], DECIMAL[(p[,s])], FLOAT, DOUBLE, REAL, DATE, DATETIME, TIMESTAMP, TIME, JSON. | MySQL and MariaDB |
CONVERT | CONVERT(expr, type) is CAST(expr AS type). | MySQL and MariaDB |
BINARY#
BINARY exprAccepted in front of an expression so that MySQL scripts parse, but it changes nothing: the value is the same and the comparison still ignores case (real MySQL gives 0 for BINARY 'a' = 'A').
Example:
SELECT BINARY 'a' = 'A';Result: 1 (MySQL gives 0)
CAST#
CAST(expr AS type)Converts expr to type: SIGNED [INTEGER], UNSIGNED [INTEGER], CHAR[(n)], NCHAR[(n)], BINARY[(n)], DECIMAL[(p[,s])], FLOAT, DOUBLE, REAL, DATE, DATETIME, TIMESTAMP, TIME, JSON. A CHARACTER SET or COLLATE after the type is read and ignored. CAST(0xAA AS UNSIGNED) is the number 170. Text that starts with digits converts to those digits ('12abc' becomes 12); text that does not becomes 0. A decimal converted to SIGNED is rounded.
Example:
SELECT CAST('12abc' AS SIGNED), CAST('2024-05-06 07:08:09' AS DATE);Result: 12, 2024-05-06
CONVERT#
CONVERT(expr, type)
CONVERT(expr USING charset)CONVERT(expr, type) is CAST(expr AS type). CONVERT(expr USING charset) returns expr unchanged, as every text of Raft DB is utf8mb4.
Example:
SELECT CONVERT('7', SIGNED);Result: 7