Questions 261–280 of 501 · 0 of 20 on this page marked learned
261.sql-0261Mediummid
Write a query that compares each month's revenue with the same month one year earlier.
Aggregate revenue per month, then LEFT JOIN the result to itself on the same month number one year earlier. LAG(revenue, 12) works only if every month is present, so the join on computed keys is safer when months can be missing.
Full answer
sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT cur.month, cur.revenue, prev.revenue AS last_year,
ROUND(100.0 * (cur.revenue - prev.revenue) / NULLIF(prev.revenue, 0), 1) AS yoy_pct
FROM m cur
LEFT JOIN m prev ON prev.month = printf('%04d', CAST(substr(cur.month, 1, 4) AS INTEGER) - 1) || substr(cur.month, 5)
WHERE cur.month >= '2026-01'
ORDER BY cur.month;
month
revenue
last_year
yoy_pct
2026-02
90
NULL
NULL
2026-03
130
100
30.0
March 2026 compares with March 2025. February 2026 has no row a year earlier, so the LEFT JOIN keeps it with NULL rather than dropping it.
The LAG version is shorter but assumes exactly 12 rows per year in order. With a missing month, LAG(revenue, 12) silently compares with the wrong month:
sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT month, revenue, LAG(revenue, 12) OVER (ORDER BY month) AS lag12 FROM m ORDER BY month;
month
revenue
lag12
2025-03
100
NULL
2025-04
80
NULL
2026-02
90
NULL
2026-03
130
NULL
Here only four months exist, so LAG finds nothing 12 rows back and returns NULL everywhere, including for March 2026, which does have a prior-year month. Fill the calendar first if you want to use LAG.
sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT cur.month, cur.revenue, prev.revenue AS last_year,
ROUND(100.0 * (cur.revenue - prev.revenue) / NULLIF(prev.revenue, 0), 1) AS yoy_pct
FROM m cur
LEFT JOIN m prev ON prev.month = printf('%04d', CAST(substr(cur.month, 1, 4) AS INTEGER) - 1) || substr(cur.month, 5)
WHERE cur.month >= '2026-01'
ORDER BY cur.month;
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT month, revenue, LAG(revenue, 12) OVER (ORDER BY month) AS lag12 FROM m ORDER BY month;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Aggregate per month first
Join each month to the same month a year earlier
LEFT JOIN keeps months without history
LAG(x, 12) needs a complete month series
Common mistakes
Using LAG(12) on data with missing months
Dividing by a NULL or zero prior value without NULLIF
Follow-ups
How would you compute the growth percentage?
How would you handle a fiscal year starting in April?
Tips
Mention the missing-month risk
262.sql-0262Easyfresher
For each customer, return the date and id of their first order.
Rank each customer's orders by date with ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) and keep row 1. MIN(order_date) per customer gives the date but not the id, and joining back on the date can return two rows if a customer ordered twice that day.
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 r AS (
SELECT customer_id, id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) AS rn
FROM orders WHERE customer_id IS NOT NULL
)
SELECT customer_id, id AS first_order, order_date FROM r WHERE rn = 1 ORDER BY customer_id;
customer_id
first_order
order_date
1
101
2026-01-05
2
103
2026-02-14
3
104
2026-03-01
The id tie-breaker makes the choice deterministic when two orders share a date. The guest order with no customer is excluded.
If only the date is needed, a plain aggregate is simplest:
sql
SELECT customer_id, MIN(order_date) AS first_date FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id ORDER BY customer_id;
customer_id
first_date
1
2026-01-05
2
2026-02-14
3
2026-03-01
SQLite also has a documented shortcut: in a query with a single MIN or MAX aggregate, bare columns come from the row that held the minimum, so the id comes from each customer's earliest order:
sql
SELECT customer_id, MIN(order_date) AS first_date, id FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id ORDER BY customer_id;
customer_id
first_date
id
1
2026-01-05
101
2
2026-02-14
103
3
2026-03-01
104
It is SQLite-specific, and PostgreSQL rejects it:
sql
SELECT customer_id, MIN(order_date), id FROM orders GROUP BY customer_id; -- error on purpose
text
Error: column "orders.id" must appear in the GROUP BY clause or be used in an aggregate function
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 r AS (
SELECT customer_id, id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) AS rn
FROM orders WHERE customer_id IS NOT NULL
)
SELECT customer_id, id AS first_order, order_date FROM r WHERE rn = 1 ORDER BY customer_id;
SELECT customer_id, MIN(order_date) AS first_date FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id ORDER BY customer_id;
SELECT customer_id, MIN(order_date) AS first_date, id FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id ORDER BY customer_id;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
ROW_NUMBER per customer ordered by date, keep row 1
Add a tie-breaker for same-day orders
MIN gives the date but not the row
SQLite's bare-column MIN rule is not portable
Common mistakes
Joining back on MIN(date) and getting duplicates
Relying on SQLite's bare columns in portable code
Follow-ups
How would you get each customer's latest order instead?
How would you get the first order's total amount?
Tips
Mention the tie-breaker
263.sql-0263Mediummid
Write a query that returns the best-selling product (by quantity) in each order status, including ties.
Aggregate quantity per status and product, rank products within each status with RANK() OVER (PARTITION BY status ORDER BY total_qty DESC), and keep rank 1. RANK keeps every product tied for first; ROW_NUMBER would pick 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);
sql
WITH t AS (
SELECT o.status, i.product, SUM(i.qty) AS total_qty,
RANK() OVER (PARTITION BY o.status ORDER BY SUM(i.qty) DESC) AS rnk
FROM orders o JOIN order_items i ON i.order_id = o.id
GROUP BY o.status, i.product
)
SELECT status, product, total_qty FROM t WHERE rnk = 1 ORDER BY status, product;
status
product
total_qty
cancelled
Pen
10
pending
Lamp
1
shipped
Pen
7
Pen leads in both cancelled and shipped orders. In pending orders only Lamp was sold, so it is the top by default.
Two levels of grouping are involved: the GROUP BY totals quantities per status and product, and the window ranks those totals within each status. The window runs after the GROUP BY, which is why SUM(i.qty) can appear inside its ORDER BY.
Swapping RANK for ROW_NUMBER returns exactly one row per status, which suits a dashboard tile but hides ties. Say which behaviour you chose.
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 t AS (
SELECT o.status, i.product, SUM(i.qty) AS total_qty,
RANK() OVER (PARTITION BY o.status ORDER BY SUM(i.qty) DESC) AS rnk
FROM orders o JOIN order_items i ON i.order_id = o.id
GROUP BY o.status, i.product
)
SELECT status, product, total_qty FROM t WHERE rnk = 1 ORDER BY status, product;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Aggregate, then rank within each group
RANK keeps all ties for first place
Window functions can order by aggregates
State the tie behaviour
Common mistakes
Ranking raw order lines instead of totals
Using ROW_NUMBER and hiding a tie
Follow-ups
How would you return the top 2 per status?
How would you rank by revenue instead?
Tips
Mention both levels of grouping
264.sql-0264Mediummid
Return a random sample of 3 rows from a table. What are the trade-offs of ORDER BY random()?
ORDER BY random() LIMIT 3 is simple and correct but sorts the whole table, which is slow on large data. Faster options include picking random ids within the id range (biased if ids have gaps), filtering with WHERE random() % 100 = 0 for an approximate share, or PostgreSQL's TABLESAMPLE.
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');
sql
SELECT COUNT(*) AS sampled FROM (SELECT id FROM employees ORDER BY random() LIMIT 3);
sampled
3
The output changes on every run, so only the row count is shown here, which stays the same. Sorting by a random key gives every row an equal chance but needs a full scan and sort.
For a rough 1-in-N sample without sorting, filter instead. The share is approximate:
text
SELECT * FROM big_table WHERE abs(random()) % 100 = 0; -- about 1 percent
PostgreSQL offers TABLESAMPLE SYSTEM (1) (page-level, fast, clustered) and TABLESAMPLE BERNOULLI (1) (row-level, slower, more even), and setseed() or REPEATABLE (seed) for reproducible samples (not run here).
For tests that must be reproducible, sample by a hash of the id rather than a random function.
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 COUNT(*) AS sampled FROM (SELECT id FROM employees ORDER BY random() LIMIT 3);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
ORDER BY random() LIMIT n is simple but sorts everything
Random filters give approximate fractions cheaply
PostgreSQL TABLESAMPLE samples pages or rows
Hash-based sampling is reproducible
Common mistakes
Using ORDER BY random() on very large tables
Picking random ids when ids have big gaps
Follow-ups
How would you sample 1 percent of users per country?
How would you make a sample reproducible?
Tips
Mention the sort cost
265.sql-0265Mediummid
Write a query that shows, for each day, the number of orders and the number of distinct customers, including days with no orders, for 2026-03-01 to 2026-03-12.
Generate the date range with a recursive CTE, LEFT JOIN orders on the date, and aggregate with COUNT(o.id) and COUNT(DISTINCT o.customer_id). Counting a column from the orders side gives 0 on empty days, while COUNT(*) would count the calendar row and return 1.
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 RECURSIVE d(day) AS (
SELECT '2026-03-01' UNION ALL SELECT date(day, '+1 day') FROM d WHERE day < '2026-03-12'
)
SELECT d.day, COUNT(o.id) AS orders, COUNT(DISTINCT o.customer_id) AS customers
FROM d LEFT JOIN orders o ON o.order_date = d.day
GROUP BY d.day
HAVING d.day IN ('2026-03-01', '2026-03-02', '2026-03-09', '2026-03-12')
ORDER BY d.day;
day
orders
customers
2026-03-01
1
1
2026-03-02
0
0
2026-03-09
1
1
2026-03-12
1
0
Only three days in the range have orders. COUNT(o.id) returns 0 elsewhere because the joined order columns are NULL. COUNT(*) would return 1 for those days, which is a classic mistake in gap-filled reports.
The guest order on 12 March has no customer, so it counts as an order but adds nothing to distinct customers.
In PostgreSQL, generate_series(DATE '2026-03-01', DATE '2026-03-12', INTERVAL '1 day') replaces the recursive CTE.
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 RECURSIVE d(day) AS (
SELECT '2026-03-01' UNION ALL SELECT date(day, '+1 day') FROM d WHERE day < '2026-03-12'
)
SELECT d.day, COUNT(o.id) AS orders, COUNT(DISTINCT o.customer_id) AS customers
FROM d LEFT JOIN orders o ON o.order_date = d.day
GROUP BY d.day
HAVING d.day IN ('2026-03-01', '2026-03-02', '2026-03-09', '2026-03-12')
ORDER BY d.day;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Generate the calendar, then LEFT JOIN
COUNT a column from the joined side
COUNT(*) counts the calendar row on empty days
COUNT(DISTINCT) ignores NULL customers
Common mistakes
Using COUNT(*) after a LEFT JOIN
Filtering the joined table in WHERE and losing empty days
Follow-ups
How would you show a 7-day rolling count?
How would you do this per country?
Tips
Point out COUNT(*) versus COUNT(col)
266.sql-0266Easyfresher
A student table has a marks column. Write a query that returns each student's mark and the class average, and flags whether they are above it.
Use AVG(marks) OVER () to put the overall average on every row, then compare with CASE. A scalar subquery (SELECT AVG(marks) FROM ...) does the same. Both ignore NULL marks in the average.
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
SELECT student_id, course_id, marks,
ROUND(AVG(marks) OVER (), 1) AS class_avg,
CASE WHEN marks IS NULL THEN 'no mark'
WHEN marks > AVG(marks) OVER () THEN 'above'
ELSE 'not above' END AS flag
FROM enrolments ORDER BY student_id, course_id;
student_id
course_id
marks
class_avg
flag
1
10
88
75.0
above
1
20
92
75.0
above
2
10
75
75.0
not above
2
30
NULL
75.0
no mark
3
10
64
75.0
not above
3
20
71
75.0
not above
3
30
80
75.0
above
5
20
55
75.0
not above
The seven non-NULL marks average exactly 75.0; AVG skips the NULL, so it divides by seven, not eight. Ben's 75 in Databases equals the average and is therefore 'not above'.
Ben's NULL mark is labelled 'no mark' by testing for NULL first. Without that branch, NULL > 75 would be unknown, the CASE would fall through to ELSE, and the row would be labelled 'not above', which is misleading.
The scalar subquery form is equivalent:
sql
SELECT COUNT(*) AS above_avg FROM enrolments WHERE marks > (SELECT AVG(marks) FROM enrolments);
above_avg
3
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);
SELECT student_id, course_id, marks,
ROUND(AVG(marks) OVER (), 1) AS class_avg,
CASE WHEN marks IS NULL THEN 'no mark'
WHEN marks > AVG(marks) OVER () THEN 'above'
ELSE 'not above' END AS flag
FROM enrolments ORDER BY student_id, course_id;
SELECT COUNT(*) AS above_avg FROM enrolments WHERE marks > (SELECT AVG(marks) FROM enrolments);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
AVG(x) OVER () gives an overall average per row
A scalar subquery is an alternative
AVG ignores NULLs
Handle NULL before comparing
Common mistakes
Using GROUP BY and losing the per-student rows
Labelling NULL marks as below average
Follow-ups
How would you compare with the course average instead?
How would you show the difference from the average?
Tips
Handle the NULL row explicitly
267.sql-0267Easyfresher
How would you return customers who ordered in January but not in February?
Find January customers and remove February customers: EXCEPT between two SELECT DISTINCT customer_id queries, or NOT EXISTS for a February order per January customer. Use date ranges so the month filters stay index-friendly, and exclude NULL guest customers.
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 FROM orders WHERE order_date >= '2026-01-01' AND order_date < '2026-02-01'
EXCEPT
SELECT customer_id FROM orders WHERE order_date >= '2026-02-01' AND order_date < '2026-03-01';
customer_id
(0 rows)
Ana ordered on 5 January and again on 11 February, so she does not qualify. No other customer ordered in January, so the result is empty, which is a valid answer. Changing the second month to March shows the shape of a non-empty result:
sql
SELECT customer_id FROM orders WHERE order_date >= '2026-01-01' AND order_date < '2026-02-01'
EXCEPT
SELECT customer_id FROM orders WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';
customer_id
1
The NOT EXISTS form returns the same rows and is easier to extend with extra columns:
text
SELECT DISTINCT o.customer_id FROM orders o
WHERE o.order_date >= '2026-01-01' AND o.order_date < '2026-02-01'
AND NOT EXISTS (SELECT 1 FROM orders x WHERE x.customer_id = o.customer_id
AND x.order_date >= '2026-02-01' AND x.order_date < '2026-03-01');
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
SELECT customer_id FROM orders WHERE order_date >= '2026-01-01' AND order_date < '2026-02-01'
EXCEPT
SELECT customer_id FROM orders WHERE order_date >= '2026-02-01' AND order_date < '2026-03-01';
SELECT customer_id FROM orders WHERE order_date >= '2026-01-01' AND order_date < '2026-02-01'
EXCEPT
SELECT customer_id FROM orders WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';
Checked on SQLite 3.46.1, run twice with identical output.
Key points
EXCEPT removes one set from another
NOT EXISTS is the per-row equivalent
Use half-open date ranges
Empty results can be correct
Common mistakes
Using NOT IN against a column with NULL guests
Filtering months with substr and losing index use
Follow-ups
How would you find customers active in every month?
How would you count churned customers per month?
Tips
Check the empty-result case
268.sql-0268Hardsenior
Given a table of seats with a taken flag, find runs of at least three adjacent free seats.
Filter to free seats, then apply the islands trick: seat_no - ROW_NUMBER() OVER (ORDER BY seat_no) is constant within a run of adjacent numbers. Group by that key and keep groups with COUNT(*) >= 3, returning the first and last seat of each run.
Full answer
sql
WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
free AS (SELECT seat_no, seat_no - ROW_NUMBER() OVER (ORDER BY seat_no) AS grp FROM seats WHERE taken = 0)
SELECT MIN(seat_no) AS first_seat, MAX(seat_no) AS last_seat, COUNT(*) AS seats
FROM free GROUP BY grp HAVING COUNT(*) >= 3;
first_seat
last_seat
seats
5
8
4
Free seats are 1, 2, 5, 6, 7, 8 and 10. Subtracting the row number gives keys 0, 0, 2, 2, 2, 2 and 3, so the islands are 1 to 2, 5 to 8 and 10 alone. Only 5 to 8 has at least three seats.
For booking, return every possible starting seat for a group of three instead of whole runs:
sql
WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
f AS (SELECT seat_no, LEAD(seat_no, 2) OVER (ORDER BY seat_no) AS two_ahead FROM seats WHERE taken = 0)
SELECT seat_no AS start_seat FROM f WHERE two_ahead = seat_no + 2 ORDER BY seat_no;
start_seat
5
6
Seat 5 and seat 6 can each start a block of three. Real seating has rows and aisles, so partition by row and treat an aisle as a break.
sql
WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
free AS (SELECT seat_no, seat_no - ROW_NUMBER() OVER (ORDER BY seat_no) AS grp FROM seats WHERE taken = 0)
SELECT MIN(seat_no) AS first_seat, MAX(seat_no) AS last_seat, COUNT(*) AS seats
FROM free GROUP BY grp HAVING COUNT(*) >= 3;
WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
f AS (SELECT seat_no, LEAD(seat_no, 2) OVER (ORDER BY seat_no) AS two_ahead FROM seats WHERE taken = 0)
SELECT seat_no AS start_seat FROM f WHERE two_ahead = seat_no + 2 ORDER BY seat_no;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Filter to free seats first
seat_no minus ROW_NUMBER identifies adjacent runs
Keep runs with at least N seats
LEAD(seat, N-1) finds valid starting seats
Common mistakes
Applying the trick before filtering out taken seats
Ignoring row boundaries in real seating plans
Follow-ups
How would you partition by seating row?
How would you reserve the seats atomically?
Tips
Show the intermediate keys
269.sql-0269Easyfresher
Compute each employee's salary as a percentage of their department's total, rounded to one decimal place.
Divide each salary by SUM(salary) OVER (PARTITION BY dept_id) and multiply by 100.0. The window keeps every employee row while giving each one its department total, and the 100.0 avoids 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');
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;
name
dept_id
salary
pct_of_dept
Asha
1
120000
38.7
Mei
1
95000
30.6
Ravi
1
95000
30.6
Tom
2
70000
53.0
Sara
2
62000
47.0
Diego
3
55000
53.4
Omar
3
48000
46.6
Each department's percentages add up to about 100, allowing for rounding. Asha's 120000 of Engineering's 310000 is 38.7 percent.
Lena has no department and no salary, so she is excluded by the WHERE clause; otherwise her row would show NULL.
Rounded values may not sum to exactly 100.0. If a report must total 100, adjust the largest remainder or show one more decimal place.
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 (PARTITION BY dept_id), 1) AS pct_of_dept
FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
SUM(x) OVER (PARTITION BY g) gives the group total per row
Multiply by 100.0 to avoid integer division
Rounded shares may not add up to exactly 100
Exclude or label NULL rows
Common mistakes
Integer division returning 0 for every share
Using GROUP BY and losing individual rows
Follow-ups
How would you show the share of the company total too?
How would you handle rounding so shares add up to 100?
Tips
Mention the rounding caveat
270.sql-0270Easyfresher
What is SQL injection? Show how string concatenation lets input change a query.
SQL injection happens when user input is pasted into SQL text, so specially crafted input becomes part of the query's logic. Input like x' OR '1'='1 turns a lookup for one user into a query that matches every row. The fix is to pass values as bound parameters, which the driver sends separately from the SQL text.
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);
Suppose an application builds SELECT ... WHERE name = ' + input + '. With the input x' OR '1'='1, the final SQL is:
sql
SELECT id, name FROM customers WHERE name = 'x' OR '1'='1' ORDER BY id;
id
name
1
Ana
2
Bilal
3
Chloe
4
Dev
The quote in the input closed the string early, and the OR '1'='1' that followed is always true, so every customer is returned. Worse inputs can read other tables with UNION or, where the driver allows several statements, modify data.
With a parameter, the same input is just a strange name that matches nobody:
text
cursor.execute("SELECT id, name FROM customers WHERE name = ?", (user_input,))
Escaping quotes by hand is fragile (encodings, different quote rules, numeric contexts). Bound parameters are the primary defence; least-privilege database accounts limit the damage if something slips through.
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 id, name FROM customers WHERE name = 'x' OR '1'='1' ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Injection: input becomes part of the SQL text
Quotes in input can end strings early
Bound parameters keep data separate from code
Least privilege limits damage
Common mistakes
Escaping quotes by hand instead of using parameters
Thinking only login forms are at risk
Follow-ups
Can you bind a table or column name as a parameter?
How does an ORM help or hurt here?
Tips
Show the final SQL string the attacker produces
271.sql-0271Mediummid
Parameters cannot be used for table or column names. How do you safely let users choose the sort column?
Map user choices to a fixed allow-list of column names in application code, and insert only the mapped name into the SQL. Reject anything not in the list. Bind parameters still carry every value; only identifiers that come from your own list are concatenated.
Full answer
Placeholders stand for values, so ORDER BY ? sorts by a constant string, not a column. Developers then reach for concatenation, which reopens injection.
An allow-list keeps control in code:
text
SORTS = {"name": "name", "newest": "created DESC", "price": "unit_price"}
order_by = SORTS.get(request_sort, "name")
sql = f"SELECT id, name FROM products ORDER BY {order_by} LIMIT ?"
cursor.execute(sql, (page_size,))
The same applies to the sort direction (ASC/DESC from a two-item list), table names in multi-tenant setups, and dynamic filters, where each optional condition is a fixed SQL fragment with its own parameter.
In PostgreSQL functions that build SQL, format('%I', name) quotes identifiers and %L quotes literals, and EXECUTE ... USING binds values. Quoting identifiers prevents breaking out of the name, but an allow-list also prevents sorting by columns users should not see.
Key points
Placeholders bind values, not identifiers
Use an allow-list for column and direction choices
Bind every value as a parameter
PostgreSQL format('%I') quotes identifiers in dynamic SQL
Common mistakes
Concatenating a sort column from the query string
Binding ORDER BY ? and wondering why the sort does nothing
Follow-ups
How would you build optional filters safely?
How do you test for injection?
Tips
Show the allow-list mapping
272.sql-0272Mediummid
How do GRANT and REVOKE work, and what does least privilege mean for an application's database account?
GRANT gives a role specific privileges on specific objects, such as SELECT on a table or EXECUTE on a function, and REVOKE removes them. Least privilege means the application's role can do only what it needs: no DDL, no superuser, no access to tables it does not use. Separate roles for migrations, the application and read-only reporting limit the damage from bugs or stolen credentials.
Full answer
A PostgreSQL example:
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
CREATE ROLE reporting_demo NOLOGIN;
GRANT USAGE ON SCHEMA ib TO reporting_demo;
GRANT SELECT ON orders TO reporting_demo;
SELECT privilege_type FROM information_schema.role_table_grants
WHERE grantee = 'reporting_demo' ORDER BY privilege_type;
REVOKE ALL ON orders FROM reporting_demo;
REVOKE USAGE ON SCHEMA ib FROM reporting_demo;
DROP ROLE reporting_demo;
privilege_type
SELECT
The reporting role can read orders but cannot change them, and it can read nothing else. SQLite has no users or GRANT; access control there is the file system's permissions plus whatever the application enforces.
A common layout:
app_migrator: owns the schema, runs DDL during deployments only.
app_rw: SELECT, INSERT, UPDATE, DELETE on application tables, no DDL.
app_ro: SELECT only, for reports and analysts, often on a replica.
Grant to roles, then grant roles to login users, so access changes in one place. ALTER DEFAULT PRIVILEGES covers tables created later. Views and row-level security can restrict columns and rows further.
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);
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
GRANT gives privileges; REVOKE removes them
Least privilege: only what the role needs
Separate migration, read-write and read-only roles
SQLite relies on file permissions instead
Common mistakes
Running the application as the database owner or superuser
Granting to individual users instead of roles
Follow-ups
What is row-level security?
How would you give analysts access without personal data?
Tips
Describe a three-role layout
273.sql-0273Easyfresher
How would you extract a nested value, such as the user's country, from a JSON text column in SQLite and in PostgreSQL?
In SQLite use json_extract(payload, '$.user.country') or the ->> operator (3.38+). In PostgreSQL, cast to jsonb and use payload::jsonb -> 'user' ->> 'country', or #>> '{user,country}'. The ->> forms return text; -> returns JSON.
Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
sql
SELECT id, json_extract(payload, '$.user.country') AS country, payload ->> '$.type' AS type
FROM events ORDER BY id;
id
country
type
1
IN
signup
2
FR
purchase
3
IN
purchase
$.user.country is a JSON path: start at the root, go into user, then country. A missing key returns NULL rather than an error, which is why event 3, which has no tags, can still be queried.
PostgreSQL:
sql
SELECT id, payload::jsonb -> 'user' ->> 'country' AS country, payload::jsonb #>> '{user,id}' AS user_id
FROM events ORDER BY id;
id
country
user_id
1
IN
7
2
FR
8
3
IN
7
Store JSON as jsonb in PostgreSQL rather than json or text, so it is parsed once, indexable and comparable. In SQLite, JSON is text; SQLite 3.45 added an internal binary form (JSONB functions) for speed.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
SELECT id, json_extract(payload, '$.user.country') AS country, payload ->> '$.type' AS type
FROM events ORDER BY id;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
SQLite: json_extract or ->> with a path
PostgreSQL: -> for JSON, ->> for text, #>> for paths
Missing keys return NULL
Prefer jsonb columns in PostgreSQL
Common mistakes
Using -> and comparing JSON with text
Storing JSON as plain text in PostgreSQL
Follow-ups
How would you index a JSON field?
How would you filter events by country?
Tips
Show both engines
274.sql-0274Mediummid
How do you turn a JSON array inside a row into one row per element?
In SQLite join the table to json_each(payload, '$.tags'), which returns one row per array element with a value column. In PostgreSQL use jsonb_array_elements_text(payload::jsonb -> 'tags') in a lateral join. Rows without the array produce no output with an inner join; use LEFT JOIN to keep them.
Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
sql
SELECT e.id, t.value AS tag
FROM events e JOIN json_each(e.payload, '$.tags') t
ORDER BY e.id, t.key;
id
tag
1
web
1
promo
2
app
Event 3 has no tags array, so the join produces nothing for it. A LEFT JOIN keeps it with a NULL tag:
sql
SELECT e.id, t.value AS tag
FROM events e LEFT JOIN json_each(e.payload, '$.tags') t ON true
ORDER BY e.id, t.key;
id
tag
1
web
1
promo
2
app
3
NULL
PostgreSQL:
sql
SELECT e.id, t.tag
FROM events e CROSS JOIN LATERAL jsonb_array_elements_text(e.payload::jsonb -> 'tags') AS t(tag)
ORDER BY e.id, t.tag;
id
tag
1
promo
1
web
2
app
Counting tags is then an ordinary GROUP BY on the expanded rows. If arrays are queried this way all the time, a child table with one row per tag may be the better design.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
SELECT e.id, t.value AS tag
FROM events e JOIN json_each(e.payload, '$.tags') t
ORDER BY e.id, t.key;
SELECT e.id, t.value AS tag
FROM events e LEFT JOIN json_each(e.payload, '$.tags') t ON true
ORDER BY e.id, t.key;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
SQLite json_each expands arrays into rows
PostgreSQL uses jsonb_array_elements(_text)
Inner joins drop rows without the array
LEFT JOIN ... ON true keeps them
Common mistakes
Losing rows that have no array
Parsing arrays with string functions
Follow-ups
How would you count events per tag?
When should the array become a child table?
Tips
Mention the LEFT JOIN case
275.sql-0275Mediummid
Write a query that totals purchase amounts per country from JSON event payloads.
Extract the fields with json_extract (or ->>) in the SELECT, filter on the extracted type, and GROUP BY the extracted country. Cast numeric fields when the engine returns text: SQLite's json_extract returns a number for JSON numbers, while PostgreSQL's ->> returns text that needs ::numeric.
Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
sql
SELECT json_extract(payload, '$.user.country') AS country, SUM(json_extract(payload, '$.amount')) AS total
FROM events
WHERE json_extract(payload, '$.type') = 'purchase'
GROUP BY country ORDER BY country;
country
total
FR
30
IN
12
India has one purchase of 12 and France one of 30. The signup event has no amount and is excluded by the type filter.
PostgreSQL needs a cast, because ->> returns text:
sql
SELECT payload::jsonb -> 'user' ->> 'country' AS country, SUM((payload::jsonb ->> 'amount')::numeric) AS total
FROM events WHERE payload::jsonb ->> 'type' = 'purchase'
GROUP BY 1 ORDER BY 1;
country
total
FR
30
IN
12
If this report runs often, extract the fields into real columns, or use a generated column or an expression index, such as CREATE INDEX ON events ((payload ->> '$.type')) in SQLite, so the filter does not parse every payload.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
SELECT json_extract(payload, '$.user.country') AS country, SUM(json_extract(payload, '$.amount')) AS total
FROM events
WHERE json_extract(payload, '$.type') = 'purchase'
GROUP BY country ORDER BY country;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Extract fields in SELECT, WHERE and GROUP BY
SQLite json_extract keeps JSON numbers numeric
PostgreSQL ->> returns text; cast to numeric
Index extracted expressions for frequent queries
Common mistakes
Summing text values in PostgreSQL
Parsing every payload on every report query
Follow-ups
How would you make this fast on millions of rows?
What happens with a malformed payload?
Tips
Mention the cast difference
276.sql-0276Mediummid
How do you build a JSON object or array from query results?
SQLite has json_object(key, value, ...) for one object and json_group_array(...) to aggregate rows into an array. PostgreSQL has jsonb_build_object and jsonb_agg (or json_agg). Combining them returns nested documents, such as each customer with an array of their orders, in one query.
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 c.name,
CASE WHEN COUNT(o.id) = 0 THEN json('[]')
ELSE json_group_array(json_object('id', o.id, 'status', o.status)) END AS orders
FROM customers c LEFT JOIN (SELECT * FROM orders ORDER BY id) o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
Each customer becomes one row with a JSON array of their orders, ordered by id. Dev has no orders; the LEFT JOIN gives one row with NULL order values, which json_group_array turns into [null] unless filtered. The CASE returns an empty array for him instead.
PostgreSQL:
sql
SELECT c.name,
COALESCE(jsonb_agg(jsonb_build_object('id', o.id, 'status', o.status) ORDER BY o.id) FILTER (WHERE o.id IS NOT NULL), '[]'::jsonb)::text AS orders
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
Building JSON in the database saves round trips for API responses, but large nested documents are harder to page and cache. Keep it for small, bounded collections.
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 c.name,
CASE WHEN COUNT(o.id) = 0 THEN json('[]')
ELSE json_group_array(json_object('id', o.id, 'status', o.status)) END AS orders
FROM customers c LEFT JOIN (SELECT * FROM orders ORDER BY id) o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
SQLite: json_object and json_group_array
PostgreSQL: jsonb_build_object and jsonb_agg
Handle empty groups to avoid [null]
Good for small nested API responses
Common mistakes
Returning [null] for parents with no children
Building huge nested documents in one query
Follow-ups
How would you order elements inside the array?
How would you return an object keyed by id?
Tips
Show the empty-group handling
277.sql-0277Hardsenior
How would you index JSON data so that filters on a JSON field are fast?
For a specific field, create an expression index on the extracted value, in SQLite or PostgreSQL. For containment queries over many keys in PostgreSQL, a GIN index on a jsonb column supports @> and key-existence operators. Queries must use the same expression or operator for the index to apply.
Full answer
An expression index in SQLite:
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
sql
CREATE INDEX events_type ON events (json_extract(payload, '$.type'));
EXPLAIN QUERY PLAN SELECT id FROM events WHERE json_extract(payload, '$.type') = 'purchase';
text
QUERY PLAN
SEARCH events USING INDEX events_type (<expr>=?)
The plan searches the index because the WHERE uses the indexed expression exactly.
PostgreSQL's GIN index serves containment queries such as "events whose payload contains type purchase":
sql
ALTER TABLE events ALTER COLUMN payload TYPE jsonb USING payload::jsonb;
CREATE INDEX events_payload_gin ON events USING gin (payload);
SELECT id FROM events WHERE payload @> '{"type": "purchase"}' ORDER BY id;
id
2
3
The containment query returns events 2 and 3. On a table this small the planner prefers a sequential scan, so the result shows the operator working, not the index; on a large table the planner would use the GIN index for @> (plan not shown here). jsonb_path_ops makes a smaller, faster GIN index that supports only @>.
If a field is filtered constantly, promoting it to a real column (or a generated column) is usually simplest and gives normal statistics to the planner.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
CREATE INDEX events_type ON events (json_extract(payload, '$.type'));
EXPLAIN QUERY PLAN SELECT id FROM events WHERE json_extract(payload, '$.type') = 'purchase';
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Expression indexes serve one extracted field
GIN on jsonb serves containment and key-existence queries
Queries must match the indexed expression or operator
Promote hot fields to real columns
Common mistakes
Indexing the whole JSON text with a B-tree
Querying with ->> when only @> is indexed
Follow-ups
What is jsonb_path_ops?
Why do planners need statistics on JSON fields?
Tips
Distinguish field indexes from containment indexes
278.sql-0278Mediummid
How can you update one field inside a JSON column without rewriting the whole document by hand?
SQLite has json_set (insert or replace), json_replace (only existing keys), json_insert (only new keys) and json_remove. PostgreSQL has jsonb_set(doc, '{path}', value) and the - operator to remove keys. The engine still writes the whole value, but the expression changes only the chosen path.
Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
sql
UPDATE events SET payload = json_set(payload, '$.amount', 25, '$.refunded', json('true')) WHERE id = 2;
SELECT json_extract(payload, '$.amount') AS amount, json_extract(payload, '$.refunded') AS refunded FROM events WHERE id = 2;
amount
refunded
25
1
json_set replaced the amount and added a refunded flag in one call. json_remove drops a key:
sql
UPDATE events SET payload = json_remove(payload, '$.tags') WHERE id = 1;
SELECT payload FROM events WHERE id = 1;
payload
{"type":"signup","user":{"id":7,"country":"IN"}}
PostgreSQL:
sql
UPDATE events SET payload = jsonb_set(payload::jsonb, '{amount}', '25')::text WHERE id = 2;
SELECT payload::jsonb ->> 'amount' AS amount FROM events WHERE id = 2;
amount
25
Frequent single-field updates on large documents rewrite the whole value each time, which costs disk writes and, in PostgreSQL, creates a new row version. Fields that change often are better as normal columns.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
(1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
(2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
(3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
UPDATE events SET payload = json_set(payload, '$.amount', 25, '$.refunded', json('true')) WHERE id = 2;
SELECT json_extract(payload, '$.amount') AS amount, json_extract(payload, '$.refunded') AS refunded FROM events WHERE id = 2;
UPDATE events SET payload = json_remove(payload, '$.tags') WHERE id = 1;
SELECT payload FROM events WHERE id = 1;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Using json_replace and expecting it to add new keys
Follow-ups
How would you append to a JSON array?
How would you rename a key?
Tips
Name the SQLite function variants
279.sql-0279Mediummid
How would you validate that a text column holds well-formed JSON with a required key?
In SQLite add CHECK (json_valid(payload) AND json_extract(payload, '$.type') IS NOT NULL). In PostgreSQL, a jsonb column rejects malformed JSON on insert, and a CHECK (payload ? 'type') requires the key. Validation in the database protects against every client, not just the main application.
Full answer
sql
CREATE TABLE ev (payload TEXT CHECK (json_valid(payload) AND json_extract(payload, '$.type') IS NOT NULL));
INSERT INTO ev VALUES ('{not json');
-- error on purpose
text
Error: CHECK constraint failed: json_valid(payload) AND json_extract(payload, '$.type') IS NOT NULL
sql
CREATE TABLE ev2 (payload TEXT CHECK (json_valid(payload) AND json_extract(payload, '$.type') IS NOT NULL));
INSERT INTO ev2 VALUES ('{"amount": 5}');
-- error on purpose
text
Error: CHECK constraint failed: json_valid(payload) AND json_extract(payload, '$.type') IS NOT NULL
The first bad row is not JSON at all; the second is valid JSON without type. Both are rejected.
PostgreSQL enforces syntax through the type, and the ? operator checks for a key:
sql
CREATE TABLE ev (payload jsonb CHECK (payload ? 'type'));
INSERT INTO ev VALUES ('{"amount": 5}');
-- error on purpose
text
Error: new row for relation "ev" violates check constraint "ev_payload_check"
Deeper rules, such as "amount must be a positive number", can be added the same way with json_type in SQLite or jsonb_typeof in PostgreSQL. Full JSON Schema validation needs an extension or the application.
sql
-- error on purpose
CREATE TABLE ev (payload TEXT CHECK (json_valid(payload) AND json_extract(payload, '$.type') IS NOT NULL));
INSERT INTO ev VALUES ('{not json');
-- error on purpose
CREATE TABLE ev2 (payload TEXT CHECK (json_valid(payload) AND json_extract(payload, '$.type') IS NOT NULL));
INSERT INTO ev2 VALUES ('{"amount": 5}');
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
SQLite: CHECK with json_valid and json_extract
PostgreSQL jsonb rejects malformed JSON
PostgreSQL ? checks for a key
Database checks protect against every client
Common mistakes
Storing unchecked JSON text and failing later at read time
Validating only in one of several writers
Follow-ups
How would you require amount to be numeric?
When is JSON Schema validation worth an extension?
Tips
Show one syntax error and one missing key
280.sql-0280Mediummid
How do you implement full-text search in SQLite, and why is LIKE '%word%' a poor substitute?
Create an FTS5 virtual table and query it with MATCH, which uses an inverted index of tokens, supports phrases, prefixes and boolean operators, and ranks results with bm25(). LIKE '%word%' scans every row, matches inside other words ('cat' in 'concatenate'), and offers no ranking.
Full answer
sql
CREATE VIRTUAL TABLE docs USING fts5(title, body);
INSERT INTO docs VALUES ('Indexes', 'An index speeds up lookups'), ('Joins', 'Join tables on keys'), ('Plans', 'Read the plan to see if an index is used'), ('Strings', 'Use concatenate to join text');
SELECT title FROM docs WHERE docs MATCH 'index' ORDER BY rank;
title
Indexes
Plans
MATCH 'index' found both posts with the word, ranked by relevance; ORDER BY rank uses bm25 by default. A substring LIKE would also match words that merely contain the letters:
sql
SELECT title FROM docs WHERE body LIKE '%cat%' ORDER BY title;
title
Strings
'concatenate' matched %cat%, which a word-based search would not do. FTS5 also supports "exact phrase", prefix* and NEAR.
PostgreSQL's equivalent is to_tsvector(...) @@ to_tsquery(...) with a GIN index:
sql
SELECT title FROM (VALUES ('Indexes', 'An index speeds up lookups'), ('Plans', 'Read the plan to see if an index is used'), ('Strings', 'Use concatenate to join text')) AS d(title, body)
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'index')
ORDER BY title;
title
Indexes
Plans
sql
CREATE VIRTUAL TABLE docs USING fts5(title, body);
INSERT INTO docs VALUES ('Indexes', 'An index speeds up lookups'), ('Joins', 'Join tables on keys'), ('Plans', 'Read the plan to see if an index is used'), ('Strings', 'Use concatenate to join text');
SELECT title FROM docs WHERE docs MATCH 'index' ORDER BY rank;
SELECT title FROM docs WHERE body LIKE '%cat%' ORDER BY title;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
FTS5 builds an inverted token index
MATCH supports phrases, prefixes and boolean operators
bm25 ranks results
LIKE '%x%' scans and matches inside words
Common mistakes
Building search on LIKE for large text
Forgetting to keep the FTS table in sync with the source
Follow-ups
How would you keep an FTS table in sync with triggers?