// conversion reference

SQL CAST function

Converts a value to a target type: text to number, number to text, timestamp to date. CAST is the SQL-standard spelling and the one to reach for when portability matters.

Categoría
Conversion
Returns
the target type
In this category
1 of 39

Sintaxis

CAST(expression AS type)

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí Supported under this name.
SQLite Sí Supported under this name.
Oracle Sí Supported under this name.

Ejemplos

PostgreSQL

-- CAST('42' AS SIGNED) on MySQL
SELECT CAST('42' AS INTEGER) AS n;

Any engine

SELECT CAST(total AS DECIMAL(10, 2)) AS money
FROM orders;

PostgreSQL

SELECT created_at::date AS day FROM orders;

Conviene saberlo

  • Integer division happens before any CAST of the result: 7/2 is 3 on SQL Server, PostgreSQL and SQLite, so CAST(7/2 AS DECIMAL(5,2)) is 3.00. Cast an operand instead: CAST(7 AS DECIMAL(5,2)) / 2. MySQL's / already returns 3.5.
  • Bad input: CAST('abc' AS INT) raises an error on SQL Server, PostgreSQL and Oracle. MySQL returns 0 with a warning in a SELECT, and SQLite returns 0 silently. CAST('12abc' AS INTEGER) is 12 on SQLite.
  • Target type names differ: MySQL's CAST takes SIGNED, UNSIGNED, DECIMAL, CHAR, DATE and a few others, not INTEGER or VARCHAR, so CAST(x AS INTEGER) is a syntax error there.
  • Shorthands: PostgreSQL also accepts expression::type; SQL Server and MySQL have CONVERT. CAST is the standard form.

Questions about CAST

What is the difference between CAST and CONVERT?

CAST is SQL standard with one fixed syntax. CONVERT exists in SQL Server (with style numbers) and MySQL (with reversed argument order). Prefer CAST unless you need a CONVERT-only feature like SQL Server's styles.

Why is 1/2 equal to 0 in my query?

Both operands are integers, so SQL Server, PostgreSQL and SQLite do integer division and drop the fraction. CAST(1 AS DECIMAL(10,2)) / 2, or 1.0 / 2, gives 0.5. MySQL returns 0.5000 already, and Oracle has no integer division.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.