SQL CAST truncation behaviour
A cast that loses information does not lose it the same way everywhere: CAST(2.7 AS INT) is 3 on some engines and 2 on others.
- Returns
the target type- In this category
- 11 of 39
语法
CAST(expression AS INTEGER)
CAST(expression AS SIGNED) -- MySQL
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | Supported under this name. |
| Oracle | 是 | Supported under this name. |
示例
SQL Server
SELECT CAST(2.7 AS INT) AS n; -- 2
PostgreSQL
SELECT CAST(2.7 AS integer) AS n; -- 3
MySQL
SELECT CAST(2.7 AS SIGNED) AS n; -- 3
SQL Server
SELECT CAST('abcdefgh' AS varchar(4)) AS cut; -- abcd
值得了解
- Exact decimal to integer: PostgreSQL, MySQL and Oracle round half away from zero (2.5 becomes 3, -2.5 becomes -3); SQL Server and SQLite truncate toward zero (2.7 becomes 2). PostgreSQL rounds a float8 2.5 to 2, half to even.
- Text with a fraction: CAST('123.9' AS INTEGER) errors on PostgreSQL and SQL Server, returns 124 on Oracle, and returns 123 on SQLite. MySQL's CAST('123.9' AS SIGNED) gives 123 with a warning. Cast to DECIMAL first, then round on purpose.
- Shrinking text: CAST('abcdefgh' AS varchar(4)) is 'abcd' with no error on SQL Server, PostgreSQL and Oracle, and MySQL only adds a warning. SQLite ignores the length entirely and returns all eight characters.
- MySQL has no INTEGER cast target: CAST(x AS INTEGER) is a syntax error there. Write CAST(x AS SIGNED) or CAST(x AS UNSIGNED).
- Casting a timestamp to date drops the time without rounding. Oracle is the exception: its DATE type has a time part, so CAST(ts AS DATE) keeps hours, minutes and seconds and drops only fractional seconds.
Questions about CAST truncation
How do I get the same answer on every engine?
Say which rounding you want instead of relying on the cast: ROUND(x) or TRUNC(x) on PostgreSQL and Oracle, ROUND(x, 0) or TRUNCATE(x, 0) on MySQL, ROUND(x, 0) or ROUND(x, 0, 1) to truncate on SQL Server, then cast the result.
Does CAST ever warn about lost data?
MySQL does: truncated text and partly numeric strings add warnings you can read with SHOW WARNINGS. The other engines cut text silently. Numeric overflow, such as CAST(300 AS TINYINT) on SQL Server, raises an error everywhere it applies.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.