CAST

Convert a value to a specific data type. This function explicitly converts a value from one type to another, such as string to integer.

Syntax

CAST(expr AS type)

Description

The CAST() function takes a value of one type and produces a value of another 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.

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

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 will trigger warnings, since x'aa' and 'X'aa' doesn't behave as a number. In all versions of MySQL, no warnings are triggered since they did erroneously behave as a number:

Casting to Intervals

See Also

This page is licensed: GPLv2, originally from fill_help_tables.sql

Last updated

Was this helpful?