CAST

Complete CAST reference for MariaDB. Complete function guide with syntax, parameters, return values, and usage examples with comprehensive examples and best.

Syntax

CAST(expr AS type)

Description

The CAST() function takes a value of one data type and produces a value of another data type, similar to the CONVERT() function.

The type can be one of the following values:

The main difference between CAST and CONVERT() is that CONVERT(expr,type) is ODBC syntax, while CAST(expr as type) and CONVERT(... USING ...) are SQL92 syntax.

To cast a value to a string data type while specifying the character set, use this extended syntax:

See the examples for casting to character sets.

circle-info

Using an introducer like _utf8mb4'text' is often more efficient than CAST('text' AS CHAR CHARACTER SET utf8mb4), but CAST is necessary when converting data types (like numbers to strings) into a specific encoding. See this example, too.

You can use the CAST() function with the INTERVAL keyword.

This introduced an incompatibility with previous versions of MariaDB, and all versions of MySQL (see the example below).

Examples

Simple Casts

circle-exclamation

If you also want to change the collation, you have to use the COLLATE operator:

Using CAST() to order an ENUM field as a CHAR rather than the internal numerical value:

The following CAST() gives warnings, because x'aa' and 'X'aa' don't behave as a number. In all versions of MySQL, no warnings are triggered because they erroneously behave as a number:

Casting to Intervals

Casting to Character Sets

Casting a Literal to a Specific Character Set

Casting a Binary Literal to a Readable Character Set

Using an Introducer Inside a CAST

See Also

This page is licensed: GPLv2, originally from fill_help_tables.sqlarrow-up-right

spinner

Last updated

Was this helpful?