Questions 221–240 of 501 · 0 of 20 on this page marked learned
221.sql-0221Hardsenior
What is a clustered index, and how do SQLite rowid tables and PostgreSQL heap tables relate to it?
A clustered index stores the table rows themselves in index order, so the table is the index. In SQLite, an ordinary table is a B-tree keyed by rowid (or the INTEGER PRIMARY KEY), and a WITHOUT ROWID table is clustered on its declared primary key. PostgreSQL stores rows in an unordered heap and every index, including the primary key, points into it; CLUSTER reorders the heap once but does not maintain the order.
Full answer
SQL Server and MySQL InnoDB cluster tables on the primary key, so range scans on the key read neighbouring rows, and secondary indexes store the primary key to find rows.
SQLite works similarly. A rowid table is a B-tree on rowid; an INTEGER PRIMARY KEY is an alias for rowid, so lookups by it go straight to the row:
sql
CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);
EXPLAIN QUERY PLAN SELECT v FROM t WHERE id = 5;
text
QUERY PLAN
SEARCH t USING INTEGER PRIMARY KEY (rowid=?)
A WITHOUT ROWID table is organized by its primary key, which suits composite keys, as in a junction table:
sql
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id)) WITHOUT ROWID;
EXPLAIN QUERY PLAN SELECT course_id FROM enrol WHERE student_id = 1;
text
QUERY PLAN
SEARCH enrol USING PRIMARY KEY (student_id=?)
PostgreSQL's heap means the primary key index is just another index. CLUSTER table USING index sorts the heap once, and later inserts are not kept in order.
Why it matters: a random UUID as a clustered key scatters inserts across the whole B-tree, while an increasing key appends at the end.
sql
CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);
EXPLAIN QUERY PLAN SELECT v FROM t WHERE id = 5;
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id)) WITHOUT ROWID;
EXPLAIN QUERY PLAN SELECT course_id FROM enrol WHERE student_id = 1;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A clustered index stores rows in key order
SQLite tables are B-trees on rowid; INTEGER PRIMARY KEY aliases it
WITHOUT ROWID tables cluster on the primary key
PostgreSQL uses an unordered heap; CLUSTER is one-off
Common mistakes
Assuming PostgreSQL keeps rows in primary key order
Choosing random clustered keys for insert-heavy tables
Follow-ups
When would WITHOUT ROWID be a good fit?
How do secondary indexes find rows in a clustered table?
Tips
Contrast heap and clustered storage
222.sql-0222Mediummid
How does an index on the join column change the plan for orders joined to order_items?
Without an index on order_items.order_id, SQLite has to scan order_items to find the lines of an order. With the index, each order looks up its items directly with SEARCH ... USING INDEX. Index foreign key columns that are used in joins and parent deletes.
Full answer
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
EXPLAIN QUERY PLAN
SELECT o.id, i.product FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.id = 104;
text
QUERY PLAN
SEARCH o USING INTEGER PRIMARY KEY (rowid=?)
SCAN i
The order itself is found by primary key, but its lines need a SCAN of order_items. On a large table that scan dominates the cost. With an index on the join column, the lines are found by a search:
sql
CREATE INDEX items_order ON order_items(order_id);
EXPLAIN QUERY PLAN
SELECT o.id, i.product FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.id = 104;
text
QUERY PLAN
SEARCH o USING INTEGER PRIMARY KEY (rowid=?)
SEARCH i USING INDEX items_order (order_id=?)
On PostgreSQL, the planner would weigh a hash join, which needs no index, against a nested loop with index lookups. For small result sets driven by a filtered outer table, the indexed nested loop usually wins. For joining two whole large tables, a hash join with no index is often best, so an index is not always the answer.
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
EXPLAIN QUERY PLAN
SELECT o.id, i.product FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.id = 104;
CREATE INDEX items_order ON order_items(order_id);
EXPLAIN QUERY PLAN
SELECT o.id, i.product FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.id = 104;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Index child foreign key columns used in joins
SQLite scans the child table without an index on the join column
Indexed nested loops suit selective joins
Hash joins need no index for large full joins
Common mistakes
Leaving foreign key columns unindexed
Assuming every join needs an index
Follow-ups
What is a hash join?
How does an unindexed foreign key slow parent deletes?
Tips
Read the SCAN line and say which index would remove it
223.sql-0223Easyfresher
What is a transaction, and what do COMMIT and ROLLBACK do?
A transaction groups statements into one unit that either takes effect completely or not at all. COMMIT makes the changes permanent and visible to others; ROLLBACK discards every change made since BEGIN. Without an explicit BEGIN, most engines run each statement in its own transaction (autocommit).
Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
sql
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;
id
balance
1
100
2
50
The transfer was applied inside the transaction and then rolled back, so both balances are back to their starting values. Replacing ROLLBACK with COMMIT would keep both updates together.
Grouping matters because a transfer is two writes. If the program crashed between them in autocommit mode, 30 would leave Ana's account and never arrive in Bilal's. Inside a transaction, a crash before COMMIT leaves neither change, because the engine undoes incomplete transactions on recovery.
Keep transactions short. An open transaction holds locks (or, in MVCC engines, old row versions) until it ends.
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A transaction is all-or-nothing
COMMIT makes changes permanent
ROLLBACK undoes changes since BEGIN
Autocommit wraps each statement separately
Common mistakes
Running related writes in autocommit mode
Leaving transactions open while waiting for user input
Follow-ups
What does ACID stand for?
What happens to an open transaction if the connection drops?
Tips
Use a money transfer as the example
224.sql-0224Easyfresher
Explain each letter of ACID with a concrete example.
Atomicity: a transfer's debit and credit happen together or not at all. Consistency: a transaction moves the database from one valid state to another, respecting constraints such as balance >= 0. Isolation: concurrent transactions do not see each other's partial work, to the degree the isolation level promises. Durability: once COMMIT returns, the change survives a crash.
Full answer
Atomicity. The engine logs changes so it can undo an incomplete transaction. A crash halfway through a transfer leaves both accounts unchanged.
Consistency. Constraints, foreign keys and triggers are enforced, so a committed state never violates the declared rules. Application-level rules, such as "total money in the system is unchanged", are the application's job, helped by atomicity.
Isolation. Each transaction behaves as if it ran with less interference from others. Weaker levels allow specific anomalies in exchange for concurrency; SERIALIZABLE aims for results equivalent to some serial order.
Durability. The commit is written to stable storage (a write-ahead log or journal) before success is reported. Settings such as SQLite's PRAGMA synchronous = OFF or PostgreSQL's synchronous_commit = off trade some durability for speed.
A common interview follow-up is that the C in ACID differs from the C in the CAP theorem, which is about replicas agreeing.
Key points
Atomicity: all or nothing
Consistency: constraints hold after every commit
Isolation: controlled visibility between concurrent transactions
Durability: committed data survives crashes
Common mistakes
Describing consistency as 'data is correct' without mentioning constraints
Assuming every isolation level prevents every anomaly
Follow-ups
Which anomalies does READ COMMITTED allow?
How does a write-ahead log provide durability?
Tips
Give one example per letter
225.sql-0225Hardsenior
Inside a transaction, the second of two UPDATEs fails a CHECK constraint. Is the first UPDATE undone automatically?
Not in SQLite: only the failing statement is rolled back, and the transaction stays open with the first UPDATE still applied until the application issues ROLLBACK or COMMIT. PostgreSQL marks the whole transaction as aborted, rejects further statements, and can only roll back. In both cases the application must catch the error and roll back explicitly.
Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
Ana has 100. The first statement takes 30 from Bilal; the second tries to take 200 from Ana and breaks the CHECK:
sql
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 2;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
-- error on purpose
text
Error: CHECK constraint failed: balance >= 0
The transaction is still open. Reading inside it shows that the first update survived the error:
sql
SELECT id, balance FROM accounts ORDER BY id;
id
balance
1
100
2
20
If the application now ran COMMIT, half a transfer would be saved. Rolling back restores both balances:
sql
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;
id
balance
1
100
2
50
In PostgreSQL, any statement after the error fails with "current transaction is aborted, commands ignored until end of transaction block", and COMMIT turns into a rollback (described from the documentation, not run as a multi-step session here). Savepoints let PostgreSQL code recover from an expected error without abandoning the whole transaction.
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
-- error on purpose
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 2;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
SELECT id, balance FROM accounts ORDER BY id;
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
SQLite rolls back only the failing statement
The SQLite transaction stays open with earlier changes
PostgreSQL aborts the whole transaction
Always ROLLBACK in the error handler
Common mistakes
Committing after a caught error in SQLite
Assuming one failure undoes the whole transaction on every engine
Follow-ups
How would a savepoint help here?
How do database drivers usually handle this?
Tips
Show the open transaction state
226.sql-0226Mediummid
Name the read anomalies that isolation levels are defined by, and which levels prevent each.
Dirty read: seeing another transaction's uncommitted change. Non-repeatable read: reading the same row twice and getting different committed values. Phantom read: rerunning a range query and finding new rows. READ UNCOMMITTED allows all three, READ COMMITTED prevents dirty reads, REPEATABLE READ also prevents non-repeatable reads, and SERIALIZABLE prevents all three plus other anomalies such as write skew.
Full answer
The SQL standard defines four levels by which anomalies they forbid:
text
Level Dirty read Non-repeatable Phantom
READ UNCOMMITTED possible possible possible
READ COMMITTED no possible possible
REPEATABLE READ no no possible
SERIALIZABLE no no no
Real engines are often stricter than the table requires:
PostgreSQL treats READ UNCOMMITTED as READ COMMITTED, and its REPEATABLE READ (snapshot isolation) also prevents phantoms. Its default is READ COMMITTED.
MySQL InnoDB defaults to REPEATABLE READ.
SQLite transactions are serializable, because only one writer runs at a time and readers see a consistent snapshot.
PostgreSQL's default can be read directly:
sql
SHOW default_transaction_isolation;
default_transaction_isolation
read committed
The table leaves out lost updates and write skew, which matter just as much in practice and are covered separately.
Key points
Dirty, non-repeatable and phantom reads define the standard levels
Each stronger level forbids one more anomaly
PostgreSQL defaults to READ COMMITTED; InnoDB to REPEATABLE READ
SQLite transactions are serializable
Common mistakes
Assuming every engine's REPEATABLE READ behaves the same
Forgetting lost updates and write skew
Follow-ups
What is write skew?
Why might you not run everything at SERIALIZABLE?
Tips
Draw the table from memory
227.sql-0227Mediummid
While connection A has an uncommitted UPDATE in SQLite, what does connection B read?
B reads the last committed value, not A's pending change, so SQLite does not allow dirty reads. In the default rollback-journal mode, B can read while A holds its write lock but before A starts writing to the database file at commit. After A commits, B sees the new value.
Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
A starts a transaction and changes Ana's balance without committing:
sql
BEGIN;
UPDATE accounts SET balance = 70 WHERE id = 1;
SELECT balance FROM accounts WHERE id = 1;
balance
70
B reads the same row:
sql
SELECT balance FROM accounts WHERE id = 1;
balance
100
B sees 100, the committed value. A then commits:
sql
COMMIT;
SELECT 'committed' AS a_status;
a_status
committed
sql
SELECT balance FROM accounts WHERE id = 1;
balance
70
Now B sees 70. No isolation level in SQLite exposes uncommitted data from another connection. (The read_uncommitted pragma applies only to connections sharing a cache in one process.)
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
BEGIN;
UPDATE accounts SET balance = 70 WHERE id = 1;
SELECT balance FROM accounts WHERE id = 1;
-- second session
SELECT balance FROM accounts WHERE id = 1;
COMMIT;
SELECT 'committed' AS a_status;
-- second session
SELECT balance FROM accounts WHERE id = 1;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
SQLite never shows another connection's uncommitted changes
Readers see the last committed state
After COMMIT, new reads see the change
Dirty reads are prevented by default
Common mistakes
Assuming a reader blocks until the writer commits
Confusing shared-cache read_uncommitted with normal behaviour
Follow-ups
What happens if B tries to write while A holds the lock?
How does WAL mode change reader behaviour?
Tips
Narrate the A and B timeline
228.sql-0228Mediummid
Two connections try to write to the same SQLite database at the same time. What happens to the second one?
SQLite allows one writer at a time for the whole database. While A holds the write lock, B's write fails with 'database is locked' (SQLITE_BUSY), unless B has a busy timeout, in which case it waits and retries until A finishes or the timeout expires. Applications should set a busy timeout and keep write transactions short.
Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
A begins a write transaction:
sql
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SELECT 'A holds the write lock' AS a_status;
a_status
A holds the write lock
B tries to write a different row:
sql
UPDATE accounts SET balance = balance + 10 WHERE id = 2; -- error on purpose
text
Error: database is locked
The lock is on the database, not on rows, so even an unrelated row cannot be written. These connections use a timeout of 0 to show the error immediately. With PRAGMA busy_timeout = 5000 (or the driver's timeout option), B would wait up to five seconds for A.
Once A commits, B can write:
sql
COMMIT;
SELECT 'A committed' AS a_status;
a_status
A committed
sql
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
SELECT id, balance FROM accounts ORDER BY id;
id
balance
1
90
2
60
This single-writer design is why SQLite suits many readers and modest write rates, and why server engines with row-level locking suit heavy concurrent writes.
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SELECT 'A holds the write lock' AS a_status;
-- error on purpose
-- second session
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;
SELECT 'A committed' AS a_status;
-- second session
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
SELECT id, balance FROM accounts ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
SQLite has one writer at a time per database
A second writer gets SQLITE_BUSY ('database is locked')
busy_timeout makes it wait and retry
Keep write transactions short
Common mistakes
Running with no busy timeout and failing under light concurrency
Holding write transactions open across slow work
Follow-ups
How does WAL mode change concurrency?
What is BEGIN IMMEDIATE for?
Tips
Mention the busy timeout
229.sql-0229Mediummid
What does WAL mode change for SQLite readers and writers?
In write-ahead log mode, writers append changes to a separate WAL file, so readers keep reading the last committed snapshot while a write is in progress, and a reader does not block the writer. There is still only one writer at a time. A reader inside a transaction keeps its snapshot until that transaction ends.
B starts a read transaction and reads Ana's balance:
sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
balance
100
A updates and commits while B's transaction is still open:
sql
UPDATE accounts SET balance = 60 WHERE id = 1;
SELECT balance AS a_sees FROM accounts WHERE id = 1;
a_sees
60
B still sees 100, because its read transaction pinned a snapshot:
sql
SELECT balance AS b_sees_in_old_txn FROM accounts WHERE id = 1;
b_sees_in_old_txn
100
After B ends its transaction, a new read sees A's change:
sql
COMMIT;
SELECT balance AS b_sees_after FROM accounts WHERE id = 1;
b_sees_after
60
That snapshot behaviour is a simple form of MVCC: different transactions see different committed versions. WAL needs the database on a local file system (shared memory is used for the index), and the WAL file is merged back into the main file at checkpoints.
sql
PRAGMA journal_mode = WAL;
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
-- second session
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
UPDATE accounts SET balance = 60 WHERE id = 1;
SELECT balance AS a_sees FROM accounts WHERE id = 1;
-- second session
SELECT balance AS b_sees_in_old_txn FROM accounts WHERE id = 1;
-- second session
COMMIT;
SELECT balance AS b_sees_after FROM accounts WHERE id = 1;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
WAL lets readers and the writer work at the same time
Readers see a stable snapshot for their whole transaction
Still one writer at a time
Checkpoints move WAL content into the main file
Common mistakes
Expecting WAL to allow multiple concurrent writers
Keeping long read transactions open and letting the WAL grow
Follow-ups
What is a checkpoint?
Why does WAL not work well on network file systems?
Tips
Show the reader keeping its old snapshot
230.sql-0230Mediummid
Two users each read a stock count of 5, subtract 1 in application code, and write back 4. What went wrong, and how do you fix it?
This is a lost update: both read the same value, both wrote a result based on it, and one decrement vanished. Fix it with an atomic UPDATE that computes in the database (SET qty = qty - 1 WHERE qty > 0), with SELECT ... FOR UPDATE to lock the row before reading, or with optimistic concurrency using a version column.
Full answer
The broken pattern:
text
A: SELECT qty FROM stock WHERE sku = 'pen'; -- 5
B: SELECT qty FROM stock WHERE sku = 'pen'; -- 5
A: UPDATE stock SET qty = 4 WHERE sku = 'pen';
B: UPDATE stock SET qty = 4 WHERE sku = 'pen'; -- should be 3
The atomic version leaves no gap between read and write, and the WHERE stops overselling:
sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 1);
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
SELECT qty FROM stock;
qty
0
Optimistic concurrency checks that nobody changed the row since it was read. If the version moved on, zero rows change and the application retries:
sql
CREATE TABLE doc (id INTEGER PRIMARY KEY, body TEXT, version INTEGER NOT NULL);
INSERT INTO doc VALUES (1, 'v1 text', 1);
UPDATE doc SET body = 'edit by A', version = version + 1 WHERE id = 1 AND version = 1;
UPDATE doc SET body = 'edit by B', version = version + 1 WHERE id = 1 AND version = 1;
SELECT body, version, changes() AS rows_changed_by_last_update FROM doc;
body
version
rows_changed_by_last_update
edit by A
2
0
On PostgreSQL, SELECT ... FOR UPDATE inside a transaction makes the second reader wait for the first to finish. REPEATABLE READ in PostgreSQL also detects this conflict and fails the second transaction with a serialization error, which the application must retry (not run as a concurrent session here).
sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 1);
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
SELECT qty FROM stock;
CREATE TABLE doc (id INTEGER PRIMARY KEY, body TEXT, version INTEGER NOT NULL);
INSERT INTO doc VALUES (1, 'v1 text', 1);
UPDATE doc SET body = 'edit by A', version = version + 1 WHERE id = 1 AND version = 1;
UPDATE doc SET body = 'edit by B', version = version + 1 WHERE id = 1 AND version = 1;
SELECT body, version, changes() AS rows_changed_by_last_update FROM doc;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Lost update: concurrent read-modify-write cycles overwrite each other
Compute in the UPDATE itself when possible
SELECT ... FOR UPDATE locks the row before reading
Version columns give optimistic concurrency
Common mistakes
Computing new values in application code from a stale read
Ignoring the zero-rows-updated result of an optimistic update
Follow-ups
When is optimistic locking better than FOR UPDATE?
How would you reserve stock for a cart for 10 minutes?
Tips
Write the two-session timeline
231.sql-0231Hardsenior
Two on-call doctors each check that at least one other doctor is on call, then go off call at the same time, leaving nobody. Which anomaly is this, and which isolation level prevents it?
This is write skew: each transaction reads an overlapping set of rows, makes a decision based on it, and writes a different row, so neither write conflicts directly. Snapshot isolation (PostgreSQL REPEATABLE READ) allows it. SERIALIZABLE prevents it; in PostgreSQL one transaction fails with a serialization error and must be retried. Explicit locks on the rows read also work.
Full answer
Timeline under snapshot isolation:
text
T1: SELECT count(*) FROM doctors WHERE on_call; -- 2, fine to leave
T2: SELECT count(*) FROM doctors WHERE on_call; -- 2, fine to leave
T1: UPDATE doctors SET on_call = false WHERE name = 'Ravi';
T2: UPDATE doctors SET on_call = false WHERE name = 'Mei';
T1: COMMIT; T2: COMMIT; -- nobody on call
The two updates touch different rows, so row locks never collide. Each transaction's snapshot was valid when read, but the combination breaks the rule.
Fixes:
SERIALIZABLE in PostgreSQL tracks read/write dependencies and aborts one of the two with SQLSTATE 40001. Code must retry.
SELECT ... FOR UPDATE on all on-call rows makes the second transaction wait and then see the first one's change.
Materialize the rule as a row that both must update, such as a shift row with a counter and a CHECK.
SQLite avoids this specific case because its writers are serialized. The multi-session PostgreSQL behaviour is described from its documentation and was not run here.
Key points
Write skew: decisions on overlapping reads, writes to different rows
Snapshot isolation allows it
SERIALIZABLE prevents it with retryable errors
FOR UPDATE on the read set or a shared counter row also work
Common mistakes
Assuming REPEATABLE READ prevents every anomaly
Running SERIALIZABLE without retry logic
Follow-ups
How would you implement retries for serialization failures?
Why do row locks not help here by default?
Tips
Tell it as a two-transaction timeline
232.sql-0232Mediummid
What is a deadlock, and how do you reduce the chance of one?
A deadlock happens when two transactions each hold a lock the other needs, so neither can continue. Server engines detect the cycle and abort one transaction with an error. Reduce deadlocks by locking rows in a consistent order, keeping transactions short, and touching as few rows as possible; and retry the aborted transaction.
Full answer
A classic case is two transfers in opposite directions:
text
T1: UPDATE accounts SET ... WHERE id = 1; -- locks row 1
T2: UPDATE accounts SET ... WHERE id = 2; -- locks row 2
T1: UPDATE accounts SET ... WHERE id = 2; -- waits for T2
T2: UPDATE accounts SET ... WHERE id = 1; -- waits for T1: deadlock
PostgreSQL checks for cycles after deadlock_timeout (1 second by default) and cancels one transaction with "deadlock detected".
Prevention:
Lock in a fixed order, for example always the lower account id first. Then both transfers queue on row 1 instead of crossing.
Lock everything up front with one SELECT ... FOR UPDATE ... ORDER BY id.
Keep transactions short and avoid user interaction inside them.
Treat the deadlock error as retryable.
SQLite has no row locks; its equivalent problem is two deferred transactions that both read and then both try to write, covered in the BEGIN IMMEDIATE question.
Key points
Deadlock: a cycle of transactions waiting on each other's locks
Engines detect it and abort one transaction
Lock rows in a consistent order
Keep transactions short and retry on deadlock errors
Common mistakes
Updating rows in request order instead of a fixed order
Treating a deadlock error as a fatal bug instead of retrying
Follow-ups
How does PostgreSQL choose which transaction to cancel?
How do you find which queries deadlocked?
Tips
Use the opposite-direction transfer example
233.sql-0233Hardsenior
In SQLite, why can two transactions that both read and then write fail with 'database is locked', and how does BEGIN IMMEDIATE help?
A plain BEGIN is deferred: it takes no lock until the first read or write. If two connections both read first, then try to write, the second writer finds the database already reserved, and in WAL mode its snapshot is out of date, so it gets SQLITE_BUSY even with a busy timeout. BEGIN IMMEDIATE takes the write lock at the start, so the second transaction waits at BEGIN instead of failing midway.
Both connections start deferred transactions and read:
sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
balance
100
sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
balance
100
A writes and commits. B, still in its old read snapshot, now tries to write:
sql
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
COMMIT;
SELECT balance AS after_a FROM accounts WHERE id = 1;
after_a
90
sql
UPDATE accounts SET balance = balance - 20 WHERE id = 1; -- error on purpose
text
Error: database is locked
B cannot upgrade, because its snapshot is older than the latest commit. Waiting would not help; B must roll back and start again.
With BEGIN IMMEDIATE, the transaction that intends to write takes the lock up front, so a second writer is turned away at its own BEGIN, before it has read anything stale:
sql
ROLLBACK;
BEGIN IMMEDIATE;
SELECT 'B holds the write lock' AS b_status;
b_status
B holds the write lock
sql
BEGIN IMMEDIATE; -- error on purpose
text
Error: database is locked
Use BEGIN IMMEDIATE for any transaction that may write, and set a busy timeout so the second one waits at BEGIN rather than failing.
sql
PRAGMA journal_mode = WAL;
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
-- second session
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
COMMIT;
SELECT balance AS after_a FROM accounts WHERE id = 1;
-- error on purpose
-- second session
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
-- second session
ROLLBACK;
BEGIN IMMEDIATE;
SELECT 'B holds the write lock' AS b_status;
-- error on purpose
BEGIN IMMEDIATE;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Deferred BEGIN takes no lock until first use
A reader that later writes can fail if another writer committed
In WAL mode a stale snapshot cannot be upgraded to a writer
BEGIN IMMEDIATE takes the write lock up front
Common mistakes
Using plain BEGIN for read-then-write transactions
Retrying the failing statement instead of the whole transaction
Follow-ups
What does BEGIN EXCLUSIVE add?
How should an app retry SQLITE_BUSY?
Tips
Explain why waiting does not help the stale snapshot
234.sql-0234Mediummid
What is a savepoint, and how would you use one to keep a batch going when one row fails?
A savepoint marks a point inside a transaction. ROLLBACK TO name undoes only the work after that point, and the outer transaction continues. In a batch import, set a savepoint before each row, roll back to it when the row fails, log the failure, and commit the good rows at the end.
Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
sql
BEGIN;
SAVEPOINT row1;
INSERT INTO accounts VALUES (3, 'Chloe', 40);
RELEASE row1;
SAVEPOINT row2;
INSERT INTO accounts VALUES (4, 'Dev', -5);
-- error on purpose
text
Error: CHECK constraint failed: balance >= 0
The second row breaks the CHECK. The program rolls back to its savepoint (shown as the next step here) and moves on:
sql
ROLLBACK TO row2;
RELEASE row2;
SAVEPOINT row3;
INSERT INTO accounts VALUES (5, 'Eli', 20);
RELEASE row3;
COMMIT;
SELECT 'committed' AS status;
status
committed
sql
SELECT id, owner, balance FROM accounts ORDER BY id;
id
owner
balance
1
Ana
100
2
Bilal
50
3
Chloe
40
5
Eli
20
Both good rows were committed, and the bad one left nothing behind. In PostgreSQL this pattern is the standard way to continue after an error, since otherwise the whole transaction is aborted. RELEASE name discards a savepoint without undoing anything.
Savepoints have a cost per use; for very large imports, validating rows first or loading into a staging table is faster.
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
-- error on purpose
BEGIN;
SAVEPOINT row1;
INSERT INTO accounts VALUES (3, 'Chloe', 40);
RELEASE row1;
SAVEPOINT row2;
INSERT INTO accounts VALUES (4, 'Dev', -5);
ROLLBACK TO row2;
RELEASE row2;
SAVEPOINT row3;
INSERT INTO accounts VALUES (5, 'Eli', 20);
RELEASE row3;
COMMIT;
SELECT 'committed' AS status;
SELECT id, owner, balance FROM accounts ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
SAVEPOINT marks a point inside a transaction
ROLLBACK TO undoes work after that point only
RELEASE removes the savepoint and keeps the work
Lets a batch skip bad rows and commit the rest
Common mistakes
Rolling back the whole batch because of one bad row
Forgetting that ROLLBACK TO keeps the transaction open
Follow-ups
How would you report which rows failed?
When is a staging table better?
Tips
Describe the per-row savepoint loop
235.sql-0235Hardsenior
How would several workers take jobs from a PostgreSQL queue table without two workers getting the same job?
Each worker selects one pending job with SELECT ... FOR UPDATE SKIP LOCKED inside a transaction, marks it as running, and commits. FOR UPDATE locks the chosen row, and SKIP LOCKED makes other workers pass over rows that are already locked instead of waiting. A partial index on pending jobs keeps the lookup fast.
Full answer
sql
CREATE TABLE jobs (id int PRIMARY KEY, status text NOT NULL, created int NOT NULL);
CREATE INDEX jobs_pending ON jobs(created) WHERE status = 'pending';
INSERT INTO jobs VALUES (1, 'pending', 1), (2, 'pending', 2), (3, 'done', 0);
SELECT id, status FROM jobs ORDER BY id;
id
status
1
pending
2
pending
3
done
One worker's claim, as a single statement with a CTE:
sql
WITH next AS (
SELECT id FROM jobs WHERE status = 'pending'
ORDER BY created LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE jobs SET status = 'running' FROM next WHERE jobs.id = next.id
RETURNING jobs.id, jobs.status;
id
status
1
running
Job 1 is claimed and returned. A second worker running the same statement at the same moment would skip job 1, because it is locked, and claim job 2 (the concurrent part is from the documentation; only one session ran here).
Details that matter in production:
Order by priority or creation time so old jobs are not starved.
Record locked_at and requeue jobs whose worker died, by resetting jobs stuck in 'running' too long.
Keep the claim transaction short; do the actual work after committing the status change.
SQLite has no FOR UPDATE; with a single writer, an UPDATE ... WHERE id = (SELECT ... LIMIT 1) RETURNING id in a BEGIN IMMEDIATE transaction gives the same effect.
Key points
FOR UPDATE locks the selected rows
SKIP LOCKED skips rows other workers hold
Claim in a short transaction, work after commit
Requeue jobs whose workers die
A partial index on pending rows keeps it fast
Common mistakes
Selecting a job without locking and marking it later
Doing long work inside the claim transaction
Follow-ups
How would you add retries with backoff?
What changes if jobs have priorities?
Tips
Mention crash recovery for claimed jobs
236.sql-0236Mediummid
Why are long-running transactions a problem, even when they only read?
An open transaction holds its locks and its snapshot. In PostgreSQL, a snapshot prevents VACUUM from removing row versions that the transaction might still see, so tables and indexes bloat. In SQLite WAL mode, an open reader stops checkpoints from resetting the WAL, so the file keeps growing. Writers queue behind held locks, and replicas may lag or cancel queries.
Full answer
Typical causes are a report that runs for an hour inside one transaction, an application that opens a transaction and then waits for a remote API, and an idle session left in "idle in transaction" state by a forgotten BEGIN.
Effects to name in an interview:
Bloat in MVCC engines, because dead row versions cannot be cleaned.
Lock waits that pile up behind the long transaction, sometimes cascading into timeouts across the application.
Growing WAL or undo logs.
On PostgreSQL replicas, conflicts that cancel queries or delay replay.
Mitigations: keep transactions to the database work only, use idle_in_transaction_session_timeout and statement_timeout in PostgreSQL, run large reports on a replica or from a snapshot export, and monitor pg_stat_activity for old xact_start values.
In SQLite, the same advice holds: end read transactions promptly so WAL checkpoints can complete.
Key points
Open transactions hold locks and snapshots
Old snapshots block cleanup and cause bloat
WAL files grow while readers stay open
Use timeouts and monitoring for idle transactions
Common mistakes
Calling external services inside a database transaction
Leaving sessions idle in transaction
Follow-ups
What does idle_in_transaction_session_timeout do?
How would you run a large consistent report without a long lock?
Tips
Mention both locks and MVCC cleanup
237.sql-0237Easyfresher
What is a view, and what are good reasons to create one?
A view is a stored, named query that behaves like a table when you select from it. It does not store data; the query runs each time. Views give a stable name to complex joins, hide columns or rows from some users, and let you change the underlying tables while keeping the interface the same.
Full answer
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
CREATE VIEW shipped_revenue AS
SELECT c.name, SUM(i.qty * i.unit_price) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.id AND o.status = 'shipped'
JOIN order_items i ON i.order_id = o.id
GROUP BY c.id, c.name;
SELECT * FROM shipped_revenue ORDER BY revenue DESC;
name
revenue
Ana
43
Chloe
42
The view hides the join and the cancelled-order filter. Every report that reads shipped_revenue uses the same definition, so the rule "cancelled orders do not count" lives in one place.
Good uses:
Naming business definitions (active customer, net revenue).
Restricting access: grant SELECT on a view that omits salary or personal columns, and not on the base table.
Keeping old column names working during a migration.
Views do not make queries faster by themselves; the engine expands the view into the outer query. Stacking views on views can produce plans that are hard to read and tune.
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
CREATE VIEW shipped_revenue AS
SELECT c.name, SUM(i.qty * i.unit_price) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.id AND o.status = 'shipped'
JOIN order_items i ON i.order_id = o.id
GROUP BY c.id, c.name;
SELECT * FROM shipped_revenue ORDER BY revenue DESC;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A view is a named, stored query
It stores no data; it runs on each use
Useful for shared definitions, security and migrations
Views do not speed up queries on their own
Common mistakes
Expecting a plain view to cache results
Building deep stacks of views that nobody can tune
Follow-ups
What is a materialized view?
Can you INSERT into a view?
Tips
Mention the single-definition benefit
238.sql-0238Mediummid
How does a materialized view differ from a regular view, and what does refreshing involve?
A materialized view stores the query's result as data, so reads are fast, but the data is only as fresh as the last REFRESH. PostgreSQL supports CREATE MATERIALIZED VIEW and REFRESH MATERIALIZED VIEW, with CONCURRENTLY to avoid blocking readers if a unique index exists. SQLite has no materialized views; a table rebuilt by a job plays the same role.
Full answer
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
CREATE MATERIALIZED VIEW mv_orders AS SELECT COUNT(*) AS shipped FROM orders WHERE status = 'shipped';
SELECT shipped FROM mv_orders;
shipped
4
A new shipped order does not appear until the refresh:
sql
INSERT INTO orders VALUES (107, 3, '2026-03-20', 'shipped');
SELECT (SELECT shipped FROM mv_orders) AS before_refresh;
REFRESH MATERIALIZED VIEW mv_orders;
SELECT shipped AS after_refresh FROM mv_orders;
after_refresh
5
The first read after the insert still shows the old total; after REFRESH the view recomputes. A plain refresh locks the view against reads while it runs. REFRESH MATERIALIZED VIEW CONCURRENTLY keeps it readable but needs a unique index on the view and takes longer.
Use materialized views for expensive aggregations read far more often than the data changes, such as dashboards refreshed every few minutes. For data that must always be current, use a regular view, a summary table maintained by triggers, or an index that makes the base query fast.
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Materialized views store results
Data is stale until REFRESH
CONCURRENTLY avoids blocking readers but needs a unique index
SQLite has no materialized views
Common mistakes
Expecting a materialized view to update automatically
Refreshing large views on every write
Follow-ups
How would you schedule refreshes?
How would you keep a summary table current with triggers instead?
Tips
Show stale then refreshed data
239.sql-0239Mediummid
Can you UPDATE or INSERT through a view?
In PostgreSQL, a simple view over one table, with no aggregates, DISTINCT or joins, is automatically updatable. SQLite views are read-only unless you add INSTEAD OF triggers that turn writes into changes on the base tables. WITH CHECK OPTION in PostgreSQL rejects writes that would make the row disappear from the view.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SQLite rejects a write to a view:
sql
CREATE VIEW eng AS SELECT id, name, salary FROM employees WHERE dept_id = 1;
UPDATE eng SET salary = salary + 1000 WHERE id = 2;
-- error on purpose
text
Error: cannot modify eng because it is a view
PostgreSQL updates the base table through a simple view:
sql
CREATE VIEW eng AS SELECT id, name, salary, dept_id FROM employees WHERE dept_id = 1;
UPDATE eng SET salary = salary + 1000 WHERE id = 2;
SELECT name, salary FROM employees WHERE id = 2;
name
salary
Ravi
96000
WITH CHECK OPTION stops changes that would move a row outside the view's filter:
sql
CREATE VIEW eng_checked AS SELECT id, name, dept_id FROM employees WHERE dept_id = 1 WITH CHECK OPTION;
UPDATE eng_checked SET dept_id = 2 WHERE id = 3;
-- error on purpose
text
Error: new row violates check option for view "eng_checked"
In SQLite, an INSTEAD OF trigger makes the view writable by defining what a write means:
sql
CREATE VIEW eng2 AS SELECT id, name, salary FROM employees WHERE dept_id = 1;
CREATE TRIGGER eng2_update INSTEAD OF UPDATE OF salary ON eng2
BEGIN
UPDATE employees SET salary = NEW.salary WHERE id = OLD.id;
END;
UPDATE eng2 SET salary = salary + 1000 WHERE id = 2;
SELECT name, salary FROM employees WHERE id = 2;
name
salary
Ravi
96000
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
-- error on purpose
CREATE VIEW eng AS SELECT id, name, salary FROM employees WHERE dept_id = 1;
UPDATE eng SET salary = salary + 1000 WHERE id = 2;
CREATE VIEW eng2 AS SELECT id, name, salary FROM employees WHERE dept_id = 1;
CREATE TRIGGER eng2_update INSTEAD OF UPDATE OF salary ON eng2
BEGIN
UPDATE employees SET salary = NEW.salary WHERE id = OLD.id;
END;
UPDATE eng2 SET salary = salary + 1000 WHERE id = 2;
SELECT name, salary FROM employees WHERE id = 2;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
PostgreSQL simple views are automatically updatable
SQLite views are read-only without INSTEAD OF triggers
WITH CHECK OPTION keeps writes inside the view's filter
Views with joins or aggregates need triggers to be writable
Common mistakes
Assuming every view can be updated
Letting updates move rows out of a filtered view silently
Follow-ups
How would you make a join view writable?
What is LOCAL versus CASCADED CHECK OPTION?
Tips
Contrast the two engines
240.sql-0240Mediummid
What is a trigger? Write one that records every salary change in an audit table.
A trigger is code the database runs automatically before or after INSERT, UPDATE or DELETE on a table. An AFTER UPDATE OF salary trigger can insert OLD.salary and NEW.salary into an audit table, so the history is captured however the change was made. Keep trigger logic small, because it runs inside every affected write.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
sql
CREATE TABLE salary_audit (emp_id INTEGER, old_salary INTEGER, new_salary INTEGER, changed_at TEXT DEFAULT CURRENT_TIMESTAMP);
CREATE TRIGGER trg_salary_audit AFTER UPDATE OF salary ON employees
WHEN OLD.salary IS NOT NEW.salary
BEGIN
INSERT INTO salary_audit (emp_id, old_salary, new_salary) VALUES (OLD.id, OLD.salary, NEW.salary);
END;
UPDATE employees SET salary = 100000 WHERE id = 2;
UPDATE employees SET salary = 120000 WHERE id = 1;
SELECT emp_id, old_salary, new_salary FROM salary_audit;
emp_id
old_salary
new_salary
2
95000
100000
The trigger fired only for Ravi's row. OLD and NEW refer to the row before and after the update. The WHEN clause skips updates that do not change the value, including Asha's, which set the salary to what it already was.
IS NOT is SQLite's NULL-safe inequality; PostgreSQL would use IS DISTINCT FROM. In PostgreSQL, a trigger calls a function written in PL/pgSQL rather than holding the statements inline.
Triggers are invisible to anyone reading the application code, so document them, and avoid business workflows (emails, external calls) inside them.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
CREATE TABLE salary_audit (emp_id INTEGER, old_salary INTEGER, new_salary INTEGER, changed_at TEXT DEFAULT CURRENT_TIMESTAMP);
CREATE TRIGGER trg_salary_audit AFTER UPDATE OF salary ON employees
WHEN OLD.salary IS NOT NEW.salary
BEGIN
INSERT INTO salary_audit (emp_id, old_salary, new_salary) VALUES (OLD.id, OLD.salary, NEW.salary);
END;
UPDATE employees SET salary = 100000 WHERE id = 2;
UPDATE employees SET salary = 120000 WHERE id = 1;
SELECT emp_id, old_salary, new_salary FROM salary_audit;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Triggers run automatically on INSERT, UPDATE or DELETE
OLD and NEW give the row before and after
WHEN limits when the trigger fires
Keep triggers small and documented
Common mistakes
Auditing with application code that some paths bypass
Putting slow or external work inside triggers
Follow-ups
How would you also record who made the change?
When would a statement-level trigger suit better than a row-level one?