← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 23 of 26

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

Page 23 of 26

Questions 441–460 of 501 · 0 of 20 on this page marked learned

441.sql-0441Mediummid

The application sends a query with 50,000 ids in an IN list. It is slow and sometimes fails. What would you do instead?

Very large IN lists bloat the SQL text, slow parsing and planning, and can hit parameter limits (SQLite allows 32,766 parameters by default in recent versions). Load the ids into a temporary table and join, pass them as one array parameter in PostgreSQL (= ANY($1)), or better, express the selection as a query so the ids never leave the database.

Full answer

Alternatives:

  • Temporary table: insert ids in batches into tmp_ids(id PRIMARY KEY), then SELECT ... FROM items JOIN tmp_ids USING (id). The planner sees a real table with statistics.
  • Array parameter (PostgreSQL): WHERE id = ANY($1::bigint[]) sends one parameter regardless of length and keeps one cached plan.
  • JSON parameter: json_each(?) in SQLite or jsonb_array_elements in PostgreSQL turns a JSON array into rows.
  • Push the logic down: if the ids came from another query, use that query as a subquery or join instead of round-tripping ids through the application.
  • Batching: split into chunks of a few hundred when nothing else is possible.

The parameter limit for SQLite is SQLITE_MAX_VARIABLE_NUMBER, 32,766 by default since 3.32; older builds used 999. These limits are stated from documentation and were not run here.

Key points

  • Huge IN lists slow parsing and hit limits
  • Temp tables give real joins
  • Array parameters keep one plan
  • JSON arrays can become rows
  • Avoid round-tripping ids

Common mistakes

  • Concatenating ids into SQL text
  • Assuming no parameter limit exists

Follow-ups

  • How does json_each work in SQLite?
  • When is batching acceptable?

Tips

  • Prefer moving the logic into SQL
442.sql-0442Hardsenior

A finance report reads several tables and must reflect one consistent moment, while orders keep arriving. How do you guarantee that?

Run all the report's queries in one transaction at REPEATABLE READ (PostgreSQL) or inside one read transaction in SQLite WAL mode, so every query sees the same snapshot. Under READ COMMITTED, each statement sees a new snapshot, and totals across tables can disagree. A defined cut-off timestamp is still needed for business meaning.

Full answer

The problem under READ COMMITTED (PostgreSQL's default): query 1 sums orders, an order commits, query 2 sums payments including that order's payment. The report now shows payments without the matching order.

Fix in PostgreSQL:

text
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT SUM(total) FROM orders WHERE placed_at < :cutoff;
SELECT SUM(amount) FROM payments WHERE paid_at < :cutoff;
COMMIT;

Every statement sees the snapshot taken at the first query. SERIALIZABLE READ ONLY DEFERRABLE waits for a snapshot that is guaranteed free of serialization anomalies, useful for long reports.

In SQLite with WAL, a read transaction (BEGIN followed by the first SELECT) also keeps one snapshot until it ends, while writers continue on the WAL.

Snapshots fix consistency between queries; the cut-off timestamp fixes which business events belong in the period. Long snapshots on a busy PostgreSQL primary delay vacuum, so run them on a replica or keep them short. Described here, not run.

Key points

  • READ COMMITTED gives each statement a new snapshot
  • REPEATABLE READ keeps one snapshot per transaction
  • SQLite WAL read transactions also hold a snapshot
  • Use a business cut-off as well
  • Long snapshots delay vacuum

Common mistakes

  • Running report queries in separate transactions
  • Relying on query speed to avoid inconsistency

Follow-ups

  • What does READ ONLY DEFERRABLE do?
  • How would you run this on a replica?

Tips

  • Show where totals can disagree
443.sql-0443Mediummid

A query that filters on ROW_NUMBER() in WHERE to get each department's top earner fails. Fix it.

Window functions are computed after WHERE, GROUP BY and HAVING, so they cannot appear in WHERE. Compute the row number in a subquery or CTE and filter on it in the outer query.

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 dept_id, name, salary FROM employees WHERE ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) = 1;  -- error on purpose
text
Error: misuse of window function ROW_NUMBER()

SQLite rejects the query as a misuse of the window function. WHERE decides which rows exist before any window is evaluated, so the row numbers are not available yet. PostgreSQL rejects it too, saying window functions are not allowed in WHERE (not run here).

A corrected version:

sql
SELECT dept_id, name, salary FROM (
  SELECT dept_id, name, salary, ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC, id) AS rn
  FROM employees WHERE dept_id IS NOT NULL
) WHERE rn = 1 ORDER BY dept_id;
dept_idnamesalary
1Asha120000
2Tom70000
3Diego55000

The inner query numbers rows per department; the outer query keeps the first. Asha leads Engineering, Tom leads Sales and Diego leads Support. The id tiebreaker keeps the choice stable if two people share the top salary; use RANK instead when all tied top earners should be listed. Some engines (for example DuckDB and Snowflake) offer a QUALIFY clause for this pattern, but SQLite and PostgreSQL do not.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

-- error on purpose
SELECT dept_id, name, salary FROM employees WHERE ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) = 1;

SELECT dept_id, name, salary FROM (
  SELECT dept_id, name, salary, ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC, id) AS rn
  FROM employees WHERE dept_id IS NOT NULL
) WHERE rn = 1 ORDER BY dept_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Window functions run after WHERE
  • Filter window results in an outer query
  • Add a tiebreaker or use RANK for ties

Common mistakes

  • Trying HAVING instead, which also runs before windows
  • Omitting a tiebreaker

Follow-ups

  • How would you return the top two per department?
  • What does QUALIFY do in engines that support it?

Tips

  • Recall the logical clause order
444.sql-0444Easyfresher

SELECT DISTINCT(dept_id), name returns a row for every employee instead of one per department. Why?

DISTINCT is not a function and applies to the whole select list; the parentheses around dept_id only group that expression. Since every (dept_id, name) pair is unique, nothing is removed. Select only dept_id, or aggregate the names per department.

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 DISTINCT(dept_id), name FROM employees ORDER BY dept_id, name;
dept_idname
NULLLena
1Asha
1Mei
1Ravi
2Sara
2Tom
3Diego
3Omar

The query returns all eight employees. DISTINCT(dept_id), name means DISTINCT dept_id, name: duplicates are removed only when both columns match.

A corrected version:

sql
SELECT dept_id, COUNT(*) AS staff, group_concat(name, ', ') AS names FROM employees GROUP BY dept_id ORDER BY dept_id;
dept_idstaffnames
NULL1Lena
13Asha, Ravi, Mei
22Tom, Sara
32Diego, Omar

Grouping by department gives one row each, with a count and a list of names. The order of names inside group_concat is not guaranteed unless an ORDER BY is given inside the aggregate (group_concat(name, ', ' ORDER BY name) in SQLite 3.44+). PostgreSQL's DISTINCT ON (dept_id) is the tool when one whole row per department is wanted.

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 DISTINCT(dept_id), name FROM employees ORDER BY dept_id, name;

SELECT dept_id, COUNT(*) AS staff, group_concat(name, ', ') AS names FROM employees GROUP BY dept_id ORDER BY dept_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • DISTINCT applies to the entire row
  • Parentheses do not make it per column
  • Use GROUP BY with aggregates for one row per key
  • DISTINCT ON picks one row per key in PostgreSQL

Common mistakes

  • Treating DISTINCT as a function
  • Expecting one arbitrary name per department

Follow-ups

  • How would you show the highest-paid name per department?
  • How does COUNT(DISTINCT x) differ?

Tips

  • Rewrite without the parentheses
445.sql-0445Easyfresher

A report grouped with GROUP BY 1 started grouping by the wrong column after someone reordered the select list. Explain and fix.

GROUP BY 1 refers to the first select-list column, whatever it is. When a new column was put first, the grouping silently changed. Name the grouping columns explicitly.

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 customer_id, status, COUNT(*) AS n FROM orders GROUP BY 1 ORDER BY 1;
customer_idstatusn
NULLshipped1
1shipped2
2cancelled2
3shipped1

The original query was SELECT status, customer_id, COUNT(*) ... GROUP BY 1, meant to count orders per status. With customer_id moved first, it now groups by customer, and the status column shows a value from an arbitrary row of each group, which SQLite allows without warning.

A corrected version:

sql
SELECT status, COUNT(*) AS n FROM orders GROUP BY status ORDER BY status;
statusn
cancelled1
pending1
shipped4

Naming status makes the intent survive edits, and dropping the ungrouped customer_id removes the arbitrary value. PostgreSQL would have rejected the broken version, because status was neither grouped nor aggregated (not run here). Ordinals are handy in quick exploration but risky in saved reports.

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, status, COUNT(*) AS n FROM orders GROUP BY 1 ORDER BY 1;

SELECT status, COUNT(*) AS n FROM orders GROUP BY status ORDER BY status;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Ordinals depend on select-list order
  • Name grouping columns in saved queries
  • SQLite allows ungrouped bare columns silently

Common mistakes

  • Reordering columns without checking ordinals
  • Trusting bare columns in grouped queries

Follow-ups

  • Is ORDER BY 1 equally risky?
  • How would a linter catch this?

Tips

  • Point to the moved column
446.sql-0446Easyfresher

Building a full name with 'first' + ' ' + 'last' returns 0 in SQLite. What went wrong?

In SQLite (and standard SQL), + is numeric addition, so the strings are converted to numbers, which are 0 for non-numeric text. Use the || operator, or concat() in PostgreSQL and SQLite 3.44+, which also treats NULL as an empty string.

Full answer
sql
CREATE TABLE people (first TEXT, last TEXT);
INSERT INTO people VALUES ('Asha', 'Rao'), ('Ben', NULL);

The query as written:

sql
SELECT first + ' ' + last AS full_name FROM people;
full_name
0
NULL

Asha's row shows 0 because each piece is converted to a number, and 'Asha', ' ' and 'Rao' all convert to 0. Ben's row is NULL, because arithmetic with his NULL last name gives NULL. The habit comes from SQL Server, where + concatenates strings.

A corrected version:

sql
SELECT first || ' ' || last AS with_pipes, concat(first, ' ', last) AS with_concat, trim(first || ' ' || COALESCE(last, '')) AS safe FROM people;
with_pipeswith_concatsafe
Asha RaoAsha RaoAsha Rao
NULLBenBen

|| gives 'Asha Rao' but NULL for Ben, because concatenating NULL yields NULL. concat() skips NULL arguments, giving 'Ben ' with a trailing space, and the COALESCE plus trim version returns a clean 'Ben'. concat_ws(' ', first, last) is another option that skips NULLs and separators together.

sql
CREATE TABLE people (first TEXT, last TEXT);
INSERT INTO people VALUES ('Asha', 'Rao'), ('Ben', NULL);

SELECT first + ' ' + last AS full_name FROM people;

SELECT first || ' ' || last AS with_pipes, concat(first, ' ', last) AS with_concat, trim(first || ' ' || COALESCE(last, '')) AS safe FROM people;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • + is addition in SQLite and PostgreSQL
  • Use || or concat() for strings
  • || with NULL gives NULL
  • concat and concat_ws skip NULLs

Common mistakes

  • Carrying SQL Server habits to other engines
  • Forgetting NULL parts of names

Follow-ups

  • How does concat_ws handle separators?
  • What does PostgreSQL do with 'a' + 'b'?

Tips

  • Name the operator for each engine
447.sql-0447Mediummid

Dates stored as '2026-9-5' and '2026-10-01' sort in the wrong order. Fix the data and the query.

Without zero padding, text comparison puts '2026-10-01' before '2026-9-5' because '1' sorts before '9'. Normalise the values to ISO 'YYYY-MM-DD' with zero padding (for example with printf and string splitting), then store only that format, checked by a CHECK constraint.

Full answer
sql
CREATE TABLE visits (id INTEGER PRIMARY KEY, d TEXT);
INSERT INTO visits VALUES (1, '2026-9-5'), (2, '2026-10-01'), (3, '2026-9-28'), (4, '2026-11-2');

The query as written:

sql
SELECT id, d FROM visits ORDER BY d;
idd
22026-10-01
42026-11-2
32026-9-28
12026-9-5

Text sorts character by character: after '2026-', the '1' of October and November comes before the '9' of September, so the months appear out of order. Date functions also fail on such values: date('2026-9-5') returns NULL because SQLite's date functions require two-digit months and days.

A corrected version:

sql
UPDATE visits SET d = printf('%04d-%02d-%02d',
  CAST(substr(d, 1, 4) AS INTEGER),
  CAST(substr(d, 6, instr(substr(d, 6), '-') - 1) AS INTEGER),
  CAST(substr(substr(d, 6), instr(substr(d, 6), '-') + 1) AS INTEGER));
SELECT id, d, date(d) AS parsed FROM visits ORDER BY d;
iddparsed
12026-09-052026-09-05
32026-09-282026-09-28
22026-10-012026-10-01
42026-11-022026-11-02

The UPDATE splits each value at the dashes and rebuilds it with zero padding, so sorting and date() both work, as the parsed column confirms. Adding CHECK (d = date(d)) to the table rejects badly formatted values in future, since date() returns NULL or a different string for them.

sql
CREATE TABLE visits (id INTEGER PRIMARY KEY, d TEXT);
INSERT INTO visits VALUES (1, '2026-9-5'), (2, '2026-10-01'), (3, '2026-9-28'), (4, '2026-11-2');

SELECT id, d FROM visits ORDER BY d;

UPDATE visits SET d = printf('%04d-%02d-%02d',
  CAST(substr(d, 1, 4) AS INTEGER),
  CAST(substr(d, 6, instr(substr(d, 6), '-') - 1) AS INTEGER),
  CAST(substr(substr(d, 6), instr(substr(d, 6), '-') + 1) AS INTEGER));
SELECT id, d, date(d) AS parsed FROM visits ORDER BY d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Unpadded dates sort wrongly as text
  • SQLite date functions need ISO format
  • Normalise with printf
  • CHECK (d = date(d)) enforces the format

Common mistakes

  • Sorting by a date stored in local formats
  • Fixing only the query and leaving bad data

Follow-ups

  • How would you parse DD/MM/YYYY values?
  • Why does ISO format sort correctly?

Tips

  • Show why '1' sorts before '9'
448.sql-0448Easyfresher

An archive copy shows customers' names in the country column and the other way round. Find the bug in the INSERT ... SELECT.

INSERT ... SELECT matches columns by position, not by name. The target list named (name, country) but the SELECT produced country first, so values went into the wrong columns. List the same columns in the same order on both sides.

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 customers_archive (id INTEGER PRIMARY KEY, name TEXT, country TEXT);
CREATE TABLE customers_archive2 (id INTEGER PRIMARY KEY, name TEXT, country TEXT);

The query as written:

sql
INSERT INTO customers_archive (id, name, country) SELECT id, country, name FROM customers;
SELECT * FROM customers_archive ORDER BY id;
idnamecountry
1SpainAna
2UAEBilal
3FranceChloe
4IndiaDev

Every row has the country where the name should be. Both columns are TEXT, so no type error warned about the mismatch; with different types, SQLite's flexible typing would often still accept the data.

A corrected version:

sql
INSERT INTO customers_archive2 (id, name, country) SELECT id, name, country FROM customers;
SELECT * FROM customers_archive2 ORDER BY id;
idnamecountry
1AnaSpain
2BilalUAE
3ChloeFrance
4DevIndia

With matching order, the copy is correct. Writing the column lists on both sides, one per line and aligned, makes such swaps easy to spot in review, and a quick check such as comparing a few rows between source and target after each load catches them early.

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 customers_archive (id INTEGER PRIMARY KEY, name TEXT, country TEXT);
CREATE TABLE customers_archive2 (id INTEGER PRIMARY KEY, name TEXT, country TEXT);

INSERT INTO customers_archive (id, name, country) SELECT id, country, name FROM customers;
SELECT * FROM customers_archive ORDER BY id;

INSERT INTO customers_archive2 (id, name, country) SELECT id, name, country FROM customers;
SELECT * FROM customers_archive2 ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • INSERT ... SELECT maps by position
  • Always list target columns
  • Match the select order exactly
  • Same types hide swaps

Common mistakes

  • Relying on names to match automatically
  • INSERT INTO t SELECT * after schema changes

Follow-ups

  • Why is INSERT INTO t SELECT * risky?
  • How would you verify an archive copy?

Tips

  • Line up both column lists
449.sql-0449Mediummid

Total order value per customer uses SUM(DISTINCT qty * unit_price) to avoid double counting, and now some totals are too low. Why?

SUM(DISTINCT ...) removes equal values, not duplicate rows, so two genuinely different order lines with the same value are counted once. The real fix for double counting is to aggregate before joining, so each line is summed exactly once.

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);
INSERT INTO order_items VALUES (102, 'Pen', 30, 1);

The query as written:

sql
SELECT o.customer_id, SUM(DISTINCT oi.qty * oi.unit_price) AS total FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.customer_id = 1 GROUP BY o.customer_id;
customer_idtotal
143

Ana's lines are worth 8, 5, 30 and, after the added line of 30 pens, another 30. DISTINCT drops the second 30, so the total is 43 instead of 73.

A corrected version:

sql
SELECT o.customer_id, SUM(t.order_total) AS total FROM orders o
JOIN (SELECT order_id, SUM(qty * unit_price) AS order_total FROM order_items GROUP BY order_id) t ON t.order_id = o.id
WHERE o.customer_id = 1 GROUP BY o.customer_id;
customer_idtotal
173

Summing lines per order first and then per customer counts every line once, giving 73. When the original double counting came from joining a second one-to-many table (such as payments), pre-aggregate each child table separately and join the summaries. SUM(DISTINCT) is almost never correct for money.

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);
INSERT INTO order_items VALUES (102, 'Pen', 30, 1);

SELECT o.customer_id, SUM(DISTINCT oi.qty * oi.unit_price) AS total FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.customer_id = 1 GROUP BY o.customer_id;

SELECT o.customer_id, SUM(t.order_total) AS total FROM orders o
JOIN (SELECT order_id, SUM(qty * unit_price) AS order_total FROM order_items GROUP BY order_id) t ON t.order_id = o.id
WHERE o.customer_id = 1 GROUP BY o.customer_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SUM(DISTINCT) removes equal values
  • Equal amounts are often legitimate
  • Pre-aggregate to avoid fan-out
  • Join summaries, not raw child rows

Common mistakes

  • Using DISTINCT to hide join duplication
  • Testing only with data where all values differ

Follow-ups

  • How would you sum order items and payments per customer in one query?
  • When is SUM(DISTINCT) correct?

Tips

  • Separate duplicate rows from equal values
450.sql-0450Hardsenior

A query listing each department with 'its' employee name works in SQLite but fails in PostgreSQL. Explain the difference.

A scalar subquery must return at most one row. SQLite silently uses the first row when several are returned, while PostgreSQL raises 'more than one row returned by a subquery used as an expression'. Decide which single value is wanted and make the subquery return exactly that, for example with ORDER BY and LIMIT 1 or an aggregate.

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 d.name, (SELECT e.name FROM employees e WHERE e.dept_id = d.id) AS employee FROM departments d ORDER BY d.id;
nameemployee
EngineeringAsha
SalesTom
SupportDiego
LegalNULL

Engineering has three employees, but SQLite returns one of them without any warning, and which one is not defined. Legal has none, so it shows NULL. PostgreSQL stops instead:

sql
SELECT d.name, (SELECT e.name FROM employees e WHERE e.dept_id = d.id) AS employee FROM departments d ORDER BY d.id;  -- error on purpose
text
Error: more than one row returned by a subquery used as an expression

A corrected version:

sql
SELECT d.name, (SELECT e.name FROM employees e WHERE e.dept_id = d.id ORDER BY e.salary DESC, e.id LIMIT 1) AS top_earner FROM departments d ORDER BY d.id;
nametop_earner
EngineeringAsha
SalesTom
SupportDiego
LegalNULL

Ordering inside the subquery and taking one row makes the intent explicit: the top earner per department. The same corrected query succeeds in PostgreSQL:

sql
SELECT d.name, (SELECT e.name FROM employees e WHERE e.dept_id = d.id ORDER BY e.salary DESC, e.id LIMIT 1) AS top_earner FROM departments d ORDER BY d.id;
nametop_earner
EngineeringAsha
SalesTom
SupportDiego
LegalNULL

When all names are wanted, aggregate them instead (group_concat in SQLite, string_agg in PostgreSQL).

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 d.name, (SELECT e.name FROM employees e WHERE e.dept_id = d.id) AS employee FROM departments d ORDER BY d.id;

SELECT d.name, (SELECT e.name FROM employees e WHERE e.dept_id = d.id ORDER BY e.salary DESC, e.id LIMIT 1) AS top_earner FROM departments d ORDER BY d.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

  • Scalar subqueries must return one row
  • SQLite takes the first row silently
  • PostgreSQL raises an error
  • Make the choice explicit with ORDER BY and LIMIT 1

Common mistakes

  • Relying on SQLite's silent first row
  • Using LIMIT 1 without ORDER BY

Follow-ups

  • How would you list all employees per department in one column?
  • How would a LATERAL join express this?

Tips

  • Contrast the engines
451.sql-0451Easyfresher

A filter salary BETWEEN 100000 AND 60000 returns no rows. What is wrong?

BETWEEN a AND b means value >= a AND value <= b, so the lower bound must come first. With the bounds reversed, no value can satisfy both conditions. Swap them, or compute the bounds with min() and max() when they come from user input.

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 name, salary FROM employees WHERE salary BETWEEN 100000 AND 60000;
namesalary

(0 rows)

No salary is both at least 100000 and at most 60000, so the result is empty and no error is raised. Range filters built from two user-entered values hit this whenever the user enters them in the other order.

A corrected version:

sql
SELECT name, salary FROM employees WHERE salary BETWEEN 60000 AND 100000 ORDER BY salary DESC;
namesalary
Ravi95000
Mei95000
Tom70000
Sara62000

With the bounds in order, Ravi, Mei, Tom and Sara are returned. For user input, BETWEEN min(:a, :b) AND max(:a, :b) (SQLite's scalar min and max) or LEAST and GREATEST in PostgreSQL protect against reversed values. PostgreSQL also offers BETWEEN SYMMETRIC, which accepts bounds in either order (not run here).

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 name, salary FROM employees WHERE salary BETWEEN 100000 AND 60000;

SELECT name, salary FROM employees WHERE salary BETWEEN 60000 AND 100000 ORDER BY salary DESC;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • BETWEEN needs low then high
  • Reversed bounds silently return nothing
  • Normalise user bounds with min and max
  • PostgreSQL has BETWEEN SYMMETRIC

Common mistakes

  • Passing user-entered bounds unchecked
  • Assuming BETWEEN is order-independent

Follow-ups

  • Is BETWEEN inclusive at both ends?
  • How would you write an exclusive upper bound?

Tips

  • Expand BETWEEN into two comparisons
452.sql-0452Hardsenior

An order service must save an order and publish an 'order placed' event to a message broker. How do you avoid saving without publishing, or publishing without saving?

Use the transactional outbox pattern: in the same database transaction as the order, insert the event into an outbox table. A separate relay process reads unsent outbox rows, publishes them to the broker and marks them sent. Since the order and the event commit together, neither can exist without the other; consumers must handle the occasional duplicate delivery.

Full answer
text
outbox(id bigserial PK, aggregate_type, aggregate_id, event_type, payload jsonb,
       created_at, published_at NULL)
CREATE INDEX ON outbox (id) WHERE published_at IS NULL;

Flow:

  1. BEGIN; INSERT INTO orders ...; INSERT INTO outbox (... 'OrderPlaced' ...); COMMIT;
  2. The relay polls WHERE published_at IS NULL ORDER BY id LIMIT 100 (with FOR UPDATE SKIP LOCKED if several relays run), publishes, then sets published_at.
  3. If the relay crashes after publishing but before marking, the event is published again on restart, so delivery is at least once. Consumers deduplicate by event id.

Why not publish directly from the service: the commit can succeed and the publish fail (lost event), or the publish succeed and the commit roll back (event about an order that does not exist). Two-phase commit across the database and broker is possible in theory but rarely supported or worth its cost.

Change data capture on the outbox table (reading the write-ahead log) is an alternative to polling.

Key points

  • Write the event in the same transaction
  • A relay publishes and marks rows
  • Delivery is at least once
  • Consumers deduplicate by event id
  • CDC can replace polling

Common mistakes

  • Publishing to the broker inside the transaction
  • Assuming exactly-once delivery

Follow-ups

  • How would you keep events in order per order id?
  • How would you clean up old outbox rows?

Tips

  • Explain both failure modes it prevents
453.sql-0453Mediummid

What is optimistic concurrency control, and how does it compare with locking rows up front?

Optimistic control lets transactions proceed without locks and checks at write time that the row has not changed, typically with a version column in the UPDATE's WHERE clause; zero rows updated means a conflict to retry or report. Pessimistic control locks rows first (SELECT ... FOR UPDATE), making others wait. Optimistic suits low-conflict, user-facing edits; pessimistic suits short, high-conflict updates.

Full answer

Optimistic, with a version column:

text
SELECT id, title, version FROM docs WHERE id = 7;        -- version = 3
UPDATE docs SET title = :t, version = version + 1 WHERE id = 7 AND version = 3;

If another user saved first, version is now 4, the UPDATE affects 0 rows, and the app shows 'this document changed, reload'. No locks are held while the user edits for minutes.

Pessimistic:

text
BEGIN; SELECT ... FROM accounts WHERE id = 7 FOR UPDATE; UPDATE ...; COMMIT;

Others wanting the row wait until commit. Good for short operations with frequent contention, such as decrementing stock, but holding locks across user think-time blocks everyone.

Trade-offs: optimistic control wastes work on conflict (retries), pessimistic control risks waits and deadlocks. Many systems use both: optimistic for forms, atomic updates or short locks for counters and balances.

Key points

  • Optimistic checks a version at write time
  • Zero rows updated signals a conflict
  • Pessimistic locks rows before changing them
  • Optimistic suits long user edits
  • Pessimistic suits short contended updates

Common mistakes

  • Holding row locks while a user edits a form
  • Ignoring the affected row count in optimistic updates

Follow-ups

  • Can a timestamp replace a version number?
  • How do ORMs implement optimistic locking?

Tips

  • Show the version check
454.sql-0454Hardsenior

What is CQRS, and when would a team keep separate read models in SQL?

Command Query Responsibility Segregation separates the model that handles writes (normalised, enforcing rules) from models optimised for reads (denormalised tables or views shaped for specific screens). Read models are updated from the write side, often asynchronously via events, so they may lag. It helps when read and write needs differ greatly, and adds complexity otherwise.

Full answer

Example: an order system writes to normalised orders, order_lines and payments. A dashboard needs 'orders with customer name, item count, paid amount and last status change', filtered and sorted many ways.

Read model:

text
order_summaries(order_id PK, customer_name, item_count, total_minor, paid_minor,
                status, last_change_at)   -- indexed for the dashboard's filters

Updated by:

  • triggers or the same transaction (synchronous, simpler, consistent), or
  • events from an outbox consumed by a projector (asynchronous, scales out, eventually consistent).

When it pays off: very different read and write volumes, many specialised screens, or reads served from a different store (search engine, cache). When it does not: simple CRUD apps, where a view or a few indexes on the normalised tables are enough.

Rebuilding a read model from the source data (or event log) must be possible, since projections can have bugs.

Key points

  • Separate write and read models
  • Read models are denormalised for screens
  • Updates can be synchronous or event-driven
  • Asynchronous read models lag
  • Must be rebuildable

Common mistakes

  • Applying CQRS to simple CRUD
  • Read models that cannot be rebuilt

Follow-ups

  • How does CQRS relate to materialized views?
  • How would you handle read-your-writes with an async read model?

Tips

  • State when it is not worth it
455.sql-0455Hardsenior

How does event sourcing store data, and what are its costs?

Event sourcing stores every change as an immutable event (AccountOpened, MoneyDeposited) in an append-only log, and derives current state by replaying events, usually into snapshot or read-model tables. It gives a complete history and easy audit, but queries on current state need projections, event schemas must be versioned, and correcting mistakes means appending compensating events.

Full answer
text
events(stream_id, version, type, payload jsonb, recorded_at,
       PRIMARY KEY (stream_id, version))

Appending with optimistic concurrency: INSERT ... (stream_id, version) VALUES (:acct, :expected + 1); the primary key rejects a concurrent writer who read the same version.

Current balance: replay the stream's events, or read a projection table updated as events are appended. Snapshots every N events speed up replays for long streams.

Benefits:

  • Full history and 'state as of any time'.
  • New read models can be built later from old events.
  • Natural fit for audit-heavy domains (finance, logistics).

Costs:

  • Two models to maintain (events and projections).
  • Event schema evolution: old events must remain readable forever, with upcasters.
  • Deleting personal data conflicts with immutability; crypto-shredding (deleting per-user keys) is one workaround.
  • Simple questions become projection work.

Many teams use an audit log or outbox instead, keeping state tables as the source of truth.

Key points

  • Events are the source of truth
  • State comes from replays or projections
  • Version keys give optimistic concurrency
  • Schema evolution is a lasting cost
  • Privacy deletion is hard

Common mistakes

  • Choosing event sourcing for simple CRUD
  • Editing past events

Follow-ups

  • How would you rebuild a projection?
  • How does an audit log differ from event sourcing?

Tips

  • Weigh history against complexity
456.sql-0456Mediummid

In a microservices system, should each service have its own database? What problems follow?

Giving each service its own database (or schema with exclusive access) keeps services independently deployable and stops hidden coupling through shared tables. The cost is that joins and transactions across services disappear: data is combined through APIs, events or read replicas, and multi-service changes need sagas with compensating actions instead of one ACID transaction.

Full answer

Benefits:

  • A service can change its schema without coordinating with others.
  • Each can choose a fitting store and scale independently.
  • Ownership is clear.

Problems and common answers:

  • Cross-service queries ('orders with customer names'): keep a local copy of the needed customer fields updated from events, or compose in an API layer.
  • Multi-step business processes (reserve stock, charge card, create shipment): a saga runs each step as a local transaction and, on failure, runs compensating steps (release stock, refund).
  • Reporting: stream all services' changes into a warehouse.
  • Consistency: data is eventually consistent; screens must tolerate brief disagreement.

A shared database used by several services is simpler at first but becomes a coupling point where one team's migration can break others. A pragmatic middle path is one database server with a schema per service and no cross-schema access.

Key points

  • Own database per service for independence
  • No cross-service joins or transactions
  • Local copies via events for queries
  • Sagas with compensation for workflows
  • Warehouses for cross-service reporting

Common mistakes

  • Services reading each other's tables
  • Expecting ACID across services

Follow-ups

  • How does a saga handle a failed payment?
  • When is a shared database acceptable?

Tips

  • Name the lost capabilities
457.sql-0457Mediummid

How would you add a cache in front of the database for product pages, and keep it correct when products change?

Use cache-aside: read from the cache, and on a miss read the database and store the result with a time-to-live. On updates, write to the database first, then delete the cache key so the next read reloads it. Short TTLs bound staleness, and versioned keys or change events help when many keys depend on one row.

Full answer

Read path: GET product:42 → miss → SELECT ... FROM products WHERE id = 42 → SET product:42 <json> EX 300.

Write path: UPDATE products ... ; COMMIT; then DEL product:42.

Pitfalls:

  • Delete after commit, not before: deleting first lets a concurrent reader repopulate the cache with the old value before the commit.
  • Even after commit, a slow reader that fetched the old row just before the update can write it to the cache after the delete. A short TTL limits how long that stale value lives; a delayed second delete narrows the window further.
  • Derived pages (category lists containing the product) need their own invalidation, often through events from an outbox or change data capture.
  • Stampedes: when a hot key expires, many requests hit the database at once; use a lock or early refresh.

Cache what is read often and changes rarely. For prices and stock, keep TTLs short or read from the database directly.

Key points

  • Cache-aside with TTL
  • Write the database, then delete the key
  • Races can still leave stale entries briefly
  • Invalidate derived keys via events
  • Guard against stampedes

Common mistakes

  • Updating the cache and database in the wrong order
  • Caching volatile values like stock with long TTLs

Follow-ups

  • What is write-through caching?
  • How would you warm the cache after a deploy?

Tips

  • Explain the order of operations on write
458.sql-0458Mediummid

A table holds ten years of orders, but almost all queries touch the last year. How would you handle the old data?

Separate hot and cold data: partition by date so recent partitions stay small and old ones can be moved, compressed or detached, or move old rows into an archive table or cheaper storage on a schedule. Keep the archive queryable when needed (a view over both, or a warehouse), and agree retention rules with the business and legal teams.

Full answer

Approaches:

  • Time partitioning: queries filtered by date prune old partitions; old partitions can sit on cheaper tablespaces or be detached and exported.
  • Archive tables: a monthly job moves rows older than N years into orders_archive in batches, inside transactions, with matching child rows (order lines, payments).
  • External storage: export old data to files in object storage or a warehouse, then delete it from the operational database.
  • Union view: CREATE VIEW all_orders AS SELECT ... FROM orders UNION ALL SELECT ... FROM orders_archive for occasional full-history reports.

Also consider:

  • Foreign keys: archiving parents requires archiving children together.
  • Indexes on the hot table shrink, which helps cache hit rates.
  • Retention law: tax records may need to be kept for a fixed number of years, while personal data may need to be removed sooner.

The goal is that daily operations only pay for the data they use.

Key points

  • Separate hot and cold data
  • Partition by time for pruning
  • Move old rows with their children
  • Keep archives queryable if needed
  • Follow retention rules

Common mistakes

  • Keeping everything in one ever-growing table without a plan
  • Archiving parents without children

Follow-ups

  • How would you restore an archived order on request?
  • How do partitions help with archiving?

Tips

  • Tie the approach to query patterns
459.sql-0459Easyfresher

Design storage for product names and descriptions in several languages.

Keep language-neutral fields (price, SKU) on products, and put translatable text in product_translations(product_id, locale, name, description) with a primary key on (product_id, locale). Queries join on the requested locale with a fallback to a default language via LEFT JOIN and COALESCE.

Full answer
text
products(id PK, sku, price_minor)
product_translations(product_id FK, locale TEXT, name, description,
                     PRIMARY KEY (product_id, locale))

Reading in Hindi with English fallback:

text
SELECT p.id, COALESCE(hi.name, en.name) AS name
FROM products p
LEFT JOIN product_translations hi ON hi.product_id = p.id AND hi.locale = 'hi'
LEFT JOIN product_translations en ON en.product_id = p.id AND en.locale = 'en';

Alternatives:

  • Columns per language (name_en, name_hi) are simple for two fixed languages but need schema changes for each new one.
  • A JSON column ({"en": "...", "hi": "..."}) is compact but harder to constrain and index per language.

Search across languages may need per-language full-text configurations. Locale codes should follow a standard (BCP 47, such as 'en', 'hi', 'pt-BR'). The queries are illustrative and were not run here.

Key points

  • Translations table keyed by entity and locale
  • Fallback via LEFT JOIN and COALESCE
  • Columns per language do not scale
  • JSON is compact but harder to constrain
  • Use standard locale codes

Common mistakes

  • Duplicating whole product rows per language
  • No fallback for missing translations

Follow-ups

  • How would you find products missing a translation?
  • How would full-text search work per language?

Tips

  • Show the fallback join
460.sql-0460Mediummid

How would you design a tagging feature where items can have many tags and users filter by several tags?

Use tags(id, name UNIQUE) and a junction table item_tags(item_id, tag_id) with a composite primary key and an index on (tag_id, item_id). 'Has any of these tags' is a join with IN; 'has all of these tags' is relational division, grouping by item and requiring COUNT(DISTINCT tag) to equal the number of tags requested.

Full answer
text
tags(id PK, name UNIQUE)            -- normalise case: store lower(name)
item_tags(item_id FK, tag_id FK, PRIMARY KEY (item_id, tag_id))
CREATE INDEX ON item_tags (tag_id, item_id);

Items with all of 'sql', 'joins' and 'beginner':

text
SELECT it.item_id FROM item_tags it JOIN tags t ON t.id = it.tag_id
WHERE t.name IN ('sql', 'joins', 'beginner')
GROUP BY it.item_id HAVING COUNT(DISTINCT t.id) = 3;

Tag counts for a tag cloud come from GROUP BY tag_id and can be cached. Alternatives such as a comma-separated string or an array column (PostgreSQL text[] with a GIN index) are compact, but the junction table supports constraints, renames and statistics cleanly. Renaming a tag is then a single-row update. The all-tags query is shown for illustration and was not run here; COUNT(DISTINCT) matters because a tag listed twice in the IN list or duplicated in data would otherwise inflate the count.

Key points

  • Tags plus a junction table
  • Index both directions
  • Any-of is a join with IN
  • All-of is GROUP BY with HAVING COUNT
  • Normalise tag case

Common mistakes

  • Comma-separated tag strings
  • Forgetting DISTINCT in the HAVING count

Follow-ups

  • How would you suggest related tags?
  • When is an array column acceptable?

Tips

  • Show the all-tags query