SQL BOOLEAN cast
CAST(x AS BOOLEAN) works on PostgreSQL and Oracle 23ai, is a syntax error on MySQL, and has no target on SQL Server, where bit plays the part. Each engine stores truth differently.
- Returns
boolean or integer- In this category
- 15 of 39
語法
CAST(expression AS BOOLEAN) -- PostgreSQL, Oracle 23ai
CAST(expression AS bit) -- SQL Server
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Different name or syntax | bit: 0, 1 and NULL only |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Different name or syntax | BOOL is a column-type alias for TINYINT(1); not a CAST target |
| SQLite | Different name or syntax | no boolean type; TRUE and FALSE are 1 and 0 |
| Oracle | 是 | SQL BOOLEAN from 23ai; PL/SQL only before that |
範例
PostgreSQL
SELECT 'true'::boolean, 1::boolean AS t;
SQL Server
SELECT CAST(1 AS bit) AS active;
Oracle
SELECT CAST(1 AS BOOLEAN) AS flag FROM dual; -- 23ai
小知識
- MySQL has no BOOLEAN cast target: CAST(x AS BOOLEAN) and CAST(x AS BOOL) are syntax errors. A BOOL column is TINYINT(1) and stores 2 as 2, so col = TRUE is false for it while col IS TRUE is true.
- SQL Server bit stores 0, 1 and NULL and has no TRUE/FALSE keywords. Any non-zero number casts to 1, and the strings 'true' and 'false' convert to 1 and 0.
- Oracle added a SQL BOOLEAN type in 23ai; CAST(1 AS BOOLEAN) and CAST('yes' AS BOOLEAN) both return TRUE there. Older releases store CHAR(1) 'Y'/'N' or NUMBER(1) and compare explicitly.
- SQLite has no boolean storage class: TRUE and FALSE are keywords for 1 and 0, and filters treat any non-zero value as true. CAST(x AS BOOLEAN) only applies NUMERIC affinity.
Questions about Boolean casts
Why does true fail on SQL Server?
SQL Server has no TRUE or FALSE keywords: bit columns take 1 and 0 (or the strings 'true' and 'false'). PostgreSQL, Oracle 23ai, MySQL and SQLite all accept TRUE and FALSE, though MySQL and SQLite read them as 1 and 0.
How do I get a strict 0/1 flag on MySQL?
Compare instead of casting: (x <> 0) returns exactly 0 or 1, or NULL for NULL. MySQL has no boolean cast, and a BOOL column will store any TINYINT value you give it.
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.