Questions 421–440 of 501 · 0 of 20 on this page marked learned
421.sql-0421Mediummid
For each month, count customers whose first order was in that month, and show the cumulative total.
First find each customer's first order month with MIN(order_date) grouped by customer. Then count customers per first month and add a running SUM over the months for the cumulative customer base.
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
WITH firsts AS (
SELECT customer_id, strftime('%Y-%m', MIN(order_date)) AS first_month FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id
)
SELECT first_month, COUNT(*) AS new_customers, SUM(COUNT(*)) OVER (ORDER BY first_month) AS cumulative
FROM firsts GROUP BY first_month ORDER BY first_month;
first_month
new_customers
cumulative
2026-01
1
1
2026-02
1
2
2026-03
1
3
Ana first ordered in January, Bilal in February and Chloe in March, so each month gains one new customer and the running total climbs 1, 2, 3. The window SUM(COUNT(*)) OVER (...) runs after grouping, summing the per-month counts. Months with no new customers would be missing; join to a month calendar when the chart needs every month. Excluding orders without a customer keeps the anonymous order 106 from counting as a customer.
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);
WITH firsts AS (
SELECT customer_id, strftime('%Y-%m', MIN(order_date)) AS first_month FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id
)
SELECT first_month, COUNT(*) AS new_customers, SUM(COUNT(*)) OVER (ORDER BY first_month) AS cumulative
FROM firsts GROUP BY first_month ORDER BY first_month;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Find first purchase per customer first
Count by first month
Window over grouped results for cumulative totals
Use a calendar for empty months
Common mistakes
Counting distinct customers per month, which repeats returning customers
Including orders with no customer
Follow-ups
How would you count returning customers per month?
How would you add revenue from new customers?
Tips
Separate first purchase from later orders
422.sql-0422Mediummid
Show monthly revenue with the change from the previous month as a percentage.
Aggregate revenue per month first, then use LAG over the months to fetch the previous value and compute 100.0 * (current - previous) / previous, guarding against division by zero with NULLIF. The first month has no previous value and shows NULL.
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
WITH monthly AS (
SELECT strftime('%Y-%m', o.order_date) AS month, SUM(oi.qty * oi.unit_price) AS revenue
FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.status = 'shipped' GROUP BY month
)
SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly ORDER BY month;
month
revenue
prev
pct_change
2026-01
13
NULL
NULL
2026-02
30
13
130.8
2026-03
44
30
46.7
Shipped revenue is 13 in January, 30 in February and 44 in March (order 104 plus the 2-unit pen order 106). February grew by about 130.8 percent and March by about 46.7 percent over the month before. Aggregating in a CTE first matters, because LAG must compare month totals, not individual order lines. A named window (WINDOW w AS (ORDER BY month)) avoids repeating the OVER clause, and a calendar join is needed if a month can have no sales at all.
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);
WITH monthly AS (
SELECT strftime('%Y-%m', o.order_date) AS month, SUM(oi.qty * oi.unit_price) AS revenue
FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.status = 'shipped' GROUP BY month
)
SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly ORDER BY month;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Aggregate first, then LAG
NULLIF guards division by zero
First month has no previous value
Named windows reduce repetition
Common mistakes
Applying LAG to raw rows before aggregating
Integer division in the percentage
Follow-ups
How would you compute year-over-year change?
How would you handle months with no sales?
Tips
Aggregate before comparing
423.sql-0423Mediummid
Find the missing invoice numbers in a sequence.
Use LEAD to pair each number with the next existing one; wherever the next number is more than one higher, the numbers in between are missing. Report each gap as a range from current + 1 to next - 1.
Full answer
sql
CREATE TABLE invoices (no INTEGER PRIMARY KEY);
INSERT INTO invoices VALUES (1), (2), (3), (6), (7), (9), (12);
sql
SELECT no + 1 AS gap_start, next_no - 1 AS gap_end FROM (
SELECT no, LEAD(no) OVER (ORDER BY no) AS next_no FROM invoices
) WHERE next_no - no > 1 ORDER BY gap_start;
gap_start
gap_end
4
5
8
8
10
11
Three gaps appear: 4 to 5, 8 on its own, and 10 to 11. Reporting ranges keeps the output small even when a gap is large; a recursive CTE or a numbers table could list every missing value individually if needed. The last row has no LEAD and is excluded by the filter, so numbers missing after the maximum are not reported, which is usually right. In PostgreSQL, generate_series(min, max) EXCEPT SELECT no is an alternative for listing each missing number.
sql
CREATE TABLE invoices (no INTEGER PRIMARY KEY);
INSERT INTO invoices VALUES (1), (2), (3), (6), (7), (9), (12);
SELECT no + 1 AS gap_start, next_no - 1 AS gap_end FROM (
SELECT no, LEAD(no) OVER (ORDER BY no) AS next_no FROM invoices
) WHERE next_no - no > 1 ORDER BY gap_start;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
LEAD pairs each row with the next
A difference above 1 marks a gap
Report ranges, not every value
generate_series EXCEPT lists values in PostgreSQL
Common mistakes
Self-joining on no + 1, which finds gap starts but not ends
Generating huge number lists for sparse gaps
Follow-ups
How would you list each missing number?
Why do auto-increment ids have gaps?
Tips
Show gap ranges
424.sql-0424Mediummid
Which pairs of products are most often bought in the same order?
Self-join order_items on the same order with a.product < b.product, so each unordered pair appears once and a product never pairs with itself, then count orders per pair and sort by the count.
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 a.product AS product_a, b.product AS product_b, COUNT(DISTINCT a.order_id) AS orders_together
FROM order_items a JOIN order_items b ON b.order_id = a.order_id AND a.product < b.product
GROUP BY a.product, b.product ORDER BY orders_together DESC, product_a, product_b;
product_a
product_b
orders_together
Bag
Notebook
1
Notebook
Pen
1
Order 101 contains Notebook and Pen, and order 104 contains Bag and Notebook, so each of those pairs appears once. The < condition is the important part: <> would count each pair twice (A,B and B,A), and no condition at all would pair every product with itself. COUNT(DISTINCT order_id) protects against an order listing the same product on two lines. On a large table the self-join grows quickly with basket size, so production analyses often restrict to recent orders or use a sampling approach.
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 a.product AS product_a, b.product AS product_b, COUNT(DISTINCT a.order_id) AS orders_together
FROM order_items a JOIN order_items b ON b.order_id = a.order_id AND a.product < b.product
GROUP BY a.product, b.product ORDER BY orders_together DESC, product_a, product_b;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Self-join within the same order
a < b gives each unordered pair once
Count distinct orders per pair
Self-joins grow with basket size
Common mistakes
Using <> and double counting
Counting rows instead of orders
Follow-ups
How would you compute support and confidence?
How would you find triples?
Tips
Explain the < condition
425.sql-0425Hardsenior
Find the order at which each customer's cumulative spend first reached 40 or more.
Compute a running total of order value per customer ordered by date, then keep the first order where the running total is at least 40 and the previous running total was below 40 (or there was none). ROW_NUMBER over the qualifying orders, or a comparison of the running total minus the current order, identifies the crossing.
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
WITH order_totals AS (
SELECT o.id, o.customer_id, o.order_date, SUM(oi.qty * oi.unit_price) AS value
FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.customer_id IS NOT NULL GROUP BY o.id
), running AS (
SELECT *, SUM(value) OVER (PARTITION BY customer_id ORDER BY order_date, id ROWS UNBOUNDED PRECEDING) AS cum FROM order_totals
)
SELECT customer_id, id AS crossing_order, order_date, cum FROM running
WHERE cum >= 40 AND cum - value < 40 ORDER BY customer_id;
customer_id
crossing_order
order_date
cum
1
102
2026-02-11
43
3
104
2026-03-01
42
Ana's first order is worth 13 and her second 30, so her cumulative spend reaches 43 at order 102. Chloe's single order 104 is worth 42 and crosses at once. Bilal's two orders total 35, so he never reaches 40 and does not appear. The test cum - value < 40 checks that the total before this order was below the threshold, which finds exactly one crossing row per customer without a second window.
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);
WITH order_totals AS (
SELECT o.id, o.customer_id, o.order_date, SUM(oi.qty * oi.unit_price) AS value
FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.customer_id IS NOT NULL GROUP BY o.id
), running AS (
SELECT *, SUM(value) OVER (PARTITION BY customer_id ORDER BY order_date, id ROWS UNBOUNDED PRECEDING) AS cum FROM order_totals
)
SELECT customer_id, id AS crossing_order, order_date, cum FROM running
WHERE cum >= 40 AND cum - value < 40 ORDER BY customer_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Aggregate order values first
Running SUM per customer
cum - value < threshold <= cum finds the crossing
Customers who never cross are absent
Common mistakes
Returning every order after the crossing
Running totals without a tiebreaker on equal dates
Follow-ups
How would you report how many days it took to cross?
How would you include customers who never crossed with NULL?
Tips
Show the crossing condition
426.sql-0426Mediummid
For each customer, show the number of days between consecutive orders and their average gap.
Use LAG(order_date) partitioned by customer to get the previous order date, subtract with julianday() to get days, and average the gaps per customer with a window AVG or a second grouping step. The first order of each customer has no gap.
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 customer_id, id, order_date,
CAST(julianday(order_date) - julianday(LAG(order_date) OVER w) AS INTEGER) AS days_since_prev,
AVG(julianday(order_date) - julianday(LAG(order_date) OVER w)) OVER (PARTITION BY customer_id) AS avg_gap
FROM orders WHERE customer_id IS NOT NULL
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date)
ORDER BY customer_id, order_date;
-- error on purpose
text
Error: misuse of window function LAG()
SQLite does not allow a window function inside another window function's argument, so this attempt fails, which is a useful lesson in itself. The fix is to compute the gaps in one step and average them in the next:
sql
WITH gaps AS (
SELECT customer_id, id, order_date,
julianday(order_date) - julianday(LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date)) AS gap
FROM orders WHERE customer_id IS NOT NULL
)
SELECT customer_id, id, order_date, CAST(gap AS INTEGER) AS days_since_prev, AVG(gap) OVER (PARTITION BY customer_id) AS avg_gap
FROM gaps ORDER BY customer_id, order_date;
customer_id
id
order_date
days_since_prev
avg_gap
1
101
2026-01-05
NULL
37.0
1
102
2026-02-11
37
37.0
2
103
2026-02-14
NULL
23.0
2
105
2026-03-09
23
23.0
3
104
2026-03-01
NULL
NULL
Ana's two orders are 37 days apart and Bilal's are 23 days apart, while Chloe has a single order and no gap. AVG ignores the NULL gap on each first order, so the averages are 37.0 and 23.0. In PostgreSQL, subtracting two dates gives an integer number of days directly.
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);
-- error on purpose
SELECT customer_id, id, order_date,
CAST(julianday(order_date) - julianday(LAG(order_date) OVER w) AS INTEGER) AS days_since_prev,
AVG(julianday(order_date) - julianday(LAG(order_date) OVER w)) OVER (PARTITION BY customer_id) AS avg_gap
FROM orders WHERE customer_id IS NOT NULL
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date)
ORDER BY customer_id, order_date;
WITH gaps AS (
SELECT customer_id, id, order_date,
julianday(order_date) - julianday(LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date)) AS gap
FROM orders WHERE customer_id IS NOT NULL
)
SELECT customer_id, id, order_date, CAST(gap AS INTEGER) AS days_since_prev, AVG(gap) OVER (PARTITION BY customer_id) AS avg_gap
FROM gaps ORDER BY customer_id, order_date;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
LAG over customer partitions finds the previous order
julianday differences give days in SQLite
Window functions cannot nest
Compute gaps first, then aggregate
Common mistakes
Nesting window functions
Counting the first order's NULL gap as zero
Follow-ups
How would you flag customers whose gap is growing?
How would you predict the next order date?
Tips
Split into two steps
427.sql-0427Hardsenior
List users who viewed a product, then added it to the cart, then purchased it, in that order.
Join the events table to itself three times on user and product, requiring the view time before the cart time and the cart time before the purchase time. EXISTS-based filters or MIN timestamps per step avoid row multiplication when a user repeats a step.
SELECT DISTINCT v.user_id, v.product
FROM events v
JOIN events c ON c.user_id = v.user_id AND c.product = v.product AND c.kind = 'cart' AND c.ts > v.ts
JOIN events p ON p.user_id = v.user_id AND p.product = v.product AND p.kind = 'purchase' AND p.ts > c.ts
WHERE v.kind = 'view' ORDER BY v.user_id;
user_id
product
1
Lamp
Only user 1 completed the steps in order. User 2 bought the lamp but added it to the cart before viewing it, so the ordered funnel rejects them, and user 3 never purchased. DISTINCT removes duplicate matches when a step repeats, as user 3's two views would produce if they had gone on to buy. For funnel counts per step, a common pattern computes each user's first timestamp per step with conditional MIN, then compares those timestamps; that scales better than chained self-joins.
sql
CREATE TABLE events (user_id INTEGER, product TEXT, kind TEXT, ts TEXT);
INSERT INTO events VALUES
(1, 'Lamp', 'view', '2026-03-01 10:00'), (1, 'Lamp', 'cart', '2026-03-01 10:05'), (1, 'Lamp', 'purchase', '2026-03-01 10:09'),
(2, 'Lamp', 'cart', '2026-03-02 09:00'), (2, 'Lamp', 'view', '2026-03-02 09:01'), (2, 'Lamp', 'purchase', '2026-03-02 09:03'),
(3, 'Bag', 'view', '2026-03-03 12:00'), (3, 'Bag', 'view', '2026-03-03 12:01'), (3, 'Bag', 'cart', '2026-03-03 12:02');
SELECT DISTINCT v.user_id, v.product
FROM events v
JOIN events c ON c.user_id = v.user_id AND c.product = v.product AND c.kind = 'cart' AND c.ts > v.ts
JOIN events p ON p.user_id = v.user_id AND p.product = v.product AND p.kind = 'purchase' AND p.ts > c.ts
WHERE v.kind = 'view' ORDER BY v.user_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Chain steps with self-joins and time order
Match on user and product
DISTINCT handles repeated steps
Conditional MIN per step scales better
Common mistakes
Ignoring event order
Counting duplicate matches from repeated events
Follow-ups
How would you count users at each funnel step?
How would you require all steps within 30 minutes?
Tips
State the ordering rule
428.sql-0428Mediummid
Rank customers by revenue within each country and keep the top one per country, including ties.
Compute revenue per customer, apply RANK() OVER (PARTITION BY country ORDER BY revenue DESC), and keep rows with rank 1. RANK gives tied customers the same rank, so ties are all kept, unlike ROW_NUMBER, which picks one arbitrarily.
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 customers VALUES (5, 'Esa', 'Spain');
INSERT INTO orders VALUES (107, 5, '2026-03-20', 'shipped');
INSERT INTO order_items VALUES (107, 'Bag', 1, 30), (107, 'Notebook', 3, 4), (107, 'Pen', 1, 1);
sql
WITH revenue AS (
SELECT c.id, c.name, c.country, SUM(oi.qty * oi.unit_price) AS revenue
FROM customers c JOIN orders o ON o.customer_id = c.id JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'shipped' GROUP BY c.id
)
SELECT country, name, revenue FROM (
SELECT *, RANK() OVER (PARTITION BY country ORDER BY revenue DESC) AS rnk FROM revenue
) WHERE rnk = 1 ORDER BY country, name;
country
name
revenue
France
Chloe
42
Spain
Ana
43
Spain
Esa
43
Ana and the added customer Esa both have 43 in shipped revenue in Spain, so both rank first and both are returned. Chloe leads France with 42. Bilal (UAE) has no shipped orders and is absent from the revenue CTE altogether; a LEFT JOIN with COALESCE would include such customers with zero. Changing RANK to ROW_NUMBER would return only one of the two Spanish customers, and which one would not be defined without a tiebreaker.
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 customers VALUES (5, 'Esa', 'Spain');
INSERT INTO orders VALUES (107, 5, '2026-03-20', 'shipped');
INSERT INTO order_items VALUES (107, 'Bag', 1, 30), (107, 'Notebook', 3, 4), (107, 'Pen', 1, 1);
WITH revenue AS (
SELECT c.id, c.name, c.country, SUM(oi.qty * oi.unit_price) AS revenue
FROM customers c JOIN orders o ON o.customer_id = c.id JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'shipped' GROUP BY c.id
)
SELECT country, name, revenue FROM (
SELECT *, RANK() OVER (PARTITION BY country ORDER BY revenue DESC) AS rnk FROM revenue
) WHERE rnk = 1 ORDER BY country, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Aggregate, then rank within partitions
RANK keeps ties at the top
ROW_NUMBER picks one arbitrarily
Customers without qualifying rows drop out
Common mistakes
Using ROW_NUMBER when ties should be kept
Ranking before aggregating
Follow-ups
How would you keep the top two per country?
How would you include customers with no shipped orders?
Tips
Explain RANK versus ROW_NUMBER
429.sql-0429Mediummid
A heavy monthly report slows the production database for everyone while it runs. What are the options?
Move the load away from the primary: run the report on a read replica, precompute it with a materialized view or summary table refreshed off-peak, or load data into a separate warehouse built for analytics. Also tune the query itself and, if it must stay on the primary, run it at a quiet time with a statement timeout.
Full answer
Options, from least to most effort:
Tune: check the plan, add an index for the report's filter, and avoid fetching unneeded columns.
Schedule: run it off-peak with statement_timeout so a runaway query is cancelled instead of degrading the service.
Replica: point reporting connections at a replica. Lag of a few seconds is usually fine for monthly reports.
Precompute: a summary table (orders per day per product) updated nightly or incrementally turns a full scan into a small read. PostgreSQL materialized views with REFRESH MATERIALIZED VIEW CONCURRENTLY keep reads available during refresh.
Warehouse: export changes to a columnar analytics store when reports multiply and need joins across many sources.
The right answer depends on freshness needs: a finance close needs exact numbers as of a cut-off time, while a trend chart tolerates a day's delay.
Key points
Tune the query first
Use replicas for reporting reads
Precompute summaries
Warehouses suit growing analytics
Match freshness to the need
Common mistakes
Adding hardware before checking the query
Running ad-hoc analytics on the primary at peak
Follow-ups
How would you keep a summary table up to date incrementally?
What problems can long queries cause on a replica?
Tips
Order the options by effort
430.sql-0430Mediummid
Daily sales totals are wrong for users in India because timestamps are stored in UTC. How do you group by the local day?
Convert each UTC timestamp to the business's time zone before taking the date, then group. In SQLite that means applying the offset (or 'localtime' on a server set to that zone); in PostgreSQL use (ts AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Kolkata' or a timestamptz with AT TIME ZONE. Grouping by the UTC date shifts orders placed between midnight and 05:30 IST into the previous day.
SELECT date(ts) AS utc_day, SUM(amount) AS total FROM sales_utc GROUP BY utc_day ORDER BY utc_day;
utc_day
total
2026-03-01
150
2026-03-02
70
Grouping by the India date (UTC+05:30, which has no daylight saving):
sql
SELECT date(ts, '+5 hours', '+30 minutes') AS ist_day, SUM(amount) AS total FROM sales_utc GROUP BY ist_day ORDER BY ist_day;
ist_day
total
2026-03-01
100
2026-03-02
120
The order at 20:00 UTC on 1 March is 01:30 on 2 March in India, so it moves to the next day, and the totals change for both days. A fixed offset is safe for India; for zones with daylight saving, a fixed offset is wrong for part of the year, so PostgreSQL's named zones (AT TIME ZONE 'Europe/London') or conversion in the application are needed. Store instants in UTC, and decide explicitly which zone defines a 'business day' for each report.
sql
CREATE TABLE sales_utc (id INTEGER PRIMARY KEY, ts TEXT, amount INTEGER);
INSERT INTO sales_utc VALUES (1, '2026-03-01 04:00:00', 100), (2, '2026-03-01 20:00:00', 50), (3, '2026-03-02 10:00:00', 70);
SELECT date(ts) AS utc_day, SUM(amount) AS total FROM sales_utc GROUP BY utc_day ORDER BY utc_day;
SELECT date(ts, '+5 hours', '+30 minutes') AS ist_day, SUM(amount) AS total FROM sales_utc GROUP BY ist_day ORDER BY ist_day;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Convert to the business zone before taking the date
UTC dates misplace late-evening or early-morning orders
Fixed offsets only work without daylight saving
Use named zones in PostgreSQL
Define the reporting zone explicitly
Common mistakes
Grouping by date(ts) on UTC values for local reports
Hard-coding offsets for zones with daylight saving
Follow-ups
How would you report for several countries at once?
Why store UTC at all?
Tips
Show an order that changes day
431.sql-0431Mediummid
SELECT COUNT(*) on a 500-million-row table takes minutes, and a dashboard runs it on every page load. How would you fix that?
Exact counts on large tables must scan a table or index, especially in PostgreSQL where MVCC prevents a stored row count. Use an estimate from planner statistics when approximate is fine, maintain a counter table updated by triggers or batch jobs when exact counts are needed, or cache the result for a short time.
Full answer
Choices:
Estimate: PostgreSQL keeps reltuples in pg_class, refreshed by VACUUM and ANALYZE. SELECT reltuples::bigint FROM pg_class WHERE relname = 'events' returns instantly and is usually within a few percent.
Filtered estimates: EXPLAIN output includes estimated rows for a WHERE clause, which some apps parse for 'about 1.2M results'.
Counter table: event_counts(day, n) updated in the same transaction as inserts or by a periodic job. Exact, cheap to read, but adds write work and hot rows if one row is shared.
Caching: compute once a minute and serve the cached value.
Index-only scans can speed exact counts when the visibility map is current, but still read every index entry.
Most dashboards show '1.2M events' and need no exact count; ask what precision the user needs. These are PostgreSQL behaviours described here, not run.
Key points
Exact counts scan data
Planner statistics give fast estimates
Counter tables give exact cheap reads
Cache expensive aggregates
Ask what precision is needed
Common mistakes
Running COUNT(*) on every request
A single global counter row updated by every insert
Follow-ups
How accurate is reltuples after a bulk load?
How would you count rows per day cheaply?
Tips
Ask whether an estimate is acceptable
432.sql-0432Easyfresher
Users who double-click 'Place order' sometimes create two identical orders. How do you prevent it at the database level?
Give each checkout attempt a unique token generated when the page loads, store it on the order with a UNIQUE constraint, and insert with ON CONFLICT DO NOTHING (or catch the violation) so the second click returns the first order. Disabling the button helps the user but cannot be trusted alone.
Full answer
text
orders(id, customer_id, checkout_token TEXT UNIQUE, ...)
INSERT INTO orders (customer_id, checkout_token, ...) VALUES (:c, :token, ...)
ON CONFLICT (checkout_token) DO NOTHING
RETURNING id;
If RETURNING yields no row, look up the existing order by token and return it, so both requests show the same confirmation page.
Why the database: two requests can arrive at different servers within milliseconds. Application checks ('does an order with this cart exist?') race, but a unique constraint is checked atomically. The same idea protects payments, sign-ups and any form that creates records.
Front-end measures (disabling the button, showing a spinner) reduce the frequency but do not cover retries from flaky networks or browser resubmits.
Key points
A unique token per attempt
UNIQUE constraint catches the second insert
Return the existing order on conflict
UI measures are not enough
Common mistakes
Deduplicating by comparing order contents and times
Relying only on disabling the button
Follow-ups
How long should tokens remain valid?
How does this relate to idempotency keys in APIs?
Tips
Explain why application checks race
433.sql-0433Mediummid
A team plans to move an app from SQLite to PostgreSQL. Which differences should they check?
Check type strictness (SQLite's flexible typing lets bad values in), date and time storage (text versus native types), booleans, auto-increment syntax, case sensitivity of LIKE and identifiers, upsert and RETURNING syntax, and functions such as strftime, ifnull and group_concat. Test queries on PostgreSQL with real data, because some differences give wrong results silently rather than errors.
Full answer
Checklist:
Types: SQLite accepts '12abc' in an INTEGER column; PostgreSQL rejects it. Scan columns with typeof() before migrating.
Dates: SQLite stores text or numbers; convert to date, timestamp or timestamptz, deciding the zone.
Booleans: 0 and 1 become boolean; SUM(flag) no longer works directly.
Keys: INTEGER PRIMARY KEY becomes bigint GENERATED ALWAYS AS IDENTITY; reset sequences after copying data.
Strings: LIKE is case-insensitive for ASCII in SQLite but case-sensitive in PostgreSQL (use ILIKE); || with NULL gives NULL in both.
Functions: strftime to to_char or date_trunc, ifnull to coalesce, group_concat to string_agg, instr to strpos.
Grouping: bare columns in GROUP BY queries are errors in PostgreSQL.
Division: integer division behaves the same, but division by zero errors in PostgreSQL instead of returning NULL.
Concurrency: PostgreSQL allows many writers, so code that relied on SQLite's single writer may need explicit locking.
Many of these differences are demonstrated by runs elsewhere in this bank; the checklist itself is guidance, not a run.
Key points
Strict types reject bad data
Convert dates to native types
Rename SQLite-only functions
Bare GROUP BY columns fail in PostgreSQL
Division by zero and LIKE case differ
Common mistakes
Assuming identical results because queries parse
Copying data without fixing sequences
Follow-ups
How would you verify the migrated data?
How would you run both databases during a transition?
Tips
Group the checklist by category
434.sql-0434Hardsenior
Someone ran DELETE FROM orders without a WHERE clause on production. What do you do?
Stop further damage first (pause jobs and writes that depend on the table), then restore the deleted rows from a point-in-time recovery to a separate server, just before the DELETE, and copy them back. If the session is still open and uncommitted, ROLLBACK. Afterwards, add safeguards such as reviewed scripts, least-privilege roles and statement guards.
Full answer
Steps:
If the DELETE ran inside an open transaction in your session, ROLLBACK undoes it immediately.
Otherwise, contain: stop jobs that might cascade or act on missing orders.
Find the time: the database log or audit trail gives the timestamp of the statement.
Restore a copy: recover a backup plus WAL to a new server, stopping just before that moment (recovery_target_time). Do not restore over production, which would lose later legitimate writes.
Copy back: export the orders table from the restored copy and insert the missing rows, taking care with rows changed or added since, and with dependent tables if ON DELETE CASCADE removed children.
Verify counts and totals, then resume.
Prevention:
Application and human roles without DELETE on critical tables, or deletes allowed only through functions.
Run manual changes inside BEGIN, check the row count, then commit.
Tools that refuse UPDATE or DELETE without WHERE (MySQL's safe-updates mode; review policies elsewhere).
Soft delete or audit logs for critical records.
Replicas do not help here, because the DELETE replicated to them within seconds.
Key points
Rollback if still in the transaction
Contain before fixing
Restore to a separate server at a point in time
Copy missing rows back carefully
Add guardrails afterwards
Common mistakes
Restoring the whole database over production
Assuming replicas keep the deleted rows
Follow-ups
What if cascades deleted order items too?
How would you rehearse this recovery?
Tips
Describe the restore-to-side approach
435.sql-0435Mediummid
Two dashboards show different revenue for the same month. How would you find out why?
Compare the definitions line by line: which statuses count (cancelled, refunded), which date defines the month (order date, ship date, payment date), the time zone, currency conversion, tax and discounts, and joins that may duplicate or drop rows. Reconcile at a fine grain, such as per day or per order, to find where the numbers diverge, then agree on one documented definition.
Full answer
Typical causes:
Filters: one includes cancelled or test orders, the other excludes them.
Dates: one uses order_date, the other paid_at; month boundaries in UTC versus local time.
Joins: a join to order items and payments together fans out rows and inflates sums; an inner join to a lookup drops rows without a match.
Amounts: gross versus net of discounts, tax, shipping or refunds; mixed currencies.
Freshness: one reads a replica or a nightly snapshot.
Method:
Get both SQL statements.
Run both at the order level and full-outer-join the results on order id to see which orders differ.
Explain each difference category and its amount.
Agree on a definition, put it in a shared view or semantic layer, and point both dashboards at it.
Metric definitions belong in one place; otherwise every new report invents its own.
Key points
Compare definitions, not just numbers
Reconcile at order level
Check fan-out and dropped rows
Time zones and date choice matter
Centralise metric definitions
Common mistakes
Adjusting one dashboard to match without understanding why
Comparing only monthly totals
Follow-ups
How would a full outer join help reconcile?
How would you test a metric definition?
Tips
Reconcile at the finest grain
436.sql-0436Mediummid
Searching product names with LIKE '%term%' is slow on a large table. What are the options?
A leading wildcard prevents B-tree index use, so every row is scanned. In PostgreSQL, a trigram GIN index (pg_trgm) supports LIKE and ILIKE with leading wildcards and similarity search; full-text search suits word-based queries; SQLite offers FTS5. For prefix-only searches, LIKE 'term%' can use a suitable B-tree index.
Full answer
Choices:
Prefix search: WHERE name LIKE 'lam%' can use a B-tree index (in PostgreSQL with text_pattern_ops or the C collation; in SQLite with matching case sensitivity settings).
Substring search: CREATE EXTENSION pg_trgm; CREATE INDEX ON products USING gin (name gin_trgm_ops); then ILIKE '%amp%' uses the index. Very short terms (one or two characters) still match many rows.
Word search: full-text search with stemming and ranking (tsvector in PostgreSQL, FTS5 in SQLite) suits descriptions and multi-word queries.
Typo tolerance: trigram similarity() or % operator finds 'lmap' for 'lamp'.
External search engines when relevance tuning, facets and synonyms grow important.
Measure with EXPLAIN before and after; trigram indexes are large and slow writes somewhat. The PostgreSQL statements here are illustrative and were not run.
Key points
Leading wildcards block B-tree use
Trigram GIN indexes serve substring search
Full-text search suits word queries
Prefix LIKE can use B-trees
Measure index size and write cost
Common mistakes
Adding a plain B-tree and expecting '%term%' to use it
Using LIKE for relevance-ranked search
Follow-ups
How does pg_trgm split a word into trigrams?
When would you move to a search engine?
Tips
Separate prefix, substring and word search
437.sql-0437Hardsenior
A column rename is needed, but old and new versions of the application will run side by side during deployment. How do you do it safely?
Make each step compatible with both versions: add the new column, write to both (via the application or a trigger), backfill, switch reads to the new column, then stop writing the old one and drop it in a later release. Renaming in place breaks whichever version still uses the old name.
Full answer
Why not ALTER TABLE ... RENAME COLUMN: the rename is instant, but during a rolling deploy some servers run the old code, which immediately fails with 'column does not exist'.
Expand and contract sequence:
Migration: add full_name (nullable).
Release A: write both name and full_name; read name.
Backfill full_name from name in batches.
Release B: read full_name; still write both, so a rollback to A works.
Release C: stop writing name.
Migration: drop name.
A trigger that copies between the columns can replace dual writes in code. Alternatively, a view exposing the old name lets old code continue reading while the base table changes.
The general rule: every migration must work with the code version before and after it, because both run at the same time for a while.
Key points
Rolling deploys run two code versions
In-place renames break the old version
Expand, dual write, backfill, switch, contract
Each step must support a rollback
Views or triggers can bridge versions
Common mistakes
Renaming columns in the same release as the code change
Dropping the old column before all servers stop using it
Follow-ups
How would you rename a table the same way?
How do you decide when to drop the old column?
Tips
State the two-version rule
438.sql-0438Mediummid
How would you test code that runs SQL, so tests are fast and do not interfere with each other?
Run tests against the same database engine as production, create the schema from migrations, and isolate each test by wrapping it in a transaction that is rolled back at the end, or by using a fresh database or schema per test worker. Keep fixtures small and explicit, and test edge cases such as NULLs, ties and empty tables.
Full answer
Practices:
Same engine: SQLite in tests and PostgreSQL in production hides differences in typing, NULL ordering and errors. Containers make a real PostgreSQL cheap in CI.
Schema from migrations: tests then also verify the migrations.
Isolation: begin a transaction before each test and roll back afterwards; tests that need commits (for example to test concurrency) use a separate database per worker instead.
Fixtures: build only the rows a test needs, with factories, so each test shows its own data.
Edge cases: empty results, NULL values, duplicate sort keys, time zones, large values.
Query counts: assert the number of queries an endpoint makes to catch N+1 regressions.
Plans: for critical queries, a test can assert that EXPLAIN uses an index on realistic data volumes.
Every query in this bank was run twice and the outputs compared, which is a small example of checking that results are deterministic.
Key points
Test on the production engine
Build schemas from migrations
Roll back per test or use per-worker databases
Small explicit fixtures
Cover NULLs, ties and empty tables
Common mistakes
Sharing one mutable database across parallel tests
Mocking the database entirely for query logic
Follow-ups
How would you test concurrent updates?
How do you keep test data realistic without copying production?
Tips
Mention isolation explicitly
439.sql-0439Mediummid
Analysts need access to order data but must not see customers' personal details. How can the database enforce that?
Give analysts a role without access to the base tables and grant SELECT on views that omit or mask personal columns (for example a hashed customer id and only the country). PostgreSQL also supports column-level privileges and row-level security. Separate analytics copies with masked data are a further option.
Full answer
Approaches:
Views: CREATE VIEW analytics.orders AS SELECT o.id, md5(o.customer_id::text || :salt) AS customer_key, c.country, o.total FROM orders o JOIN customers c ... and grant SELECT on the view only.
Column privileges: GRANT SELECT (id, country, created_at) ON customers TO analyst; blocks other columns.
Row-level security: restrict rows, for example to the analyst's region.
Masked copies: a nightly job copies data into an analytics database with personal fields removed or tokenised, so mistakes in the primary's grants cannot leak data.
Hashing ids keeps joins possible across tables without revealing identities, but small groups can still identify people; aggregate thresholds (no groups under 10 people) reduce that risk. Audit which roles can read raw personal data and review it regularly. The statements shown are illustrative and were not run here.
Key points
Grant views, not base tables
Column privileges restrict fields
Row-level security restricts rows
Masked analytics copies isolate risk
Small groups can still identify people
Common mistakes
Granting SELECT on all tables to analysts
Assuming hashing alone guarantees anonymity
Follow-ups
How would you mask email addresses but keep domains?
How does pseudonymisation differ from anonymisation?
Tips
Name views and privileges together
440.sql-0440Mediummid
A nightly CSV import sometimes loads bad rows that break reports. How would you make the import safer?
Load the file into a staging table first, validate it with SQL checks (types, required fields, valid references, duplicates), and move only valid rows into the real table in one transaction, recording rejected rows with reasons. Constraints on the target table act as the final guard.
Full answer
Pipeline:
Staging: load raw text into staging_orders with permissive TEXT columns, so the load itself never fails halfway.
Validate with queries, for example:
required fields: WHERE order_id IS NULL OR trim(order_id) = ''
types: values that do not look like integers or dates
references: customer_id values with no matching customer
duplicates within the file and against existing rows
Reject: insert failing rows into import_rejects(row_no, reason, raw) and report counts.
Publish: INSERT INTO orders SELECT ... FROM staging_orders WHERE valid inside a transaction; if the reject rate passes a threshold, abort the whole batch instead.
Constraints (NOT NULL, CHECK, foreign keys, unique keys) on orders stop anything the checks missed.
Keeping the raw file and the batch id on imported rows makes it possible to undo a bad import precisely.