← Back to SQL, page 9

sql-0169 · Easy fresher

How are boolean values stored in SQLite compared with PostgreSQL?

SQLite has no separate boolean type; TRUE and FALSE are aliases for 1 and 0, and comparisons return 1 or 0. PostgreSQL has a real boolean type with true, false and NULL, and it will not compare a boolean with an integer directly. Write conditions as col = 1 in SQLite and col in PostgreSQL, or use a CHECK to restrict SQLite values to 0 and 1.

Full answer
sql
SELECT TRUE AS t, FALSE AS f, TRUE + TRUE AS two, 5 > 3 AS cmp, typeof(5 > 3) AS cmp_type;
tftwocmpcmp_type
1021integer

In SQLite, TRUE is simply 1, so TRUE + TRUE is 2 and a comparison like 5 > 3 produces the integer 1.

PostgreSQL keeps booleans separate:

sql
SELECT TRUE AS t, 5 > 3 AS cmp, pg_typeof(5 > 3) AS cmp_type;
tcmpcmp_type
truetrueboolean
sql
SELECT TRUE + TRUE;  -- error on purpose
text
Error: operator does not exist: boolean + boolean

A portable SQLite schema can restrict a flag column with CHECK (active IN (0, 1)), otherwise any value can be stored. Summing a flag (SUM(active)) counts true rows in SQLite; PostgreSQL needs COUNT(*) FILTER (WHERE active) or SUM(active::int).

sql
SELECT TRUE AS t, FALSE AS f, TRUE + TRUE AS two, 5 > 3 AS cmp, typeof(5 > 3) AS cmp_type;

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 TRUE and FALSE are 1 and 0
  • Comparisons in SQLite return integers
  • PostgreSQL has a strict boolean type
  • Constrain SQLite flag columns with CHECK

Common mistakes

  • Adding booleans in PostgreSQL without a cast
  • Storing 'Y', 'yes' and 1 in the same SQLite flag column

Follow-ups

  • How would you count active users on each engine?
  • How does NULL behave in a boolean column?

Tips

  • Show TRUE + TRUE on SQLite