← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 17 of 26

Want the full pack? Interview packs · Mock interview · Mentora

Page 17 of 26

Questions 321–340 of 501 · 0 of 20 on this page marked learned

321.sql-0321Hardsenior

Design storage for a game leaderboard that shows a player's rank among millions of players.

Store scores in a table indexed on (score DESC, player_id). Top-N pages are cheap index reads. A single player's rank is COUNT(*) of players with a higher score, which an index range count answers but still touches many entries at the top of large boards. At very large scale, keep ranks in a cache such as a sorted set, or precompute rank buckets periodically.

Full answer
sql
CREATE TABLE scores (player_id INTEGER PRIMARY KEY, score INTEGER NOT NULL);
CREATE INDEX scores_score ON scores(score DESC, player_id);
INSERT INTO scores VALUES (1, 900), (2, 750), (3, 750), (4, 500), (5, 990);
SELECT player_id, score, (SELECT COUNT(*) FROM scores s2 WHERE s2.score > s.score) + 1 AS rank
FROM scores s ORDER BY score DESC, player_id;
player_idscorerank
59901
19002
27503
37503
45005

The rank is "how many players score more, plus one", which ties naturally share. With an index on score, the count reads index entries above the player's score.

Scaling notes:

  • Top 100: index read, always fast.
  • A player near the top: small count, fast.
  • A player near the bottom of 10 million: the count touches millions of index entries, which can be slow under load.

Common answers: compute ranks periodically into a table (rank as of five minutes ago is often acceptable), use score buckets with counts per bucket to estimate rank quickly, or keep the live board in an in-memory sorted structure and treat the database as the record of truth.

Ties need a rule: equal rank, or earlier achievement wins (add achieved_at to the ordering).

sql
CREATE TABLE scores (player_id INTEGER PRIMARY KEY, score INTEGER NOT NULL);
CREATE INDEX scores_score ON scores(score DESC, player_id);
INSERT INTO scores VALUES (1, 900), (2, 750), (3, 750), (4, 500), (5, 990);
SELECT player_id, score, (SELECT COUNT(*) FROM scores s2 WHERE s2.score > s.score) + 1 AS rank
FROM scores s ORDER BY score DESC, player_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Index scores for top-N reads
  • Rank = count of higher scores + 1
  • Exact ranks for low positions get expensive
  • Periodic snapshots or buckets scale better
  • Define the tie rule

Common mistakes

  • Running a full window rank on every request
  • Ignoring ties

Follow-ups

  • How would you show the players ranked just above and below a given player?
  • How would you shard a global leaderboard?

Tips

  • Separate top-N reads from single-player rank
322.sql-0322Mediummid

Design the database for a URL shortener.

A links table with a short code as the primary key, the target URL, owner and created_at serves the redirect lookup by key. Generate codes from an id with base62 encoding or random strings checked by the unique key. Store click events separately, ideally aggregated per day, because redirects are read-heavy and click logging is write-heavy.

Full answer
text
links(code TEXT PRIMARY KEY, target_url TEXT NOT NULL, owner_id, created_at, expires_at)
clicks_daily(code, day, clicks, PRIMARY KEY (code, day))
  • The redirect is a primary key lookup; cache hot codes in memory.
  • Code generation: base62 of an auto-increment id is short and collision-free but guessable; random 7-character codes need a retry on unique violation.
  • Raw click events can go to a log or queue and be rolled up into clicks_daily with an upsert (ON CONFLICT DO UPDATE SET clicks = clicks + excluded.clicks).
  • Custom aliases share the same key space; reserve words such as 'admin'.
  • Abuse handling: a disabled flag and a check against blocked domains at creation.

The database is rarely the bottleneck for redirects if reads are cached; it is the source of truth for codes and owners.

Key points

  • Short code as primary key for fast redirects
  • Base62 ids or random codes with uniqueness retries
  • Separate, aggregated click storage
  • Cache hot codes

Common mistakes

  • Writing a row per click synchronously on the redirect path
  • Sequential codes where guessability matters

Follow-ups

  • How would you support link expiry?
  • How would you count unique visitors?

Tips

  • Separate the read path from analytics
323.sql-0323Mediummid

How would you model role-based access control (users, roles, permissions) in SQL?

Use users, roles, permissions, and two junction tables: user_roles and role_permissions. A permission check joins user to roles to permissions and tests for one permission name. Scope roles to a tenant or project when access differs per workspace, by adding that column to user_roles.

Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE roles (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE permissions (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE user_roles (user_id INTEGER, role_id INTEGER, PRIMARY KEY (user_id, role_id));
CREATE TABLE role_permissions (role_id INTEGER, permission_id INTEGER, PRIMARY KEY (role_id, permission_id));
INSERT INTO users VALUES (1, 'Ana'), (2, 'Ben');
INSERT INTO roles VALUES (1, 'viewer'), (2, 'editor');
INSERT INTO permissions VALUES (1, 'post.read'), (2, 'post.publish');
INSERT INTO user_roles VALUES (1, 1), (2, 2);
INSERT INTO role_permissions VALUES (1, 1), (2, 1), (2, 2);
SELECT u.name, EXISTS (
  SELECT 1 FROM user_roles ur JOIN role_permissions rp ON rp.role_id = ur.role_id
  JOIN permissions p ON p.id = rp.permission_id
  WHERE ur.user_id = u.id AND p.name = 'post.publish') AS can_publish
FROM users u ORDER BY u.id;
namecan_publish
Ana0
Ben1

The check is an EXISTS over two junctions. Ben is an editor, and editors can publish, so he passes; a viewer would not.

Design notes:

  • Permissions are fine-grained names (post.publish); roles bundle them.
  • user_roles(user_id, role_id, project_id) supports "editor in project A, viewer in project B".
  • Cache a user's permission set per session; recompute when roles change.
  • Audit changes to user_roles, because privilege changes matter in security reviews.

Avoid storing permissions as a comma-separated list on the user: it cannot be joined or constrained and makes "who can publish?" a scan.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE roles (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE permissions (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE user_roles (user_id INTEGER, role_id INTEGER, PRIMARY KEY (user_id, role_id));
CREATE TABLE role_permissions (role_id INTEGER, permission_id INTEGER, PRIMARY KEY (role_id, permission_id));
INSERT INTO users VALUES (1, 'Ana'), (2, 'Ben');
INSERT INTO roles VALUES (1, 'viewer'), (2, 'editor');
INSERT INTO permissions VALUES (1, 'post.read'), (2, 'post.publish');
INSERT INTO user_roles VALUES (1, 1), (2, 2);
INSERT INTO role_permissions VALUES (1, 1), (2, 1), (2, 2);
SELECT u.name, EXISTS (
  SELECT 1 FROM user_roles ur JOIN role_permissions rp ON rp.role_id = ur.role_id
  JOIN permissions p ON p.id = rp.permission_id
  WHERE ur.user_id = u.id AND p.name = 'post.publish') AS can_publish
FROM users u ORDER BY u.id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • users, roles, permissions plus two junction tables
  • Permission checks are EXISTS over the junctions
  • Scope role assignments to projects or tenants when needed
  • Audit role changes

Common mistakes

  • Hard-coding role names in application checks
  • Comma-separated permission lists

Follow-ups

  • How would you add per-object permissions?
  • How would you list everyone who can publish?

Tips

  • Show the permission check query
324.sql-0324Mediummid

How would you store inventory for products held in several warehouses, so that stock never goes negative?

Keep a stock table keyed by (warehouse_id, product_id) with an on_hand quantity and CHECK (on_hand >= 0). Change stock with atomic UPDATEs such as SET on_hand = on_hand - :n WHERE on_hand >= :n, and record every movement in a ledger table. The ledger explains the balance; the CHECK and conditional update stop overselling.

Full answer
sql
CREATE TABLE stock (warehouse_id INTEGER, product_id INTEGER, on_hand INTEGER NOT NULL CHECK (on_hand >= 0), PRIMARY KEY (warehouse_id, product_id));
INSERT INTO stock VALUES (1, 10, 5);
UPDATE stock SET on_hand = on_hand - 3 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 3;
UPDATE stock SET on_hand = on_hand - 4 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 4;
SELECT on_hand, changes() AS rows_changed_by_last FROM stock;
on_handrows_changed_by_last
20

The second reservation asked for more than remained, so the conditional UPDATE changed no rows (changes() is 0) and the application can report "out of stock". The CHECK is a second line of defence if some code path forgets the condition.

A movements ledger (stock_moves(id, warehouse_id, product_id, delta, reason, created_at)) written in the same transaction gives an audit trail and lets you rebuild balances. Reservations for carts can be a separate reserved column or table with expiry, so "available = on_hand - reserved".

sql
CREATE TABLE stock (warehouse_id INTEGER, product_id INTEGER, on_hand INTEGER NOT NULL CHECK (on_hand >= 0), PRIMARY KEY (warehouse_id, product_id));
INSERT INTO stock VALUES (1, 10, 5);
UPDATE stock SET on_hand = on_hand - 3 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 3;
UPDATE stock SET on_hand = on_hand - 4 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 4;
SELECT on_hand, changes() AS rows_changed_by_last FROM stock;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Stock per (warehouse, product) with CHECK on_hand >= 0
  • Conditional atomic UPDATEs prevent overselling
  • A movements ledger explains every change
  • Reservations reduce available stock separately

Common mistakes

  • Read-then-write stock updates in application code
  • Balances without an audit trail

Follow-ups

  • How would you allocate an order across warehouses?
  • How would cart reservations expire?

Tips

  • Show the zero-rows-changed case
325.sql-0325Mediummid

How do read replicas help scale a database, and what problems does replication lag cause?

Replicas copy changes from the primary and serve read queries, which spreads read load and adds failover options. Asynchronous replicas lag behind, so a user who just wrote data may not see it on a replica. Route read-your-own-writes requests to the primary, or wait until the replica has caught up to the write's position.

Full answer

Typical setup: one primary accepts writes; several replicas apply the primary's write-ahead log and answer SELECTs. Reports, search pages and analytics move to replicas.

Lag problems:

  • Read-your-writes: a user saves a profile and the next page, served by a replica, shows old data.
  • Monotonic reads: two requests hitting different replicas can make data appear to go backwards.
  • Long queries on a PostgreSQL replica can conflict with cleanup on the primary and get cancelled, or delay replay if configured to wait.

Mitigations:

  • Send a user's reads to the primary for a short time after they write (session stickiness).
  • Track the primary's log position after a write and read from a replica only once it has replayed past it.
  • Use synchronous replication for data that must never be lost on failover, accepting slower writes.

Replicas do not help write throughput; that needs partitioning, sharding or a lighter write path.

Key points

  • Replicas scale reads, not writes
  • Asynchronous lag breaks read-your-writes
  • Route recent writers to the primary or wait for replay
  • Synchronous replication trades latency for safety

Common mistakes

  • Sending every read to replicas without considering lag
  • Expecting replicas to increase write capacity

Follow-ups

  • When is synchronous replication worth its write latency?
  • How would you handle failover?

Tips

  • Give the read-your-writes example
326.sql-0326Hardsenior

A table of sensor readings grows by 100 million rows a month. How would you keep queries and maintenance manageable?

Partition the table by time, for example one partition per month, so queries for recent data touch only recent partitions and old data can be dropped by detaching a partition instead of running huge DELETEs. Index within partitions on (sensor_id, ts), roll up old raw data into hourly or daily aggregates, and consider a time-series extension or columnar store for analytics.

Full answer

PostgreSQL declarative partitioning:

text
CREATE TABLE readings (sensor_id int, ts timestamptz, value double precision)
  PARTITION BY RANGE (ts);
CREATE TABLE readings_2026_03 PARTITION OF readings
  FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');

Benefits:

  • Partition pruning: WHERE ts >= now() - interval '1 day' scans only the newest partition.
  • Retention: DROP TABLE readings_2025_01 is instant, unlike deleting 100 million rows.
  • Smaller indexes per partition, and maintenance (VACUUM, reindex) per partition.

Also plan:

  • Rollups (hourly averages, min, max) for dashboards, so raw data can expire sooner.
  • Batched inserts or COPY instead of row-by-row inserts.
  • Queries that always include the partition key, or pruning cannot help.

SQLite has no partitioning; at this volume it is usually the wrong engine, though per-period database files are a workable pattern for embedded use. The PostgreSQL DDL above is shown for illustration and was not run here.

Key points

  • Partition by time for pruning and cheap retention
  • Drop old partitions instead of mass DELETE
  • Roll up raw data into aggregates
  • Queries must filter on the partition key
  • Batch inserts at high volume

Common mistakes

  • Deleting old rows in one huge DELETE
  • Partitioning by a column that queries do not filter on

Follow-ups

  • How many partitions are too many?
  • When would a columnar store be better?

Tips

  • Name pruning and retention as the two wins
327.sql-0327Hardsenior

How would you change a column's type on a large, busy table without downtime?

Use expand and contract: add a new column with the new type, write to both columns from the application, backfill old rows in small batches, switch reads to the new column, then stop writing the old one and drop it. A direct ALTER COLUMN TYPE often rewrites the whole table under a lock that blocks traffic.

Full answer

Steps for changing amount from integer dollars to integer cents, or id from int to bigint:

  1. Expand: ALTER TABLE t ADD COLUMN amount_cents bigint; (fast, no rewrite, when there is no default).
  2. Dual write: deploy code that writes both columns, or add a trigger that copies values.
  3. Backfill in batches: UPDATE t SET amount_cents = amount * 100 WHERE id BETWEEN :a AND :b AND amount_cents IS NULL; with pauses, so replicas and locks keep up.
  4. Verify: compare counts and sums between the columns.
  5. Switch reads to the new column; add NOT NULL (in PostgreSQL, add a CHECK ... NOT VALID, then VALIDATE CONSTRAINT, to avoid a long lock).
  6. Contract: stop writing the old column, then drop it in a later release.

Each step is reversible until the last one. Set a lock_timeout for DDL so a blocked ALTER fails fast instead of queuing every query behind it. These are PostgreSQL practices described from experience with its locking rules; they were not run here.

Key points

  • Expand, migrate, contract
  • Add the new column without a rewrite
  • Dual write and backfill in batches
  • Validate constraints separately to shorten locks
  • Set lock_timeout for DDL

Common mistakes

  • Running ALTER COLUMN TYPE on a huge table at peak
  • One giant backfill UPDATE

Follow-ups

  • Why does a queued ALTER block reads?
  • How would you rename a column without downtime?

Tips

  • Explain why each step is reversible
328.sql-0328Mediummid

A report should list every student with their Statistics mark, showing NULL for students not taking it. It returns only two rows. Find the bug.

The filter on the right-hand table sits in WHERE, which removes the NULL-extended rows and turns the LEFT JOIN into an inner join. Move the course condition into the ON clause so it limits which enrolments match, not which students survive.

Full answer
sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

The query as written:

sql
SELECT s.name, e.marks FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE e.course_id = 30
ORDER BY s.id;
namemarks
BenNULL
Chen80

Students without a Statistics enrolment get NULL in every enrolment column. WHERE e.course_id = 30 is then NULL for them, so they are dropped. Only Ben and Chen remain, and Ben's NULL mark only appears because his enrolment row exists with no mark.

A corrected version:

sql
SELECT s.name, e.marks FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id AND e.course_id = 30
ORDER BY s.id;
namemarks
AshaNULL
BenNULL
Chen80
DaraNULL
EliNULL

With the condition in ON, every student is kept and only the Statistics enrolment is attached when it exists. The output now has five rows. Note that Ben and Asha both show NULL for different reasons: Ben has an unmarked enrolment, Asha has none. Add e.course_id to the select list when that distinction matters.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT s.name, e.marks FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE e.course_id = 30
ORDER BY s.id;

SELECT s.name, e.marks FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id AND e.course_id = 30
ORDER BY s.id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • WHERE on the right table can cancel a LEFT JOIN
  • Put right-table filters in ON
  • NULL marks can mean no row or an unmarked row

Common mistakes

  • Adding OR e.course_id IS NULL, which also keeps students with other courses wrongly
  • Switching to INNER JOIN and losing students

Follow-ups

  • How would you tell 'not enrolled' from 'enrolled, no mark'?
  • Does the same rule apply to RIGHT and FULL joins?

Tips

  • Say which rows the WHERE removed
329.sql-0329Mediummid

A pay-rise script set most employees' salaries to NULL. Explain why, and fix it.

An UPDATE without a WHERE clause touches every row, and the correlated subquery returns NULL for employees with no matching raise. Restrict the update with WHERE EXISTS (or an UPDATE ... FROM join) so only employees with a raise change.

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');
CREATE TABLE raises (emp_id INTEGER PRIMARY KEY, new_salary INTEGER);
INSERT INTO raises VALUES (4, 75000), (5, 66000);
CREATE TABLE employees_copy AS SELECT * FROM employees;

The query as written:

sql
UPDATE employees SET salary = (SELECT new_salary FROM raises WHERE raises.emp_id = employees.id);
SELECT id, name, salary FROM employees ORDER BY id;
idnamesalary
1AshaNULL
2RaviNULL
3MeiNULL
4Tom75000
5Sara66000
6DiegoNULL
7LenaNULL
8OmarNULL

The subquery is evaluated per row. For Tom and Sara it finds a raise; for everyone else it finds no row, and a scalar subquery with no row yields NULL. Every row without a raise, six in all, now holds NULL; Lena's salary was already NULL, so five real salaries were lost.

A corrected version:

sql
UPDATE employees_copy SET salary = (SELECT new_salary FROM raises WHERE raises.emp_id = employees_copy.id)
WHERE EXISTS (SELECT 1 FROM raises WHERE raises.emp_id = employees_copy.id);
SELECT id, name, salary FROM employees_copy ORDER BY id;
idnamesalary
1Asha120000
2Ravi95000
3Mei95000
4Tom75000
5Sara66000
6Diego55000
7LenaNULL
8Omar48000

The fix ran on an untouched copy of the table. Only rows with a raise are updated, and the other salaries stay as they were. SQLite 3.33+ and PostgreSQL also accept UPDATE employees SET salary = r.new_salary FROM raises r WHERE r.emp_id = employees.id, which reads more naturally. Before any bulk update, run the same logic as a SELECT and check the row count inside a transaction.

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 raises (emp_id INTEGER PRIMARY KEY, new_salary INTEGER);
INSERT INTO raises VALUES (4, 75000), (5, 66000);
CREATE TABLE employees_copy AS SELECT * FROM employees;

UPDATE employees SET salary = (SELECT new_salary FROM raises WHERE raises.emp_id = employees.id);
SELECT id, name, salary FROM employees ORDER BY id;

UPDATE employees_copy SET salary = (SELECT new_salary FROM raises WHERE raises.emp_id = employees_copy.id)
WHERE EXISTS (SELECT 1 FROM raises WHERE raises.emp_id = employees_copy.id);
SELECT id, name, salary FROM employees_copy ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • UPDATE without WHERE changes every row
  • Scalar subqueries with no match give NULL
  • Restrict with WHERE EXISTS or UPDATE ... FROM
  • Preview bulk updates as SELECTs in a transaction

Common mistakes

  • Trusting that the subquery limits which rows change
  • Running bulk updates outside a transaction

Follow-ups

  • How would you undo this if there were no backup?
  • How does UPDATE ... FROM behave when several rows match?

Tips

  • Preview row counts before updating
330.sql-0330Easyfresher

A query for March 9 orders misses an order placed that afternoon. What is wrong?

BETWEEN '2026-03-01' AND '2026-03-09' compares text, and '2026-03-09 14:30' sorts after '2026-03-09', so it falls outside the range. Use a half-open range: ts >= '2026-03-01' AND ts < '2026-03-10'.

Full answer
sql
CREATE TABLE web_orders (id INTEGER PRIMARY KEY, ts TEXT NOT NULL);
INSERT INTO web_orders VALUES (1, '2026-03-01 09:00'), (2, '2026-03-05 12:00'), (3, '2026-03-09 14:30'), (4, '2026-03-10 08:00');

The query as written:

sql
SELECT id, ts FROM web_orders WHERE ts BETWEEN '2026-03-01' AND '2026-03-09' ORDER BY id;
idts
12026-03-01 09:00
22026-03-05 12:00

Order 3 is missing. The upper bound '2026-03-09' is the very start of that day as text, and any time on that day compares greater than it. The same problem appears in PostgreSQL with timestamp columns, where the date literal means midnight.

A corrected version:

sql
SELECT id, ts FROM web_orders WHERE ts >= '2026-03-01' AND ts < '2026-03-10' ORDER BY id;
idts
12026-03-01 09:00
22026-03-05 12:00
32026-03-09 14:30

The half-open range includes all of March 9 and nothing from March 10, whatever the time precision. It also lets an index on ts be used, unlike wrapping the column in date(ts).

sql
CREATE TABLE web_orders (id INTEGER PRIMARY KEY, ts TEXT NOT NULL);
INSERT INTO web_orders VALUES (1, '2026-03-01 09:00'), (2, '2026-03-05 12:00'), (3, '2026-03-09 14:30'), (4, '2026-03-10 08:00');

SELECT id, ts FROM web_orders WHERE ts BETWEEN '2026-03-01' AND '2026-03-09' ORDER BY id;

SELECT id, ts FROM web_orders WHERE ts >= '2026-03-01' AND ts < '2026-03-10' ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • BETWEEN is inclusive but a date bound means midnight
  • Use >= start AND < next day
  • Half-open ranges are index friendly

Common mistakes

  • Writing '2026-03-09 23:59:59', which misses fractional seconds
  • Wrapping the column in date() and losing index use

Follow-ups

  • How would you query a whole month?
  • What changes if timestamps are stored in UTC?

Tips

  • State the half-open rule
331.sql-0331Easyfresher

The share of shipped orders shows 0 instead of about 67 percent. Fix the calculation.

Both operands are integers, so SQLite (and PostgreSQL) perform integer division: 4 / 6 is 0, and 0 * 100 is still 0. Multiply by 100.0 first, or cast one side to a real or numeric, and round the result.

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);

The query as written:

sql
SELECT SUM(status = 'shipped') / COUNT(*) * 100 AS pct_shipped FROM orders;
pct_shipped
0

SUM(status = 'shipped') is 4 and COUNT(*) is 6. Integer division truncates 4 / 6 to 0 before the multiplication happens, so the order of operations makes things worse.

A corrected version:

sql
SELECT ROUND(100.0 * SUM(status = 'shipped') / COUNT(*), 1) AS pct_shipped FROM orders;
pct_shipped
66.7

Starting with 100.0 makes the whole expression real arithmetic, giving 66.7. In PostgreSQL, status = 'shipped' is a boolean that SUM rejects, so write COUNT(*) FILTER (WHERE status = 'shipped') or SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) there. The PostgreSQL run with FILTER returns the same value:

sql
SELECT ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'shipped') / COUNT(*), 1) AS pct_shipped FROM orders;
pct_shipped
66.7
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);

SELECT SUM(status = 'shipped') / COUNT(*) * 100 AS pct_shipped FROM orders;

SELECT ROUND(100.0 * SUM(status = 'shipped') / COUNT(*), 1) AS pct_shipped FROM orders;

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

Key points

  • Integer / integer truncates
  • Put the 100.0 first
  • PostgreSQL needs FILTER or CASE instead of summing booleans

Common mistakes

  • Multiplying by 100 after the division
  • Casting the final result, which is already 0

Follow-ups

  • How would you show the percentage per customer?
  • Why might NUMERIC be preferred over float here?

Tips

  • Show where truncation happens
332.sql-0332Mediummid

A page-view counter keeps losing the first_seen date. Find the cause.

INSERT OR REPLACE deletes the conflicting row and inserts a new one, so columns not listed in the insert reset to their defaults (NULL here) and the count restarts. Use INSERT ... ON CONFLICT (page) DO UPDATE SET views = views + 1, which updates the existing row in place.

Full answer
sql
CREATE TABLE pv_bad (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
CREATE TABLE pv_good (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
INSERT INTO pv_bad VALUES ('home', 5, '2026-01-01');
INSERT INTO pv_good VALUES ('home', 5, '2026-01-01');

The query as written:

sql
INSERT OR REPLACE INTO pv_bad (page, views) VALUES ('home', 1);
SELECT * FROM pv_bad;
pageviewsfirst_seen
home1NULL

REPLACE resolves the primary key conflict by removing the old row. The new row has views = 1 and first_seen = NULL, so both history and the running count are gone. It also fires delete triggers and, with foreign keys on, can cascade deletes.

A corrected version:

sql
INSERT INTO pv_good (page, views, first_seen) VALUES ('home', 1, '2026-03-09')
ON CONFLICT (page) DO UPDATE SET views = pv_good.views + 1;
SELECT * FROM pv_good;
pageviewsfirst_seen
home62026-01-01

The upsert keeps the row, increments views to 6 and leaves first_seen alone, because the SET list names only views. The same ON CONFLICT syntax works in PostgreSQL, where excluded.col refers to the value that was proposed for insertion.

sql
CREATE TABLE pv_bad (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
CREATE TABLE pv_good (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
INSERT INTO pv_bad VALUES ('home', 5, '2026-01-01');
INSERT INTO pv_good VALUES ('home', 5, '2026-01-01');

INSERT OR REPLACE INTO pv_bad (page, views) VALUES ('home', 1);
SELECT * FROM pv_bad;

INSERT INTO pv_good (page, views, first_seen) VALUES ('home', 1, '2026-03-09')
ON CONFLICT (page) DO UPDATE SET views = pv_good.views + 1;
SELECT * FROM pv_good;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • REPLACE is delete plus insert
  • Unlisted columns reset under REPLACE
  • ON CONFLICT DO UPDATE changes the row in place
  • excluded refers to the proposed row

Common mistakes

  • Using REPLACE as a generic upsert
  • Forgetting that REPLACE can cascade deletes

Follow-ups

  • How would you insert many rows and add their counts?
  • How does MySQL's ON DUPLICATE KEY UPDATE compare?

Tips

  • Name delete-then-insert as the cause
333.sql-0333Hardsenior

Page 2 of an employee list sorted by salary skips an employee. Find the bug in the keyset query.

Page 1 ended at salary 95000, and the next page asks for salary < 95000, which skips any other employee who also earns 95000. Keyset pagination needs a unique tiebreaker: continue after (salary, id) with salary < 95000 OR (salary = 95000 AND id > 2), matching ORDER BY salary DESC, id.

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');

The query as written:

sql
SELECT id, name, salary FROM employees
WHERE salary < 95000
ORDER BY salary DESC, id LIMIT 2;
idnamesalary
4Tom70000
5Sara62000

Page 1 (ORDER BY salary DESC, id LIMIT 2) returned Asha and Ravi, so the last row seen was (95000, 2). Mei also earns 95000 with id 3, and the strict salary < 95000 condition jumps straight to Tom and Sara. Mei never appears on any page.

A corrected version:

sql
SELECT id, name, salary FROM employees
WHERE salary < 95000 OR (salary = 95000 AND id > 2)
ORDER BY salary DESC, id LIMIT 2;
idnamesalary
3Mei95000
4Tom70000

Including the tiebreaker in the condition resumes exactly after the last row, so Mei comes first, then Tom. An index on (salary DESC, id) supports the query. Row-value syntax cannot express mixed directions here, because salary is descending and id is ascending, so the expanded OR form is needed.

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');

SELECT id, name, salary FROM employees
WHERE salary < 95000
ORDER BY salary DESC, id LIMIT 2;

SELECT id, name, salary FROM employees
WHERE salary < 95000 OR (salary = 95000 AND id > 2)
ORDER BY salary DESC, id LIMIT 2;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Keyset cursors need a unique tiebreaker
  • The WHERE must match the ORDER BY columns and directions
  • Strict comparison on a non-unique column skips ties

Common mistakes

  • Using only the sort column as the cursor
  • Row values with mixed sort directions

Follow-ups

  • How would you page backwards?
  • Which index serves this query?

Tips

  • Trace the last row of page 1
334.sql-0334Easyfresher

A grading query gives every passing student a C. What is wrong with the CASE?

CASE checks its WHEN branches in order and returns the first true one. Since marks >= 50 is listed first, it is true for every passing mark and the A and B branches are never reached. List the highest thresholds first.

Full answer
sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

The query as written:

sql
SELECT student_id, course_id, marks,
  CASE WHEN marks >= 50 THEN 'C' WHEN marks >= 70 THEN 'B' WHEN marks >= 85 THEN 'A' ELSE 'F' END AS grade
FROM enrolments ORDER BY student_id, course_id;
student_idcourse_idmarksgrade
11088C
12092C
21075C
230NULLF
31064C
32071C
33080C
52055C

A mark of 92 satisfies marks >= 50, so the CASE stops there and returns C. The NULL mark falls through to ELSE and shows F, which is a second bug: an unmarked enrolment is not a failure.

A corrected version:

sql
SELECT student_id, course_id, marks,
  CASE WHEN marks IS NULL THEN 'pending' WHEN marks >= 85 THEN 'A' WHEN marks >= 70 THEN 'B' WHEN marks >= 50 THEN 'C' ELSE 'F' END AS grade
FROM enrolments ORDER BY student_id, course_id;
student_idcourse_idmarksgrade
11088A
12092A
21075B
230NULLpending
31064C
32071B
33080B
52055C

Ordering thresholds from high to low makes each branch reachable, and an explicit NULL branch labels the missing mark. Marks of 88 and 92 now show A, 75, 71 and 80 show B, 64 and 55 show C.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT student_id, course_id, marks,
  CASE WHEN marks >= 50 THEN 'C' WHEN marks >= 70 THEN 'B' WHEN marks >= 85 THEN 'A' ELSE 'F' END AS grade
FROM enrolments ORDER BY student_id, course_id;

SELECT student_id, course_id, marks,
  CASE WHEN marks IS NULL THEN 'pending' WHEN marks >= 85 THEN 'A' WHEN marks >= 70 THEN 'B' WHEN marks >= 50 THEN 'C' ELSE 'F' END AS grade
FROM enrolments ORDER BY student_id, course_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CASE returns the first true branch
  • Order range checks from most to least specific
  • Handle NULL explicitly before ELSE

Common mistakes

  • Overlapping ranges in the wrong order
  • Letting NULL fall into ELSE

Follow-ups

  • How would you store grade thresholds in a table instead?
  • How would you count students per grade?

Tips

  • Mention the NULL branch too
335.sql-0335Mediummid

Average order value per customer works on SQLite but fails on PostgreSQL. Explain and fix it.

When a customer has no shipped orders the divisor is 0. SQLite returns NULL for division by zero, while PostgreSQL raises an error. Wrap the divisor in NULLIF(x, 0) so both engines return NULL, then COALESCE if a display value is needed.

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);

The query as written:

sql
SELECT c.name, SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
  COUNT(o.id) / SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS orders_per_shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
nameshippedorders_per_shipped
Ana21
Bilal0NULL
Chloe11
Dev0NULL

Bilal and Dev have no shipped orders, so the divisor is 0 for them. SQLite quietly returns NULL, which hides the problem during development. The PostgreSQL run of the same query stops with an error:

sql
SELECT c.name, COUNT(o.id) / SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS orders_per_shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
-- error on purpose
text
Error: division by zero

A corrected version:

sql
SELECT c.name, SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
  COUNT(o.id) / NULLIF(SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END), 0) AS orders_per_shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
nameshippedorders_per_shipped
Ana21
Bilal0NULL
Chloe11
Dev0NULL

NULLIF(divisor, 0) turns a zero divisor into NULL, and dividing by NULL gives NULL on every engine. The PostgreSQL run of the fixed query succeeds:

sql
SELECT c.name, COUNT(o.id) / NULLIF(SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END), 0) AS orders_per_shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
nameorders_per_shipped
Ana1
BilalNULL
Chloe1
DevNULL

Testing on the production engine, not only SQLite, catches this class of bug.

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);

SELECT c.name, SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
  COUNT(o.id) / SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS orders_per_shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;

SELECT c.name, SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
  COUNT(o.id) / NULLIF(SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END), 0) AS orders_per_shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.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 returns NULL on division by zero
  • PostgreSQL raises division by zero
  • NULLIF(divisor, 0) makes both return NULL
  • Test on the production engine

Common mistakes

  • Assuming SQLite behaviour matches the server
  • Filtering out zero rows and losing customers from the report

Follow-ups

  • How would you show 0 instead of NULL?
  • Where else do SQLite and PostgreSQL differ on errors?

Tips

  • Contrast the two engines
336.sql-0336Easyfresher

Customer balances show NULL for customers who have never paid. Fix the query.

SUM over no rows returns NULL, and any arithmetic with NULL is NULL, so invoice minus payments becomes NULL for customers without payments. Wrap each SUM in COALESCE(..., 0).

Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, invoiced INTEGER);
CREATE TABLE payments (account_id INTEGER, amount INTEGER);
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
INSERT INTO payments VALUES (1, 30), (1, 20);

The query as written:

sql
SELECT name, invoiced - (SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id) AS balance
FROM accounts a ORDER BY id;
namebalance
Ana50
BilalNULL

Ana's payments sum to 50, so her balance is 50. Bilal has no payments; the subquery's SUM is NULL and the subtraction propagates it, which a report reads as 'unknown' rather than 'owes 50'.

A corrected version:

sql
SELECT name, invoiced - COALESCE((SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id), 0) AS balance
FROM accounts a ORDER BY id;
namebalance
Ana50
Bilal50

COALESCE replaces the missing total with 0, so Bilal's balance is 50 as well. Totals computed over joins have the same problem and the same fix; apply it to each side that may have no rows.

sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, invoiced INTEGER);
CREATE TABLE payments (account_id INTEGER, amount INTEGER);
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
INSERT INTO payments VALUES (1, 30), (1, 20);

SELECT name, invoiced - (SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id) AS balance
FROM accounts a ORDER BY id;

SELECT name, invoiced - COALESCE((SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id), 0) AS balance
FROM accounts a ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SUM of no rows is NULL
  • NULL in arithmetic gives NULL
  • COALESCE the aggregate, not the final expression only

Common mistakes

  • Using COUNT logic to assume SUM returns 0
  • COALESCE on the whole result, which hides real NULL invoices

Follow-ups

  • When is NULL the correct answer here?
  • How would you compute balances with a join instead?

Tips

  • Say why SUM returns NULL
337.sql-0337Mediummid

After joining a rates table, revenue for Spain doubled. Find the cause.

The rates table has two rows for Spain (an old and a new rate), so each Spanish order line matches twice and its revenue is counted twice. Join to exactly one row per key, for example by filtering to the current rate or enforcing a unique key on the lookup.

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);
CREATE TABLE vat_rates (country TEXT, rate REAL, valid_from TEXT);
INSERT INTO vat_rates VALUES ('Spain', 0.18, '2020-01-01'), ('Spain', 0.21, '2024-01-01'), ('France', 0.20, '2020-01-01');

The query as written:

sql
SELECT c.country, SUM(oi.qty * oi.unit_price) AS revenue
FROM customers c JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
JOIN vat_rates v ON v.country = c.country
GROUP BY c.country ORDER BY c.country;
countryrevenue
France42
Spain86

Ana's real revenue is 24 + 51 + 30 = 43, but each line matched both Spanish rates, so 86 is reported. France has one rate and is correct at 42. Bilal (UAE) disappears entirely because there is no rate row for UAE, a second bug caused by the inner join.

A corrected version:

sql
SELECT c.country, SUM(oi.qty * oi.unit_price) AS revenue
FROM customers c JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
LEFT JOIN vat_rates v ON v.country = c.country
  AND v.valid_from = (SELECT MAX(valid_from) FROM vat_rates v2 WHERE v2.country = c.country)
GROUP BY c.country ORDER BY c.country;
countryrevenue
France42
Spain43
UAE35

Restricting the join to the latest rate gives one match per row, and the LEFT JOIN keeps countries without a rate. A quick check for fan-out is to compare COUNT(*) before and after adding a join. Lookups should have a unique key on the join columns, here (country, valid_from).

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 TABLE vat_rates (country TEXT, rate REAL, valid_from TEXT);
INSERT INTO vat_rates VALUES ('Spain', 0.18, '2020-01-01'), ('Spain', 0.21, '2024-01-01'), ('France', 0.20, '2020-01-01');

SELECT c.country, SUM(oi.qty * oi.unit_price) AS revenue
FROM customers c JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
JOIN vat_rates v ON v.country = c.country
GROUP BY c.country ORDER BY c.country;

SELECT c.country, SUM(oi.qty * oi.unit_price) AS revenue
FROM customers c JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
LEFT JOIN vat_rates v ON v.country = c.country
  AND v.valid_from = (SELECT MAX(valid_from) FROM vat_rates v2 WHERE v2.country = c.country)
GROUP BY c.country ORDER BY c.country;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A non-unique lookup multiplies rows
  • Compare row counts before and after a join
  • Pick exactly one lookup row per key
  • Inner joins to lookups drop unmatched rows

Common mistakes

  • Hiding duplicates with DISTINCT inside SUM
  • Assuming lookup tables have one row per key

Follow-ups

  • How would you apply the rate valid at each order's date?
  • How would you enforce one current rate per country?

Tips

  • Check the join key's uniqueness
338.sql-0338Easyfresher

A query for shipped or pending orders of customer 2 also returns other customers' orders. What is wrong?

AND binds tighter than OR, so status = 'shipped' OR status = 'pending' AND customer_id = 2 means shipped orders of anyone, plus pending orders of customer 2. Add parentheses around the OR, or use status IN ('shipped', 'pending').

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);

The query as written:

sql
SELECT id, customer_id, status FROM orders
WHERE status = 'shipped' OR status = 'pending' AND customer_id = 2
ORDER BY id;
idcustomer_idstatus
1011shipped
1021shipped
1043shipped
1052pending
106NULLshipped

The query returns every shipped order (101, 102, 104 and 106, which belong to other customers or none) plus order 105. The intended filter on customer 2 only applied to the pending branch.

A corrected version:

sql
SELECT id, customer_id, status FROM orders
WHERE status IN ('shipped', 'pending') AND customer_id = 2
ORDER BY id;
idcustomer_idstatus
1052pending

Now only order 105 qualifies, since Bilal's other order is cancelled. IN reads clearly and avoids the precedence trap; when OR is needed, wrap it in parentheses. The same precedence applies in every SQL engine.

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);

SELECT id, customer_id, status FROM orders
WHERE status = 'shipped' OR status = 'pending' AND customer_id = 2
ORDER BY id;

SELECT id, customer_id, status FROM orders
WHERE status IN ('shipped', 'pending') AND customer_id = 2
ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • AND is evaluated before OR
  • Parenthesise OR groups
  • IN lists avoid the trap

Common mistakes

  • Relying on left-to-right reading
  • Testing only with data where the bug is invisible

Follow-ups

  • How does NOT interact with AND and OR?
  • How would you write this with a customer list?

Tips

  • Rewrite the WHERE with parentheses
339.sql-0339Hardsenior

A filter on a text column of quantities returns 9 as greater than 10. Explain the SQLite behaviour and fix it.

The column has TEXT affinity, so SQLite applies text affinity to the numeric literal and compares strings: '9' > '10' because '9' sorts after '1'. Cast the column with CAST(qty AS INTEGER), or better, store numbers in an INTEGER column.

Full answer
sql
CREATE TABLE imports (id INTEGER PRIMARY KEY, qty TEXT);
INSERT INTO imports VALUES (1, '9'), (2, '10'), (3, '25');

The query as written:

sql
SELECT id, qty FROM imports WHERE qty > 10 ORDER BY id;
idqty
19
325

The result contains id 1 ('9') and id 3 ('25'), so id 1 ('9') appears even though 9 is less than 10. The comparison ran as text, where '9' > '10'. When one side is a TEXT-affinity column and the other a literal, SQLite converts the literal to text before comparing.

A corrected version:

sql
SELECT id, qty FROM imports WHERE CAST(qty AS INTEGER) > 10 ORDER BY id;
idqty
325

With the cast, only 25 is greater than 10. The cast blocks index use on qty, so the lasting fix is a migration to an INTEGER column, with bad values rejected on import. PostgreSQL refuses to compare text with an integer without a cast, which surfaces the problem at once (described here, not run).

sql
CREATE TABLE imports (id INTEGER PRIMARY KEY, qty TEXT);
INSERT INTO imports VALUES (1, '9'), (2, '10'), (3, '25');

SELECT id, qty FROM imports WHERE qty > 10 ORDER BY id;

SELECT id, qty FROM imports WHERE CAST(qty AS INTEGER) > 10 ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • TEXT affinity makes literal comparisons textual
  • Text order: '9' > '10'
  • CAST fixes the query; the right column type fixes the data
  • PostgreSQL requires explicit casts

Common mistakes

  • Storing numbers as text from CSV imports
  • Assuming SQLite compares the way the data looks

Follow-ups

  • What are SQLite's five affinities?
  • How would STRICT tables prevent this?

Tips

  • Name the affinity rule
340.sql-0340Easyfresher

A dashboard says 5 customers placed orders, but the shop has only 3 who did. Fix the count.

COUNT(customer_id) counts non-NULL values, one per order, not distinct customers. Use COUNT(DISTINCT customer_id) to count each customer once; it also skips the order with no customer.

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);

The query as written:

sql
SELECT COUNT(customer_id) AS customers_with_orders FROM orders;
customers_with_orders
5

There are six orders. COUNT skips the one with a NULL customer and counts the other five, so customers with two orders (Ana and Bilal) are counted twice.

A corrected version:

sql
SELECT COUNT(DISTINCT customer_id) AS customers_with_orders FROM orders;
customers_with_orders
3

DISTINCT collapses repeat customers, giving 3: Ana, Bilal and Chloe. If cancelled orders should not count, add WHERE status <> 'cancelled' before counting. Labels on dashboards should say exactly what is counted.

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);

SELECT COUNT(customer_id) AS customers_with_orders FROM orders;

SELECT COUNT(DISTINCT customer_id) AS customers_with_orders FROM orders;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • COUNT(col) counts non-NULL rows
  • COUNT(DISTINCT col) counts unique values
  • Decide whether cancelled orders count

Common mistakes

  • Using COUNT(*) for 'how many customers'
  • Counting distinct values after a fan-out join without noticing

Follow-ups

  • How would you count customers per month?
  • How expensive is COUNT(DISTINCT) on large tables?

Tips

  • Say what each COUNT counts