// math reference

SQL cast decimal to integer

Shows whether converting a decimal to an integer rounds or truncates: MySQL, PostgreSQL and Oracle round to nearest, while SQL Server and SQLite chop the fraction.

Categoría
Math
Returns
integer
In this category
71 of 82

Sintaxis

CAST(12.9 AS INT)
12.9::int
CAST(12.9 AS SIGNED)

Each block is a separate form. The support table and the examples show which engine takes which.

Soporte del motor

MotorSupportNotas
SQL Server Sí Truncates toward zero: CAST(12.9 AS INT) is 12, CAST(-12.9 AS INT) is -12
PostgreSQL Sí Rounds to nearest: 12.9::int is 13. numeric ties go away from zero (2.5::int is 3), double precision ties go to even (2.5::float8::int is 2)
MySQL Sí CAST(x AS SIGNED) rounds to nearest: 12.9 becomes 13
SQLite Sí CAST truncates toward zero: CAST(12.9 AS INTEGER) is 12
Oracle Sí CAST to INT is a NUMBER(38, 0) cast and rounds to nearest: CAST(12.9 AS INT) is 13; TRUNC(x) truncates explicitly

Ejemplos

SQL Server

SELECT CAST(12.9 AS INT) AS truncated;  -- 12

PostgreSQL

SELECT 12.9::int AS rounded;  -- 13

MySQL

SELECT CAST(12.9 AS SIGNED) AS rounded;  -- 13

SQLite

SELECT CAST(12.9 AS INTEGER) AS truncated;  -- 12

Oracle

SELECT CAST(12.9 AS INT) AS rounded FROM dual;  -- 13

Conviene saberlo

  • Negative values follow the same per-engine rule: SQL Server and SQLite go toward zero (-12.9 to -12), MySQL, PostgreSQL and Oracle go to nearest (-12.9 to -13).
  • FLOOR and CEILING remove the ambiguity: FLOOR(x) always down, CEILING(x) always up, on every engine; prefer them when the intent matters.
  • Out-of-range casts error or clamp per the overflow rules; PostgreSQL's 1e20::int raises 'integer out of range' rather than wrapping.

Questions about CAST to INT

Does CAST to INT round or truncate?

Depends on the engine: MySQL, PostgreSQL and Oracle round to nearest (12.9 becomes 13); SQL Server and SQLite truncate the fraction (12.9 becomes 12). Use FLOOR or CEILING when the direction matters.

Why do engines disagree?

The SQL standard leaves it open. The engines split historically and kept their behaviour for compatibility, which is exactly why the explicit FLOOR/CEILING/ROUND trio exists.

What happens to the fractional part of a negative?

Truncators (SQL Server, SQLite) go toward zero: -12.9 becomes -12. Rounders (MySQL, PostgreSQL, Oracle) go to nearest: -12.9 becomes -13.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.