← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 20 of 26

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

Page 20 of 26

Questions 381–400 of 501 · 0 of 20 on this page marked learned

381.sql-0381Mediummid

Use PostgreSQL's DISTINCT ON to return each customer's most recent order.

DISTINCT ON (customer_id) keeps the first row for each customer according to ORDER BY, so ordering by customer_id and then order_date DESC keeps the latest order. It is concise and fast with a matching index, but it is PostgreSQL-only; portable code uses ROW_NUMBER.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
SELECT DISTINCT ON (customer_id) customer_id, id, order_date FROM orders ORDER BY customer_id, order_date DESC;
customer_ididorder_date
11022026-02-11
21052026-03-09
31042026-03-01
NULL1062026-03-12

The ORDER BY must start with the DISTINCT ON expressions; the columns after them decide which row is first in each group. Order 106 has no customer, and NULL forms its own group, so it appears too. Add WHERE customer_id IS NOT NULL to drop it.

The portable version on SQLite uses a window function:

sql
SELECT customer_id, id, order_date FROM (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, id DESC) AS rn FROM orders o
) WHERE rn = 1 ORDER BY customer_id;
customer_ididorder_date
NULL1062026-03-12
11022026-02-11
21052026-03-09
31042026-03-01

Both return one row per customer, but the NULL group sorts last in PostgreSQL and first in SQLite, which is each engine's default NULL ordering; add NULLS LAST or NULLS FIRST when the position matters. With ties on the date, DISTINCT ON picks an arbitrary row among them unless another ORDER BY column breaks the tie, so add id DESC for a stable result. An index on (customer_id, order_date DESC) lets PostgreSQL read groups in order.

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 customer_id, id, order_date FROM (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, id DESC) AS rn FROM orders o
) WHERE rn = 1 ORDER BY customer_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

  • DISTINCT ON keeps the first row per key by ORDER BY
  • ORDER BY must begin with the DISTINCT ON columns
  • Add a tiebreaker for stable results
  • ROW_NUMBER is the portable equivalent

Common mistakes

  • ORDER BY that does not start with the DISTINCT ON columns
  • Expecting DISTINCT ON to work in SQLite or MySQL

Follow-ups

  • How would you return the latest two orders per customer?
  • Which index helps DISTINCT ON?

Tips

  • Mention the ORDER BY rule
382.sql-0382Mediummid

Why do PostgreSQL sequences leave gaps in id values, and should that be fixed?

nextval() is never rolled back, so a failed or rolled-back insert consumes a value, and cached sequence values can be lost on a crash. Gaps are normal and harmless for surrogate keys. When gap-free numbers are legally required, such as invoice numbers, generate them from a counter row updated inside the same transaction, accepting that it serialises inserts.

Full answer
sql
BEGIN;
SELECT nextval('demo_seq');
ROLLBACK;
SELECT nextval('demo_seq') AS next_value;
next_value
2

The value 1 was taken inside a transaction that rolled back, yet the next call returns 2. Sequences are deliberately non-transactional so concurrent inserts never wait for each other's commit.

Other sources of gaps:

  • INSERT ... ON CONFLICT DO NOTHING consumes a value even when no row is inserted.
  • Sequence caching per session (CACHE 20) discards unused values when the session ends.
  • Deleted rows leave holes.

If a business needs consecutive numbers, keep invoice_counters(year, last_no) and run UPDATE invoice_counters SET last_no = last_no + 1 WHERE year = 2026 RETURNING last_no in the invoice transaction. A rollback then also rolls back the number. SQLite's INTEGER PRIMARY KEY without AUTOINCREMENT can reuse the largest deleted rowid instead of leaving a gap, which is a different behaviour again.

Key points

  • nextval is not rolled back
  • Gaps come from rollbacks, conflicts and caching
  • Gaps are fine for surrogate keys
  • Gap-free numbering needs a counter row in the transaction

Common mistakes

  • Reusing ids to fill gaps
  • Using MAX(id) + 1, which races

Follow-ups

  • Why is MAX(id) + 1 unsafe?
  • How does SQLite AUTOINCREMENT differ?

Tips

  • Show the rollback case
383.sql-0383Hardsenior

What are PostgreSQL advisory locks, and when are they useful?

Advisory locks are application-defined locks on an arbitrary number, taken with functions such as pg_advisory_lock(key) or pg_try_advisory_xact_lock(key). The database does not tie them to rows; the application decides what a key means. They are handy for 'only one worker runs this job' or serialising work per customer without a dedicated lock table.

Full answer
sql
BEGIN;
SELECT pg_try_advisory_xact_lock(42) AS got_lock;
got_lock
true

pg_try_advisory_xact_lock returns true when the lock was taken and false when another session holds it, without waiting. The _xact_ variant releases automatically at the end of the transaction; session-level locks (pg_advisory_lock) last until explicitly released or the session ends.

Typical uses:

  • Cron jobs on several servers: each tries the lock for 'nightly-report' and only the winner runs.
  • Per-entity serialisation: lock hashtext('customer:' || id) before recalculating that customer's balance.
  • Migrations: tools take an advisory lock so two deploys do not migrate at once.

Cautions: session locks leak if code forgets to release them, and with transaction-mode connection poolers a session lock may stay attached to a pooled connection. Prefer transaction-level locks in pooled setups. SQLite has no equivalent; its single-writer lock covers the whole database.

Key points

  • Locks on application-chosen keys
  • try variants do not wait
  • Transaction-level locks release at commit or rollback
  • Useful for singleton jobs and per-entity serialisation
  • Session locks and poolers mix badly

Common mistakes

  • Forgetting to release session-level locks
  • Using session locks behind a transaction pooler

Follow-ups

  • How would you map a string key to a lock number?
  • How do advisory locks differ from SELECT ... FOR UPDATE?

Tips

  • Contrast session and transaction locks
384.sql-0384Mediummid

How does basic full-text search work in PostgreSQL, compared with LIKE?

to_tsvector turns text into normalised lexemes (stemmed words without stop words), and to_tsquery builds a search expression; @@ tests a match. Unlike LIKE '%word%', it matches word forms such as 'running' for 'run', ranks results and can use a GIN index. Store a generated tsvector column and index it for speed.

Full answer
sql
SELECT to_tsvector('english', 'The cats are running')::text AS lexemes;
lexemes
'cat':2 'run':4

The English configuration dropped the stop words 'The' and 'are', stemmed 'cats' to 'cat' and 'running' to 'run', and recorded word positions.

sql
SELECT to_tsvector('english', 'The cats are running') @@ to_tsquery('english', 'cat & run') AS matches;
matches
true

The query cat & run matches although neither word appears literally. A LIKE search for '%cat%run%' would also match 'concatenate rune', and cannot use a B-tree index.

Production setup:

text
ALTER TABLE articles ADD COLUMN search tsvector
  GENERATED ALWAYS AS (to_tsvector('english', coalesce(title,'') || ' ' || coalesce(body,''))) STORED;
CREATE INDEX articles_search ON articles USING gin (search);
SELECT id FROM articles WHERE search @@ websearch_to_tsquery('english', 'cat running')
ORDER BY ts_rank(search, websearch_to_tsquery('english', 'cat running')) DESC;

The DDL above is illustrative and was not run here. SQLite provides full-text search through the FTS5 module instead.

Key points

  • to_tsvector normalises text into lexemes
  • to_tsquery and @@ match word forms
  • GIN indexes speed up searches
  • Stored generated tsvector columns keep it in sync
  • LIKE matches substrings, not words

Common mistakes

  • Using LIKE '%x%' for search over large text
  • Mixing text search configurations between indexing and querying

Follow-ups

  • How would you rank results?
  • When would an external search engine be better?

Tips

  • Show the lexemes
385.sql-0385Mediummid

Show full-text search in SQLite with the FTS5 module.

Create a virtual table with USING fts5(...), insert documents, and query with MATCH. FTS5 supports phrase queries, prefix searches such as 'data*', boolean operators and ranking with bm25 through the hidden rank column, ordered ascending because lower is better.

Full answer
sql
CREATE VIRTUAL TABLE notes USING fts5(title, body);
INSERT INTO notes (rowid, title, body) VALUES (1, 'Indexes', 'An index speeds up lookups'), (2, 'Joins', 'A left join keeps unmatched rows'), (3, 'Tuning', 'Too many indexes slow writes');
sql
SELECT rowid, title FROM notes WHERE notes MATCH 'index*' ORDER BY rank;
rowidtitle
1Indexes
3Tuning

The prefix query index* matches 'index' and 'indexes', so documents 1 and 3 are returned, best match first by FTS5's built-in rank.

sql
SELECT rowid, title FROM notes WHERE notes MATCH '"left join"';
rowidtitle
2Joins

A quoted phrase must appear as consecutive words, so only document 2 matches. The default tokenizer (unicode61) is case-insensitive and does not stem; tokenize = 'porter unicode61' adds English stemming. For an existing table, an external-content FTS table plus triggers keeps the index in sync without storing text twice. These runs used the FTS5 module compiled into SQLite 3.46.1 here; some builds omit it.

sql
CREATE VIRTUAL TABLE notes USING fts5(title, body);
INSERT INTO notes (rowid, title, body) VALUES (1, 'Indexes', 'An index speeds up lookups'), (2, 'Joins', 'A left join keeps unmatched rows'), (3, 'Tuning', 'Too many indexes slow writes');

SELECT rowid, title FROM notes WHERE notes MATCH 'index*' ORDER BY rank;

SELECT rowid, title FROM notes WHERE notes MATCH '"left join"';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • FTS5 is a virtual table queried with MATCH
  • Prefix and phrase queries are supported
  • ORDER BY rank sorts by bm25 relevance
  • Porter tokenizer adds stemming
  • External-content tables avoid duplicate storage

Common mistakes

  • Using LIKE for search on large text in SQLite
  • Forgetting that FTS5 may be missing in some builds

Follow-ups

  • How would you keep an FTS index in sync with a normal table?
  • How would you highlight matches?

Tips

  • Show prefix and phrase queries
386.sql-0386Hardsenior

What is a BRIN index in PostgreSQL, and when does it beat a B-tree?

A BRIN (block range) index stores only the minimum and maximum value for each range of table pages. It is tiny and cheap to maintain, and it works well when the column's values correlate with physical order, such as an append-only timestamp. For random data it is nearly useless, because every range overlaps the search.

Full answer

How it works: for each block range (128 pages by default), BRIN records the min and max of the column. A query for ts >= '2026-03-01' skips ranges whose max is earlier and reads the rest.

Where it shines:

  • Append-only logs and sensor data where rows arrive in time order.
  • Very large tables where a B-tree would be gigabytes; a BRIN index may be a few hundred kilobytes.
  • Insert-heavy workloads, since maintenance is minimal.

Limitations:

  • Results are lossy: matching ranges are scanned and rows rechecked, so point lookups are slower than with a B-tree.
  • Updates or out-of-order inserts break the correlation and widen ranges.
  • No uniqueness, no index-only scans.

Check pg_stats.correlation for the column; values near 1 or -1 suggest BRIN will help. This is described from PostgreSQL documentation and was not run here.

Key points

  • BRIN stores min and max per block range
  • Tiny and cheap to maintain
  • Needs correlation with physical order
  • Lossy, so rows are rechecked
  • Check pg_stats.correlation

Common mistakes

  • Using BRIN on randomly ordered columns
  • Expecting fast point lookups from BRIN

Follow-ups

  • How does pages_per_range affect BRIN?
  • Could partitioning replace a BRIN index?

Tips

  • Tie BRIN to physical order
387.sql-0387Hardsenior

Why can a SECURITY DEFINER function in PostgreSQL be dangerous, and how is it made safe?

A SECURITY DEFINER function runs with its owner's privileges, not the caller's. If it resolves unqualified names through search_path, a caller can create an object with the same name in a schema they control and have the function call it with elevated rights. Set a fixed search_path on the function, qualify names, and grant EXECUTE narrowly.

Full answer

Safe definition pattern (illustrative, not run here):

text
CREATE FUNCTION app.reset_password(uid int) RETURNS void
LANGUAGE sql SECURITY DEFINER
SET search_path = pg_catalog, app
AS $$ UPDATE app.users SET password_hash = NULL WHERE id = uid $$;
REVOKE ALL ON FUNCTION app.reset_password(int) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION app.reset_password(int) TO support_role;

Points:

  • The SET search_path clause pins name resolution, putting pg_temp last implicitly when not listed, so temporary objects cannot shadow real ones.
  • Functions are executable by PUBLIC by default; revoke that and grant to specific roles.
  • Keep the function small and validate inputs, since it bypasses normal permission checks.
  • The owner should be a dedicated role with only the rights the function needs, not a superuser.

SECURITY INVOKER (the default) runs with the caller's rights and avoids the issue when elevation is not needed.

Key points

  • SECURITY DEFINER runs with the owner's rights
  • Unpinned search_path allows object shadowing
  • Set search_path on the function
  • Revoke EXECUTE from PUBLIC
  • Owner should be a minimal role

Common mistakes

  • Owning definer functions by a superuser
  • Relying on the caller's search_path

Follow-ups

  • How does row-level security interact with definer functions?
  • Which privileges does a new function get by default?

Tips

  • Name the search_path attack
388.sql-0388Mediummid

How do prepared statements and plan caching affect performance and correctness?

A prepared statement is parsed and planned once and executed many times with parameters, which saves parsing work and keeps data separate from SQL text, preventing injection. Some engines reuse a generic plan that ignores parameter values, which can be poor for skewed data. PostgreSQL decides between custom and generic plans after several executions.

Full answer

Benefits:

  • Parameters are sent separately from the SQL, so user input cannot change the statement's structure.
  • Repeated statements skip parsing and, when a generic plan is cached, planning.

Pitfalls:

  • Skewed data: WHERE status = $1 may deserve an index scan for rare statuses and a sequential scan for common ones. A generic plan picks one for all. PostgreSQL plans custom plans for the first five executions and then switches to a generic plan if it is not estimated to be worse; plan_cache_mode = force_custom_plan overrides that.
  • Schema changes invalidate cached plans; most engines replan automatically.
  • Connection poolers in transaction mode historically broke named prepared statements, because the next execution may land on another server connection. Newer PgBouncer versions track them.

SQLite caches compiled statements in the driver (Python's sqlite3 keeps a statement cache) and plans with the actual parameter values only in limited cases. These behaviours are described here, not run.

Key points

  • Prepare once, execute many
  • Parameters prevent SQL injection
  • Generic plans can misfit skewed values
  • PostgreSQL chooses custom or generic plans adaptively
  • Poolers may interfere with named statements

Common mistakes

  • Building SQL by string concatenation
  • Blaming the query when a generic plan is the cause

Follow-ups

  • How would you detect a bad generic plan?
  • Can identifiers such as table names be parameters?

Tips

  • Mention injection and plan reuse together
389.sql-0389Mediummid

Fill in missing days of sales with zero using PostgreSQL's generate_series.

Generate every date in the range with generate_series(start, end, interval '1 day'), LEFT JOIN the sales table on the day, and COALESCE missing amounts to 0. This produces one row per calendar day, which charts and moving averages need.

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);
sql
SELECT d::date AS day, COALESCE(s.amount, 0) AS amount
FROM generate_series(DATE '2026-03-01', DATE '2026-03-09', INTERVAL '1 day') AS d
LEFT JOIN daily_sales s ON s.day = to_char(d, 'YYYY-MM-DD')
ORDER BY day;
dayamount
2026-03-01120
2026-03-0280
2026-03-03150
2026-03-040
2026-03-0590
2026-03-0660
2026-03-070
2026-03-080
2026-03-09200

The series supplies the 4th, 7th and 8th even though the table has no rows for them, and COALESCE shows 0 instead of NULL. generate_series with timestamps returns timestamps, so the cast to date makes the join and the output clean. In SQLite the same calendar comes from a recursive CTE:

sql
WITH RECURSIVE cal(day) AS (SELECT '2026-03-01' UNION ALL SELECT date(day, '+1 day') FROM cal WHERE day < '2026-03-09')
SELECT c.day, COALESCE(s.amount, 0) AS amount FROM cal c LEFT JOIN daily_sales s ON s.day = c.day ORDER BY c.day;
dayamount
2026-03-01120
2026-03-0280
2026-03-03150
2026-03-040
2026-03-0590
2026-03-0660
2026-03-070
2026-03-080
2026-03-09200

Both runs return nine rows. A permanent calendar table (one row per day for many years, with flags such as weekday and holiday) is a common alternative that also serves reporting joins.

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

WITH RECURSIVE cal(day) AS (SELECT '2026-03-01' UNION ALL SELECT date(day, '+1 day') FROM cal WHERE day < '2026-03-09')
SELECT c.day, COALESCE(s.amount, 0) AS amount FROM cal c LEFT JOIN daily_sales s ON s.day = c.day ORDER BY c.day;

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

Key points

  • generate_series creates a date spine
  • LEFT JOIN facts onto the spine
  • COALESCE gaps to zero
  • Recursive CTEs do the same in SQLite
  • Calendar tables are a reusable option

Common mistakes

  • Joining the spine with an inner join
  • Forgetting the cast from timestamp to date

Follow-ups

  • How would you compute a 7-day moving average over the filled series?
  • What should happen when zero and missing mean different things?

Tips

  • Show both engines
390.sql-0390Mediummid

Loading ten million rows with individual INSERT statements takes hours. How would you speed it up?

Batch the work: in PostgreSQL use COPY, which streams rows with far less overhead than separate INSERTs; otherwise use multi-row INSERTs inside large transactions. Drop or defer secondary indexes and foreign key checks during the load and rebuild them afterwards, then run ANALYZE. In SQLite, one transaction around many inserts is the biggest single gain.

Full answer

Where the time goes with row-by-row inserts: a network round trip per row, a parse per statement and, in autocommit mode, a commit (and disk flush) per row.

Improvements, roughly in order of impact:

  1. One transaction per large batch (tens of thousands of rows), so commits happen rarely.
  2. Multi-row INSERT ... VALUES (...), (...), ... or prepared statements executed in batches.
  3. PostgreSQL COPY table FROM STDIN (or \copy in psql), which is designed for bulk loads.
  4. Load into a table without secondary indexes, then CREATE INDEX once; building an index in one pass is faster than maintaining it row by row.
  5. Add foreign keys after the load (or validate them later) if the data is trusted.
  6. ANALYZE afterwards so the planner knows the new data.

For SQLite, wrapping inserts in BEGIN ... COMMIT and using executemany with one prepared statement typically turns hours into seconds. These figures are typical experience, not measured here.

Key points

  • Per-row commits dominate load time
  • Batch rows inside transactions
  • COPY is the fast path in PostgreSQL
  • Build indexes after loading
  • ANALYZE after bulk loads

Common mistakes

  • Autocommit for each row
  • Loading into a heavily indexed table

Follow-ups

  • How would you load data while the table stays online?
  • How do you handle bad rows during COPY?

Tips

  • Start with transaction batching
391.sql-0391Hardsenior

Design the tables behind a social feed where users follow each other and see recent posts from people they follow.

Store follows(follower_id, followee_id) and posts(id, author_id, created_at). A pull model builds the feed at read time by joining follows to recent posts; a push model writes each new post into a feed_items table for every follower. Pull is simple and suits modest scale; push makes reads fast but is costly for authors with millions of followers, so large systems mix the two.

Full answer
text
follows(follower_id, followee_id, created_at, PRIMARY KEY (follower_id, followee_id))
posts(id, author_id, body, created_at)          -- index (author_id, created_at DESC)
feed_items(user_id, post_id, created_at, PRIMARY KEY (user_id, created_at, post_id))

Pull (fan-out on read):

text
SELECT p.* FROM follows f JOIN posts p ON p.author_id = f.followee_id
WHERE f.follower_id = :me AND p.created_at < :cursor
ORDER BY p.created_at DESC LIMIT 50;

Fine for hundreds of followees; slow when a user follows thousands.

Push (fan-out on write): on each post, insert a feed row per follower, so reading is one index range on feed_items. A celebrity with ten million followers creates ten million rows per post.

Hybrid: push for normal authors, pull for very popular ones, merged at read time. A reverse index follows(followee_id, follower_id) serves 'who follows me'. Feed rows can be trimmed to the latest few hundred per user.

Key points

  • follows as a two-column key
  • Pull joins at read time
  • Push writes per follower
  • Celebrities break pure push
  • Hybrid models are common

Common mistakes

  • Pure push with no special case for huge accounts
  • OFFSET paging through feeds

Follow-ups

  • How would you remove posts from feeds when someone unfollows?
  • How would you rank the feed instead of sorting by time?

Tips

  • Compare read and write costs of both models
392.sql-0392Mediummid

Design tables to track learners' progress through online courses made of modules and lessons.

Model courses, modules and lessons with an ordering column, enrolments linking learners to courses, and lesson_progress rows (learner, lesson, status, completed_at) keyed by learner and lesson. Course completion is derived by comparing completed lessons with the course's required lessons, or cached on the enrolment and refreshed when progress changes.

Full answer
text
courses(id, title, published_at)
modules(id, course_id, position, title, UNIQUE (course_id, position))
lessons(id, module_id, position, title, required BOOLEAN DEFAULT true)
enrolments(learner_id, course_id, enrolled_at, completed_at, PRIMARY KEY (learner_id, course_id))
lesson_progress(learner_id, lesson_id, status CHECK IN ('started','completed'),
                score, updated_at, PRIMARY KEY (learner_id, lesson_id))

Progress percentage for one learner:

text
SELECT 100.0 * COUNT(lp.lesson_id) FILTER (WHERE lp.status = 'completed') / COUNT(*) AS pct
FROM lessons l JOIN modules m ON m.id = l.module_id
LEFT JOIN lesson_progress lp ON lp.lesson_id = l.id AND lp.learner_id = :learner
WHERE m.course_id = :course AND l.required;

Decisions:

  • position columns keep order explicit; leave gaps (10, 20, 30) so lessons can be inserted.
  • When a course changes after learners started, decide whether completion uses the current lesson set or a versioned one.
  • Quiz attempts belong in their own table, since a learner can retry.

The progress query divides completed required lessons by all required lessons; the LEFT JOIN keeps lessons the learner has not opened, so they count as not done. Caching completed_at on the enrolment makes dashboards cheap, and a trigger or the save-progress code sets it when the last required lesson is completed. The SQL above is illustrative and was not run here.

Key points

  • Ordered modules and lessons
  • Progress per learner and lesson
  • Derived or cached completion
  • Plan for course content changes
  • Separate attempts from progress

Common mistakes

  • One progress column per lesson on the enrolment
  • Counting lessons without the required flag

Follow-ups

  • How would you show a leaderboard per course?
  • How would certificates be issued?

Tips

  • Explain how completion is computed
393.sql-0393Hardsenior

Design a clinic appointment system where patients book 15-minute slots with doctors.

Store doctors' working hours as rules, generate bookable slots (or compute them), and store appointments with doctor_id and start time under a unique constraint so a slot can be booked only once. In PostgreSQL an exclusion constraint on (doctor_id, tsrange) also prevents overlapping appointments of different lengths.

Full answer
text
doctors(id, name, tz)
working_hours(doctor_id, weekday, start_local, end_local)
time_off(doctor_id, starts_at, ends_at)
appointments(id, doctor_id, patient_id, starts_at timestamptz, ends_at timestamptz,
             status, UNIQUE (doctor_id, starts_at))

Availability for a day: generate 15-minute starts within working hours, remove time off and existing non-cancelled appointments. Generating slots on the fly avoids storing millions of empty rows; a materialised slots table for the next few weeks is the alternative when searches are heavy.

Double booking:

  • Fixed slot lengths: the unique key on (doctor_id, starts_at) is enough; two concurrent inserts for the same slot cannot both succeed.
  • Variable lengths: EXCLUDE USING gist (doctor_id WITH =, tstzrange(starts_at, ends_at) WITH &&) WHERE (status <> 'cancelled').

Store instants in UTC and working hours in the doctor's local time, so daylight saving changes keep clinic hours correct. Cancelled appointments should free the slot, which the partial constraint handles.

Key points

  • Rules for working hours, rows for bookings
  • Unique (doctor_id, starts_at) for fixed slots
  • Exclusion constraints for variable lengths
  • Compute or materialise availability
  • Local working hours, UTC instants

Common mistakes

  • Checking availability in code without a constraint
  • A unique constraint that also blocks rebooking after cancellation

Follow-ups

  • How would you support group sessions with several patients?
  • How would reminders be scheduled?

Tips

  • Show the constraint that prevents double booking
394.sql-0394Hardsenior

Design the ledger for an in-app wallet so balances are always explainable.

Use double-entry bookkeeping: every transfer is a transaction with two or more entries whose amounts sum to zero, written atomically. Balances are the sum of an account's entries, optionally cached with the cache updated in the same transaction. Entries are never updated or deleted; corrections are new reversing entries.

Full answer
text
accounts(id, owner_id, currency, kind)                 -- user wallet, cash, fees, ...
ledger_transactions(id, kind, reference, created_at)
ledger_entries(id, transaction_id FK, account_id FK, amount_minor BIGINT, created_at)
account_balances(account_id PK, balance_minor BIGINT, CHECK (balance_minor >= 0 OR kind ...))

A top-up of 500 from a card: entries +500 to the user's wallet and -500 to the external funding account, in one transaction. A purchase moves money from wallet to merchant; a fee adds a third entry to a fees account. A check that SUM(amount_minor) = 0 per transaction (in a trigger or a periodic audit) catches bugs.

Why this shape:

  • Every balance can be recomputed from entries and reconciled with the cached value.
  • History is immutable, which auditors and dispute handling require.
  • Overdraft protection is a conditional update on the cached balance (... WHERE balance_minor >= :amount) in the same transaction as the entries.

Idempotency keys on ledger_transactions.reference stop a retried request from posting twice.

Key points

  • Entries per transaction sum to zero
  • Never update or delete entries
  • Balances are sums, cached atomically
  • Conditional update prevents overdrafts
  • Idempotency keys on transactions

Common mistakes

  • A single mutable balance column with no history
  • Fixing mistakes by editing old rows

Follow-ups

  • How would you reconcile with the payment provider?
  • How would you handle currency conversion in the ledger?

Tips

  • State the sum-to-zero rule
395.sql-0395Mediummid

Design coupon codes that can be redeemed at most 100 times in total and once per customer.

Store coupons with max_redemptions and a redeemed_count, and a redemptions table with a unique (coupon_id, customer_id). Redeem in one transaction: insert the redemption (the unique key enforces once per customer) and increment the counter with a conditional UPDATE ... WHERE redeemed_count < max_redemptions; if no row changes, roll back.

Full answer
text
coupons(id, code UNIQUE, discount, valid_from, valid_to, max_redemptions, redeemed_count DEFAULT 0)
coupon_redemptions(coupon_id, customer_id, order_id, redeemed_at,
                   PRIMARY KEY (coupon_id, customer_id))

Redemption transaction:

  1. INSERT INTO coupon_redemptions ... fails with a unique violation if the customer already used it.
  2. UPDATE coupons SET redeemed_count = redeemed_count + 1 WHERE id = :c AND redeemed_count < max_redemptions AND now() BETWEEN valid_from AND valid_to;
  3. If step 2 changed zero rows, roll back: the coupon is exhausted or expired.

The conditional update makes the limit safe under concurrency, because the row lock serialises competing increments and each re-checks the condition. Counting redemptions with SELECT COUNT(*) and then inserting would let the 101st customer through. If an order is cancelled, delete the redemption and decrement the counter in one transaction, according to the business rule.

Key points

  • Unique key for once per customer
  • Conditional increment for the global limit
  • Both in one transaction
  • Count-then-insert races

Common mistakes

  • Checking the limit with COUNT(*) before inserting
  • Case-sensitive code lookups that confuse users

Follow-ups

  • How would you generate a million unique single-use codes?
  • How would you restore a redemption on refund?

Tips

  • Show why the conditional update is safe
396.sql-0396Hardsenior

Design tables for subscription billing with plans, upgrades and monthly invoices.

Keep plans (with versioned prices), subscriptions (customer, plan, status, current period start and end) and an append-only subscription_events history. Invoices and invoice lines are generated per period and store the amounts charged, including proration for mid-period changes. Never compute past invoices from current plan prices.

Full answer
text
plans(id, name)
plan_prices(id, plan_id, currency, amount_minor, interval, valid_from, valid_to)
subscriptions(id, customer_id, plan_price_id, status, current_period_start,
              current_period_end, cancel_at_period_end)
subscription_events(id, subscription_id, kind, from_price_id, to_price_id, at)
invoices(id, customer_id, period_start, period_end, status, total_minor)
invoice_lines(invoice_id, description, quantity, amount_minor, subscription_id)

Upgrade mid-month: record an event, switch plan_price_id, and add proration lines (a credit for unused time on the old price, a charge for the new one) to the next invoice. Price changes create a new plan_prices row, and existing subscribers move only when the business decides.

Status transitions (trialing, active, past_due, cancelled) are driven by a scheduled job and payment outcomes, and each one is logged. A unique key on (subscription_id, period_start) for generated invoices makes the billing job safe to rerun.

Key points

  • Versioned prices
  • Subscriptions hold the current period
  • Append-only event history
  • Invoices store amounts charged
  • Idempotent invoice generation

Common mistakes

  • Recomputing old invoices from current prices
  • Overwriting plan prices in place

Follow-ups

  • How would you handle failed payments and retries?
  • How would usage-based charges fit?

Tips

  • Explain proration
397.sql-0397Mediummid

Design storage for feature flags that can target specific users, tenants or a percentage of traffic.

A flags table holds the key, default state and rollout percentage; a flag_rules table holds targeting rules such as tenant or user lists, evaluated in priority order. Percentage rollout hashes the user id with the flag key so each user gets a stable result. Applications cache flags in memory and refresh on change.

Full answer
text
flags(key PK, description, enabled_default BOOLEAN, rollout_percent INT CHECK BETWEEN 0 AND 100,
      updated_at, updated_by)
flag_rules(id, flag_key FK, priority, attribute, operator, value, result BOOLEAN)
flag_audit(id, flag_key, change jsonb, changed_by, changed_at)

Evaluation for a user:

  1. Apply rules by ascending priority (for example tenant_id IN (7, 9) -> true, country = 'IN' -> false); the first match wins.
  2. Otherwise, if hash(flag_key || user_id) % 100 < rollout_percent, enable.
  3. Otherwise use the default.

Hashing with the flag key gives independent rollouts per flag, and the same user stays in or out as the percentage grows. Audit every change, because flags change production behaviour without a deploy. Remove flags after full rollout so stale rules do not pile up.

Key points

  • Flags with defaults and rollout percentages
  • Ordered targeting rules
  • Stable hashing for percentage rollout
  • Cache in applications
  • Audit and retire flags

Common mistakes

  • Random per-request rollout, which flickers
  • Never deleting finished flags

Follow-ups

  • How would you run an A/B test with flags?
  • How would changes reach all servers quickly?

Tips

  • Explain stable bucketing
398.sql-0398Mediummid

How would you implement a per-user API rate limit of 100 requests per minute with a SQL table?

A fixed-window counter table keyed by (user_id, window_start) works: each request upserts the row for the current minute, incrementing the count, and is rejected if the new count exceeds 100. It is simple but allows bursts at window edges and writes once per request, so high-traffic systems usually move this to an in-memory store.

Full answer
text
rate_counts(user_id, window_start, count, PRIMARY KEY (user_id, window_start))

INSERT INTO rate_counts (user_id, window_start, count)
VALUES (:u, date_trunc('minute', now()), 1)
ON CONFLICT (user_id, window_start) DO UPDATE SET count = rate_counts.count + 1
RETURNING count;

If the returned count is above 100, reject with HTTP 429. Old windows are deleted by a periodic job.

Trade-offs:

  • Fixed windows allow up to 200 requests across a minute boundary. A sliding window (weighting the previous minute's count) or a token bucket smooths this.
  • Every request is a write, and a busy user's row becomes a hot row.
  • In-memory stores with atomic increments and expiry suit this better at scale, with the database kept for long-term quotas such as monthly limits.

The upsert pattern itself is the same as in other counter items in this bank and was not run here with date_trunc.

Key points

  • Upsert a counter per user and window
  • Reject when the count passes the limit
  • Fixed windows allow edge bursts
  • Every request writes
  • In-memory stores suit high traffic

Common mistakes

  • Counting rows in a request log on every call
  • Never cleaning up old windows

Follow-ups

  • How does a token bucket work?
  • How would you enforce a monthly quota?

Tips

  • Mention the boundary burst
399.sql-0399Easyfresher

Design tables for product reviews with star ratings and a fast average rating on product pages.

Store reviews with product, customer, rating (CHECK between 1 and 5), text and status, with a unique (product_id, customer_id) for one review per customer. Keep rating_count and rating_sum on the product (or a summary table), updated in the same transaction as review changes, so pages read the average without scanning reviews.

Full answer
text
reviews(id, product_id, customer_id, rating INT CHECK (rating BETWEEN 1 AND 5),
        body, status CHECK IN ('pending','published','rejected'), created_at,
        UNIQUE (product_id, customer_id))
product_rating_summary(product_id PK, rating_count, rating_sum)

Average = rating_sum * 1.0 / NULLIF(rating_count, 0). Storing sum and count rather than the average itself lets each change adjust the totals exactly.

Rules to decide:

  • Only published reviews count; moderation changes must update the summary.
  • Editing a rating subtracts the old value and adds the new one.
  • A periodic job recomputes summaries from reviews to correct any drift.
  • For sorting by quality, a Bayesian average (pulling products with few reviews towards the site mean) avoids a single 5-star review topping the list.

Index reviews(product_id, status, created_at DESC) for the review list on the product page.

Key points

  • Rating CHECK 1 to 5
  • One review per customer per product
  • Cache sum and count, not the average
  • Recompute periodically
  • Bayesian average for ranking

Common mistakes

  • Computing AVG over all reviews on every page view
  • Counting unmoderated reviews

Follow-ups

  • How would you show the rating distribution?
  • How would you detect fake reviews?

Tips

  • Explain sum and count over a stored average
400.sql-0400Easyfresher

Design storage for in-app notifications with read and unread state.

Store one row per recipient with type, payload, created_at and read_at (NULL while unread). A partial index on (user_id, created_at) WHERE read_at IS NULL makes the unread badge and list fast. Group repetitive events (ten likes) into one notification, and delete or archive old rows on a schedule.

Full answer
text
notifications(id, user_id, kind, actor_id, object_type, object_id, payload jsonb,
              created_at, read_at, group_key)
CREATE INDEX ON notifications (user_id, created_at DESC);
CREATE INDEX ON notifications (user_id) WHERE read_at IS NULL;
  • Unread badge: SELECT COUNT(*) FROM notifications WHERE user_id = :u AND read_at IS NULL, served by the partial index.
  • Mark all as read: UPDATE ... SET read_at = now() WHERE user_id = :u AND read_at IS NULL.
  • Grouping: a group_key such as 'like:post:42' lets the writer update an existing unread row ('Asha and 9 others liked your post') instead of inserting ten.
  • Retention: keep 90 days, then delete in batches.

Delivery channels (email, push) are a separate concern, usually a queue with per-user preferences in their own table.

Key points

  • One row per recipient
  • read_at NULL means unread
  • Partial index for unread counts
  • Group repetitive events
  • Apply retention

Common mistakes

  • A separate read-receipts table joined on every badge request
  • Keeping notifications forever

Follow-ups

  • How would you add per-user channel preferences?
  • How would you send a notification to a million users?

Tips

  • Show the unread query