PostgreSQL vs SQLite: Concurrency, Types, Foreign Keys

Updated

Postgres and SQLite comparison

Pick SQLite when exactly one process writes the database. Pick PostgreSQL the moment a second one might. That is the decision — not database size, not “small project vs large project”. You can watch it happen in two terminals:

# terminal 1 holds a write transaction open
sqlite3 app.db 'BEGIN IMMEDIATE; UPDATE counter SET n=n+1 WHERE id=1;'

# terminal 2, a different row, same file
$ sqlite3 app.db 'UPDATE counter SET n=n+100 WHERE id=2;'
Error: stepping, database is locked (5)

PostgreSQL, given the same two statements, commits both. The rest of this page is the four differences that follow from that, each one run rather than asserted.

1. One writer, or many

SQLite locks the whole database file to write. Not the row, not the table — the file. Eight shell processes, each issuing 50 UPDATE statements, at SQLite’s default settings:

SQLITE_BUSY failures: 273
final n = 127

400 attempted, 127 applied. The other 273 returned exit status 5 and did nothing. An application that does not check the return code of every write just lost two-thirds of them silently. The exact split varies run to run; the failures do not, so postgres-vs-sqlite.sh asserts the pattern instead of the 273 and 127: failures at the default setting, none with busy_timeout=5000, and none on PostgreSQL.

The fix is one pragma — SQLite will wait for the lock instead of giving up instantly:

# PRAGMA busy_timeout=5000 before each UPDATE
SQLITE_BUSY failures: 0
final n = 400

Nothing got faster; the writers queued. busy_timeout is not a performance setting — it converts a hard error into a wait, and the waiting is still strictly serial.

The same eight-process, 400-increment workload against PostgreSQL:

PostgreSQL write failures: 0
final n = 400

PostgreSQL uses MVCC, so writers only contend when they touch the same row. Two sessions, one holding an open transaction on row 1:

-- session B, different row: succeeds immediately
UPDATE counter SET n=n+100 WHERE id=2;
UPDATE 1

-- session B, same row: blocks. Forced to give up with a 3s timeout to prove it was waiting:
SET statement_timeout='3s';
UPDATE counter SET n=n+100 WHERE id=1;
ERROR:  canceling statement due to statement timeout
CONTEXT:  while updating tuple (0,1) in relation "counter"

Waiting on the same row is normal. Failing on a different row is what you are signing up for with SQLite. WAL mode does not change it: with PRAGMA journal_mode=WAL a reader sails through an open write transaction, but a second writer gets the same error:

-- reader during an open WAL write transaction:  0        (exit 0)
-- second writer during the same transaction:
Error: stepping, database is locked (5)

2. Declared types are a suggestion in SQLite

SQLite columns have type affinity, not types. This is legal and succeeds:

$ sqlite3 app.db "CREATE TABLE t(id INTEGER PRIMARY KEY, qty INTEGER, name TEXT);"
$ sqlite3 app.db "INSERT INTO t(id,qty,name) VALUES(1,'banana',42);"
$ sqlite3 app.db "SELECT id, qty, typeof(qty), name, typeof(name) FROM t;"
1|banana|text|42|text

The string banana now sits in a column declared INTEGER. PostgreSQL, same statement:

ERROR:  invalid input syntax for type integer: "banana"

It gets worse with types SQLite does not have at all. It has five storage classes — NULL, INTEGER, REAL, TEXT, BLOB. No date, no boolean, no exact decimal:

SQLite:  CREATE TABLE d(when_ DATE);        INSERT INTO d VALUES('2026-02-30');
         2026-02-30|text            -- a date that does not exist, stored happily
SQLite:  CREATE TABLE b(flag BOOLEAN);      INSERT INTO b VALUES('maybe');
         maybe|text
SQLite:  CREATE TABLE v(c VARCHAR(3));      INSERT INTO v VALUES('abcdefghij');
         abcdefghij|10              -- the (3) is not enforced

Postgres: ERROR:  date/time field value out of range: "2026-02-30"
Postgres: ERROR:  invalid input syntax for type boolean: "maybe"
Postgres: ERROR:  value too long for type character varying(3)

The money case is the one to look at twice. A DECIMAL(10,2) column in SQLite gets NUMERIC affinity and stores IEEE-754 doubles:

SQLite    sum(price), typeof(sum(price)), sum(price)=0.3   ->  0.3|real|0
Postgres  sum(price), pg_typeof(sum(price)), sum(price)=0.3 -> 0.30|numeric|t

SQLite prints 0.3 and then tells you it is not equal to 0.3 — floating point behaving exactly as specified, in a column you declared decimal.

STRICT tables fix half of this

SQLite 3.37 (2021) added STRICT tables. Append the keyword and the affinity rules stop applying:

$ sqlite3 app.db "CREATE TABLE ts(id INTEGER PRIMARY KEY, qty INTEGER, name TEXT) STRICT;"
$ sqlite3 app.db "INSERT INTO ts(id,qty,name) VALUES(1,'banana',42);"
Error: stepping, cannot store TEXT value in INTEGER column ts.qty (19)

What STRICT does not do is supply the missing types. It accepts only INT, INTEGER, REAL, TEXT, BLOB and ANY, so the fictional types now fail at CREATE time instead of being reinterpreted:

STRICT column type DECIMAL(10,2)  => Error: in prepare, unknown datatype for s.c: "DECIMAL(10,2)"
STRICT column type DATE           => Error: in prepare, unknown datatype for s.c: "DATE"
STRICT column type BOOLEAN        => Error: in prepare, unknown datatype for s.c: "BOOLEAN"
STRICT column type VARCHAR(20)    => Error: in prepare, unknown datatype for s.c: "VARCHAR(20)"
STRICT column type TEXT           => accepted
STRICT column type INTEGER        => accepted
STRICT column type ANY            => accepted

An honest error beats a silent cast, but you still store money and dates as text or integers and enforce the format yourself.

3. Foreign keys are off by default

SQLite parses REFERENCES, records it in the schema, and then ignores it unless the connection turned enforcement on:

$ sqlite3 g.db "CREATE TABLE parent(id INTEGER PRIMARY KEY);
                CREATE TABLE child(id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES parent(id));
                INSERT INTO child VALUES(1, 999);
                SELECT 'foreign_keys pragma =', * FROM pragma_foreign_keys;"
foreign_keys pragma =|0

$ sqlite3 g.db "SELECT 'orphan rows =', count(*) FROM child WHERE parent_id NOT IN (SELECT id FROM parent);"
orphan rows =|1

With the pragma set it behaves as written — and the pragma is per connection, so every connection your app opens must set it:

$ sqlite3 g.db "PRAGMA foreign_keys=ON; INSERT INTO child VALUES(2,999);"
Error: stepping, FOREIGN KEY constraint failed (19)

PostgreSQL has no equivalent switch:

ERROR:  insert or update on table "child" violates foreign key constraint "child_parent_id_fkey"
DETAIL:  Key (parent_id)=(999) is not present in table "parent".

4. ALTER TABLE runs out of road

SQLite has added a lot here — RENAME COLUMN in 3.25, DROP COLUMN in 3.35 — but the ceiling is low. Every statement below ran against SQLite 3.51.0:

ALTER TABLE t ALTER COLUMN qty TYPE BIGINT;         => Error: near "ALTER": syntax error
ALTER TABLE t MODIFY COLUMN qty BIGINT;             => Error: near "MODIFY": syntax error
ALTER TABLE t ADD COLUMN sku TEXT UNIQUE;           => Error: Cannot add a UNIQUE column
ALTER TABLE t ADD COLUMN c TEXT NOT NULL
              DEFAULT (datetime('now'));            => Error: Cannot add a column with non-constant default
ALTER TABLE t ADD COLUMN c2 TEXT NOT NULL
              DEFAULT 'x';                          => ok
ALTER TABLE t ADD CONSTRAINT qty_pos CHECK (qty>=0);=> Error: near "CONSTRAINT": syntax error
ALTER TABLE t RENAME COLUMN name TO label;          => ok
ALTER TABLE t DROP COLUMN label;                    => ok
ALTER TABLE t DROP COLUMN id;                       => Error: cannot drop PRIMARY KEY column: "id"

All of those failures succeed on PostgreSQL 17.10. In SQLite, changing a column type or adding a constraint means the documented rebuild: create a new table with the shape you want, copy the rows, drop the old one, rename. Your ORM’s migration tool is doing that for you, which is why SQLite migrations are slower and riskier than the one-line statement suggests. Going the other way on PostgreSQL is a single ALTER TABLE as well, with one wrinkle worth reading first: dropping a constraint needs the constraint’s real name, not the column’s.

What SQLite actually has

SQLite has window functions, common table expressions and JSON:

sqlite> SELECT region, amt, sum(amt) OVER (PARTITION BY region ORDER BY amt) AS running FROM sales;
region  amt  running
------  ---  -------
north   10   10
north   30   40
south   5    5
south   20   25

sqlite> WITH RECURSIVE c(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM c WHERE n<5)
   ...> SELECT group_concat(n) AS cte FROM c;
1,2,3,4,5

sqlite> SELECT json_extract('{"a":{"b":7}}','$.a.b'), json_object('k',1);
7|{"k":1}

sqlite> SELECT count(*) FROM sales s FULL OUTER JOIN r ON 1=0;   -- also claimed missing
6

Generated columns and RETURNING work too. There is no CREATE FUNCTION statement:

Error: in prepare, near "FUNCTION": syntax error

But user-defined functions exist; you register them from the host language. Three lines of Python:

>>> c.create_function('shout', 1, lambda s: s.upper())
>>> c.execute("select shout('hi')").fetchone()[0]
'HI'

What SQLite genuinely lacks is everything to do with being a server: no roles, no GRANT, no network listener, no replication.

$ sqlite3 :memory: "GRANT SELECT ON x TO app;"
Error: in prepare, near "GRANT": syntax error

Access control is filesystem permissions on the database file. That is a design decision, not an oversight — but “the reporting user may read this table and not that one” has no answer in SQLite.

Why there is no benchmark here

Many pages on this topic publish a transactions-per-second table. The omission here is deliberate.

SQLite is a function call inside your process; PostgreSQL is a round trip to another process over a socket, with a parser, planner and WAL flush at the far end. A single-machine benchmark measures that architectural gap and nothing else, always flatters SQLite, and does not predict what you would get on your hardware. The failure counts above are different in kind: they are a property of the locking model and reproduce anywhere.

Choosing

SQLite is right for an application that owns its data file: desktop and mobile apps, CLI tools, test fixtures, on-disk caches, a read-mostly site served by one process, and as a file format. Turn on foreign_keys, use WAL, set a busy_timeout, declare tables STRICT.

PostgreSQL is right as soon as a second process writes, or you need types the database enforces, or roles, or a migration that changes a column. The cost is a server to run and back up. Everything else — window functions, CTEs, JSON, upserts — both have.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.