Questions 61–80 of 501 · 0 of 20 on this page marked learned
61.sql-0061Easyfresher
Does FROM a, b WHERE a.id = b.a_id behave any differently from FROM a JOIN b ON a.id = b.a_id?
For inner joins the two forms return the same rows; the comma form is the older SQL-89 style. Explicit JOIN ... ON keeps each join condition next to its table, separates join logic from filters, and makes a forgotten condition obvious. With the comma form, a missing condition silently becomes a cross join.
Full answer
Both of these return the same result:
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 e.name, d.name AS dept
FROM employees e, departments d
WHERE d.id = e.dept_id AND e.salary > 90000
ORDER BY e.name;
name
dept
Asha
Engineering
Mei
Engineering
Ravi
Engineering
sql
SELECT e.name, d.name AS dept
FROM employees e
JOIN departments d ON d.id = e.dept_id
WHERE e.salary > 90000
ORDER BY e.name;
name
dept
Asha
Engineering
Mei
Engineering
Ravi
Engineering
The optimizer treats them the same way, so this is about readability and safety, not speed.
The explicit form wins in practice for three reasons. Each join condition sits next to the table it belongs to, so a five-table query can be read top to bottom. Join conditions and filters are separated: ON says how tables relate, WHERE says which rows you want. And outer joins need the explicit syntax anyway (the old vendor forms such as Oracle's (+) are obsolete).
The biggest risk with commas is a missing condition. Forget it, and every employee pairs with every department:
sql
SELECT COUNT(*) AS rows_returned
FROM employees e, departments d
WHERE e.salary > 0 OR e.salary IS NULL;
rows_returned
32
Eight employees times four departments gives 32 rows, with no error. With explicit JOIN syntax on PostgreSQL, leaving out ON is a syntax error instead:
sql
SELECT e.name FROM employees e JOIN departments d WHERE e.salary > 90000; -- error on purpose
text
Error: syntax error at or near "WHERE"
SQLite is more permissive and accepts JOIN without ON as a cross join, so the protection depends on the engine.
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 e.name, d.name AS dept
FROM employees e, departments d
WHERE d.id = e.dept_id AND e.salary > 90000
ORDER BY e.name;
SELECT e.name, d.name AS dept
FROM employees e
JOIN departments d ON d.id = e.dept_id
WHERE e.salary > 90000
ORDER BY e.name;
SELECT COUNT(*) AS rows_returned
FROM employees e, departments d
WHERE e.salary > 0 OR e.salary IS NULL;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Comma joins and JOIN ... ON give the same inner join result
Explicit JOIN keeps conditions next to tables and apart from filters
A forgotten condition in comma style becomes a silent cross join
PostgreSQL rejects JOIN without ON; SQLite treats it as a cross join
Common mistakes
Mixing comma joins and explicit joins in one FROM clause
Forgetting one condition in a long comma-separated FROM list
Follow-ups
How do you write a LEFT JOIN in the comma style?
Can mixing comma and JOIN syntax change how aliases are resolved?
Tips
Mention the silent cross join; it is the practical reason for the rule
62.sql-0062Mediummid
A report counts students per course with a LEFT JOIN and COUNT(*). Ethics has no students but shows 1. Why?
A LEFT JOIN returns one row for Ethics with NULLs on the enrolment side, and COUNT(*) counts that row. Count a column from the right table instead, such as COUNT(e.student_id), which skips the NULL and returns 0.
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 c.title, COUNT(*) AS students
FROM courses c
LEFT JOIN enrolments e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY c.title;
title
students
Algorithms
3
Databases
3
Ethics
1
Statistics
2
Ethics has nobody enrolled, but the LEFT JOIN still produced one row for it, filled with NULLs on the right side, so that the course is not lost. COUNT(*) counts rows, and there is one row.
Count something that only exists when there is a real match:
sql
SELECT c.title, COUNT(e.student_id) AS students
FROM courses c
LEFT JOIN enrolments e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY c.title;
title
students
Algorithms
3
Databases
3
Ethics
0
Statistics
2
COUNT(e.student_id) skips NULLs, so Ethics correctly gets 0. Use the right table's key or another NOT NULL column of the right table. Counting a nullable column such as marks would give the wrong answer for Statistics, where one enrolled student has no mark yet:
sql
SELECT c.title,
COUNT(e.student_id) AS students,
COUNT(e.marks) AS marked
FROM courses c
LEFT JOIN enrolments e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY c.title;
title
students
marked
Algorithms
3
3
Databases
3
3
Ethics
0
0
Statistics
2
1
Statistics has two students but only one mark. Pick the column whose meaning matches the question: count enrolments with the key, count marked papers with marks.
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 c.title, COUNT(*) AS students
FROM courses c
LEFT JOIN enrolments e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY c.title;
SELECT c.title, COUNT(e.student_id) AS students
FROM courses c
LEFT JOIN enrolments e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY c.title;
SELECT c.title,
COUNT(e.student_id) AS students,
COUNT(e.marks) AS marked
FROM courses c
LEFT JOIN enrolments e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY c.title;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A LEFT JOIN produces one NULL-filled row for unmatched left rows
COUNT(*) counts that row; COUNT(right.key) does not
Count a NOT NULL column of the right table for 'number of matches'
COUNT(nullable column) answers a different question
Common mistakes
Using COUNT(*) after a LEFT JOIN and reporting 1 for empty groups
Counting a nullable column and undercounting real matches
Follow-ups
How would you also show the average mark per course, blank for Ethics?
Would an INNER JOIN fix it?
Tips
Explain where the extra row comes from before giving the fix
63.sql-0063Mediummid
How do you list customers who have placed at least one order, without duplicates? Compare EXISTS with JOIN and DISTINCT.
EXISTS expresses a semi-join: return each customer once if at least one matching order exists. A plain JOIN returns one row per order, so a customer with two orders appears twice, and DISTINCT is then needed to undo the duplication. EXISTS states the intent directly and lets the engine stop at the first match.
Full answer
"Customers who have ordered" is a yes-or-no question per customer. A join answers a different question, "customer and order pairs":
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
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.name;
name
Ana
Ana
Bilal
Bilal
Chloe
Ana and Bilal appear twice because they have two orders each. Adding DISTINCT hides that:
sql
SELECT DISTINCT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.name;
name
Ana
Bilal
Chloe
The result is now right, but the database built all pairs and then removed duplicates. EXISTS asks the yes-or-no question directly:
sql
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
ORDER BY c.name;
name
Ana
Bilal
Chloe
This is called a semi-join: rows from the left side are returned at most once, and no columns from the right side are needed. Many planners turn EXISTS, IN (subquery) and sometimes JOIN + DISTINCT into the same semi-join plan, so measure before claiming one is faster. The readability argument stands on its own: EXISTS says what you mean, and it cannot multiply rows.
IN (SELECT customer_id FROM orders) is another correct form here. Unlike NOT IN, plain IN is safe even with the guest order's NULL customer_id.
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
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.name;
SELECT DISTINCT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.name;
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
ORDER BY c.name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
JOIN returns one row per match, so parents repeat
DISTINCT after a join removes the repeats but hides intent
EXISTS expresses a semi-join and never duplicates left rows
Planners often produce the same plan; verify before claiming speed
Common mistakes
Joining to a child table to filter parents and then summing parent columns
Claiming EXISTS is always faster without looking at the plan
Follow-ups
How do you list customers with no orders?
What happens to a SUM of customer credit limits if you filter with a JOIN instead of EXISTS?
Tips
Use the words semi-join and anti-join; interviewers listen for them
64.sql-0064Mediummid
Write a query to find students enrolled in both Databases and Algorithms.
Filter enrolments to the two courses, group by student, and keep groups where COUNT(DISTINCT course_id) = 2. INTERSECT of the two student lists also works. A WHERE course_id = 10 AND course_id = 20 is always false, because one row cannot hold two values at once.
Full answer
The tempting first attempt does not work:
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 FROM enrolments WHERE course_id = 10 AND course_id = 20;
student_id
(0 rows)
WHERE looks at one row at a time, and no single enrolment row is in both courses. The condition is about a student across several rows, so it needs grouping:
sql
SELECT s.name
FROM enrolments e
JOIN students s ON s.id = e.student_id
WHERE e.course_id IN (10, 20)
GROUP BY s.id, s.name
HAVING COUNT(DISTINCT e.course_id) = 2
ORDER BY s.name;
name
Asha
Chen
COUNT(DISTINCT e.course_id) = 2 means "this student has rows for both courses". DISTINCT protects against duplicate enrolment rows if the table allowed them.
INTERSECT gives the same answer by taking the students common to both lists:
sql
SELECT s.name FROM students s WHERE s.id IN (
SELECT student_id FROM enrolments WHERE course_id = 10
INTERSECT
SELECT student_id FROM enrolments WHERE course_id = 20
)
ORDER BY s.name;
name
Asha
Chen
The grouping version generalises better. "At least two of these three courses" becomes HAVING COUNT(DISTINCT course_id) >= 2, which INTERSECT cannot express. Changing it to "all of the listed courses" is a form of relational division, which comes up as its own interview question.
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 FROM enrolments WHERE course_id = 10 AND course_id = 20;
SELECT s.name
FROM enrolments e
JOIN students s ON s.id = e.student_id
WHERE e.course_id IN (10, 20)
GROUP BY s.id, s.name
HAVING COUNT(DISTINCT e.course_id) = 2
ORDER BY s.name;
SELECT s.name FROM students s WHERE s.id IN (
SELECT student_id FROM enrolments WHERE course_id = 10
INTERSECT
SELECT student_id FROM enrolments WHERE course_id = 20
)
ORDER BY s.name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A WHERE condition sees one row at a time
Conditions across several rows need GROUP BY and HAVING
COUNT(DISTINCT course) = number of required courses
INTERSECT is an alternative for exactly two lists
Common mistakes
Writing course_id = 10 AND course_id = 20
Using OR and returning students in either course
Follow-ups
How would you find students in Databases but not Algorithms?
How would you find students enrolled in every course?
Tips
Explain why the AND version is always empty; it shows you understand row-wise evaluation
65.sql-0065Hardsenior
How do you find students who have taken every 4-credit course? Explain relational division.
Relational division asks for rows related to all members of another set. Count method: join enrolments to the required courses, group by student, and keep students whose count of distinct required courses equals the size of the set. Double NOT EXISTS method: keep a student if there is no required course they have not taken.
Full answer
"Students who took every 4-credit course" is relational division: divide the enrolment relation by the set of required courses.
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);
The 4-credit courses are Databases (10) and Algorithms (20).
The counting method compares each student's number of required courses with the size of the set:
sql
SELECT s.name
FROM students s
JOIN enrolments e ON e.student_id = s.id
JOIN courses c ON c.id = e.course_id AND c.credits = 4
GROUP BY s.id, s.name
HAVING COUNT(DISTINCT c.id) = (SELECT COUNT(*) FROM courses WHERE credits = 4)
ORDER BY s.name;
name
Asha
Chen
Asha and Chen have both. Ben took Databases only, Eli took Algorithms only.
The double NOT EXISTS method reads like the definition: "there is no required course that this student has not taken".
sql
SELECT s.name
FROM students s
WHERE NOT EXISTS (
SELECT 1 FROM courses c
WHERE c.credits = 4
AND NOT EXISTS (
SELECT 1 FROM enrolments e
WHERE e.student_id = s.id AND e.course_id = c.id))
ORDER BY s.name;
name
Asha
Chen
Both give the same answer. The counting version is usually easier to read and adapt. The double negative is worth knowing because it handles one edge case more naturally: if the required set is empty, NOT EXISTS returns every student (every student has taken "all" of zero courses), while the counting version above returns none, because the inner join leaves no rows to group. Decide which behaviour is right for the business and test it:
sql
SELECT COUNT(*) AS students_returned_for_empty_set
FROM students s
WHERE NOT EXISTS (
SELECT 1 FROM courses c
WHERE c.credits = 99
AND NOT EXISTS (
SELECT 1 FROM enrolments e
WHERE e.student_id = s.id AND e.course_id = c.id));
students_returned_for_empty_set
5
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 s.name
FROM students s
JOIN enrolments e ON e.student_id = s.id
JOIN courses c ON c.id = e.course_id AND c.credits = 4
GROUP BY s.id, s.name
HAVING COUNT(DISTINCT c.id) = (SELECT COUNT(*) FROM courses WHERE credits = 4)
ORDER BY s.name;
SELECT s.name
FROM students s
WHERE NOT EXISTS (
SELECT 1 FROM courses c
WHERE c.credits = 4
AND NOT EXISTS (
SELECT 1 FROM enrolments e
WHERE e.student_id = s.id AND e.course_id = c.id))
ORDER BY s.name;
SELECT COUNT(*) AS students_returned_for_empty_set
FROM students s
WHERE NOT EXISTS (
SELECT 1 FROM courses c
WHERE c.credits = 99
AND NOT EXISTS (
SELECT 1 FROM enrolments e
WHERE e.student_id = s.id AND e.course_id = c.id));
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Relational division: related to every member of a set
Counting: COUNT(DISTINCT required) = size of the set
Double NOT EXISTS: no required item is missing
The two forms differ when the required set is empty
Common mistakes
Using IN, which returns students with any required course, not all
Comparing with a hard-coded count that goes stale when courses change
Follow-ups
How would you find students who took exactly the required courses and nothing else?
Which form performs better on a large table, and how would you check?
Tips
Name the pattern; interviewers often ask for 'relational division' by name
66.sql-0066Hardsenior
Given a follows(follower, followee) table, write a query for pairs of users who follow each other.
Self join follows to itself where a.follower = b.followee and a.followee = b.follower. That finds each mutual pair twice, once in each direction, so add a.follower < a.followee to keep one copy.
Full answer
A follow is a directed edge: Ana follows Ben does not mean Ben follows Ana. A mutual pair needs both edges.
Join the table to itself, looking for the reverse edge of each row:
sql
SELECT a.follower, a.followee
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
ORDER BY a.follower, a.followee;
follower
followee
Ana
Ben
Ben
Ana
Chen
Dara
Dara
Chen
Each mutual pair shows up twice, once starting from each side. Keep one copy by ordering the pair:
sql
SELECT a.follower AS user_1, a.followee AS user_2
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
WHERE a.follower < a.followee
ORDER BY user_1;
user_1
user_2
Ana
Ben
Chen
Dara
Ana and Ben follow each other, and so do Chen and Dara. Ana follows Chen but Chen does not follow back, so that pair is not mutual.
An index on (follower, followee) makes the reverse lookup cheap: for each row, the database seeks the index for the swapped pair. The primary key here already provides it. If the table may contain duplicate follow rows, the result may repeat; a primary key on the pair prevents that.
sql
CREATE TABLE follows (follower TEXT, followee TEXT, PRIMARY KEY (follower, followee));
INSERT INTO follows VALUES ('Ana','Ben'),('Ben','Ana'),('Ana','Chen'),('Chen','Dara'),('Dara','Chen'),('Ben','Dara');
SELECT a.follower, a.followee
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
ORDER BY a.follower, a.followee;
SELECT a.follower AS user_1, a.followee AS user_2
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
WHERE a.follower < a.followee
ORDER BY user_1;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Mutual means both directed edges exist
Self join on swapped columns finds the reverse edge
a.follower < a.followee keeps one copy of each pair
A key on (follower, followee) supports the lookup and prevents duplicates
Common mistakes
Forgetting the ordering condition and reporting each pair twice
Joining on only one column and matching unrelated edges
Follow-ups
How would you find users followed by someone they do not follow back?
How would you count mutual friends for a pair of users?
Tips
Draw the two arrows; it makes the join condition obvious
67.sql-0067Hardsenior
Prices change over time and are stored with valid_from dates. Write a query that charges each order line the price that was valid on the order date.
For each order line, the right price is the row with the latest valid_from that is on or before the order date. One way is a correlated subquery picking MAX(valid_from) <= order_date; another is storing valid_to and joining on order_date >= valid_from AND order_date < valid_to. The valid_to version is simpler to join and easier to index.
Full answer
This is an effective-dated, or temporal, lookup. The price table has one row per change:
SELECT product, valid_from, valid_to, price FROM product_prices ORDER BY product, valid_from;
product
valid_from
valid_to
price
Bag
2026-01-01
NULL
30
Pen
2026-01-01
2026-03-01
1
Pen
2026-03-01
NULL
2
An equality join on product would match every price row. The order needs the most recent price as of its date. A correlated subquery finds that date per line:
sql
SELECT l.id, l.order_date, l.product, p.price, l.qty * p.price AS line_total
FROM order_lines l
JOIN product_prices p
ON p.product = l.product
AND p.valid_from = (SELECT MAX(p2.valid_from)
FROM product_prices p2
WHERE p2.product = l.product
AND p2.valid_from <= l.order_date)
ORDER BY l.id;
id
order_date
product
price
line_total
1
2026-02-10
Pen
1
5
2
2026-03-01
Pen
2
10
3
2026-03-05
Bag
30
30
The order on 10 February gets the 1 January price; the order on 1 March gets the price that started on 1 March, because valid_from is inclusive.
Many systems also store valid_to, the date the price stopped applying (the next row's valid_from), with NULL for the current price. Then the lookup is a plain range join:
sql
SELECT l.id, l.order_date, l.product, p.price
FROM order_lines l
JOIN product_prices p
ON p.product = l.product
AND l.order_date >= p.valid_from
AND (p.valid_to IS NULL OR l.order_date < p.valid_to)
ORDER BY l.id;
id
order_date
product
price
1
2026-02-10
Pen
1
2
2026-03-01
Pen
2
3
2026-03-05
Bag
30
Storing both ends has a cost: the application must update the old row's valid_to when a new price arrives, ideally in the same transaction. In return, every query becomes a simple range join, and an index on (product, valid_from) serves both versions. Make sure ranges for one product never overlap, or a line will match two prices and be double-counted.
sql
CREATE TABLE product_prices (product TEXT, valid_from TEXT, valid_to TEXT, price INTEGER);
INSERT INTO product_prices VALUES
('Pen','2026-01-01','2026-03-01',1),
('Pen','2026-03-01',NULL,2),
('Bag','2026-01-01',NULL,30);
CREATE TABLE order_lines (id INTEGER PRIMARY KEY, order_date TEXT, product TEXT, qty INTEGER);
INSERT INTO order_lines VALUES (1,'2026-02-10','Pen',5),(2,'2026-03-01','Pen',5),(3,'2026-03-05','Bag',1);
SELECT product, valid_from, valid_to, price FROM product_prices ORDER BY product, valid_from;
SELECT l.id, l.order_date, l.product, p.price, l.qty * p.price AS line_total
FROM order_lines l
JOIN product_prices p
ON p.product = l.product
AND p.valid_from = (SELECT MAX(p2.valid_from)
FROM product_prices p2
WHERE p2.product = l.product
AND p2.valid_from <= l.order_date)
ORDER BY l.id;
SELECT l.id, l.order_date, l.product, p.price
FROM order_lines l
JOIN product_prices p
ON p.product = l.product
AND l.order_date >= p.valid_from
AND (p.valid_to IS NULL OR l.order_date < p.valid_to)
ORDER BY l.id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Effective-dated lookup: latest row on or before the event date
Correlated MAX(valid_from) <= event date works with only start dates
Joining on product alone and multiplying order lines by price history
Using inclusive valid_to and charging two prices on the change day
Follow-ups
How would you compute valid_to from valid_from with a window function?
How would you prevent overlapping ranges in PostgreSQL?
Tips
Mention the half-open range; boundary days are where these joins break
68.sql-0068Mediummid
Does the order of tables in a FROM clause affect performance?
For inner joins, usually not: the optimizer reorders tables to find a cheap plan, so FROM a JOIN b and FROM b JOIN a get the same plan. Outer joins restrict reordering because swapping sides changes the result. Some engines let you force an order on purpose, for example SQLite treats CROSS JOIN as an instruction not to reorder.
Full answer
SQL describes what you want, and the optimizer decides how to get it. For inner joins, the join order is part of the "how", so the planner tries different orders and picks the one with the lowest estimated cost.
Writing the tables in either order gives the same plan in SQLite:
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');
CREATE INDEX idx_emp_dept ON employees(dept_id);
sql
EXPLAIN QUERY PLAN
SELECT e.name, d.name FROM employees e JOIN departments d ON d.id = e.dept_id;
text
QUERY PLAN
SCAN e
SEARCH d USING INTEGER PRIMARY KEY (rowid=?)
sql
EXPLAIN QUERY PLAN
SELECT e.name, d.name FROM departments d JOIN employees e ON d.id = e.dept_id;
text
QUERY PLAN
SCAN e
SEARCH d USING INTEGER PRIMARY KEY (rowid=?)
Both plans scan employees and find each department through its primary key, whatever order the query text used.
Outer joins are different. students LEFT JOIN enrolments and enrolments LEFT JOIN students mean different things, so the planner can only reorder in ways that keep the meaning.
Sometimes you want to override the planner, usually because its row estimates are wrong. SQLite documents CROSS JOIN as a way to force the left table to be the outer loop. Put departments on the left and the plan changes:
sql
EXPLAIN QUERY PLAN
SELECT e.name, d.name FROM departments d CROSS JOIN employees e ON d.id = e.dept_id;
text
QUERY PLAN
SCAN d
SEARCH e USING INDEX idx_emp_dept (dept_id=?)
Now departments is scanned and each department's employees are found through the dept_id index. On this data the planner's own choice was fine; forcing an order is only worth it when you have evidence the planner is wrong. Other engines have their own tools (PostgreSQL's join_collapse_limit setting, SQL Server and Oracle query hints). Use them rarely, and only after reading the plan; fixing statistics or adding an index is usually the better 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');
CREATE INDEX idx_emp_dept ON employees(dept_id);
EXPLAIN QUERY PLAN
SELECT e.name, d.name FROM employees e JOIN departments d ON d.id = e.dept_id;
EXPLAIN QUERY PLAN
SELECT e.name, d.name FROM departments d JOIN employees e ON d.id = e.dept_id;
EXPLAIN QUERY PLAN
SELECT e.name, d.name FROM departments d CROSS JOIN employees e ON d.id = e.dept_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
For inner joins the optimizer chooses the join order
Swapping tables in the text usually gives the same plan
Outer joins limit reordering because order changes meaning
SQLite CROSS JOIN forces the written order
Common mistakes
Rewriting join order by hand to 'help' the optimizer without reading the plan
Assuming LEFT JOIN tables can be swapped freely
Follow-ups
How does the planner estimate the cost of each order?
What happens to planning time when a query joins twelve tables?
Tips
Show or describe an EXPLAIN plan rather than relying on rules of thumb
69.sql-0069Hardsenior
Explain nested loop, hash and merge joins. When does a database choose each?
A nested loop join takes each row of the outer input and looks for matches in the inner input; it is best when the outer side is small and the inner side has an index. A hash join builds a hash table on the smaller input and probes it with the other; it suits large unsorted inputs with equality conditions. A merge join walks two inputs sorted on the join key; it suits inputs that are already sorted, for example by an index.
Full answer
These are the three main physical ways to execute a join. SQL text does not choose them; the planner does, based on table sizes, indexes and the join condition.
Nested loop. For every row on the outer side, find matching rows on the inner side. With an index on the inner join key, each lookup is a quick index seek, so this is excellent when the outer side has few rows: "these 20 orders and their customers". Without an index, it compares every pair, which is fine for tiny tables and terrible for large ones. It is the only one of the three that handles any join condition, including ranges and inequalities.
Hash join. Read the smaller input and build an in-memory hash table keyed on the join column. Then read the larger input and probe the hash table for each row. Cost grows roughly linearly with the total rows, so it is strong for large joins with =. It needs memory for the hash table and cannot do range conditions.
Merge join. Sort both inputs on the join key (or read them already sorted from indexes), then walk them together like merging two sorted lists. Good when both sides are large and already ordered.
PostgreSQL shows which one it picked. With small tables it chooses a hash join here, and switching methods off for the session shows the alternatives:
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
EXPLAIN (COSTS OFF)
SELECT e.name, d.name FROM employees e JOIN departments d ON d.id = e.dept_id;
text
Hash Join
Hash Cond: (e.dept_id = d.id)
-> Seq Scan on employees e
-> Hash
-> Seq Scan on departments d
sql
SET enable_hashjoin = off;
EXPLAIN (COSTS OFF)
SELECT e.name, d.name FROM employees e JOIN departments d ON d.id = e.dept_id;
text
Merge Join
Merge Cond: (d.id = e.dept_id)
-> Index Scan using departments_pkey on departments d
-> Sort
Sort Key: e.dept_id
-> Seq Scan on employees e
sql
SET enable_hashjoin = off;
SET enable_mergejoin = off;
EXPLAIN (COSTS OFF)
SELECT e.name, d.name FROM employees e JOIN departments d ON d.id = e.dept_id;
text
Nested Loop
-> Seq Scan on employees e
-> Index Scan using departments_pkey on departments d
Index Cond: (id = e.dept_id)
SQLite uses nested loops, helped by indexes and, when no index exists, an automatic temporary index it builds for the query. The enable_* settings are for experiments only; in production you fix statistics, indexes or the query instead.
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');
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Nested loop: per outer row, look up inner matches; great with an index and a small outer side
Hash join: build a hash on one side, probe with the other; equality only
Merge join: walk two sorted inputs together
Only nested loop supports arbitrary conditions such as ranges
The planner picks the method from sizes, indexes and statistics
Common mistakes
Saying one algorithm is always best
Forcing a method with planner settings in production instead of fixing the cause
Follow-ups
Why can a hash join spill to disk?
What makes the planner switch from a nested loop to a hash join as data grows?
Tips
Tie each algorithm to a situation where it wins
70.sql-0070Mediummid
An enrolments table has a composite key (student_id, course_id). What goes wrong if you join it to a moderation table on student_id only?
Each enrolment then matches every moderation row for that student, across all their courses, so rows multiply and marks get adjustments that belong to other courses. Join on every column of the composite key: ON m.student_id = e.student_id AND m.course_id = e.course_id.
Full answer
A composite key identifies a row by several columns together. An enrolment is "this student in this course", not just "this student".
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);
CREATE TABLE moderation (student_id INTEGER, course_id INTEGER, adjustment INTEGER,
PRIMARY KEY (student_id, course_id));
INSERT INTO moderation VALUES (1, 10, 2), (1, 20, -1), (3, 10, 5);
The moderation table records mark adjustments per enrolment:
sql
SELECT * FROM moderation ORDER BY student_id, course_id;
student_id
course_id
adjustment
1
10
2
1
20
-1
3
10
5
Joining on half of the key:
sql
SELECT e.student_id, e.course_id, e.marks, m.course_id AS mod_course, m.adjustment
FROM enrolments e
JOIN moderation m ON m.student_id = e.student_id
WHERE e.student_id = 1
ORDER BY e.course_id, m.course_id;
student_id
course_id
marks
mod_course
adjustment
1
10
88
10
2
1
10
88
20
-1
1
20
92
10
2
1
20
92
20
-1
Asha's two enrolments matched both of her moderation rows, so she has four rows instead of two, and her Algorithms mark is shown with the Databases adjustment as well. Any SUM over this result is wrong.
Joining on the whole key:
sql
SELECT e.student_id, e.course_id, e.marks, m.adjustment, e.marks + m.adjustment AS final
FROM enrolments e
JOIN moderation m ON m.student_id = e.student_id AND m.course_id = e.course_id
ORDER BY e.student_id, e.course_id;
student_id
course_id
marks
adjustment
final
1
10
88
2
90
1
20
92
-1
91
3
10
64
5
69
A quick check for this class of bug: compare the row count of the join with the row count of the table you expected to drive it. If joining enrolments to a lookup returns more rows than enrolments has (with the same filter), the join key is incomplete or the lookup has duplicates.
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);
CREATE TABLE moderation (student_id INTEGER, course_id INTEGER, adjustment INTEGER,
PRIMARY KEY (student_id, course_id));
INSERT INTO moderation VALUES (1, 10, 2), (1, 20, -1), (3, 10, 5);
SELECT * FROM moderation ORDER BY student_id, course_id;
SELECT e.student_id, e.course_id, e.marks, m.course_id AS mod_course, m.adjustment
FROM enrolments e
JOIN moderation m ON m.student_id = e.student_id
WHERE e.student_id = 1
ORDER BY e.course_id, m.course_id;
SELECT e.student_id, e.course_id, e.marks, m.adjustment, e.marks + m.adjustment AS final
FROM enrolments e
JOIN moderation m ON m.student_id = e.student_id AND m.course_id = e.course_id
ORDER BY e.student_id, e.course_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A composite key needs every column in the join condition
Joining on part of the key multiplies rows
Wrong pairings attach data to the wrong entity, not only duplicates
Compare row counts before and after a join as a sanity check
Common mistakes
Joining on student_id only because it 'looks like the id'
Fixing the duplicates with DISTINCT and keeping wrong pairings
Follow-ups
How would you enforce that each enrolment has at most one moderation row?
What is a surrogate key, and would it help here?
Tips
Name the row-count check; it catches this bug in any query
71.sql-0071Mediummid
Foreign keys were not enforced for a while. How do you find orphan rows, such as enrolments whose student no longer exists?
Use an anti-join from the child table to the parent: LEFT JOIN students and keep rows where the student key is NULL, or use NOT EXISTS. Ignore rows whose foreign key is itself NULL if those are allowed. In SQLite, PRAGMA foreign_key_check lists violations directly.
Full answer
SQLite only enforces foreign keys when PRAGMA foreign_keys = ON is set on the connection. If an application forgot it, deletes may have left children pointing at missing parents.
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);
Here a student is deleted while enforcement is off, so the delete succeeds and leaves enrolments behind:
sql
DELETE FROM students WHERE id = 5;
SELECT COUNT(*) AS students_left FROM students;
students_left
4
An anti-join finds them: keep enrolments with no matching student.
sql
SELECT e.student_id, e.course_id
FROM enrolments e
LEFT JOIN students s ON s.id = e.student_id
WHERE s.id IS NULL
ORDER BY e.student_id, e.course_id;
student_id
course_id
5
20
The NOT EXISTS form says the same thing and is easy to adapt into a DELETE or an UPDATE:
sql
SELECT e.student_id, e.course_id
FROM enrolments e
WHERE NOT EXISTS (SELECT 1 FROM students s WHERE s.id = e.student_id)
ORDER BY e.student_id, e.course_id;
student_id
course_id
5
20
SQLite also has a built-in checker that reports every row violating a declared foreign key:
sql
SELECT "table", rowid, parent FROM pragma_foreign_key_check('enrolments') ORDER BY rowid;
table
rowid
parent
enrolments
8
students
After cleaning up, turn enforcement on in every connection (or move to an engine that always enforces it), otherwise the orphans return. Decide what cleanup means before deleting: orphaned enrolments might need to be archived for audit rather than removed.
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);
DELETE FROM students WHERE id = 5;
SELECT COUNT(*) AS students_left FROM students;
SELECT e.student_id, e.course_id
FROM enrolments e
LEFT JOIN students s ON s.id = e.student_id
WHERE s.id IS NULL
ORDER BY e.student_id, e.course_id;
SELECT e.student_id, e.course_id
FROM enrolments e
WHERE NOT EXISTS (SELECT 1 FROM students s WHERE s.id = e.student_id)
ORDER BY e.student_id, e.course_id;
SELECT "table", rowid, parent FROM pragma_foreign_key_check('enrolments') ORDER BY rowid;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Orphans are child rows whose parent key has no match
LEFT JOIN ... WHERE parent.key IS NULL or NOT EXISTS finds them
Enable enforcement after cleanup so orphans do not return
Common mistakes
Counting NULL foreign keys as orphans when NULL is allowed
Deleting orphans without checking whether they must be kept for audit
Follow-ups
How would you delete the orphans in one statement?
What ON DELETE options could have prevented this?
Tips
Mention the SQLite pragma; it shows you know where the gap came from
72.sql-0072Easyfresher
When should a condition go in WHERE and when in HAVING?
WHERE filters individual rows before grouping, so it cannot use aggregates. HAVING filters whole groups after GROUP BY, so it is where conditions on COUNT, SUM or AVG go. A condition on a plain column can go in either place, but WHERE is better because it removes rows before the work of grouping.
Full answer
The two clauses run at different moments. WHERE sees raw rows. HAVING sees groups, after aggregates have been computed.
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');
"Departments with more than one employee earning over 65000":
sql
SELECT dept_id, COUNT(*) AS well_paid
FROM employees
WHERE salary > 65000
GROUP BY dept_id
HAVING COUNT(*) > 1
ORDER BY dept_id;
dept_id
well_paid
1
3
salary > 65000 is about each employee, so it goes in WHERE and runs first. COUNT(*) > 1 is about each department's group, so it goes in HAVING. Sales is left with only Tom after WHERE, so it fails HAVING.
Putting the aggregate in WHERE is an error, because no groups exist yet when WHERE runs:
sql
SELECT dept_id FROM employees WHERE COUNT(*) > 1 GROUP BY dept_id; -- error on purpose
text
Error: misuse of aggregate: COUNT()
The reverse, moving a row condition into HAVING, often works but is wasteful and sometimes not allowed. Standard SQL lets HAVING use only grouped columns and aggregates, so HAVING dept_id = 1 is fine, but HAVING salary > 60000 is not, because salary is not one value per group:
sql
SELECT dept_id, COUNT(*) FROM employees GROUP BY dept_id HAVING salary > 60000; -- error on purpose
text
Error: column "employees.salary" must appear in the GROUP BY clause or be used in an aggregate 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 dept_id, COUNT(*) AS well_paid
FROM employees
WHERE salary > 65000
GROUP BY dept_id
HAVING COUNT(*) > 1
ORDER BY dept_id;
-- error on purpose
SELECT dept_id FROM employees WHERE COUNT(*) > 1 GROUP BY dept_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
WHERE filters rows before grouping
HAVING filters groups after aggregates are computed
Aggregates are not allowed in WHERE
Put row conditions in WHERE so less data is grouped
Common mistakes
Writing WHERE COUNT(*) > 1
Moving every condition into HAVING out of habit
Follow-ups
Can HAVING be used without GROUP BY?
Can HAVING refer to a column alias from SELECT?
Tips
Name the evaluation order: WHERE, then GROUP BY, then HAVING
73.sql-0073Mediummid
Why does SELECT dept_id, name, COUNT(*) FROM employees GROUP BY dept_id fail in PostgreSQL but run in SQLite?
In a grouped query each output row stands for a whole group, so every selected column must be either in GROUP BY or inside an aggregate. name is neither, and a department has several names, so PostgreSQL refuses. SQLite accepts it and returns the name from an arbitrary row of each group, which is a silent source of wrong answers. MySQL rejects it by default through ONLY_FULL_GROUP_BY.
Full answer
After grouping by department, Engineering is one row standing for Asha, Ravi and Mei. Which single name should that row show? There is no correct answer, so standard SQL forbids the question.
PostgreSQL enforces the rule:
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 dept_id, name, COUNT(*) FROM employees GROUP BY dept_id; -- error on purpose
text
Error: column "employees.name" must appear in the GROUP BY clause or be used in an aggregate function
SQLite allows these "bare columns" and picks a value from some row in the group:
sql
SELECT dept_id, name, COUNT(*) AS people
FROM employees
WHERE dept_id IS NOT NULL
GROUP BY dept_id
ORDER BY dept_id;
dept_id
name
people
1
Asha
3
2
Tom
2
3
Diego
2
The query runs and looks fine, which is the danger. Nothing promises which name you get, and it can change with the plan. (SQLite does make one exception, covered separately: with a single MIN or MAX aggregate, bare columns come from the row holding that minimum or maximum.)
Decide what you actually want and say it:
sql
SELECT dept_id,
COUNT(*) AS people,
GROUP_CONCAT(name, ', ') AS names
FROM (SELECT dept_id, name FROM employees WHERE dept_id IS NOT NULL ORDER BY name)
GROUP BY dept_id
ORDER BY dept_id;
dept_id
people
names
1
3
Asha, Mei, Ravi
2
2
Sara, Tom
3
2
Diego, Omar
Other valid fixes: add name to GROUP BY if you want one row per person (then the count is per person), or use a window function if you want every employee alongside their department's count. PostgreSQL also allows a column that is functionally dependent on a grouped primary key: grouping by departments.id lets you select departments.name without listing it.
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 dept_id, name, COUNT(*) AS people
FROM employees
WHERE dept_id IS NOT NULL
GROUP BY dept_id
ORDER BY dept_id;
SELECT dept_id,
COUNT(*) AS people,
GROUP_CONCAT(name, ', ') AS names
FROM (SELECT dept_id, name FROM employees WHERE dept_id IS NOT NULL ORDER BY name)
GROUP BY dept_id
ORDER BY dept_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
Every selected column must be grouped or aggregated
PostgreSQL and MySQL (by default) reject bare columns
SQLite allows them and returns a value from an arbitrary row
Fix by aggregating, grouping, or using a window function
Common mistakes
Trusting a bare column result because the test data happened to look right
Adding columns to GROUP BY until the error goes away, without checking the meaning
Follow-ups
How would you show each employee with their department head count?
What is functional dependency in GROUP BY?
Tips
Ask 'which name would that be?' out loud; it explains the rule
74.sql-0074Hardsenior
In SQLite, what does SELECT name, MAX(salary) FROM employees return? Is that behaviour portable?
SQLite has a documented special case: when a query has exactly one MIN() or MAX() aggregate, bare columns are taken from the row that holds that minimum or maximum. So it returns Asha with 120000. If several rows tie, one of them is chosen. No other major engine does this; PostgreSQL rejects the query.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
sql
SELECT name, MAX(salary) AS top_salary FROM employees;
name
top_salary
Asha
120000
The name really is the top earner's. SQLite documents this: with a single min() or max() aggregate, bare columns take their values from the row that produced the min or max. Per department it works too:
sql
SELECT dept_id, name, MAX(salary) AS top_salary
FROM employees
WHERE dept_id IS NOT NULL
GROUP BY dept_id
ORDER BY dept_id;
dept_id
name
top_salary
1
Asha
120000
2
Tom
70000
3
Diego
55000
Ties are the first weakness. Ravi and Mei share the second-highest salary. If Asha were removed, only one of the two would be returned, and which one is not defined:
sql
SELECT name, MAX(salary) AS top_salary FROM employees WHERE name <> 'Asha';
name
top_salary
Ravi
95000
The second weakness is portability. PostgreSQL rejects the query outright:
sql
SELECT name, MAX(salary) FROM employees; -- error on purpose
text
Error: column "employees.name" must appear in the GROUP BY clause or be used in an aggregate function
The portable way to get "the row with the maximum" is a subquery or a window function, which also lets you decide what happens with ties:
sql
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE name <> 'Asha')
AND name <> 'Asha'
ORDER BY name;
name
salary
Mei
95000
Ravi
95000
Knowing the SQLite rule helps you read existing code. Writing new code that depends on it ties the query to one engine.
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, MAX(salary) AS top_salary FROM employees;
SELECT dept_id, name, MAX(salary) AS top_salary
FROM employees
WHERE dept_id IS NOT NULL
GROUP BY dept_id
ORDER BY dept_id;
SELECT name, MAX(salary) AS top_salary FROM employees WHERE name <> 'Asha';
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE name <> 'Asha')
AND name <> 'Asha'
ORDER BY name;
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: with one MIN or MAX, bare columns come from that row
Ties return one arbitrary matching row
PostgreSQL and standard SQL reject bare columns
Use a subquery or window function for a portable 'row with max'
Common mistakes
Relying on the SQLite rule and losing tied rows
Porting SQLite queries with bare columns to PostgreSQL and hitting errors
Follow-ups
How would you return all employees tied for the top salary?
Does the rule hold if the query has two aggregates?
Tips
Mention ties and portability; those are the two reasons not to depend on it
75.sql-0075Mediummid
Write a query showing, for each customer, how many orders are shipped, pending and cancelled, in a single row per customer.
Use conditional aggregation: SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) and the same for each status, grouped by customer. The standard FILTER clause, COUNT(*) FILTER (WHERE status = 'shipped'), says the same thing more directly and works in PostgreSQL and SQLite 3.30+.
Full answer
Conditional aggregation turns rows into columns, a small pivot. The CASE inside the aggregate decides, row by row, whether the row counts towards that column.
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,
SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) AS pending,
SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
name
shipped
pending
cancelled
Ana
2
0
0
Bilal
0
1
1
Chloe
1
0
0
How it works for Bilal: his two orders produce two rows. For the shipped column, CASE gives 0 and 0, so the sum is 0. For pending it gives 1 and 0, and for cancelled 0 and 1.
The FILTER clause expresses the same idea without CASE:
sql
SELECT c.name,
COUNT(*) FILTER (WHERE o.status = 'shipped') AS shipped,
COUNT(*) FILTER (WHERE o.status = 'pending') AS pending,
COUNT(*) FILTER (WHERE o.status = 'cancelled') AS cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
name
shipped
pending
cancelled
Ana
2
0
0
Bilal
0
1
1
Chloe
1
0
0
PostgreSQL gives the same result for the FILTER version:
sql
SELECT c.name,
COUNT(*) FILTER (WHERE o.status = 'shipped') AS shipped,
COUNT(*) FILTER (WHERE o.status = 'pending') AS pending,
COUNT(*) FILTER (WHERE o.status = 'cancelled') AS cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
name
shipped
pending
cancelled
Ana
2
0
0
Bilal
0
1
1
Chloe
1
0
0
Both forms scan the table once, which is the main reason to use them over three separate queries or three joins. In MySQL, which has no FILTER clause, SUM(status = 'shipped') also works because comparisons return 1 or 0 there (from MySQL documentation, not run here); SQLite accepts that trick too, but it is less readable than CASE.
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,
SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) AS pending,
SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
SELECT c.name,
COUNT(*) FILTER (WHERE o.status = 'shipped') AS shipped,
COUNT(*) FILTER (WHERE o.status = 'pending') AS pending,
COUNT(*) FILTER (WHERE o.status = 'cancelled') AS cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
CASE inside SUM or COUNT counts only matching rows
One pass over the table produces several metrics
COUNT(*) FILTER (WHERE ...) is the standard alternative
This is the usual way to pivot a known set of values
Common mistakes
Writing COUNT(CASE WHEN ... THEN 1 ELSE 0 END), which counts every row because 0 is not NULL
Running one query per status and stitching results in application code
Follow-ups
How would you add revenue per status as well?
How would you pivot when the list of statuses is not known in advance?
Tips
Point out the COUNT versus SUM trap with ELSE 0
76.sql-0076Hardsenior
Why is the average of per-student averages different from the overall average mark, and which should a report use?
AVG over all enrolments weights each mark equally, so students with more courses count more. Averaging each student's average first gives each student equal weight. They are different questions: 'average mark across all papers' versus 'average of how students perform'. Pick the one the report means and label it.
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);
The overall average treats every marked enrolment as one vote:
sql
SELECT ROUND(AVG(marks), 2) AS overall_avg, COUNT(marks) AS marked_papers FROM enrolments;
overall_avg
marked_papers
75.0
7
The per-student averages, then their average, treat every student as one vote:
sql
SELECT student_id, ROUND(AVG(marks), 2) AS student_avg, COUNT(marks) AS papers
FROM enrolments
WHERE marks IS NOT NULL
GROUP BY student_id
ORDER BY student_id;
student_id
student_avg
papers
1
90.0
2
2
75.0
1
3
71.67
3
5
55.0
1
sql
SELECT ROUND(AVG(student_avg), 2) AS avg_of_student_avgs
FROM (SELECT student_id, AVG(marks) AS student_avg
FROM enrolments WHERE marks IS NOT NULL
GROUP BY student_id);
avg_of_student_avgs
72.92
The overall figure is 75.0 and the student-weighted figure is 72.92. Chen has three marked courses, so in the overall average his marks count three times; Ben and Eli each count once.
Neither number is wrong. A course coordinator asking "how did papers score on average?" wants the first. A mentor asking "how is a typical student doing?" wants the second. The mistake is mixing them, for example averaging department averages to get a company average salary. When the groups have different sizes, an average of averages is only equal to the overall average by coincidence.
If you have pre-computed averages and counts, you can recover the overall figure as a weighted average: SUM(avg * n) / SUM(n).
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 ROUND(AVG(marks), 2) AS overall_avg, COUNT(marks) AS marked_papers FROM enrolments;
SELECT student_id, ROUND(AVG(marks), 2) AS student_avg, COUNT(marks) AS papers
FROM enrolments
WHERE marks IS NOT NULL
GROUP BY student_id
ORDER BY student_id;
SELECT ROUND(AVG(student_avg), 2) AS avg_of_student_avgs
FROM (SELECT student_id, AVG(marks) AS student_avg
FROM enrolments WHERE marks IS NOT NULL
GROUP BY student_id);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Overall AVG weights each row equally
Average of group averages weights each group equally
They match only when every group has the same size
Recover the overall average with SUM(avg * n) / SUM(n)
Common mistakes
Averaging department averages to report a company average
Presenting either number without saying which weighting it uses
Follow-ups
How would you compute a credit-weighted average mark?
What happens to both numbers if NULL marks are included?
Tips
State which question each number answers
77.sql-0077Easyfresher
Write a query for total revenue per month from the orders and order items tables.
Join orders to their items, compute qty * unit_price per line, and group by the month of the order date, such as strftime('%Y-%m', order_date) in SQLite or date_trunc('month', order_date) in PostgreSQL. Decide whether cancelled orders count and filter them in WHERE.
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 strftime('%Y-%m', o.order_date) AS month,
SUM(i.qty * i.unit_price) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;
month
revenue
2026-01
13
2026-02
30
2026-03
69
A few choices are built into this query.
The month is computed from the date. In SQLite, strftime('%Y-%m', ...) returns text like '2026-02', which sorts correctly. In PostgreSQL the usual form is date_trunc('month', order_date), which returns a timestamp at the start of the month:
sql
SELECT date_trunc('month', o.order_date)::date AS month,
SUM(i.qty * i.unit_price) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1
ORDER BY 1;
month
revenue
2026-01-01
13
2026-02-01
30
2026-03-01
69
Cancelled orders are excluded in WHERE. Whether that is right is a business rule, and it belongs in the query explicitly, not left to chance.
Revenue is computed per line, then summed. Summing qty and unit_price separately and multiplying the totals would be wrong whenever an order has lines with different prices.
Months with no orders do not appear. If the chart needs every month, generate a list of months (a calendar table or a recursive CTE) and LEFT JOIN the totals onto it.
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 strftime('%Y-%m', o.order_date) AS month,
SUM(i.qty * i.unit_price) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Group by a month expression of the order date
Compute line revenue before summing
Filter business exclusions such as cancelled orders in WHERE
Empty months need a generated month list and a LEFT JOIN
Common mistakes
Multiplying SUM(qty) by SUM(price)
Forgetting that months without orders vanish from the result
Follow-ups
How would you show months with zero revenue?
How would you compare each month with the previous one?
Tips
Say out loud which orders you excluded and why
78.sql-0078Mediummid
How do you build a comma-separated list of values per group, in a defined order? Compare GROUP_CONCAT and STRING_AGG.
SQLite has GROUP_CONCAT(expr, separator) and, since 3.44, STRING_AGG as an alias; PostgreSQL has STRING_AGG(expr, separator); MySQL has GROUP_CONCAT. Without an ORDER BY inside the aggregate, the order of items is not guaranteed. PostgreSQL, MySQL and SQLite 3.44+ accept ORDER BY inside the call.
Full answer
List aggregation collapses a group's values into one string, handy for reports and exports.
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');
SQLite, with an ORDER BY inside the aggregate (supported since 3.44):
sql
SELECT d.name AS dept,
GROUP_CONCAT(e.name, ', ' ORDER BY e.name) AS people
FROM departments d
JOIN employees e ON e.dept_id = d.id
GROUP BY d.id, d.name
ORDER BY d.name;
dept
people
Engineering
Asha, Mei, Ravi
Sales
Sara, Tom
Support
Diego, Omar
PostgreSQL uses string_agg, with the same ORDER BY syntax:
sql
SELECT d.name AS dept,
string_agg(e.name, ', ' ORDER BY e.name) AS people
FROM departments d
JOIN employees e ON e.dept_id = d.id
GROUP BY d.id, d.name
ORDER BY d.name;
dept
people
Engineering
Asha, Mei, Ravi
Sales
Sara, Tom
Support
Diego, Omar
Without the inner ORDER BY, names come out in whatever order the engine reads rows. That order often looks sorted on small data and then changes as the table grows, so tests start failing for no visible reason. An ORDER BY on the outer query does not help; it sorts the result rows, not the items inside each string.
DISTINCT works inside the aggregate too:
sql
SELECT GROUP_CONCAT(DISTINCT dept_id) AS depts_with_staff FROM employees;
depts_with_staff
1,2,3
Two practical limits. MySQL truncates GROUP_CONCAT output at group_concat_max_len (1024 bytes by default, from MySQL documentation, not run here). And a delimited string is for display; if the next step needs the values separately, keep them as rows or use a JSON or array aggregate.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT d.name AS dept,
GROUP_CONCAT(e.name, ', ' ORDER BY e.name) AS people
FROM departments d
JOIN employees e ON e.dept_id = d.id
GROUP BY d.id, d.name
ORDER BY d.name;
SELECT GROUP_CONCAT(DISTINCT dept_id) AS depts_with_staff FROM employees;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
GROUP_CONCAT (SQLite, MySQL) and STRING_AGG (PostgreSQL, SQLite 3.44+) build lists
Put ORDER BY inside the aggregate for a defined item order
The outer ORDER BY sorts rows, not list items
MySQL truncates GROUP_CONCAT at group_concat_max_len
Common mistakes
Relying on the natural order of items in the list
Splitting the string back into values in later queries
Follow-ups
How would you aggregate into a JSON array instead?
How do you remove duplicates in the list?
Tips
Mention the inner ORDER BY; it is the detail most answers miss
79.sql-0079Hardsenior
How do you add subtotals and a grand total to a grouped report? Explain ROLLUP and how to emulate it.
GROUP BY ROLLUP (a, b) returns the normal (a, b) groups plus a subtotal row per a and one grand-total row, with NULL in the rolled-up columns. PostgreSQL, MySQL, SQL Server and Oracle support it; SQLite does not, so there you UNION ALL the detail, subtotal and total queries. GROUPING() tells a rolled-up NULL apart from a real NULL.
Full answer
A sales report often wants detail rows, a subtotal per country and a grand total. ROLLUP produces all three in one query.
SELECT country, product, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP (country, product)
ORDER BY country NULLS LAST, product NULLS LAST;
country
product
total
India
Bag
30
India
Pen
15
India
NULL
45
Spain
Lamp
25
Spain
Pen
8
Spain
NULL
33
NULL
NULL
78
Rows with product NULL are the country subtotals, and the row with both NULL is the grand total. GROUPING(col) returns 1 when the NULL was produced by the rollup, which matters if the data itself can contain NULLs:
sql
SELECT country, product, GROUPING(country) AS g_country, GROUPING(product) AS g_product, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP (country, product)
ORDER BY country NULLS LAST, product NULLS LAST;
country
product
g_country
g_product
total
India
Bag
0
0
30
India
Pen
0
0
15
India
NULL
0
1
45
Spain
Lamp
0
0
25
Spain
Pen
0
0
8
Spain
NULL
0
1
33
NULL
NULL
1
1
78
SQLite has no ROLLUP:
sql
SELECT country, product, SUM(amount) FROM sales GROUP BY ROLLUP (country, product); -- error on purpose
text
Error: no such function: ROLLUP
The emulation is a UNION ALL of the three levels:
sql
SELECT country, product, total FROM (
SELECT country, product, SUM(amount) AS total, 0 AS lvl FROM sales GROUP BY country, product
UNION ALL
SELECT country, NULL, SUM(amount), 1 FROM sales GROUP BY country
UNION ALL
SELECT NULL, NULL, SUM(amount), 2 FROM sales
)
ORDER BY lvl = 2, country, lvl, product;
country
product
total
India
Bag
30
India
Pen
15
India
NULL
45
Spain
Lamp
25
Spain
Pen
8
Spain
NULL
33
NULL
NULL
78
The extra lvl column keeps the subtotal under its details and the total at the end. Related tools: GROUPING SETS ((country), (product), ()) lets you pick any combination of groupings, and CUBE (a, b) produces every combination. Each grouping level costs another aggregation pass in the emulation, so on large tables a single ROLLUP query on an engine that supports it is cheaper.
sql
CREATE TABLE sales (country TEXT, product TEXT, amount INTEGER);
INSERT INTO sales VALUES ('India','Pen',10),('India','Bag',30),('India','Pen',5),('Spain','Pen',8),('Spain','Lamp',25);
-- error on purpose
SELECT country, product, SUM(amount) FROM sales GROUP BY ROLLUP (country, product);
SELECT country, product, total FROM (
SELECT country, product, SUM(amount) AS total, 0 AS lvl FROM sales GROUP BY country, product
UNION ALL
SELECT country, NULL, SUM(amount), 1 FROM sales GROUP BY country
UNION ALL
SELECT NULL, NULL, SUM(amount), 2 FROM sales
)
ORDER BY lvl = 2, country, lvl, product;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
ROLLUP adds subtotal and grand-total rows
Rolled-up columns appear as NULL; GROUPING() identifies them
SQLite lacks ROLLUP; emulate with UNION ALL of each level
GROUPING SETS and CUBE generalise the idea
Common mistakes
Confusing a subtotal NULL with a real NULL in the data
Sorting so subtotal rows appear above their details
Follow-ups
How would you label subtotal rows as 'All products'?
What does CUBE (country, product) add on top of ROLLUP?
Tips
Show how you sort the result so subtotals sit under their group
80.sql-0080Mediummid
HAVING COUNT(*) > 1 works, but can HAVING refer to a SELECT alias, as in HAVING n > 1?
Standard SQL evaluates HAVING before SELECT, so a SELECT alias is not visible there and PostgreSQL rejects HAVING n > 1. SQLite and MySQL accept the alias as an extension. Repeating the aggregate in HAVING works everywhere.
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');
SQLite resolves the alias:
sql
SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id HAVING n > 1 ORDER BY dept_id;
dept_id
n
1
3
2
2
3
2
PostgreSQL does not:
sql
SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id HAVING n > 1; -- error on purpose
text
Error: column "n" does not exist
The reason is the logical order: FROM, WHERE, GROUP BY, HAVING, then SELECT. When HAVING runs, the alias n has not been defined yet. PostgreSQL follows that order strictly for HAVING (it does allow aliases in GROUP BY and ORDER BY as extensions).
The portable form repeats the aggregate:
sql
SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id HAVING COUNT(*) > 1 ORDER BY dept_id;
dept_id
n
1
3
2
2
3
2
Repeating COUNT(*) does not make the database count twice; the planner recognises the same expression. When the expression is long, wrap the grouped query in a subquery or CTE and filter the alias in an outer WHERE.
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 dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id HAVING n > 1 ORDER BY dept_id;
SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id HAVING COUNT(*) > 1 ORDER BY dept_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
HAVING runs before SELECT in the logical order
PostgreSQL rejects SELECT aliases in HAVING
SQLite and MySQL accept them as an extension
Repeat the aggregate, or filter in an outer query
Common mistakes
Testing HAVING alias on SQLite and failing on PostgreSQL
Assuming the repeated aggregate is computed twice
Follow-ups
Can GROUP BY use a SELECT alias in PostgreSQL?
How would you write this with a CTE?
Tips
Explain with the logical order rather than memorising engine rules