← Back to SQL, page 3

sql-0047 · Easy fresher

In SQLite, how are TRUE and FALSE represented, and what does WHERE do with a numeric column used as a condition?

SQLite has no separate boolean type. TRUE and FALSE are aliases for 1 and 0, comparisons return 1, 0 or NULL, and WHERE treats any non-zero number as true. PostgreSQL has a real boolean type and rejects WHERE on an integer column without a comparison.

Full answer

SQLite stores booleans as integers. The keywords TRUE and FALSE (accepted since 3.23) are just 1 and 0:

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, is_active INTEGER);
INSERT INTO users VALUES (1,'Ana',1),(2,'Ben',0),(3,'Chen',2),(4,'Dara',NULL);
sql
SELECT TRUE AS t, FALSE AS f, 5 > 3 AS cmp, typeof(TRUE) AS stored_as;
tfcmpstored_as
101integer

A comparison like 5 > 3 returns 1. Any non-zero numeric value counts as true in WHERE, so a column of 0s and 1s can be used directly:

sql
SELECT id, name, is_active FROM users WHERE is_active ORDER BY id;
idnameis_active
1Ana1
3Chen2

The row with is_active = 2 is also returned, since 2 is non-zero, and the NULL row is not. SQLite does not stop you storing 2 or -1 in a "boolean" column. Add CHECK (is_active IN (0, 1)) if only 0 and 1 make sense.

PostgreSQL has a true boolean type. Using an integer column as a condition is an error:

sql
SELECT id FROM users WHERE is_active;  -- error on purpose
text
Error: argument of WHERE must be type boolean, not type integer

In PostgreSQL you would declare is_active boolean, write WHERE is_active, and get true or false back. When code moves from SQLite to PostgreSQL, columns declared BOOLEAN in SQLite but filled with 0 and 1 usually need a migration step.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, is_active INTEGER);
INSERT INTO users VALUES (1,'Ana',1),(2,'Ben',0),(3,'Chen',2),(4,'Dara',NULL);

SELECT TRUE AS t, FALSE AS f, 5 > 3 AS cmp, typeof(TRUE) AS stored_as;

SELECT id, name, is_active FROM users WHERE is_active ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • SQLite has no boolean storage class; TRUE is 1 and FALSE is 0
  • Non-zero numbers are true in WHERE
  • Use CHECK (col IN (0, 1)) to keep a flag clean
  • PostgreSQL has a real boolean type and is stricter

Common mistakes

  • Storing values other than 0 and 1 in a flag column
  • Assuming WHERE int_column works on PostgreSQL

Follow-ups

  • How would you count active and inactive users in one query?
  • What does SUM(is_active) give you in SQLite?

Tips

  • Contrast with PostgreSQL in one line