← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 19 of 26

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

Page 19 of 26

Questions 361–380 of 501 · 0 of 20 on this page marked learned

361.sql-0361Mediummid

An index on email exists, yet a lookup by email still scans the whole table. Give likely reasons.

The predicate probably does not match the index: wrapping the column in a function (lower(email)), comparing with a different type that forces a cast on the column, using a leading-wildcard LIKE, or a collation mismatch. Rewrite the predicate to compare the bare column, or create an expression index that matches it.

Full answer

Typical mismatches:

  • Function on the column: WHERE lower(email) = 'a@x.com' cannot use an index on email. Create an index on lower(email) or store emails normalised.
  • Implicit cast: comparing a text column with a number, or a varchar with a parameter typed differently by a driver, may cast the column side.
  • Leading wildcard: LIKE '%@x.com' cannot use a B-tree; a trigram index (PostgreSQL pg_trgm) can.
  • LIKE prefix in PostgreSQL with a non-C collation needs a text_pattern_ops index.
  • In SQLite, LIKE is case-insensitive by default and only uses an index under specific collation settings.
  • Low selectivity or a tiny table: the planner may prefer a scan legitimately.

Use EXPLAIN to see the chosen plan and test the rewritten predicate; the fix is whichever form lets the bare indexed expression appear on one side of the comparison.

Key points

  • Functions on the column block plain indexes
  • Expression indexes match function predicates
  • Implicit casts can disable index use
  • Leading wildcards need trigram indexes
  • Small tables may scan legitimately

Common mistakes

  • Adding a second identical index
  • Ignoring driver parameter types

Follow-ups

  • How would you enforce case-insensitive unique emails?
  • What is a sargable predicate?

Tips

  • Check the predicate against the index definition
362.sql-0362Mediummid

Insert throughput on a busy table dropped after the team added many indexes. How would you decide which to keep?

Every index must be updated on each insert and on updates of its columns, so extra indexes slow writes and use memory. Check index usage statistics, drop unused or duplicate indexes, merge overlapping ones into a composite index, and keep only those that serve real queries.

Full answer

Evidence to gather:

  • Usage counts: PostgreSQL's pg_stat_user_indexes.idx_scan shows indexes that are never used since the last stats reset (check replicas too, since reports may run there).
  • Duplicates: an index on (a) is redundant when (a, b) exists, for most queries.
  • Size: large indexes compete for cache with the table itself.

Decisions:

  • Drop unused and redundant indexes, ideally with DROP INDEX CONCURRENTLY.
  • Replace several single-column indexes with one composite index matching the main filter and sort.
  • Use partial indexes for queries on a small subset (WHERE status = 'pending').
  • Keep indexes that enforce uniqueness, even if rarely scanned.

Measure insert time before and after on a copy of production data. Bulk loads can drop and recreate secondary indexes around the load.

Key points

  • Each index costs writes and memory
  • Usage statistics show unused indexes
  • Composite indexes can replace several singles
  • Partial indexes target subsets
  • Keep uniqueness indexes

Common mistakes

  • Indexing every column 'just in case'
  • Dropping a unique index because it shows few scans

Follow-ups

  • Why might an index be used only on a replica?
  • How do partial indexes save space?

Tips

  • Ground the choice in usage data
363.sql-0363Mediummid

A small web app on SQLite returns 'database is locked' errors under concurrent requests. How would you fix it?

SQLite allows one writer at a time, and in the default rollback journal mode writers also block readers. Enable WAL mode so readers and the writer do not block each other, set a busy timeout so writers wait briefly instead of failing, and keep write transactions short. If write concurrency is truly high, move to a client-server database.

Full answer

Checklist:

  • PRAGMA journal_mode = WAL; once per database file. Readers then see a consistent snapshot while one writer appends to the WAL.
  • PRAGMA busy_timeout = 5000; (or the driver's timeout setting) so a second writer waits up to five seconds for the lock.
  • Short write transactions: do not hold a transaction open across network calls or template rendering.
  • Use BEGIN IMMEDIATE for transactions that will write, so they take the write lock at the start instead of failing on upgrade from a read lock mid-transaction.
  • One connection per thread or request, not a shared connection used concurrently.

Other items in this bank show the busy error with timeout=0 in runs on SQLite 3.46.1. SQLite handles many web apps well, but sustained parallel writes or several servers sharing the file call for PostgreSQL or MySQL.

Key points

  • SQLite has one writer at a time
  • WAL lets readers and the writer proceed together
  • busy_timeout makes writers wait
  • BEGIN IMMEDIATE avoids upgrade failures
  • High write concurrency needs a server database

Common mistakes

  • Retrying in a tight loop without a timeout
  • Sharing one connection across threads

Follow-ups

  • What does a WAL checkpoint do?
  • Can SQLite work on a network file system?

Tips

  • Mention WAL and busy timeout together
364.sql-0364Hardsenior

A nightly report that checks 'at least one doctor is on call' let both doctors go off call at the same time. Which isolation problem is this, and how do you prevent it?

This is write skew: two transactions each read that two doctors are on call, each updates a different row to go off call, and neither sees the other's change, so the rule breaks. Snapshot isolation (PostgreSQL REPEATABLE READ) allows it. Use SERIALIZABLE, which aborts one transaction, or lock the rows read with SELECT ... FOR UPDATE.

Full answer

Timeline under snapshot isolation:

  1. T1 reads: on-call count = 2. T2 reads: on-call count = 2.
  2. T1 sets Alice off call. T2 sets Bob off call. Different rows, so no write conflict.
  3. Both commit. On-call count is now 0.

Prevention:

  • SERIALIZABLE in PostgreSQL detects the dangerous read-write dependency and fails one transaction with a serialization error; the application retries it.
  • Explicit locking: SELECT ... FROM doctors WHERE shift_id = :s AND on_call FOR UPDATE locks both rows, so T2 waits for T1 and then sees the new count.
  • Materialise the constraint: keep an on-call count row per shift and update it, turning the hidden conflict into a write conflict on one row.

SQLite serialises writers entirely, so this anomaly does not arise there in the same way. The PostgreSQL behaviour is described here, not run.

Key points

  • Write skew: disjoint writes based on a shared read
  • Snapshot isolation allows it
  • SERIALIZABLE detects it and aborts one transaction
  • FOR UPDATE on the read set also prevents it
  • Retry serialization failures

Common mistakes

  • Assuming REPEATABLE READ prevents all anomalies
  • Not retrying serialization errors

Follow-ups

  • How does write skew differ from a lost update?
  • What does SERIALIZABLE cost in throughput?

Tips

  • Walk through the timeline
365.sql-0365Mediummid

Deleting 50 million old rows in one statement caused replica lag and a full disk. How should it be done?

A single huge DELETE holds locks for a long time, writes a burst of log that replicas must replay, and leaves dead rows until vacuum. Delete in batches of a few thousand rows by key range with pauses, or, better, partition by time and drop old partitions. For a full purge, copy the rows to keep into a new table and swap.

Full answer

Batched delete pattern:

text
DELETE FROM events WHERE id IN (
  SELECT id FROM events WHERE created_at < '2025-01-01' ORDER BY id LIMIT 5000);

Repeat until no rows are affected, committing each batch and sleeping briefly. Each batch is a short transaction, replicas keep up, and vacuum can reclaim space as the job progresses.

Better long-term options:

  • Time partitioning, where retention becomes DROP TABLE events_2024_12, an instant metadata change.
  • Keep-and-swap: when most rows go, CREATE TABLE events_new AS SELECT ... WHERE created_at >= ..., add indexes, then rename in a short transaction.

Monitor replica lag and disk during the job, and run it off-peak.

Key points

  • Huge deletes cause long locks and log bursts
  • Batch by key with commits
  • Partitions make retention instant
  • Keep-and-swap when most rows go
  • Watch replica lag during the job

Common mistakes

  • One DELETE for millions of rows
  • Batches by OFFSET, which slow down as they go

Follow-ups

  • Why order the batch by primary key?
  • How would you throttle the job automatically?

Tips

  • Prefer partitions for recurring retention
366.sql-0366Mediummid

A team stores most product attributes in a single JSON column. When is that a good idea, and when does it hurt?

JSON columns suit sparse, varying attributes that are read as a whole, such as category-specific specifications. They hurt for fields that are filtered, joined, aggregated or constrained, because types, foreign keys and NOT NULL cannot be enforced inside the document and indexing is more limited. Keep core fields as columns and the long tail in JSON.

Full answer

Good fits:

  • Attributes that differ by product type (a laptop's RAM, a shirt's fabric).
  • Payloads from external systems stored for reference.
  • Settings read and written as a unit.

Problems when overused:

  • No column types: '12' and 12 both slip in; validation moves to the application.
  • No foreign keys or NOT NULL inside the document.
  • Queries become verbose (attrs->>'brand') and planners have poorer statistics on JSON paths.
  • Updating one key rewrites the whole value.

PostgreSQL jsonb with a GIN index supports containment queries (attrs @> '{"brand":"Acme"}'), and expression indexes serve specific paths. SQLite stores JSON as text and offers json_extract with expression indexes. A rule of thumb: once a key appears in WHERE, ORDER BY or a report, promote it to a real column.

Key points

  • JSON suits sparse, varying attributes
  • Core, filtered fields belong in columns
  • Constraints do not reach inside JSON
  • GIN and expression indexes help selected queries
  • Promote frequently queried keys

Common mistakes

  • Putting price and stock inside JSON
  • Using JSON to avoid schema design

Follow-ups

  • How would you validate JSON structure in the database?
  • How does EAV compare with JSON columns?

Tips

  • Give the promote-to-column rule
367.sql-0367Mediummid

Should uploaded files such as images and PDFs be stored in the database?

Usually not: store the file in object storage and keep a row with its key, size, type, checksum and owner in the database. Large blobs inflate backups, replication and memory use, and object stores serve files more cheaply. Small files that must be transactionally consistent with other data, such as tiny thumbnails or signatures, can live in the database.

Full answer

Typical design:

text
files(id PK, owner_id FK, storage_key UNIQUE, content_type, size_bytes,
      sha256, created_at, deleted_at)

The application uploads the object (often directly from the client with a signed URL), then records the row. Deleting marks the row and a job removes the object.

Why not blobs in tables:

  • Backups and restores grow with every upload.
  • Replicas copy all of it.
  • Reading a large blob through the database ties up a connection.

Consistency gaps (a row without its object, or an orphaned object) are handled by recording a pending state before upload and a periodic reconciliation job. For SQLite-based local apps, storing small blobs inline is reasonable, since SQLite reads small blobs efficiently.

Key points

  • Store files in object storage
  • Keep metadata and the key in the database
  • Blobs bloat backups and replicas
  • Reconcile rows and objects periodically

Common mistakes

  • Storing full file paths that break when buckets move
  • Deleting rows without deleting objects

Follow-ups

  • How would you serve private files securely?
  • How would you deduplicate identical uploads?

Tips

  • Describe the metadata row
368.sql-0368Mediummid

Design tables to store prices and payments in several currencies.

Store each amount with its currency code, as an integer of minor units or a NUMERIC, never a float. Record exchange rates in a dated table and, for each transaction, store the rate used and the converted amount in the reporting currency at that time. Remember that currencies differ in minor units, such as 0 for JPY and 3 for some others.

Full answer
text
currencies(code CHAR(3) PK, minor_units)           -- 'INR', 2; 'JPY', 0
fx_rates(base, quote, rate NUMERIC(18,8), as_of DATE, PRIMARY KEY (base, quote, as_of))
payments(id, amount_minor BIGINT, currency CHAR(3) FK, fx_rate_used NUMERIC(18,8),
         amount_reporting_minor BIGINT, paid_at)

Rules:

  • Never add amounts across currencies without converting.
  • Freeze the rate used at transaction time; recalculating with today's rate changes history.
  • Round once, with a documented rule, when converting.
  • Display formatting (symbols, separators) belongs to the presentation layer.

Floats represent many decimal fractions inexactly (0.1 + 0.2 is not 0.3), which is why integer minor units or NUMERIC are used; another item in this bank shows that float result.

Key points

  • Store amount and currency together
  • Integer minor units or NUMERIC, never float
  • Dated exchange-rate table
  • Freeze the rate used per transaction
  • Minor units vary by currency

Common mistakes

  • Summing amounts with different currencies
  • Converting historical data with current rates

Follow-ups

  • How would you report revenue in one currency?
  • Where does rounding happen?

Tips

  • Mention minor units per currency
369.sql-0369Hardsenior

How would you store recurring calendar events, such as a meeting every Tuesday?

Store the series once with a recurrence rule (for example an RRULE string), the start time in the organiser's time zone and an optional end, plus an exceptions table for moved or cancelled occurrences. Expand occurrences for the requested date range in the application or a function, and optionally materialise the next few months for fast queries.

Full answer
text
event_series(id, title, starts_local TIMESTAMP, tz TEXT, duration INTERVAL,
             rrule TEXT, until DATE)                   -- 'FREQ=WEEKLY;BYDAY=TU'
event_exceptions(series_id, original_start, new_start, cancelled BOOLEAN,
                 PRIMARY KEY (series_id, original_start))

Why store local time plus zone: a 10:00 meeting in London stays at 10:00 local across daylight saving changes; storing a fixed UTC time would shift it by an hour twice a year.

Querying a week view:

  1. Expand rules into occurrences between the view's start and end.
  2. Apply exceptions (skip cancelled, move rescheduled).
  3. Convert to the viewer's time zone.

Materialising occurrences into an event_instances table for a rolling window makes availability queries simple SQL, at the cost of regenerating them when the rule changes. Editing "this and following" events splits the series into two.

Key points

  • Store the rule, not every occurrence
  • Keep local time and time zone
  • Exceptions table for changes
  • Expand per date range
  • Optionally materialise a rolling window

Common mistakes

  • Storing recurring events in UTC only
  • Generating occurrences forever

Follow-ups

  • How would you find free slots for several people?
  • How would you edit all future occurrences?

Tips

  • Explain the time zone choice
370.sql-0370Mediummid

Design storage for documents where users need to see and restore earlier versions.

Keep a documents table for identity and current pointer, and a document_versions table with one immutable row per save (document_id, version number, content, author, created_at) under a unique (document_id, version). Restoring creates a new version copied from an old one, so history is never rewritten.

Full answer
text
documents(id PK, owner_id, current_version INT, created_at)
document_versions(document_id FK, version INT, title, body, author_id, created_at,
                  PRIMARY KEY (document_id, version))

Behaviour:

  • Saving inserts version n+1 and updates current_version in the same transaction; the primary key stops two concurrent saves from both creating version n+1, so one retries.
  • Reading the current document joins on current_version, or a latest view does it.
  • Restoring version 3 inserts a new version whose content copies version 3.

Storage grows with every save; options are storing diffs for large documents, keeping full snapshots every N versions, or pruning old versions by policy. The same pattern (immutable versions plus a current pointer) fits price lists, policies and configuration.

Key points

  • Immutable version rows
  • Unique (document_id, version)
  • Current pointer on the parent
  • Restore by creating a new version
  • Consider diffs or pruning at scale

Common mistakes

  • Overwriting rows and keeping a separate change log only
  • Using timestamps alone as version identifiers

Follow-ups

  • How would you show a diff between versions?
  • How would you handle concurrent edits?

Tips

  • Show how restore preserves history
371.sql-0371Hardsenior

Users need a 'stores near me' search. How would you support that in SQL?

Store each location's coordinates and use a spatial index. In PostgreSQL, PostGIS geography columns with a GiST index answer nearest-neighbour queries (ORDER BY location <-> point LIMIT 10) and radius filters (ST_DWithin). Without spatial support, filter first by a bounding box on indexed latitude and longitude, then compute exact distances for the remaining rows.

Full answer

PostGIS version:

text
stores(id, name, location geography(Point, 4326));
CREATE INDEX ON stores USING gist (location);
SELECT id, name FROM stores
WHERE ST_DWithin(location, ST_MakePoint(:lon, :lat)::geography, 5000)
ORDER BY location <-> ST_MakePoint(:lon, :lat)::geography LIMIT 10;

Fallback without spatial types:

  1. Compute a bounding box around the user (about 0.045 degrees of latitude per 5 km).
  2. WHERE lat BETWEEN :lat1 AND :lat2 AND lon BETWEEN :lon1 AND :lon2 using an index on (lat, lon).
  3. Calculate the haversine distance for candidates and sort.

SQLite offers an R*Tree module for bounding-box queries. Remember that longitude spacing shrinks towards the poles and the box must handle the 180-degree meridian. The PostGIS statements are shown for illustration and were not run here.

Key points

  • Use spatial types and GiST indexes when available
  • KNN ordering with <-> finds nearest rows
  • Bounding box plus exact distance as a fallback
  • SQLite has R*Tree for boxes
  • Watch the poles and the antimeridian

Common mistakes

  • Computing distance to every row in the table
  • Treating degrees of longitude as fixed distances

Follow-ups

  • How would you combine distance with opening hours?
  • Geometry or geography: which and why?

Tips

  • Describe the two-step fallback
372.sql-0372Easyfresher

A monthly order report shows one row for most of the year instead of one per month. Find the bug.

substr(order_date, 1, 6) keeps only '2026-0', which is the same for January to September, so those months merge into one group. Use substr(order_date, 1, 7) or strftime('%Y-%m', order_date) to keep the full year and month.

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 substr(order_date, 1, 6) AS month, COUNT(*) AS orders FROM orders GROUP BY month ORDER BY month;
monthorders
2026-06

All six orders fall in January to March, and every one of those dates starts with '2026-0'. The report shows a single row with 6 orders, hiding the monthly pattern completely.

A corrected version:

sql
SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders FROM orders GROUP BY month ORDER BY month;
monthorders
2026-011
2026-022
2026-033

With the full 'YYYY-MM' key there is one row per month: one order in January, two in February and three in March. strftime documents the intent better than counting characters, and in PostgreSQL the equivalent is date_trunc('month', order_date) or to_char(order_date, 'YYYY-MM').

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 substr(order_date, 1, 6) AS month, COUNT(*) AS orders FROM orders GROUP BY month ORDER BY month;

SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders FROM orders GROUP BY month ORDER BY month;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Check the length of substring keys
  • strftime('%Y-%m', ...) groups by month in SQLite
  • date_trunc or to_char in PostgreSQL

Common mistakes

  • Testing on data from a single month
  • Grouping by a key that does not include the year

Follow-ups

  • How would you show months with zero orders?
  • How would you group by ISO week?

Tips

  • Show the merged key
373.sql-0373Hardsenior

A query for customers without orders returns every customer, even ones with orders. Find the subtle bug.

Inside the subquery, the unqualified id resolves to orders.id, not customers.id, because the nearest table with that column wins. The condition compares each order's customer_id with its own id, which never matches, so NOT EXISTS is always true. Qualify column names in correlated subqueries.

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 name FROM customers WHERE NOT EXISTS (SELECT 1 FROM orders WHERE customer_id = id) ORDER BY id;
name
Ana
Bilal
Chloe
Dev

SQL resolves an unqualified name in the innermost scope first. orders has an id column, so customer_id = id means orders.customer_id = orders.id, comparing values like 1 and 101. No row satisfies it, the subquery is always empty, and all four customers are returned.

A corrected version:

sql
SELECT c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) ORDER BY c.id;
name
Dev

With aliases, the correlation points at the outer row, and only Dev, who has no orders, remains. A related trap is WHERE id IN (SELECT id FROM order_items): order_items has no id, so id silently refers to the outer table and the filter keeps every row. Aliasing every column in subqueries prevents both.

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 name FROM customers WHERE NOT EXISTS (SELECT 1 FROM orders WHERE customer_id = id) ORDER BY id;

SELECT c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) ORDER BY c.id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Unqualified names resolve to the innermost table first
  • A wrong correlation can make EXISTS always true or false
  • Alias and qualify in correlated subqueries
  • Missing inner columns silently bind to the outer query

Common mistakes

  • Trusting that 'id' means the outer table
  • Testing only with data that happens to pass

Follow-ups

  • How would a linter catch this?
  • Does PostgreSQL resolve names the same way?

Tips

  • Explain the scope rule
374.sql-0374Easyfresher

A duplicate check on customer emails finds no duplicates, although there clearly are some. Fix it.

The query groups by id as well as email, and every id is unique, so each group has one row and HAVING COUNT(*) > 1 never passes. Group by the email only (normalised with lower() if case should not matter).

Full answer
sql
CREATE TABLE signups (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO signups VALUES (1, 'a@x.com'), (2, 'b@x.com'), (3, 'A@x.com'), (4, 'a@x.com');

The query as written:

sql
SELECT id, email, COUNT(*) AS n FROM signups GROUP BY id, email HAVING COUNT(*) > 1;
idemailn

(0 rows)

The result is empty. Adding id to the select list forced it into GROUP BY, which made every group a single row.

A corrected version:

sql
SELECT lower(email) AS email, COUNT(*) AS n, group_concat(id) AS ids FROM signups GROUP BY lower(email) HAVING COUNT(*) > 1;
emailnids
a@x.com31,3,4

Grouping by the normalised email finds the three rows for a@x.com, and group_concat lists their ids so they can be reviewed or merged. The order of ids inside group_concat is not guaranteed without an ORDER BY inside the aggregate. Add a unique index on lower(email) afterwards to stop new duplicates.

sql
CREATE TABLE signups (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO signups VALUES (1, 'a@x.com'), (2, 'b@x.com'), (3, 'A@x.com'), (4, 'a@x.com');

SELECT id, email, COUNT(*) AS n FROM signups GROUP BY id, email HAVING COUNT(*) > 1;

SELECT lower(email) AS email, COUNT(*) AS n, group_concat(id) AS ids FROM signups GROUP BY lower(email) HAVING COUNT(*) > 1;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Group only by the duplicate key
  • Extra GROUP BY columns split groups
  • Normalise case before comparing emails
  • Prevent recurrence with a unique index

Common mistakes

  • Adding id to GROUP BY to satisfy the select list
  • Comparing emails case-sensitively

Follow-ups

  • How would you keep the lowest id and delete the rest?
  • How would you enforce case-insensitive uniqueness?

Tips

  • Explain why each group has one row
375.sql-0375Mediummid

A day-over-day comparison drops some days. Find the problem with the self-join.

The join looks for a row exactly one calendar day earlier, so days after a gap (no sales on the 4th, 7th or 8th) find no partner and the inner join removes them. If the intent is 'compared with the previous recorded day', use LAG over ORDER BY day; if it is 'compared with yesterday', use a LEFT JOIN and show NULL.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

The query as written:

sql
SELECT t.day, t.amount, y.amount AS prev_amount
FROM daily_sales t JOIN daily_sales y ON y.day = date(t.day, '-1 day')
ORDER BY t.day;
dayamountprev_amount
2026-03-0280120
2026-03-0315080
2026-03-066090

Only three days appear: the 2nd, 3rd and 6th, each of which has a sale on the calendar day before. The 1st, 5th and 9th vanish without any warning.

A corrected version:

sql
SELECT day, amount, LAG(amount) OVER (ORDER BY day) AS prev_amount, LAG(day) OVER (ORDER BY day) AS prev_day
FROM daily_sales ORDER BY day;
dayamountprev_amountprev_day
2026-03-01120NULLNULL
2026-03-02801202026-03-01
2026-03-03150802026-03-02
2026-03-05901502026-03-03
2026-03-0660902026-03-05
2026-03-09200602026-03-06

LAG returns the previous row in date order, so every day appears and prev_day makes the comparison base visible. The first day has no predecessor and shows NULL. Which version is right depends on the business question, and the report should state it.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT t.day, t.amount, y.amount AS prev_amount
FROM daily_sales t JOIN daily_sales y ON y.day = date(t.day, '-1 day')
ORDER BY t.day;

SELECT day, amount, LAG(amount) OVER (ORDER BY day) AS prev_amount, LAG(day) OVER (ORDER BY day) AS prev_day
FROM daily_sales ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Inner self-joins drop rows without a partner
  • LAG gives the previous recorded row
  • LEFT JOIN keeps calendar-day comparisons with NULLs
  • State which comparison base is used

Common mistakes

  • Assuming every day has data
  • Mixing 'previous row' and 'previous calendar day'

Follow-ups

  • How would you fill missing days with zero?
  • How would you compute percentage change?

Tips

  • Name both possible intents
376.sql-0376Hardsenior

A recursive query that walks a management chain never finishes on some data. Why, and how do you make it safe?

The data contains a cycle (A manages B, B manages A), so the recursion keeps adding the same people forever. Track the visited path and stop when the next id is already in it, or cap the depth. PostgreSQL 14+ also has a CYCLE clause for this.

Full answer
sql
CREATE TABLE org (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO org VALUES (1, 'Ana', 3), (2, 'Ben', 1), (3, 'Cy', 2), (4, 'Dee', 1);

The query as written:

sql
WITH RECURSIVE chain(id, name, depth) AS (
  SELECT id, name, 0 FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1 FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
)
SELECT * FROM chain LIMIT 7;
idnamedepth
2Ben0
1Ana1
3Cy2
2Ben3
1Ana4
3Cy5
2Ben6

Ben's manager is Ana, Ana's is Cy and Cy's is Ben again, so the chain repeats. The LIMIT 7 was added here only so the demonstration ends; without it the query runs until memory or a timeout stops it.

A corrected version:

sql
WITH RECURSIVE chain(id, name, depth, path) AS (
  SELECT id, name, 0, '/' || id || '/' FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1, c.path || o.id || '/' FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
  WHERE c.path NOT LIKE '%/' || o.id || '/%'
)
SELECT id, name, depth, path FROM chain;
idnamedepthpath
2Ben0/2/
1Ana1/2/1/
3Cy2/2/1/3/

The path string records visited ids, and the WHERE stops before revisiting one, so the walk ends after Ben, Ana and Cy. Using UNION instead of UNION ALL also stops exact duplicate rows, but not here, because depth differs on each lap. Fixing the data (and adding a check on updates) is the real cure; the guard keeps queries safe meanwhile.

sql
CREATE TABLE org (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO org VALUES (1, 'Ana', 3), (2, 'Ben', 1), (3, 'Cy', 2), (4, 'Dee', 1);

WITH RECURSIVE chain(id, name, depth) AS (
  SELECT id, name, 0 FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1 FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
)
SELECT * FROM chain LIMIT 7;

WITH RECURSIVE chain(id, name, depth, path) AS (
  SELECT id, name, 0, '/' || id || '/' FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1, c.path || o.id || '/' FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
  WHERE c.path NOT LIKE '%/' || o.id || '/%'
)
SELECT id, name, depth, path FROM chain;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Cycles make recursive CTEs run forever
  • Track the visited path
  • Cap depth as a backstop
  • UNION only removes identical rows
  • PostgreSQL has a CYCLE clause

Common mistakes

  • Assuming hierarchical data never has cycles
  • Relying on UNION when a depth column differs

Follow-ups

  • How would you find all cycles in the table?
  • How would you stop updates from creating a cycle?

Tips

  • Show the path guard
377.sql-0377Mediummid

Deleting a customer should delete their orders through ON DELETE CASCADE, but the orders remain in SQLite. Why?

SQLite does not enforce foreign keys unless PRAGMA foreign_keys = ON is set on each connection, so the CASCADE clause is ignored. Turn the pragma on when opening every connection (it cannot be changed inside a transaction) and then the delete cascades.

Full answer
sql
CREATE TABLE fk_customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE fk_orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES fk_customers(id) ON DELETE CASCADE);
INSERT INTO fk_customers VALUES (1, 'Ana'), (2, 'Ben');
INSERT INTO fk_orders VALUES (10, 1), (11, 1), (12, 2);

The query as written:

sql
DELETE FROM fk_customers WHERE id = 1;
SELECT id, customer_id FROM fk_orders ORDER BY id;
idcustomer_id
101
111
122

Orders 10 and 11 still reference customer 1, who no longer exists. Enforcement is off by default for backward compatibility, so the schema's promise silently does nothing.

A corrected version:

sql
PRAGMA foreign_keys = ON;
DELETE FROM fk_customers WHERE id = 2;
SELECT id, customer_id FROM fk_orders ORDER BY id;
idcustomer_id
101
111

With enforcement on, deleting Ben also deletes order 12. Orders 10 and 11 remain because they were orphaned before the pragma was set; enabling it does not check existing rows. Run PRAGMA foreign_key_check; to list such orphans. PostgreSQL always enforces declared foreign keys.

sql
CREATE TABLE fk_customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE fk_orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES fk_customers(id) ON DELETE CASCADE);
INSERT INTO fk_customers VALUES (1, 'Ana'), (2, 'Ben');
INSERT INTO fk_orders VALUES (10, 1), (11, 1), (12, 2);

DELETE FROM fk_customers WHERE id = 1;
SELECT id, customer_id FROM fk_orders ORDER BY id;

PRAGMA foreign_keys = ON;
DELETE FROM fk_customers WHERE id = 2;
SELECT id, customer_id FROM fk_orders ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SQLite foreign keys are off by default
  • Set PRAGMA foreign_keys = ON per connection
  • Existing orphans are not checked automatically
  • foreign_key_check finds orphans

Common mistakes

  • Setting the pragma once and assuming it persists in the file
  • Setting it inside a transaction, where it has no effect

Follow-ups

  • How would you clean the orphaned orders?
  • Which other SQLite settings are per connection?

Tips

  • Say that the pragma is per connection
378.sql-0378Easyfresher

A combined list of refund and payment amounts is missing rows. Find the cause.

UNION removes duplicate rows across and within both inputs, so two separate payments of the same amount collapse into one. Use UNION ALL when every row matters, and include an identifying column so distinct events stay distinct.

Full answer
sql
CREATE TABLE pay_in (id INTEGER PRIMARY KEY, amount INTEGER);
CREATE TABLE pay_out (id INTEGER PRIMARY KEY, amount INTEGER);
INSERT INTO pay_in VALUES (1, 50), (2, 50), (3, 20);
INSERT INTO pay_out VALUES (1, 20);

The query as written:

sql
SELECT amount FROM pay_in UNION SELECT -amount FROM pay_out ORDER BY amount;
amount
-20
20
50

The two payments of 50 appear once, so a total computed from this list is 50 short. UNION also sorts or hashes to find duplicates, which costs time on large inputs.

A corrected version:

sql
SELECT 'in' AS kind, id, amount FROM pay_in UNION ALL SELECT 'out', id, -amount FROM pay_out ORDER BY kind, id;
kindidamount
in150
in250
in320
out1-20

UNION ALL keeps all four rows, and the kind and id columns make each row traceable. Summing the corrected list gives the net total:

sql
SELECT SUM(amount) AS net FROM (SELECT amount FROM pay_in UNION ALL SELECT -amount FROM pay_out);
net
100
sql
CREATE TABLE pay_in (id INTEGER PRIMARY KEY, amount INTEGER);
CREATE TABLE pay_out (id INTEGER PRIMARY KEY, amount INTEGER);
INSERT INTO pay_in VALUES (1, 50), (2, 50), (3, 20);
INSERT INTO pay_out VALUES (1, 20);

SELECT amount FROM pay_in UNION SELECT -amount FROM pay_out ORDER BY amount;

SELECT 'in' AS kind, id, amount FROM pay_in UNION ALL SELECT 'out', id, -amount FROM pay_out ORDER BY kind, id;

SELECT SUM(amount) AS net FROM (SELECT amount FROM pay_in UNION ALL SELECT -amount FROM pay_out);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • UNION removes duplicates
  • UNION ALL keeps every row and is cheaper
  • Add identifying columns to unioned events

Common mistakes

  • Using UNION by habit
  • Summing a deduplicated list

Follow-ups

  • When is UNION the right choice?
  • How would you compute the net total in one query?

Tips

  • Say what UNION removed
379.sql-0379Easyfresher

A city completion report counts blank strings as known cities. Fix the count.

COUNT(city) counts every non-NULL value, and an empty string is not NULL. Normalise blanks with NULLIF(trim(city), '') inside the count, and ideally store NULL for unknown values with a CHECK that rejects empty strings.

Full answer
sql
CREATE TABLE leads (id INTEGER PRIMARY KEY, city TEXT);
INSERT INTO leads VALUES (1, 'Pune'), (2, ''), (3, NULL), (4, '  '), (5, 'Leeds');

The query as written:

sql
SELECT COUNT(*) AS total, COUNT(city) AS with_city FROM leads;
totalwith_city
54

The report claims 4 of 5 leads have a city. Two of those are an empty string and a string of spaces, which forms often submit when a field is left blank.

A corrected version:

sql
SELECT COUNT(*) AS total, COUNT(NULLIF(trim(city), '')) AS with_city FROM leads;
totalwith_city
52

Trimming and then turning '' into NULL leaves 2 real cities. For the data itself, convert blanks once with UPDATE leads SET city = NULL WHERE trim(city) = '' and add CHECK (city IS NULL OR trim(city) <> ''). Oracle treats '' as NULL, which is one more reason not to rely on blanks meaning anything.

sql
CREATE TABLE leads (id INTEGER PRIMARY KEY, city TEXT);
INSERT INTO leads VALUES (1, 'Pune'), (2, ''), (3, NULL), (4, '  '), (5, 'Leeds');

SELECT COUNT(*) AS total, COUNT(city) AS with_city FROM leads;

SELECT COUNT(*) AS total, COUNT(NULLIF(trim(city), '')) AS with_city FROM leads;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Empty strings are not NULL
  • NULLIF(trim(x), '') normalises blanks
  • Prefer storing NULL for unknown
  • A CHECK can reject blank strings

Common mistakes

  • Checking only for NULL
  • Forgetting whitespace-only values

Follow-ups

  • How would you clean the existing data safely?
  • How do engines differ on empty strings?

Tips

  • Show the normalising expression
380.sql-0380Mediummid

Two requests each read a stock level of 10 and write back 11 after adding one item. Show the lost update and the fix.

Read-modify-write in application code lets two requests compute from the same old value, so one increment is lost. Update atomically with SET qty = qty + 1, which reads and writes the current value under the row lock. Alternatively lock the row with SELECT ... FOR UPDATE (PostgreSQL) before computing.

Full answer
sql
PRAGMA journal_mode = WAL;
CREATE TABLE stock (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO stock VALUES (1, 10), (2, 10);

Connection A reads the level:

sql
SELECT qty FROM stock WHERE id = 1;
qty
10

Connection B has also read 10 and writes 11:

sql
UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;
qty
11

Connection A, unaware, writes its own computed value 11:

sql
UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;
qty
11

Two items were added, but the stock moved from 10 to 11. Each request was correct alone; the bug is computing the new value outside the database from a stale read.

The fix, on a second row, issues the increment as an atomic expression. Connection B first:

sql
UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;
qty
11

Then connection A:

sql
UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;
qty
12

Both increments land, giving 12. The database evaluates qty + 1 against the latest committed value while holding the row's write lock, so no update is lost. Where the new value needs complex logic, lock the row first or use optimistic concurrency with a version column (UPDATE ... WHERE id = ? AND version = ?, retrying when no row changes).

sql
PRAGMA journal_mode = WAL;
CREATE TABLE stock (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO stock VALUES (1, 10), (2, 10);

SELECT qty FROM stock WHERE id = 1;

-- second session
UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;

UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;

-- second session
UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;

UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Read-modify-write in code loses updates
  • SET qty = qty + 1 is atomic
  • SELECT ... FOR UPDATE locks before computing
  • Version columns give optimistic concurrency

Common mistakes

  • Computing new values from a stale read
  • Assuming transactions alone prevent lost updates at every isolation level

Follow-ups

  • How does a version column detect conflicts?
  • Which isolation level prevents lost updates in PostgreSQL?

Tips

  • Show both writes in order