Questions 481–500 of 501 · 0 of 20 on this page marked learned
481.sql-0481Mediummid
Each employee's share of their department's salary bill comes out tiny. Find the mistake.
The denominator SUM(salary) OVER () is the company-wide total, not the department total. Use SUM(salary) OVER (PARTITION BY dept_id) so each salary is divided by its own department's bill, and multiply by 100.0 to avoid integer division.
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, dept_id, salary, ROUND(100.0 * salary / SUM(salary) OVER (), 1) AS pct_of_dept FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, salary DESC;
name
dept_id
salary
pct_of_dept
Asha
1
120000
22.0
Ravi
1
95000
17.4
Mei
1
95000
17.4
Tom
2
70000
12.8
Sara
2
62000
11.4
Diego
3
55000
10.1
Omar
3
48000
8.8
Every share is computed against the total of all departments, 545000, so Asha shows 22.0 percent instead of her share of Engineering. The column name promises one thing and the window computes another.
A corrected version:
sql
SELECT name, dept_id, salary, ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY dept_id), 1) AS pct_of_dept FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, salary DESC;
name
dept_id
salary
pct_of_dept
Asha
1
120000
38.7
Ravi
1
95000
30.6
Mei
1
95000
30.6
Tom
2
70000
53.0
Sara
2
62000
47.0
Diego
3
55000
53.4
Omar
3
48000
46.6
With the partition, shares within each department add up to about 100: Asha is 38.7 percent of Engineering, Tom 53.0 percent of Sales and Diego 53.4 percent of Support. Rounding each share can make the sum 99.9 or 100.1, which reports should either accept or correct by adjusting the largest share.
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, dept_id, salary, ROUND(100.0 * salary / SUM(salary) OVER (), 1) AS pct_of_dept FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, salary DESC;
SELECT name, dept_id, salary, ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY dept_id), 1) AS pct_of_dept FROM employees WHERE dept_id IS NOT NULL ORDER BY dept_id, salary DESC;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Window totals need the right partition
OVER () is the grand total
Multiply by 100.0 first
Rounded shares may not sum to exactly 100
Common mistakes
Mixing grand totals and group totals
Integer division in percentages
Follow-ups
How would you show both department and company shares?
How would you fix rounding so shares sum to 100?
Tips
Check that shares in a group sum to 100
482.sql-0482Easyfresher
Predict SELECT 10 / 3 * 3, 10 * 3 / 3 in SQLite.
The results are 9 and 10. Both operators have the same precedence and are evaluated left to right; in the first expression 10 / 3 truncates to 3 before multiplying, while the second multiplies first and divides 30 by 3 exactly.
Full answer
sql
SELECT 10 / 3 * 3 AS divide_first, 10 * 3 / 3 AS multiply_first, 10.0 / 3 * 3 AS real_math;
divide_first
multiply_first
real_math
9
10
10.0
Integer division discards the remainder at the step where it happens, so the position of the division decides how much is lost. With a real operand, as in the third column, the arithmetic is floating point and returns 10.0. PostgreSQL behaves the same for integers. In financial calculations, multiply before dividing, or use NUMERIC or real operands, and round once at the end.
sql
SELECT 10 / 3 * 3 AS divide_first, 10 * 3 / 3 AS multiply_first, 10.0 / 3 * 3 AS real_math;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
* and / evaluate left to right
Integer division truncates at each step
Multiply before dividing to keep precision
Common mistakes
Assuming the two expressions are equal
Follow-ups
What does 10 % 3 * 3 return?
How would you compute a percentage safely?
Tips
Evaluate step by step
483.sql-0483Easyfresher
What do '10' + '5', '10' || '5' and 10 || 5 return in SQLite?
They return 15, '105' and '105'. The + operator converts text that looks numeric into numbers and adds them, while || converts its operands to text and concatenates, so the operator, not the operand types, decides the result.
Full answer
sql
SELECT '10' + '5' AS plus_text, '10' || '5' AS concat_text, 10 || 5 AS concat_numbers, typeof(10 || 5) AS concat_type;
plus_text
concat_text
concat_numbers
concat_type
15
105
105
text
SQLite applies numeric conversion for arithmetic, so the quoted values become 10 and 5. Concatenation always yields text, even with integer operands, which the typeof column confirms. PostgreSQL is stricter: '10' + '5' resolves the unknown literals to integers and returns 15, but 10 || 5 fails because || has no integer form unless one side is text (not run here). Relying on implicit conversion makes queries engine-dependent.
sql
SELECT '10' + '5' AS plus_text, '10' || '5' AS concat_text, 10 || 5 AS concat_numbers, typeof(10 || 5) AS concat_type;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
+ converts to numbers
|| converts to text
Concatenation returns text
PostgreSQL is stricter with ||
Common mistakes
Expecting + to concatenate
Follow-ups
What does 'abc' + 1 return in SQLite?
How would you build a zero-padded code from a number?
Tips
Let the operator decide the type
484.sql-0484Mediummid
Predict SELECT max('apple', 'Banana') and min(3, NULL) in SQLite.
max('apple', 'Banana') returns 'apple', because comparison is by bytes and lowercase 'a' (97) is greater than uppercase 'B' (66). min(3, NULL) returns NULL, because SQLite's multi-argument min and max return NULL if any argument is NULL, unlike the aggregate versions, which ignore NULLs.
Full answer
sql
SELECT max('apple', 'Banana') AS max_text, min(3, NULL) AS min_with_null, max(3, 5, 4) AS max_numbers;
max_text
min_with_null
max_numbers
apple
NULL
5
With two or more arguments, min() and max() are scalar functions. They compare with the usual rules, so text uses the BINARY collation unless an argument carries another collation. Any NULL argument makes the result NULL, which differs from aggregate MIN and MAX, which skip NULLs. PostgreSQL's GREATEST and LEAST ignore NULLs and return NULL only when all arguments are NULL (not run here), so the same intent gives different results across engines. Wrap arguments in COALESCE when NULL should be ignored in SQLite.
sql
SELECT max('apple', 'Banana') AS max_text, min(3, NULL) AS min_with_null, max(3, 5, 4) AS max_numbers;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Scalar min and max return NULL if any argument is NULL
Aggregate MIN and MAX ignore NULLs
Text compares by bytes by default
GREATEST and LEAST in PostgreSQL ignore NULLs
Common mistakes
Assuming scalar and aggregate forms treat NULL alike
Follow-ups
How would you take the larger of two nullable columns in SQLite?
How would you compare case-insensitively?
Tips
Spot the NULL argument
485.sql-0485Mediummid
What do strftime('%w', '2026-12-04') and strftime('%j', '2026-12-04') return?
'%w' gives the day of the week with Sunday as 0, so Friday 4 December 2026 returns '5'. '%j' gives the day of the year, '338', because January to November 2026 contain 334 days. Both results are text.
Full answer
sql
SELECT strftime('%w', '2026-12-04') AS weekday, strftime('%j', '2026-12-04') AS day_of_year, typeof(strftime('%w', '2026-12-04')) AS result_type;
weekday
day_of_year
result_type
5
338
text
strftime always returns text, so compare with '5' or cast before arithmetic. Days of the week run from Sunday (0) to Saturday (6); for a Monday-based number, (CAST(strftime('%w', d) AS INTEGER) + 6) % 7 gives Monday as 0. The day of year counts from '001'. PostgreSQL uses extract(dow FROM d) and extract(doy FROM d), which return numbers (not run here). Recent SQLite versions also support '%u' for an ISO weekday from 1 (Monday) to 7.
sql
SELECT strftime('%w', '2026-12-04') AS weekday, strftime('%j', '2026-12-04') AS day_of_year, typeof(strftime('%w', '2026-12-04')) AS result_type;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
%w: Sunday = 0
%j: day of year from 001
strftime returns text
PostgreSQL uses extract(dow / doy)
Common mistakes
Comparing strftime output with integers without casting
Follow-ups
How would you group orders by weekday name?
How would you compute the ISO week number?
Tips
Remember Sunday is 0
486.sql-0486Mediummid
Build a histogram of marks in bands of 0-49, 50-69, 70-84 and 85-100, including bands with no students.
Define the bands in a VALUES list (or a small table) with lower and upper bounds, LEFT JOIN the marks on mark BETWEEN low AND high, and count matching marks per band. Starting from the band list ensures empty bands appear with a count of zero.
Full answer
sql
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
city TEXT,
year INTEGER
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
credits INTEGER
);
CREATE TABLE enrolments (
student_id INTEGER REFERENCES students(id),
course_id INTEGER REFERENCES courses(id),
marks INTEGER,
PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
(1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
(3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
WITH bands(label, low, high) AS (VALUES ('0-49', 0, 49), ('50-69', 50, 69), ('70-84', 70, 84), ('85-100', 85, 100))
SELECT b.label, COUNT(e.marks) AS students
FROM bands b LEFT JOIN enrolments e ON e.marks BETWEEN b.low AND b.high
GROUP BY b.label, b.low ORDER BY b.low;
label
students
0-49
0
50-69
2
70-84
3
85-100
2
No mark is below 50, yet the '0-49' band still appears with 0, because the query starts from the bands. COUNT(e.marks) counts only joined rows, so empty bands show zero rather than one. The unmarked enrolment has a NULL mark, matches no band and is left out; add a separate 'not marked' line if it should be reported. A CASE expression would also bucket the marks, but bands with no rows would then be missing.
sql
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
city TEXT,
year INTEGER
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
credits INTEGER
);
CREATE TABLE enrolments (
student_id INTEGER REFERENCES students(id),
course_id INTEGER REFERENCES courses(id),
marks INTEGER,
PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
(1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
(3,10,64),(3,20,71),(3,30,80),(5,20,55);
WITH bands(label, low, high) AS (VALUES ('0-49', 0, 49), ('50-69', 50, 69), ('70-84', 70, 84), ('85-100', 85, 100))
SELECT b.label, COUNT(e.marks) AS students
FROM bands b LEFT JOIN enrolments e ON e.marks BETWEEN b.low AND b.high
GROUP BY b.label, b.low ORDER BY b.low;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Start from a band list for empty buckets
LEFT JOIN with BETWEEN bounds
COUNT the joined column, not *
NULL values match no band
Common mistakes
Bucketing with CASE and losing empty bands
COUNT(*) showing 1 for empty bands
Follow-ups
How would you make equal-width bands automatically?
How would you show percentages per band?
Tips
Explain why empty bands appear
487.sql-0487Hardsenior
Show the top three products by revenue and group the rest into an 'Other' row.
Rank products by revenue with a window function, then group again using CASE WHEN rank <= 3 THEN product ELSE 'Other' END as the label. Summing in the second step gives the top products individually and one combined row for the long tail.
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 (105, 'Mug', 2, 6), (104, 'Card', 3, 2);
sql
WITH revenue AS (
SELECT product, SUM(qty * unit_price) AS revenue FROM order_items GROUP BY product
), ranked AS (
SELECT product, revenue, RANK() OVER (ORDER BY revenue DESC) AS rnk FROM revenue
)
SELECT CASE WHEN rnk <= 3 THEN product ELSE 'Other' END AS label, SUM(revenue) AS revenue
FROM ranked GROUP BY label ORDER BY MIN(rnk);
label
revenue
Bag
60
Lamp
25
Notebook
20
Other
35
Bag (60), Lamp (25) and Notebook (20) are the top three, and Pen (17), Mug (12) and Card (6) fall into 'Other' with 35. Ordering by MIN(rnk) keeps the top products in rank order and puts 'Other' last. RANK means ties at third place would all be kept as separate rows; switch to ROW_NUMBER with a tiebreaker for exactly three. The totals across all rows still equal total revenue, which is a useful check.
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 (105, 'Mug', 2, 6), (104, 'Card', 3, 2);
WITH revenue AS (
SELECT product, SUM(qty * unit_price) AS revenue FROM order_items GROUP BY product
), ranked AS (
SELECT product, revenue, RANK() OVER (ORDER BY revenue DESC) AS rnk FROM revenue
)
SELECT CASE WHEN rnk <= 3 THEN product ELSE 'Other' END AS label, SUM(revenue) AS revenue
FROM ranked GROUP BY label ORDER BY MIN(rnk);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Rank, then relabel the tail
Group again for the Other row
Order by the best rank in each label
Totals should match overall revenue
Common mistakes
Using LIMIT 3 and losing the remainder
Not deciding how ties at the cut-off behave
Follow-ups
How would you make the cut-off a percentage of revenue?
How would you do this per month?
Tips
Check that totals still add up
488.sql-0488Hardsenior
Design tables for a loyalty programme where customers earn points on purchases and the points expire after 12 months.
Store every change as a ledger row (earned, redeemed, expired, adjusted) with its own expiry date for earned rows, and compute the balance from unexpired earned points minus redemptions. Redemptions should consume the oldest expiring points first, recorded as allocations, so the balance by expiry bucket stays explainable. A nightly job writes expiry rows, or queries ignore expired points directly.
Full answer
Illustrative PostgreSQL design (example SQL, not run here):
sql
CREATE TABLE point_ledger (
id bigserial PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers(id),
kind text NOT NULL CHECK (kind IN ('earn', 'redeem', 'expire', 'adjust')),
points integer NOT NULL, -- positive for earn, negative for the rest
expires_on date, -- only for 'earn' rows
order_id bigint,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON point_ledger (customer_id, created_at);
Balance now: the sum of all points for the customer, after expiry rows are written. If expiry is applied lazily instead, a query sums earn rows whose expires_on is in the future and subtracts redemptions, which is only correct when redemptions are matched to the earn rows they consumed.
Matching redemptions to earn rows is the hard part. The usual rule is first-expiring-first-out: when a customer redeems 300 points, a function walks their earn rows ordered by expires_on, and an allocations(redeem_id, earn_id, points) table records how much of each earn row was used. The unused remainder of an earn row is then points - sum(allocations), and the expiry job writes one expire row for that remainder on the expiry date.
Design points: the ledger is append-only, so history is never lost and disputes can be answered row by row; redemptions run in a transaction that locks the customer's earn rows with FOR UPDATE to prevent two checkouts spending the same points; a cached balance column on the customer, if needed for speed, is updated in the same transaction and verified by a nightly reconciliation against the ledger. Reversals of a returned order are new rows, never edits.
Key points
Append-only ledger of earn, redeem and expire rows
Expiry date on earned points
First-expiring-first-out allocation of redemptions
Lock earn rows while redeeming
Reconcile any cached balance
Common mistakes
Storing only a balance column
Letting redemptions ignore which points they consume
Follow-ups
How would you show a customer which points expire next month?
How would a returned order reverse earned points that were already spent?
Tips
Explain why a plain balance is not enough
489.sql-0489Mediummid
Design the tables for a multi-step approval workflow, such as leave requests that need manager and then HR approval.
Keep one row per request with its current status, a table of steps defined per request type, and an append-only history of decisions with who, when and the comment. Valid transitions are enforced by a CHECK on status values and by application or trigger logic, and the current step is derived from the history. The history table answers audits without reconstructing past states.
Full answer
Illustrative design (example SQL, not run here):
sql
CREATE TABLE request_types (id int PRIMARY KEY, name text UNIQUE);
CREATE TABLE approval_steps (
request_type_id int REFERENCES request_types(id),
step_no int,
approver_role text NOT NULL,
PRIMARY KEY (request_type_id, step_no)
);
CREATE TABLE requests (
id bigserial PRIMARY KEY,
request_type_id int NOT NULL REFERENCES request_types(id),
requester_id bigint NOT NULL,
status text NOT NULL CHECK (status IN ('pending', 'approved', 'rejected', 'withdrawn')),
current_step int,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE request_decisions (
id bigserial PRIMARY KEY,
request_id bigint NOT NULL REFERENCES requests(id),
step_no int NOT NULL,
decided_by bigint NOT NULL,
decision text NOT NULL CHECK (decision IN ('approve', 'reject')),
comment text,
decided_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (request_id, step_no)
);
How it behaves: a request starts as pending at step 1. An approval inserts a decision row and moves current_step to the next step, or sets status = 'approved' after the last one. A rejection sets rejected immediately. The unique key on (request_id, step_no) stops two approvers from deciding the same step twice, even in concurrent requests, and the update and decision insert happen in one transaction.
Alternatives and trade-offs: a table of allowed transitions (from_status, to_status) makes the state machine data instead of code; workflow engines are worth considering when routing becomes conditional (amount thresholds, parallel approvals, delegation). Delegation and out-of-office rules are best modelled as extra rows that map one approver role to another person for a period, not as special cases in code.
Key points
Request row with current status and step
Step definitions per request type
Append-only decision history
Unique key prevents double decisions
Transitions in one transaction
Common mistakes
Overwriting status without keeping history
Hard-coding the approval chain in application code only
Follow-ups
How would you support parallel approvals by two roles?
How would you report average time spent at each step?
Tips
Separate current state from history
490.sql-0490Mediummid
Design the database for a restaurant menu where dishes have optional modifiers, such as size, extra toppings and spice level, with price changes.
Model dishes, modifier groups (size, toppings) attached to dishes, and options within each group, with a price delta and rules such as minimum and maximum selections. An order line stores the dish and a child table stores the chosen options, copying prices at order time so later menu changes do not alter past orders. Availability and prices by outlet go in separate tables keyed by outlet.
Full answer
Illustrative design (example SQL, not run here):
sql
CREATE TABLE dishes (id bigserial PRIMARY KEY, name text NOT NULL, base_price numeric(8,2) NOT NULL);
CREATE TABLE modifier_groups (
id bigserial PRIMARY KEY, name text NOT NULL,
min_select int NOT NULL DEFAULT 0, max_select int NOT NULL DEFAULT 1
);
CREATE TABLE modifier_options (
id bigserial PRIMARY KEY, group_id bigint NOT NULL REFERENCES modifier_groups(id),
name text NOT NULL, price_delta numeric(8,2) NOT NULL DEFAULT 0
);
CREATE TABLE dish_modifier_groups (
dish_id bigint REFERENCES dishes(id), group_id bigint REFERENCES modifier_groups(id),
PRIMARY KEY (dish_id, group_id)
);
CREATE TABLE order_lines (id bigserial PRIMARY KEY, order_id bigint NOT NULL, dish_id bigint NOT NULL,
qty int NOT NULL, unit_price numeric(8,2) NOT NULL);
CREATE TABLE order_line_options (
order_line_id bigint REFERENCES order_lines(id), option_id bigint REFERENCES modifier_options(id),
price_delta numeric(8,2) NOT NULL,
PRIMARY KEY (order_line_id, option_id)
);
Points that interviewers look for:
Groups are reusable: a 'Size' group can attach to many dishes through the link table.
min_select and max_select express rules such as 'choose exactly one size' (1 and 1) or 'up to three toppings' (0 and 3). The database cannot easily check these per order, so the order service validates them, ideally inside the same transaction that inserts the lines.
Prices are copied into order_lines.unit_price and order_line_options.price_delta, because menu prices change and old invoices must not.
Per-outlet prices and availability: outlet_dish(outlet_id, dish_id, price, available), with the base price as a fallback.
Price history for the menu itself uses validity dates (valid_from, valid_to) when future price changes are scheduled.
Key points
Reusable modifier groups linked to dishes
Options carry price deltas
Min and max selections per group
Copy prices onto order lines
Per-outlet prices and availability
Common mistakes
Referencing live menu prices from old orders
Storing chosen modifiers as free text
Follow-ups
How would you report the most popular topping per dish?
How would you schedule a price rise for next month?
Tips
Mention price copying on orders
491.sql-0491Mediummid
Design storage for application settings with global defaults, per-tenant overrides and a history of who changed what.
Use a settings definition table for keys and defaults, an overrides table keyed by (tenant, key), and a history table or trigger that records each change with user and time. Reads use COALESCE of the override and the default. Typed values, validation rules and caching in the application keep reads cheap, and cache invalidation is triggered by writes.
Full answer
Illustrative design (example SQL, not run here):
sql
CREATE TABLE setting_defs (
key text PRIMARY KEY,
value_type text NOT NULL CHECK (value_type IN ('int', 'bool', 'text', 'json')),
default_value jsonb NOT NULL,
description text
);
CREATE TABLE tenant_settings (
tenant_id bigint NOT NULL,
key text NOT NULL REFERENCES setting_defs(key),
value jsonb NOT NULL,
updated_by bigint,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, key)
);
CREATE TABLE tenant_settings_history (
id bigserial PRIMARY KEY, tenant_id bigint, key text,
old_value jsonb, new_value jsonb, changed_by bigint, changed_at timestamptz DEFAULT now()
);
Effective value for a tenant and key:
sql
SELECT COALESCE(t.value, d.default_value)
FROM setting_defs d
LEFT JOIN tenant_settings t ON t.key = d.key AND t.tenant_id = 42
WHERE d.key = 'max_upload_mb';
Design points: keep keys in a definitions table so typos are rejected by the foreign key and every key has a default and a documented meaning; store values as jsonb or text with a declared type and validate in the service layer, since a CHECK cannot easily validate by type; write history in the same transaction as the change (a trigger guarantees it even for manual edits); cache effective settings per tenant in the application and invalidate on write; and add an additional level, such as plan-level defaults between global and tenant, only when a real need appears, using the same COALESCE chain.
Settings that must be consistent across servers immediately, such as feature kill switches, may need shorter cache lifetimes or a pub-sub invalidation.
Key points
Definitions with defaults
Overrides keyed by tenant and key
COALESCE gives the effective value
History written in the same transaction
Cache with invalidation on write
Common mistakes
Free-form keys with no definitions table
Changing settings without recording who did it
Follow-ups
How would you add plan-level defaults between global and tenant?
How would you roll back a bad settings change?
Tips
Show the COALESCE read
492.sql-0492Mediummid
A dashboard shows each product's 'average rating' as the average of the per-store averages, and it differs from the true average. Find the cause.
Averaging averages gives every group the same weight regardless of how many rows it holds, so a store with two reviews counts as much as a store with two hundred. Compute the overall average from the underlying rows, or as SUM(total) / SUM(count) from the group totals.
Full answer
sql
CREATE TABLE reviews (product TEXT, store TEXT, rating INTEGER);
INSERT INTO reviews VALUES
('Lamp','North',5),('Lamp','North',5),
('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3);
The query as written:
sql
SELECT product, AVG(store_avg) AS avg_of_averages FROM (
SELECT product, store, AVG(rating) AS store_avg FROM reviews GROUP BY product, store
) GROUP BY product;
product
avg_of_averages
Lamp
3.75
The North store has two perfect ratings and South has six lukewarm ones. Averaging the two store averages (5.0 and 2.5) gives 3.75, as if each store had the same number of reviews.
A corrected version:
sql
SELECT product, AVG(rating) AS true_avg, SUM(rating) * 1.0 / COUNT(*) AS same_thing_from_totals FROM reviews GROUP BY product;
product
true_avg
same_thing_from_totals
Lamp
3.125
3.125
The real average over all eight reviews is 3.125, and the total-over-count form agrees. A weighted average is the correct way to roll up group averages, which is why stored summaries should keep sums and counts, not just averages. Multiplying by 1.0 avoids integer division in SQLite.
sql
CREATE TABLE reviews (product TEXT, store TEXT, rating INTEGER);
INSERT INTO reviews VALUES
('Lamp','North',5),('Lamp','North',5),
('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3),('Lamp','South',2),('Lamp','South',3);
SELECT product, AVG(store_avg) AS avg_of_averages FROM (
SELECT product, store, AVG(rating) AS store_avg FROM reviews GROUP BY product, store
) GROUP BY product;
SELECT product, AVG(rating) AS true_avg, SUM(rating) * 1.0 / COUNT(*) AS same_thing_from_totals FROM reviews GROUP BY product;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Average of averages ignores group sizes
Compute from rows or from sum and count
Store sum and count in summaries
Beware integer division
Common mistakes
Rolling up pre-averaged numbers
Keeping only averages in summary tables
Follow-ups
How would you merge two stored (sum, count) summaries?
When is an unweighted average of groups actually wanted?
Tips
Use extreme group sizes in the example
493.sql-0493Mediummid
A user cannot register with an email address they used on a deleted account, although the application soft-deletes accounts. Fix the uniqueness rule.
A plain UNIQUE constraint on email also counts soft-deleted rows. Replace it with a partial unique index that applies only to live rows, WHERE deleted_at IS NULL, supported by both SQLite and PostgreSQL. Deleted rows then no longer block new accounts, while two active accounts still cannot share an email.
Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, deleted_at TEXT);
INSERT INTO accounts VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);
The query as written:
sql
INSERT INTO accounts (email) VALUES ('ana@x.com'); -- error on purpose
text
Error: UNIQUE constraint failed: accounts.email
The old account 1 is marked deleted, but its row still holds the email, so the table-wide UNIQUE constraint rejects the new registration.
A corrected version:
sql
CREATE TABLE accounts2 (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX accounts2_live_email ON accounts2 (email) WHERE deleted_at IS NULL;
INSERT INTO accounts2 VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);
INSERT INTO accounts2 (email) VALUES ('ana@x.com');
SELECT id, email, deleted_at FROM accounts2 ORDER BY id;
With the partial index, the deleted row is ignored by the uniqueness check, so Ana can register again and both rows exist side by side. A second live row with the same email would still fail. Queries on live accounts should add deleted_at IS NULL, which also lets them use the partial index. The same index definition works in PostgreSQL, where ON CONFLICT targets must repeat the predicate.
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, deleted_at TEXT);
INSERT INTO accounts VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);
-- error on purpose
INSERT INTO accounts (email) VALUES ('ana@x.com');
CREATE TABLE accounts2 (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX accounts2_live_email ON accounts2 (email) WHERE deleted_at IS NULL;
INSERT INTO accounts2 VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);
INSERT INTO accounts2 (email) VALUES ('ana@x.com');
SELECT id, email, deleted_at FROM accounts2 ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Plain UNIQUE counts deleted rows
Partial unique index limits the rule to live rows
Live queries should filter deleted_at IS NULL
Works in SQLite and PostgreSQL
Common mistakes
Appending a suffix to deleted emails as a workaround
Forgetting the predicate in queries so the index is unused
Follow-ups
How would you restore a deleted account whose email was reused?
What other constraints need the same treatment?
Tips
Show the failing insert first
494.sql-0494Easyfresher
A report shows completion rates of 0 for every course, although many students have finished. What is wrong?
Dividing one integer by another in SQLite and PostgreSQL discards the fraction, so 3 / 4 is 0. Make at least one side a decimal before dividing, for example 100.0 * done / total, and round only for display.
SELECT course, SUM(finished) / COUNT(*) AS completion_rate FROM enrolments GROUP BY course ORDER BY course;
course
completion_rate
Python
0
SQL
0
SQL has 3 of 4 finished and Python 1 of 3, but 3 / 4 and 1 / 3 are integer divisions that truncate to 0.
A corrected version:
sql
SELECT course, ROUND(100.0 * SUM(finished) / COUNT(*), 1) AS completion_pct FROM enrolments GROUP BY course ORDER BY course;
course
completion_pct
Python
33.3
SQL
75.0
Starting the expression with 100.0 forces decimal arithmetic, giving 75.0 and 33.3 percent. PostgreSQL behaves the same way with integers, so the fix is portable; there, SUM(finished)::numeric / COUNT(*) also works. Rounding belongs in the final display step, because rounding early and then averaging compounds the error.
sql
CREATE TABLE enrolments (course TEXT, student TEXT, finished INTEGER);
INSERT INTO enrolments VALUES
('SQL','a',1),('SQL','b',1),('SQL','c',1),('SQL','d',0),
('Python','a',1),('Python','b',0),('Python','c',0);
SELECT course, SUM(finished) / COUNT(*) AS completion_rate FROM enrolments GROUP BY course ORDER BY course;
SELECT course, ROUND(100.0 * SUM(finished) / COUNT(*), 1) AS completion_pct FROM enrolments GROUP BY course ORDER BY course;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Integer division truncates
Use 100.0 or a cast to force decimals
Same behaviour in PostgreSQL
Round only at the end
Common mistakes
Rounding before further arithmetic
Assuming the database promotes integers automatically
Follow-ups
What does 7 / 2 return in SQLite versus MySQL?
How would you handle a course with zero enrolments?
Tips
Show both fractions truncating
495.sql-0495Hardsenior
A subscription renews on the 31st of each month, but adding one month with date arithmetic gives dates like 3 March. How should month-end renewals work?
Adding one month to 31 January is ambiguous because February has no 31st. SQLite's date function overflows into the next month (31 January plus one month becomes 3 March), while PostgreSQL clamps to the last day of the month. Store the intended day of month and compute each renewal from the original anchor date, clamped to month end, instead of adding a month to the previous renewal.
Full answer
sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, started TEXT);
INSERT INTO subs VALUES (1, '2026-01-31');
The query as written:
sql
SELECT started, date(started, '+1 month') AS second, date(started, '+2 month') AS third, date(date(started, '+1 month'), '+1 month') AS chained_third FROM subs;
started
second
third
chained_third
2026-01-31
2026-03-03
2026-03-31
2026-04-03
Overflow moves the second renewal to 3 March, and chaining month additions from that overflowed date drifts the schedule further from the 31st.
A corrected version:
sql
SELECT started, MIN(date(started, '+1 month'), date(started, 'start of month', '+2 month', '-1 day')) AS clamped_second, date(started, 'start of month', '+3 month', '-1 day') AS third_month_end FROM subs;
started
clamped_second
third_month_end
2026-01-31
2026-02-28
2026-03-31
Clamping takes the smaller of the overflowed date and the last day of the target month, which gives 28 February; the March renewal is month end again because the anchor day (31) is kept in the schedule, not copied from the previous renewal. In PostgreSQL, started + interval '1 month' already clamps, but chaining intervals still drifts (31 Jan, 28 Feb, 28 Mar), so renewals should always be computed from the anchor. The PostgreSQL behaviour here is stated, not run.
sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, started TEXT);
INSERT INTO subs VALUES (1, '2026-01-31');
SELECT started, date(started, '+1 month') AS second, date(started, '+2 month') AS third, date(date(started, '+1 month'), '+1 month') AS chained_third FROM subs;
SELECT started, MIN(date(started, '+1 month'), date(started, 'start of month', '+2 month', '-1 day')) AS clamped_second, date(started, 'start of month', '+3 month', '-1 day') AS third_month_end FROM subs;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Month arithmetic is ambiguous at month end
SQLite overflows, PostgreSQL clamps
Compute each cycle from the anchor date
Clamp to the last day of the target month
Common mistakes
Adding a month to the previous renewal date
Assuming all databases handle month ends the same way
Follow-ups
How would you handle leap years for annual renewals?
How would you test renewal dates for every start day?
Tips
Use 31 January as the example
496.sql-0496Mediummid
A timeline page shows events from 5 March missing when filtering with WHERE created_at <= '2026-03-05 23:59'. Some rows use a 'T' separator. Why?
Text timestamps compare character by character. A space (ASCII 32) sorts before 'T' (ASCII 84), so '2026-03-05T10:00' is greater than '2026-03-05 23:59' and is excluded, while the same time written with a space is included. Normalise the format on write, store a real timestamp type, or compare using datetime() in SQLite, which parses both forms.
Full answer
sql
CREATE TABLE timeline (id INTEGER PRIMARY KEY, created_at TEXT);
INSERT INTO timeline VALUES (1,'2026-03-05 09:00'),(2,'2026-03-05T10:00'),(3,'2026-03-05 22:30'),(4,'2026-03-06 01:00');
The query as written:
sql
SELECT id, created_at FROM timeline WHERE created_at <= '2026-03-05 23:59' ORDER BY id;
id
created_at
1
2026-03-05 09:00
3
2026-03-05 22:30
Row 2 happened on 5 March at 10:00, well before the cut-off, yet it is missing: after the matching date prefix, the comparison reaches the separator, and 'T' sorts after the space in the filter value.
A corrected version:
sql
SELECT id, created_at FROM timeline WHERE datetime(created_at) <= datetime('2026-03-05 23:59') ORDER BY id;
id
created_at
1
2026-03-05 09:00
2
2026-03-05T10:00
3
2026-03-05 22:30
datetime() parses both separators into a canonical 'YYYY-MM-DD HH:MM:SS' string, so row 2 is included and only the 6 March row is excluded. The deeper fix is to store one format, ideally a native timestamp type in PostgreSQL, and reject others at insert time with a CHECK constraint. Wrapping the column in a function also prevents plain index use, which is another reason to normalise data rather than the query.
sql
CREATE TABLE timeline (id INTEGER PRIMARY KEY, created_at TEXT);
INSERT INTO timeline VALUES (1,'2026-03-05 09:00'),(2,'2026-03-05T10:00'),(3,'2026-03-05 22:30'),(4,'2026-03-06 01:00');
SELECT id, created_at FROM timeline WHERE created_at <= '2026-03-05 23:59' ORDER BY id;
SELECT id, created_at FROM timeline WHERE datetime(created_at) <= datetime('2026-03-05 23:59') ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Text timestamps compare character by character
Space sorts before T
datetime() normalises both forms
Normalise at write time
Functions on the column block plain indexes
Common mistakes
Mixing separators in text timestamps
Fixing the query while leaving the data inconsistent
Follow-ups
How would you add a CHECK that enforces one format?
How do PostgreSQL timestamp types avoid this class of bug?
Tips
Compare the separator characters
497.sql-0497Mediummid
Pagination with ORDER BY created_at LIMIT 3 OFFSET n shows the same order on two pages and skips another. Why, and how is it fixed?
When several rows share the same sort value, their relative order is not defined, so each page query may order the ties differently and rows can repeat or vanish between pages. Add a unique tie-breaker such as the id to ORDER BY, so every page sees one total order. For deep pages, keyset pagination avoids OFFSET entirely.
Full answer
sql
CREATE TABLE feed (id INTEGER PRIMARY KEY, created_at TEXT, title TEXT);
INSERT INTO feed VALUES (1,'2026-03-01','a'),(2,'2026-03-01','b'),(3,'2026-03-01','c'),(4,'2026-03-01','d'),(5,'2026-03-02','e'),(6,'2026-03-02','f');
The query as written:
sql
SELECT id, created_at FROM feed ORDER BY created_at LIMIT 3 OFFSET 0;
id
created_at
1
2026-03-01
2
2026-03-01
3
2026-03-01
Four rows share 1 March, so the first page of three could contain any three of them. The database is free to return a different three for the next page, and nothing in the query makes the order repeatable; this run happens to show insertion order, which is an accident of the current plan, not a guarantee.
A corrected version:
sql
SELECT id, created_at FROM feed WHERE (created_at, id) > ('2026-03-01', 3) ORDER BY created_at, id LIMIT 3;
id
created_at
4
2026-03-01
5
2026-03-02
6
2026-03-02
With ORDER BY created_at, id every row has one fixed position, so page boundaries are stable. The corrected query uses keyset pagination: it asks for the rows after the last seen pair (1 March, id 3), returning row 4 and then the two 2 March rows, with no OFFSET and no overlap. Row-value comparison works in SQLite 3.15+ and in PostgreSQL, and an index on (created_at, id) makes each page cheap.
sql
CREATE TABLE feed (id INTEGER PRIMARY KEY, created_at TEXT, title TEXT);
INSERT INTO feed VALUES (1,'2026-03-01','a'),(2,'2026-03-01','b'),(3,'2026-03-01','c'),(4,'2026-03-01','d'),(5,'2026-03-02','e'),(6,'2026-03-02','f');
SELECT id, created_at FROM feed ORDER BY created_at LIMIT 3 OFFSET 0;
SELECT id, created_at FROM feed WHERE (created_at, id) > ('2026-03-01', 3) ORDER BY created_at, id LIMIT 3;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Ties have no defined order
Add a unique tie-breaker to ORDER BY
Keyset pagination avoids OFFSET
Row-value comparison handles two sort keys
Index the sort columns together
Common mistakes
Paginating on a non-unique column alone
Assuming the insertion order will be repeated
Follow-ups
How would you paginate backwards?
How would an API hand the next-page position to the client?
Tips
Name the tie-breaker
498.sql-0498Hardsenior
Revenue doubles after joining orders to both payments and shipments in one query. Where does the extra revenue come from?
Joining a parent to two independent child tables produces one row per combination of children. An order with two payments and two shipments becomes four rows, so summing the order total counts it four times. Aggregate each child table separately in a subquery or CTE, and join the one-row-per-order results.
Full answer
sql
CREATE TABLE ord (id INTEGER PRIMARY KEY, total INTEGER);
CREATE TABLE payments (order_id INTEGER, amount INTEGER);
CREATE TABLE shipments (order_id INTEGER, carrier TEXT);
INSERT INTO ord VALUES (1, 100), (2, 50);
INSERT INTO payments VALUES (1, 60), (1, 40), (2, 50);
INSERT INTO shipments VALUES (1, 'A'), (1, 'B'), (2, 'A');
The query as written:
sql
SELECT SUM(o.total) AS revenue FROM ord o JOIN payments p ON p.order_id = o.id JOIN shipments s ON s.order_id = o.id;
revenue
450
The query returns 450, but the true revenue is 150. Order 1 has two payments and two shipments, producing four joined rows that each carry total 100, so it contributes 400; order 2 contributes 50.
A corrected version:
sql
SELECT SUM(o.total) AS revenue, SUM(p.paid) AS paid, SUM(s.parcels) AS parcels
FROM ord o
LEFT JOIN (SELECT order_id, SUM(amount) AS paid FROM payments GROUP BY order_id) p ON p.order_id = o.id
LEFT JOIN (SELECT order_id, COUNT(*) AS parcels FROM shipments GROUP BY order_id) s ON s.order_id = o.id;
revenue
paid
parcels
150
150
3
Each child table is collapsed to one row per order before joining, so every order is counted once: revenue 150, payments 150 and 3 parcels. The symptom, totals that grow when another join is added, is one of the most common reporting bugs; reconcile a new join by comparing the total with and without it. LEFT JOINs also keep orders that have no payments or shipments.
sql
CREATE TABLE ord (id INTEGER PRIMARY KEY, total INTEGER);
CREATE TABLE payments (order_id INTEGER, amount INTEGER);
CREATE TABLE shipments (order_id INTEGER, carrier TEXT);
INSERT INTO ord VALUES (1, 100), (2, 50);
INSERT INTO payments VALUES (1, 60), (1, 40), (2, 50);
INSERT INTO shipments VALUES (1, 'A'), (1, 'B'), (2, 'A');
SELECT SUM(o.total) AS revenue FROM ord o JOIN payments p ON p.order_id = o.id JOIN shipments s ON s.order_id = o.id;
SELECT SUM(o.total) AS revenue, SUM(p.paid) AS paid, SUM(s.parcels) AS parcels
FROM ord o
LEFT JOIN (SELECT order_id, SUM(amount) AS paid FROM payments GROUP BY order_id) p ON p.order_id = o.id
LEFT JOIN (SELECT order_id, COUNT(*) AS parcels FROM shipments GROUP BY order_id) s ON s.order_id = o.id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Two child joins multiply rows
Aggregate children before joining
Compare totals before and after each join
LEFT JOIN keeps parents without children
Common mistakes
Using SUM(DISTINCT) as a fix
Joining several one-to-many tables directly
Follow-ups
Why does SUM(DISTINCT total) fail as a repair?
How would you detect a fan-out in a large query?
Tips
Reconcile against a known total
499.sql-0499Easyfresher
A discount query assigns every order to the 'standard' tier although some orders are over 500. Why does the CASE expression ignore the larger tiers?
CASE returns the result of the first WHEN condition that is true and stops. If a broad condition such as total > 0 comes first, larger totals never reach later branches. Order the conditions from most specific to least specific, or use non-overlapping ranges.
Full answer
sql
CREATE TABLE tier_orders (id INTEGER PRIMARY KEY, total INTEGER);
INSERT INTO tier_orders VALUES (1, 80), (2, 300), (3, 750), (4, 0);
The query as written:
sql
SELECT id, total, CASE WHEN total > 0 THEN 'standard' WHEN total > 250 THEN 'silver' WHEN total > 500 THEN 'gold' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;
id
total
tier
1
80
standard
2
300
standard
3
750
standard
4
0
none
Every positive total matches the first condition, so 'silver' and 'gold' can never be reached. The ELSE branch is used only for the zero total.
A corrected version:
sql
SELECT id, total, CASE WHEN total > 500 THEN 'gold' WHEN total > 250 THEN 'silver' WHEN total > 0 THEN 'standard' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;
id
total
tier
1
80
standard
2
300
silver
3
750
gold
4
0
none
Testing the strictest condition first gives gold for 750, silver for 300, standard for 80 and none for 0. The same first-match rule applies to CASE in PostgreSQL. For tiers that live in data, a small lookup table of thresholds joined with a range condition is easier to change than editing a CASE expression, and unit tests should include a value in each band and each boundary.
sql
CREATE TABLE tier_orders (id INTEGER PRIMARY KEY, total INTEGER);
INSERT INTO tier_orders VALUES (1, 80), (2, 300), (3, 750), (4, 0);
SELECT id, total, CASE WHEN total > 0 THEN 'standard' WHEN total > 250 THEN 'silver' WHEN total > 500 THEN 'gold' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;
SELECT id, total, CASE WHEN total > 500 THEN 'gold' WHEN total > 250 THEN 'silver' WHEN total > 0 THEN 'standard' ELSE 'none' END AS tier FROM tier_orders ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
CASE stops at the first true condition
Order conditions from most to least specific
Test every band and boundary
Lookup tables suit changing thresholds
Common mistakes
Putting the broadest condition first
Leaving boundaries untested
Follow-ups
How would a threshold table express the same tiers?
What does CASE return when no branch matches and ELSE is missing?
Tips
Walk one value through the branches
500.sql-0500Hardsenior
A team wants to add a UNIQUE constraint on (customer_id, product) to a table that already contains duplicates. How do you find the duplicates, clean them safely and add the constraint?
Find duplicate groups with GROUP BY and HAVING COUNT(*) > 1, decide which row survives (often the newest or the lowest id), and merge any values that need combining, such as quantities, before deleting the rest. Do it in a transaction after a backup, then add the unique index, in PostgreSQL concurrently on large tables. Verify with a duplicate query that returns no rows.
Full answer
sql
CREATE TABLE cart_lines (id INTEGER PRIMARY KEY, customer_id INTEGER, product TEXT, qty INTEGER);
INSERT INTO cart_lines VALUES (1,1,'Pen',2),(2,1,'Pen',3),(3,1,'Bag',1),(4,2,'Bag',1),(5,2,'Bag',1),(6,2,'Bag',2);
Find the duplicate groups:
sql
SELECT customer_id, product, COUNT(*) AS copies, SUM(qty) AS total_qty FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1 ORDER BY customer_id;
customer_id
product
copies
total_qty
1
Pen
2
5
2
Bag
3
4
Merge quantities into the surviving row, keeping the lowest id, then delete the others:
sql
UPDATE cart_lines SET qty = (SELECT SUM(c.qty) FROM cart_lines c WHERE c.customer_id = cart_lines.customer_id AND c.product = cart_lines.product) WHERE id IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
DELETE FROM cart_lines WHERE id NOT IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
SELECT id, customer_id, product, qty FROM cart_lines ORDER BY id;
id
customer_id
product
qty
1
1
Pen
5
3
1
Bag
1
4
2
Bag
4
Add the constraint and confirm it now protects the table:
sql
CREATE UNIQUE INDEX cart_lines_unique ON cart_lines (customer_id, product);
SELECT COUNT(*) AS duplicate_groups FROM (SELECT 1 FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1);
duplicate_groups
0
sql
INSERT INTO cart_lines (customer_id, product, qty) VALUES (1, 'Pen', 1); -- error on purpose
The duplicate check shows customer 1's two Pen rows and customer 2's three Bag rows. The merge sums the quantities onto the lowest id in each group, so no information is lost, and the delete removes the other rows. With the unique index in place, a repeat insert fails with a constraint error naming the columns (the exact wording depends on the database), which is the point of the exercise. On PostgreSQL, build the index with CREATE UNIQUE INDEX CONCURRENTLY first and then attach it as a constraint, so writes are not blocked, and decide with the business whether duplicates should be merged or the application should switch to an upsert (INSERT ... ON CONFLICT DO UPDATE) going forward.
sql
CREATE TABLE cart_lines (id INTEGER PRIMARY KEY, customer_id INTEGER, product TEXT, qty INTEGER);
INSERT INTO cart_lines VALUES (1,1,'Pen',2),(2,1,'Pen',3),(3,1,'Bag',1),(4,2,'Bag',1),(5,2,'Bag',1),(6,2,'Bag',2);
SELECT customer_id, product, COUNT(*) AS copies, SUM(qty) AS total_qty FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1 ORDER BY customer_id;
UPDATE cart_lines SET qty = (SELECT SUM(c.qty) FROM cart_lines c WHERE c.customer_id = cart_lines.customer_id AND c.product = cart_lines.product) WHERE id IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
DELETE FROM cart_lines WHERE id NOT IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
SELECT id, customer_id, product, qty FROM cart_lines ORDER BY id;
CREATE UNIQUE INDEX cart_lines_unique ON cart_lines (customer_id, product);
SELECT COUNT(*) AS duplicate_groups FROM (SELECT 1 FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1);
-- error on purpose
INSERT INTO cart_lines (customer_id, product, qty) VALUES (1, 'Pen', 1);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Find duplicates with GROUP BY and HAVING
Choose a survivor and merge values
Clean up in a transaction
Add the unique index afterwards
Use upserts to stop new duplicates
Common mistakes
Deleting duplicates before deciding what to merge
Adding the constraint without a verification query
Follow-ups
How would you keep the newest row instead of the oldest?
How would you find near-duplicates that differ in case or spacing?