Questions 81–100 of 501 · 0 of 20 on this page marked learned
81.sql-0081Easyfresher
What does AVG return for an integer column in SQLite and in PostgreSQL, and how do you round it for display?
SQLite's AVG always returns a floating-point value, and PostgreSQL's AVG of an integer column returns an exact numeric with many decimal places. For the Engineering salaries that is 103333.33333333333 versus 103333.333333333333. Use ROUND(AVG(x), 2) on both engines when the value is shown to people.
Full answer
Integer division does not apply to AVG: both engines return a fractional result. The type differs.
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 returns a REAL (a double-precision float):
sql
SELECT AVG(salary) AS avg_salary, typeof(AVG(salary)) AS type FROM employees WHERE dept_id = 1;
avg_salary
type
103333.33333333333
real
PostgreSQL returns numeric, an exact decimal, and shows a long scale:
sql
SELECT AVG(salary) AS avg_salary, pg_typeof(AVG(salary)) AS type FROM employees WHERE dept_id = 1;
avg_salary
type
103333.333333333333
numeric
For display, round explicitly:
sql
SELECT ROUND(AVG(salary), 2) AS avg_salary FROM employees WHERE dept_id = 1;
avg_salary
103333.33
sql
SELECT ROUND(AVG(salary), 2) AS avg_salary FROM employees WHERE dept_id = 1;
avg_salary
103333.33
A float can show artefacts in other calculations (0.1 + 0.2 is not exactly 0.3 in binary floating point). PostgreSQL's numeric avoids that at some speed cost. For money, store whole units such as cents in integers, or use a decimal type, and round only at the final display step.
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 AVG(salary) AS avg_salary, typeof(AVG(salary)) AS type FROM employees WHERE dept_id = 1;
SELECT ROUND(AVG(salary), 2) AS avg_salary FROM employees WHERE dept_id = 1;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Rounding intermediate values and losing precision in totals
Follow-ups
How would you format the rounded average with a thousands separator?
Why are floats a poor fit for money?
Tips
Mention the type, not just the value; it explains the different output
82.sql-0082Mediummid
What does SUM(DISTINCT amount) do, and why is it rarely the right fix for double counting?
SUM(DISTINCT x) adds each distinct value once, so two different rows with the same amount are counted only once. That is almost never what a business total means. It sometimes appears as a patch for join fan-out, where it hides the problem on some data and gives wrong totals on other data.
Full answer
DISTINCT inside an aggregate removes duplicate values before aggregating. For COUNT that is often useful. For SUM it usually is not.
sql
CREATE TABLE receipts (id INTEGER PRIMARY KEY, customer TEXT, amount INTEGER);
INSERT INTO receipts VALUES (1,'Ana',50),(2,'Ben',50),(3,'Chen',100);
sql
SELECT COUNT(*) AS receipts, SUM(amount) AS revenue, SUM(DISTINCT amount) AS sum_distinct FROM receipts;
receipts
revenue
sum_distinct
3
200
150
Ana and Ben each paid 50 and Chen paid 100. SUM(amount) is 200, the real revenue. SUM(DISTINCT amount) is 150, because the two 50s collapsed into one.
The pattern is common in queries that suffer from join fan-out. Someone notices doubled totals, adds DISTINCT, and the test data happens to have unique amounts, so the number looks right. Then real data with repeated amounts arrives and the total is quietly too low.
The real fix for fan-out is to aggregate each child table before joining. Use SUM(DISTINCT ...) only when the question really is about distinct values, for example "the sum of the distinct ticket prices offered", which is unusual.
sql
CREATE TABLE receipts (id INTEGER PRIMARY KEY, customer TEXT, amount INTEGER);
INSERT INTO receipts VALUES (1,'Ana',50),(2,'Ben',50),(3,'Chen',100);
SELECT COUNT(*) AS receipts, SUM(amount) AS revenue, SUM(DISTINCT amount) AS sum_distinct FROM receipts;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
SUM(DISTINCT x) sums each distinct value once
Equal amounts from different rows are merged
It is not a fix for join duplication
COUNT(DISTINCT) is commonly useful; SUM(DISTINCT) rarely is
Common mistakes
Using SUM(DISTINCT) to hide fan-out from a join
Testing with data where every amount is unique
Follow-ups
How would you fix a total inflated by joining two child tables?
When is AVG(DISTINCT) meaningful?
Tips
Give a two-row example with equal amounts; it shows the flaw instantly
83.sql-0083Mediummid
How do you count distinct combinations of two columns, such as distinct (city, year) pairs?
COUNT(DISTINCT a, b) is not standard. PostgreSQL accepts COUNT(DISTINCT (a, b)) using a row value, and MySQL accepts COUNT(DISTINCT a, b). The portable way is to select the distinct pairs in a subquery and count them. Watch NULLs: rows where either column is NULL are handled differently by each form.
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);
SQLite does not accept two arguments to COUNT(DISTINCT ...):
sql
SELECT COUNT(DISTINCT city, year) FROM students; -- error on purpose
text
Error: wrong number of arguments to function COUNT()
The portable form counts the rows of a DISTINCT subquery:
sql
SELECT COUNT(*) AS distinct_pairs
FROM (SELECT DISTINCT city, year FROM students);
distinct_pairs
3
There are three distinct pairs: (Pune, 1), (Leeds, 2) and (NULL, 3). The subquery's DISTINCT treats NULLs as equal, so Dara's (NULL, 3) pair is one combination.
PostgreSQL accepts a row value inside COUNT(DISTINCT):
sql
SELECT COUNT(DISTINCT (city, year)) AS distinct_pairs FROM students;
distinct_pairs
3
PostgreSQL returns the same 3 on this data, counting the pair that contains a NULL. MySQL's COUNT(DISTINCT a, b) is documented to skip any combination containing a NULL (not run here), so the same data could give 2 there. Rather than memorise each engine's corner cases, use the subquery form, and if incomplete pairs should not count, say so with WHERE city IS NOT NULL AND year IS NOT NULL.
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);
-- error on purpose
SELECT COUNT(DISTINCT city, year) FROM students;
SELECT COUNT(*) AS distinct_pairs
FROM (SELECT DISTINCT city, year FROM students);
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
COUNT(DISTINCT a, b) is not standard SQL
SELECT COUNT(*) FROM (SELECT DISTINCT a, b ...) is portable
PostgreSQL supports COUNT(DISTINCT (a, b))
Decide whether pairs containing NULL count, and filter explicitly
Common mistakes
Concatenating columns into one string to count, which can merge different pairs like ('ab','c') and ('a','bc')
Ignoring rows with NULL in one of the columns
Follow-ups
How would you count distinct pairs per department?
Why is concatenating columns a risky shortcut?
Tips
Show the subquery form first; it works on every engine
84.sql-0084Mediummid
Write a query that shows each department's share of the total salary bill as a percentage.
Group by department to get each department's sum, then divide by the overall sum. The overall sum can come from a scalar subquery or from a window function, SUM(SUM(salary)) OVER (), which adds up the grouped sums. Multiply by 100.0 so integer division does not truncate the result.
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');
With a scalar subquery for the total:
sql
SELECT d.name AS dept,
SUM(e.salary) AS dept_total,
ROUND(100.0 * SUM(e.salary) / (SELECT SUM(salary) FROM employees WHERE dept_id IS NOT NULL), 1) AS pct
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
ORDER BY pct DESC;
dept
dept_total
pct
Engineering
310000
56.9
Sales
132000
24.2
Support
103000
18.9
The same with a window function over the grouped result. SUM(salary) is the department total; wrapping it in SUM(...) OVER () adds those totals across all groups:
sql
SELECT d.name AS dept,
SUM(e.salary) AS dept_total,
ROUND(100.0 * SUM(e.salary) / SUM(SUM(e.salary)) OVER (), 1) AS pct
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
ORDER BY pct DESC;
dept
dept_total
pct
Engineering
310000
56.9
Sales
132000
24.2
Support
103000
18.9
Window functions run after GROUP BY, which is why an aggregate can sit inside a window aggregate like this. It also avoids scanning the table a second time.
Two details. Lena's NULL salary is ignored by SUM, and since she has no department she would form her own group with a NULL sum; the WHERE clause leaves her out so the percentages describe known salaries only. And 100.0 * comes first: 100 * SUM(salary) / total with integers would truncate each percentage to a whole number.
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,
SUM(e.salary) AS dept_total,
ROUND(100.0 * SUM(e.salary) / (SELECT SUM(salary) FROM employees WHERE dept_id IS NOT NULL), 1) AS pct
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
ORDER BY pct DESC;
SELECT d.name AS dept,
SUM(e.salary) AS dept_total,
ROUND(100.0 * SUM(e.salary) / SUM(SUM(e.salary)) OVER (), 1) AS pct
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
ORDER BY pct DESC;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Department sum divided by overall sum
Overall sum via scalar subquery or SUM(SUM(x)) OVER ()
Window functions run after GROUP BY
Use 100.0 to avoid integer division
Common mistakes
Dividing by COUNT instead of the total sum
Integer division turning shares into 0 or whole numbers
Follow-ups
How would you show each employee's share of their department's total?
Do the rounded percentages always add up to 100?
Tips
Mention why the window version avoids a second scan
85.sql-0085Mediummid
Two students share the same name. Why does grouping enrolments by student name give wrong totals, and what should you group by?
GROUP BY name merges every row with that name into one group, so two different people become one. Group by the student's key (id), and select the name alongside it, either by also grouping by it or because it depends on the key. Names are labels, not identifiers.
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);
A second student called Asha joins:
sql
INSERT INTO students VALUES (6, 'Asha', 'Leeds', 2);
INSERT INTO enrolments VALUES (6, 30, 63);
SELECT id, name, city FROM students WHERE name = 'Asha' ORDER BY id;
id
name
city
1
Asha
Pune
6
Asha
Leeds
Grouping by name:
sql
SELECT s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.name;
name
courses
avg_marks
Asha
3
81.0
The report shows one Asha with three courses and an average of 81. In reality there are two people: one with 88 and 92, the other with 63.
Group by the identifier, and carry the name along:
sql
SELECT s.id, s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.id, s.name
ORDER BY s.id;
id
name
courses
avg_marks
1
Asha
2
90.0
6
Asha
1
63.0
Adding s.name to GROUP BY is harmless here, because each id has exactly one name. Leaving it out would be an error in PostgreSQL unless the grouping is on the primary key, in which case PostgreSQL accepts the dependent column.
The general rule applies to any report: group by keys, display labels. City names, product names and email addresses all look unique until they are not.
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);
INSERT INTO students VALUES (6, 'Asha', 'Leeds', 2);
INSERT INTO enrolments VALUES (6, 30, 63);
SELECT id, name, city FROM students WHERE name = 'Asha' ORDER BY id;
SELECT s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.name;
SELECT s.id, s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.id, s.name
ORDER BY s.id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Grouping by a label merges different entities with the same label
Group by the key, display the name
Adding the name to GROUP BY alongside the key does not change the groups
PostgreSQL allows columns that depend on a grouped primary key
Common mistakes
Grouping by name, email or title as if they were unique
Noticing odd totals and blaming the data instead of the grouping
Follow-ups
How would you detect names that belong to more than one id?
What makes a good natural key?
Tips
Point at the merged average; it is an easy number to check by hand
86.sql-0086Mediummid
Can you use HAVING without GROUP BY? What does SELECT COUNT(*) FROM employees HAVING COUNT(*) > 100 return?
Yes. Without GROUP BY, the whole table is one group, and HAVING decides whether that single group is returned. With 8 employees, HAVING COUNT(*) > 100 is false, so the query returns zero rows instead of a row with the count. It is a compact way to return a result only when a condition about the whole set holds.
Full answer
An aggregate query without GROUP BY normally returns exactly one row. HAVING can remove that row.
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 TABLE order_items (order_id INTEGER, qty INTEGER);
CREATE TABLE orders (id INTEGER PRIMARY KEY);
INSERT INTO orders VALUES (1), (2);
INSERT INTO order_items VALUES (1, 3), (2, 1);
sql
SELECT COUNT(*) AS n FROM employees HAVING COUNT(*) > 100;
n
(0 rows)
sql
SELECT COUNT(*) AS n FROM employees HAVING COUNT(*) > 5;
n
8
The first query returns nothing: the single group has 8 rows, which fails the condition. The second returns the row because the condition holds.
A practical use is a data check that should return rows only when something is wrong, for example "return the count of orders with no items, but only if there are any":
sql
SELECT COUNT(*) AS orders_without_items
FROM orders o
WHERE NOT EXISTS (SELECT 1 FROM order_items i WHERE i.order_id = o.id)
HAVING COUNT(*) > 0;
orders_without_items
(0 rows)
Zero rows means the check passed; a monitoring job can alert whenever the query returns a row.
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 TABLE order_items (order_id INTEGER, qty INTEGER);
CREATE TABLE orders (id INTEGER PRIMARY KEY);
INSERT INTO orders VALUES (1), (2);
INSERT INTO order_items VALUES (1, 3), (2, 1);
SELECT COUNT(*) AS n FROM employees HAVING COUNT(*) > 100;
SELECT COUNT(*) AS n FROM employees HAVING COUNT(*) > 5;
SELECT COUNT(*) AS orders_without_items
FROM orders o
WHERE NOT EXISTS (SELECT 1 FROM order_items i WHERE i.order_id = o.id)
HAVING COUNT(*) > 0;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Without GROUP BY, the whole input is one group
HAVING can remove that single row
The result is zero rows, not a row containing 0
Useful for checks that return rows only on failure
Common mistakes
Expecting a row with a count when HAVING fails
Confusing 'zero rows' with 'a row with value 0' in application code
Follow-ups
What does SELECT COUNT(*) FROM empty_table return?
How would you write the check with WHERE EXISTS instead?
Tips
Contrast zero rows with a row containing 0
87.sql-0087Easyfresher
What do MIN and MAX return for text and for ISO date strings?
MIN and MAX use the column's normal sort order. For text that is character-by-character comparison under the collation, so MIN(name) is the alphabetically first name and uppercase letters sort before lowercase in a binary collation. ISO dates (YYYY-MM-DD) sort chronologically as text, so MIN and MAX give the earliest and latest dates.
Full answer
MIN and MAX are not limited to numbers. They return the smallest and largest value by the same comparison ORDER BY uses.
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 MIN(hire_date) AS first_hire, MAX(hire_date) AS last_hire, MIN(name) AS first_name FROM employees;
first_hire
last_hire
first_name
2019-03-01
2024-09-09
Asha
The earliest hire date is Asha's 2019 date and the latest is Omar's 2024 date, which works because ISO strings put the year first, then month, then day.
Text comparison has surprises. In SQLite's default binary collation, every uppercase letter sorts before every lowercase letter:
sql
WITH t(n) AS (VALUES ('apple'), ('Zara'), ('mango'))
SELECT MIN(n) AS min_name, MAX(n) AS max_name
FROM t;
min_name
max_name
Zara
mango
'Zara' is the minimum, because 'Z' (code 90) comes before 'a' (code 97). Use COLLATE NOCASE in SQLite, or a case-insensitive collation elsewhere, for a human alphabetical order:
sql
WITH t(n) AS (VALUES ('apple'), ('Zara'), ('mango'))
SELECT MIN(n COLLATE NOCASE) AS min_name, MAX(n COLLATE NOCASE) AS max_name
FROM t;
min_name
max_name
apple
Zara
Dates stored as text in another format, such as DD/MM/YYYY, break this completely: '31/01/2026' would be greater than '01/12/2026'. Store dates in ISO format or in a real date type.
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 MIN(hire_date) AS first_hire, MAX(hire_date) AS last_hire, MIN(name) AS first_name FROM employees;
WITH t(n) AS (VALUES ('apple'), ('Zara'), ('mango'))
SELECT MIN(n) AS min_name, MAX(n) AS max_name
FROM t;
WITH t(n) AS (VALUES ('apple'), ('Zara'), ('mango'))
SELECT MIN(n COLLATE NOCASE) AS min_name, MAX(n COLLATE NOCASE) AS max_name
FROM t;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
MIN and MAX follow the column's sort order
ISO date strings sort chronologically
Binary collation puts uppercase before lowercase
Use a case-insensitive collation for human alphabetical order
Common mistakes
Storing dates as DD/MM/YYYY text and using MAX to find the latest
Expecting MIN(name) to ignore case
Follow-ups
How do MIN and MAX treat NULLs?
How would you find the employee hired most recently, not just the date?
Tips
Mention the date format condition explicitly
88.sql-0088Hardsenior
What happens when SUM goes past the largest 64-bit integer in SQLite and in PostgreSQL?
SQLite's SUM raises an 'integer overflow' error when an all-integer sum exceeds 2^63 - 1, while TOTAL() switches to floating point and loses precision silently. PostgreSQL's SUM of bigint returns numeric, which has arbitrary precision, so it returns the exact result. Arithmetic with + on bigints in PostgreSQL does raise an out-of-range error.
Full answer
The largest signed 64-bit integer is 9223372036854775807. Totals of large values, such as amounts in the smallest currency unit over many years, can approach it.
SELECT SUM(amount) FROM ledger; -- error on purpose
text
Error: integer overflow
SQLite's TOTAL() uses floating point, so it returns a result, but the low digits are lost:
sql
SELECT TOTAL(amount) AS total_float FROM ledger;
total_float
9.223372036854776e+18
PostgreSQL's SUM over bigint returns numeric, so it is exact:
sql
SELECT SUM(amount) AS exact_sum, pg_typeof(SUM(amount)) AS type FROM ledger;
exact_sum
type
9223372036854775808
numeric
Plain addition of two bigints in PostgreSQL still overflows:
sql
SELECT 9223372036854775807::bigint + 1::bigint; -- error on purpose
text
Error: bigint out of range
So the engines differ on which operation is safe. For money totals, PostgreSQL's numeric result is convenient. In SQLite, an overflow error is better than a silent rounding, and the usual remedy is choosing units so totals stay far from the limit.
sql
CREATE TABLE ledger (amount INTEGER);
INSERT INTO ledger VALUES (9223372036854775807), (1);
-- error on purpose
SELECT SUM(amount) FROM ledger;
SELECT TOTAL(amount) AS total_float FROM ledger;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Max 64-bit signed integer is 9223372036854775807
SQLite SUM raises integer overflow; TOTAL() returns an imprecise float
PostgreSQL SUM(bigint) returns exact numeric
PostgreSQL bigint + bigint can still overflow
Common mistakes
Assuming every engine silently promotes to a bigger type
Using a floating-point total for money and losing cents
Follow-ups
What type does SUM(integer) return in PostgreSQL?
How would you store large monetary amounts safely?
Tips
Mention the exact limit; it shows you know what 'large' means here
89.sql-0089Easyfresher
Write a query showing how many students there are per city and year, with the busiest combination first.
Group by both columns, count rows, and order by the count descending with the grouping columns as tie-breakers. Each output row is one distinct (city, year) combination. Rows with NULL in either column form their own combination.
Full answer
Grouping by several columns makes one group per distinct combination of their values.
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 city, year, COUNT(*) AS students
FROM students
GROUP BY city, year
ORDER BY COUNT(*) DESC, city, year;
city
year
students
Leeds
2
2
Pune
1
2
NULL
3
1
Asha and Chen share (Pune, 1); Ben and Eli share (Leeds, 2). Dara has no city, so (NULL, 3) is its own group.
ORDER BY can sort on the aggregate, even though it was not given an alias, because ORDER BY runs after grouping. The two extra sort keys break the tie between the groups with 2 students so the order is repeatable.
If the question were "per city, with a breakdown by year", the shape is the same; the order of columns in GROUP BY does not change which groups exist, only the ORDER BY decides how they are presented.
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 city, year, COUNT(*) AS students
FROM students
GROUP BY city, year
ORDER BY COUNT(*) DESC, city, year;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
GROUP BY a, b gives one group per distinct combination
Column order in GROUP BY does not change the groups
ORDER BY can use aggregates
Add tie-breakers for a repeatable order
Common mistakes
Thinking GROUP BY a, b means 'group by a, then by b separately'
Sorting only by the count and getting ties in random order
Follow-ups
How would you show only combinations with at least two students?
How would you add a subtotal per city?
Tips
Explain what a single output row represents
90.sql-0090Mediummid
Write a query that buckets employees into salary bands (under 60k, 60k to 99,999, 100k and above) and counts each band.
Compute the band with a CASE expression and group by that expression. Order the bands by a numeric rank rather than by the label text. Decide where NULL salaries go; either give them their own band or exclude them.
Full answer
GROUP BY accepts any expression, so a CASE that maps each salary to a label is enough to build a histogram.
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 CASE WHEN salary IS NULL THEN 'unknown'
WHEN salary < 60000 THEN 'under 60k'
WHEN salary < 100000 THEN '60k-99,999'
ELSE '100k+' END AS band,
CASE WHEN salary IS NULL THEN 4
WHEN salary < 60000 THEN 1
WHEN salary < 100000 THEN 2
ELSE 3 END AS sort_key,
COUNT(*) AS people
FROM employees
GROUP BY band, sort_key
ORDER BY sort_key;
band
sort_key
people
under 60k
1
2
60k-99,999
2
4
100k+
3
1
unknown
4
1
The sort_key keeps the bands in a sensible order; sorting by the label alone would put '100k+' before 'under 60k' as text. Lena's unknown salary gets its own band instead of being silently dropped. With ELSE missing, CASE would return NULL for her and she would still appear, but as an unlabelled group.
Boundaries deserve care. The bands use < 60000 and < 100000, so 60000 falls in the middle band and 100000 in the top one, and no salary falls between two bands. Writing BETWEEN 60000 AND 100000 for the middle band would overlap with >= 100000, and CASE would silently assign 100000 to whichever branch comes first.
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 CASE WHEN salary IS NULL THEN 'unknown'
WHEN salary < 60000 THEN 'under 60k'
WHEN salary < 100000 THEN '60k-99,999'
ELSE '100k+' END AS band,
CASE WHEN salary IS NULL THEN 4
WHEN salary < 60000 THEN 1
WHEN salary < 100000 THEN 2
ELSE 3 END AS sort_key,
COUNT(*) AS people
FROM employees
GROUP BY band, sort_key
ORDER BY sort_key;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
GROUP BY can use a CASE expression
Sort bands by a numeric key, not the label
Give NULLs an explicit band or exclude them on purpose
Use half-open boundaries so bands neither overlap nor leave gaps
Common mistakes
Overlapping BETWEEN ranges in CASE
Sorting bands alphabetically
Follow-ups
How would you show bands with zero employees?
How would you compute equal-width bands automatically?
Tips
Mention the boundary rule explicitly
91.sql-0091Easyfresher
Write a query for the three best-selling products by revenue, excluding cancelled orders.
Join items to orders, filter out cancelled orders in WHERE, group by product, sum qty * unit_price, order by that sum descending and LIMIT 3. Add a tie-breaker, and consider whether ties at third place should all be shown.
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 i.product, SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
JOIN orders o ON o.id = i.order_id
WHERE o.status <> 'cancelled'
GROUP BY i.product
ORDER BY revenue DESC, i.product
LIMIT 3;
product
revenue
Bag
60
Lamp
25
Notebook
20
Bag leads with two sales of 30. The cancelled order 103 had 10 pens, so the status filter matters for Pen. Without the filter and without the LIMIT, the full ranking is:
sql
SELECT i.product, SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
GROUP BY i.product
ORDER BY revenue DESC, i.product;
product
revenue
Bag
60
Lamp
25
Notebook
20
Pen
17
Pen shows 17 instead of the real 7. On this small data the top three happen not to change, but a single large cancelled order can easily push a product into the list, so the business rule has to be written into the query.
LIMIT 3 cuts at exactly three rows. If two products tied for third place, one would be dropped without any sign. When ties matter, rank the products with a window function such as DENSE_RANK() and keep ranks up to 3, or use FETCH FIRST 3 ROWS WITH TIES on PostgreSQL.
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 i.product, SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
JOIN orders o ON o.id = i.order_id
WHERE o.status <> 'cancelled'
GROUP BY i.product
ORDER BY revenue DESC, i.product
LIMIT 3;
SELECT i.product, SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
GROUP BY i.product
ORDER BY revenue DESC, i.product;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Filter business exclusions before aggregating
Group, sum revenue per product, order descending, LIMIT
Add a tie-breaker so the order is repeatable
LIMIT drops tied rows; use ranking or WITH TIES if ties matter
Common mistakes
Including cancelled or refunded orders by accident
Ranking by quantity when the question asks for revenue
Follow-ups
How would you get the top product per country?
How would you show ties at third place?
Tips
Show how one business rule changes the answer
92.sql-0092Easyfresher
Write a query that lists employees who earn more than the company's average salary.
Compute the average in a scalar subquery and compare each salary with it: WHERE salary > (SELECT AVG(salary) FROM employees). A scalar subquery returns one value, so it can be used anywhere a single value is allowed. An aggregate cannot go directly in WHERE, which is why the subquery is needed.
Full answer
The average is one number for the whole table, but WHERE looks at one row at a time and cannot contain an aggregate. A scalar subquery bridges the gap: it runs on its own, returns a single value, and the outer query compares against 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');
sql
SELECT ROUND(AVG(salary), 2) AS company_avg FROM employees;
company_avg
77857.14
sql
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC, name;
name
salary
Asha
120000
Mei
95000
Ravi
95000
AVG skips Lena's NULL salary, so the average is over seven known salaries. Lena is not in the result either, because NULL > 77857.14... is UNKNOWN.
This subquery does not depend on the outer row, so the database computes it once. Contrast that with a correlated subquery, which refers to the outer row and is logically evaluated per row; that is the tool for "above their own department's average".
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 ROUND(AVG(salary), 2) AS company_avg FROM employees;
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A scalar subquery returns one value
It lets WHERE compare against an aggregate
An uncorrelated subquery is evaluated once
AVG ignores NULL; NULL salaries also fail the comparison
Common mistakes
Writing WHERE salary > AVG(salary)
Forgetting that NULL salaries change the average's denominator
Follow-ups
How would you show each employee's difference from the average?
How would you compare against the department average instead?
Tips
Show the average itself first, so the result can be checked by eye
93.sql-0093Mediummid
Write a query for employees who earn more than the average of their own department. Explain how a correlated subquery is evaluated.
A correlated subquery refers to a column of the outer row: WHERE e.salary > (SELECT AVG(x.salary) FROM employees x WHERE x.dept_id = e.dept_id). Logically it is re-evaluated for each outer row with that row's department. Optimizers may cache results per department or rewrite it as a join to a grouped table, but the result is the same.
Full answer
"Their own department" changes from row to row, so the subquery must know which row it is serving. It does that by referring to the outer alias e.
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, e.dept_id, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(x.salary)
FROM employees x
WHERE x.dept_id = e.dept_id)
ORDER BY e.dept_id, e.name;
name
dept_id
salary
Asha
1
120000
Tom
2
70000
Diego
3
55000
Logically, for Asha the subquery computes the Engineering average (103333.33) and compares; for Tom it computes the Sales average (66000); and so on. That per-row dependency is what "correlated" means.
The same result as a join to a grouped derived table, which computes each department average once:
sql
SELECT e.name, e.dept_id, e.salary
FROM employees e
JOIN (SELECT dept_id, AVG(salary) AS avg_sal
FROM employees GROUP BY dept_id) d ON d.dept_id = e.dept_id
WHERE e.salary > d.avg_sal
ORDER BY e.dept_id, e.name;
name
dept_id
salary
Asha
1
120000
Tom
2
70000
Diego
3
55000
Which is faster depends on the engine and the data. SQLite shows the correlated version in its plan explicitly:
sql
EXPLAIN QUERY PLAN
SELECT e.name FROM employees e
WHERE e.salary > (SELECT AVG(x.salary) FROM employees x WHERE x.dept_id = e.dept_id);
text
QUERY PLAN
SCAN e
CORRELATED SCALAR SUBQUERY 1
SCAN x
PostgreSQL often decorrelates or caches such subqueries. A window function gives a third version that reads the table once: AVG(salary) OVER (PARTITION BY dept_id). In an interview, show the correlated form because it reads like the question, then mention 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');
SELECT e.name, e.dept_id, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(x.salary)
FROM employees x
WHERE x.dept_id = e.dept_id)
ORDER BY e.dept_id, e.name;
SELECT e.name, e.dept_id, e.salary
FROM employees e
JOIN (SELECT dept_id, AVG(salary) AS avg_sal
FROM employees GROUP BY dept_id) d ON d.dept_id = e.dept_id
WHERE e.salary > d.avg_sal
ORDER BY e.dept_id, e.name;
EXPLAIN QUERY PLAN
SELECT e.name FROM employees e
WHERE e.salary > (SELECT AVG(x.salary) FROM employees x WHERE x.dept_id = e.dept_id);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
A correlated subquery references the outer row
Logically evaluated once per outer row
Equivalent to a join with a grouped derived table
A window function version reads the table once
Common mistakes
Forgetting the correlation condition and comparing with the company average
Using the same alias inside and outside so the correlation silently disappears
Follow-ups
Rewrite this with a window function.
Why might a correlated subquery be slow on a large table without an index?
Tips
Name the outer alias in the subquery explicitly; it shows where the correlation is
94.sql-0094Mediummid
A scalar subquery accidentally returns two rows. What happens in SQLite and in PostgreSQL?
PostgreSQL raises 'more than one row returned by a subquery used as an expression'. SQLite does not complain: it silently uses the first row the subquery produces, which may change with the plan. Make the subquery return one row on purpose, with an aggregate, a unique key filter, or ORDER BY plus LIMIT 1.
Full answer
A scalar subquery promises one value. When the data breaks that promise, engines react very differently.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
The intent is "the manager of the Engineering team", but Engineering has three employees:
sql
SELECT d.name,
(SELECT e.name FROM employees e WHERE e.dept_id = d.id) AS someone
FROM departments d
WHERE d.id = 1;
name
someone
Engineering
Asha
PostgreSQL stops with an error, which is the safe behaviour:
sql
SELECT d.name,
(SELECT e.name FROM employees e WHERE e.dept_id = d.id) AS someone
FROM departments d
WHERE d.id = 1;
-- error on purpose
text
Error: more than one row returned by a subquery used as an expression
SQLite quietly took one of the rows. Nothing in the result shows that the subquery was ambiguous, and a different index or insert order could pick a different employee.
Decide which single row you mean and write it:
sql
SELECT d.name,
(SELECT e.name FROM employees e
WHERE e.dept_id = d.id
ORDER BY e.salary DESC, e.name
LIMIT 1) AS top_earner
FROM departments d
WHERE d.id = 1;
name
top_earner
Engineering
Asha
Or use an aggregate when the question is really about a summary value, such as (SELECT MAX(salary) ...). If a subquery should logically return one row because of a business rule, back the rule with a unique constraint so the data cannot drift.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT d.name,
(SELECT e.name FROM employees e WHERE e.dept_id = d.id) AS someone
FROM departments d
WHERE d.id = 1;
SELECT d.name,
(SELECT e.name FROM employees e
WHERE e.dept_id = d.id
ORDER BY e.salary DESC, e.name
LIMIT 1) AS top_earner
FROM departments d
WHERE d.id = 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
PostgreSQL errors when a scalar subquery returns several rows
SQLite silently uses the first row
Make single-row intent explicit with an aggregate, a key, or ORDER BY ... LIMIT 1
Back 'there is only one' rules with constraints
Common mistakes
Testing on SQLite and missing a multi-row subquery bug
Adding LIMIT 1 without ORDER BY, which still picks an arbitrary row
Follow-ups
How would you write this with a join instead?
When is a subquery in the SELECT list a good idea?
Tips
Mention that the SQLite behaviour hides data problems
95.sql-0095Hardsenior
What do the ANY and ALL operators do with a subquery? What is salary > ALL (empty set)?
x > ANY (subquery) is true if x is greater than at least one value; x > ALL (subquery) is true if x is greater than every value. Over an empty set, ALL is true and ANY is false. A NULL in the set can turn a would-be false into UNKNOWN. PostgreSQL, MySQL and SQL Server support them; SQLite does not, so there you use MIN, MAX or EXISTS.
Full answer
> ALL and > ANY compare a value with every row of a subquery.
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');
PostgreSQL: who earns more than everyone in Sales?
sql
SELECT name, salary FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE dept_id = 2)
ORDER BY name;
name
salary
Asha
120000
Mei
95000
Ravi
95000
> ALL (62000, 70000) is the same as > 70000. > ANY is the same as > 62000:
sql
SELECT name, salary FROM employees
WHERE salary > ANY (SELECT salary FROM employees WHERE dept_id = 2)
ORDER BY name;
name
salary
Asha
120000
Mei
95000
Ravi
95000
Tom
70000
The empty set is the classic trick question. Legal has no employees, so the subquery returns nothing:
sql
SELECT
(SELECT COUNT(*) FROM employees e WHERE e.salary > ALL (SELECT salary FROM employees WHERE dept_id = 4)) AS all_empty,
(SELECT COUNT(*) FROM employees e WHERE e.salary > ANY (SELECT salary FROM employees WHERE dept_id = 4)) AS any_empty;
all_empty
any_empty
8
0
> ALL over an empty set is true for every row, because there is no Legal salary to fail against. All eight employees are counted, Lena included: her NULL salary is never compared with anything. > ANY over an empty set is false, because no value exists to be greater than.
SQLite does not have ANY or ALL:
sql
SELECT name FROM employees WHERE salary > ALL (SELECT salary FROM employees WHERE dept_id = 2); -- error on purpose
text
Error: near "ALL": syntax error
The usual rewrites use MAX and MIN, but they differ on the empty set, because MAX of nothing is NULL:
sql
SELECT COUNT(*) AS max_version_empty
FROM employees
WHERE salary > (SELECT MAX(salary) FROM employees WHERE dept_id = 4);
max_version_empty
0
The MAX version returns no rows where ALL returned everyone. If empty sets can happen, decide which answer is right and write it explicitly, for example with NOT EXISTS (SELECT 1 FROM ... WHERE s.salary >= e.salary), which matches the ALL behaviour.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
-- error on purpose
SELECT name FROM employees WHERE salary > ALL (SELECT salary FROM employees WHERE dept_id = 2);
SELECT COUNT(*) AS max_version_empty
FROM employees
WHERE salary > (SELECT MAX(salary) FROM employees WHERE dept_id = 4);
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
> ALL means greater than every value; > ANY means greater than at least one
ALL over an empty set is TRUE; ANY over an empty set is FALSE
SQLite has no ANY or ALL
MAX and MIN rewrites behave differently on empty sets
NOT EXISTS reproduces ALL semantics exactly
Common mistakes
Rewriting > ALL as > (SELECT MAX ...) and losing the empty-set behaviour
Forgetting that a NULL in the set can make ALL return UNKNOWN
Follow-ups
Rewrite > ALL with NOT EXISTS.
What does x = ANY (subquery) correspond to?
Tips
Bring up the empty-set case before you are asked
96.sql-0096Hardsenior
A DELETE meant to remove customers listed in a blocklist table deleted every customer. The subquery column name was wrong. How can that happen?
If a column named in a subquery does not exist in the subquery's own tables, SQL looks for it in the outer query. WHERE id IN (SELECT id FROM blocklist), when blocklist has customer_ref but no id, silently becomes a correlated subquery comparing customers.id with itself, which is true for every row. Always qualify columns in subqueries with a table alias.
Full answer
Name resolution in subqueries works from the inside out. A column is looked up first in the subquery's FROM tables, then in the enclosing query. That is what makes correlated subqueries possible, and it is also how a typo turns into a disaster.
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
CREATE TABLE blocklist (customer_ref INTEGER);
INSERT INTO blocklist VALUES (2), (3);
The blocklist stores customer ids in a column called customer_ref. The query uses id:
sql
SELECT COUNT(*) AS would_delete
FROM customers
WHERE id IN (SELECT id FROM blocklist);
would_delete
4
Every customer matches. blocklist has no id column, so id inside the subquery refers to customers.id, the outer row. For each customer the subquery returns that customer's own id once per blocklist row, and id IN (id, id) is true. As a DELETE, this would remove the whole table without any error.
Qualifying the column with the subquery's alias turns the mistake into an error:
sql
SELECT COUNT(*) FROM customers c WHERE c.id IN (SELECT b.id FROM blocklist b); -- error on purpose
text
Error: no such column: b.id
And the correct query:
sql
SELECT c.id, c.name
FROM customers c
WHERE c.id IN (SELECT b.customer_ref FROM blocklist b)
ORDER BY c.id;
id
name
2
Bilal
3
Chloe
PostgreSQL resolves names the same way, so this is not an SQLite quirk. Protective habits: alias every table in a query with subqueries and qualify every column; run the SELECT version and check the count before running a DELETE or UPDATE; and do destructive changes inside a transaction so a surprising row count can be rolled back.
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
CREATE TABLE blocklist (customer_ref INTEGER);
INSERT INTO blocklist VALUES (2), (3);
SELECT COUNT(*) AS would_delete
FROM customers
WHERE id IN (SELECT id FROM blocklist);
-- error on purpose
SELECT COUNT(*) FROM customers c WHERE c.id IN (SELECT b.id FROM blocklist b);
SELECT c.id, c.name
FROM customers c
WHERE c.id IN (SELECT b.customer_ref FROM blocklist b)
ORDER BY c.id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Unknown columns in a subquery resolve to the outer query
A typo can create an accidental correlated subquery that is always true
Qualify subquery columns with aliases to turn typos into errors
Preview destructive statements with SELECT COUNT(*) inside a transaction
Common mistakes
Writing unqualified columns inside IN subqueries
Running a DELETE without checking how many rows it will affect
Follow-ups
How would you safely run this DELETE in a transaction and verify it?
Does PostgreSQL resolve names the same way?
Tips
Explain the inside-out lookup rule; it is the root cause
97.sql-0097Mediummid
Write a query that returns each customer's most recent order using a correlated subquery.
Keep an order only if its date equals the maximum order date for the same customer: WHERE o.order_date = (SELECT MAX(o2.order_date) FROM orders o2 WHERE o2.customer_id = o.customer_id). If a customer has two orders on the latest date, both are returned, so add a tie-breaker if exactly one is required.
Full answer
"Latest row per group" is one of the most common interview patterns. A correlated subquery expresses it directly.
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
SELECT c.name, o.id, o.order_date
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.order_date = (SELECT MAX(o2.order_date)
FROM orders o2
WHERE o2.customer_id = o.customer_id)
ORDER BY c.name;
name
id
order_date
Ana
102
2026-02-11
Bilal
105
2026-03-09
Chloe
104
2026-03-01
For each order, the subquery finds the newest date among orders of the same customer, and the order is kept only if it matches. Ana's January order is dropped; her February order is kept.
Ties need a decision. If Ana had two orders on 2026-02-11, both would be returned. When the business wants exactly one, compare on a unique key instead, such as the highest id among the latest-date orders:
sql
SELECT c.name, o.id, o.order_date
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.id = (SELECT o2.id
FROM orders o2
WHERE o2.customer_id = o.customer_id
ORDER BY o2.order_date DESC, o2.id DESC
LIMIT 1)
ORDER BY c.name;
name
id
order_date
Ana
102
2026-02-11
Bilal
105
2026-03-09
Chloe
104
2026-03-01
Order 106 has no customer and drops out of the join with customers, which is correct for a per-customer report.
For large tables, an index on (customer_id, order_date) lets each subquery jump straight to the newest order for that customer. Window functions (ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, id DESC)) are the other common answer and handle ties in the same explicit way.
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, o.id, o.order_date
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.order_date = (SELECT MAX(o2.order_date)
FROM orders o2
WHERE o2.customer_id = o.customer_id)
ORDER BY c.name;
SELECT c.name, o.id, o.order_date
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.id = (SELECT o2.id
FROM orders o2
WHERE o2.customer_id = o.customer_id
ORDER BY o2.order_date DESC, o2.id DESC
LIMIT 1)
ORDER BY c.name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Correlated MAX per group finds the latest row
Ties on the max value return several rows
Use a unique key or a deterministic ORDER BY ... LIMIT 1 for exactly one
An index on (group, date) makes each lookup cheap
Common mistakes
Using GROUP BY customer with MAX(date) and then joining back on date only, which duplicates ties
Selecting other columns next to MAX() and getting values from a different row
Follow-ups
Rewrite this with ROW_NUMBER().
How would you get the latest two orders per customer?
Tips
Mention how ties are handled before the interviewer asks
98.sql-0098Mediummid
When is a subquery in the SELECT list a good choice, and when is a join with GROUP BY better?
A scalar subquery in SELECT is clear for one or two per-row lookups, such as an order count per customer, and it never multiplies rows. With several such columns, each subquery is a separate lookup, and a single join to a pre-aggregated derived table is often cheaper and easier to read. Correctness is the same when written well; the plan decides speed.
Full answer
Both versions below answer "each customer with their number of orders and total quantity bought".
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 scalar subqueries in the select list:
sql
SELECT c.name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders,
(SELECT COALESCE(SUM(i.qty), 0)
FROM orders o JOIN order_items i ON i.order_id = o.id
WHERE o.customer_id = c.id) AS items_bought
FROM customers c
ORDER BY c.name;
name
orders
items_bought
Ana
2
8
Bilal
2
11
Chloe
1
4
Dev
0
0
With a join to one pre-aggregated table:
sql
SELECT c.name,
COALESCE(s.orders, 0) AS orders,
COALESCE(s.items_bought, 0) AS items_bought
FROM customers c
LEFT JOIN (
SELECT o.customer_id,
COUNT(DISTINCT o.id) AS orders,
SUM(i.qty) AS items_bought
FROM orders o JOIN order_items i ON i.order_id = o.id
GROUP BY o.customer_id
) s ON s.customer_id = c.id
ORDER BY c.name;
name
orders
items_bought
Ana
2
8
Bilal
2
11
Chloe
1
4
Dev
0
0
Both are correct, and Dev gets 0 in both. Each has strengths.
Subqueries in SELECT keep the outer row count fixed: there is no way for them to duplicate customers. They read naturally, one column at a time. But each one is a separate correlated lookup, so five such columns mean five lookups per customer.
The join version computes all statistics in one pass over orders and items, then joins once. It scales better as the number of metrics grows, but you must aggregate before joining or you risk fan-out, and you need LEFT JOIN plus COALESCE to keep customers with no orders.
SQLite reports each scalar subquery in the plan:
sql
EXPLAIN QUERY PLAN
SELECT c.name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders
FROM customers c;
text
QUERY PLAN
SCAN c
CORRELATED SCALAR SUBQUERY 1
SCAN o
A reasonable rule: one or two simple lookups, use a subquery; several metrics from the same child tables, pre-aggregate and join; and check the plan when the table is large.
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,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders,
(SELECT COALESCE(SUM(i.qty), 0)
FROM orders o JOIN order_items i ON i.order_id = o.id
WHERE o.customer_id = c.id) AS items_bought
FROM customers c
ORDER BY c.name;
SELECT c.name,
COALESCE(s.orders, 0) AS orders,
COALESCE(s.items_bought, 0) AS items_bought
FROM customers c
LEFT JOIN (
SELECT o.customer_id,
COUNT(DISTINCT o.id) AS orders,
SUM(i.qty) AS items_bought
FROM orders o JOIN order_items i ON i.order_id = o.id
GROUP BY o.customer_id
) s ON s.customer_id = c.id
ORDER BY c.name;
EXPLAIN QUERY PLAN
SELECT c.name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders
FROM customers c;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Scalar subqueries in SELECT never multiply outer rows
Each one is a separate correlated lookup
One pre-aggregated join scales better for many metrics
LEFT JOIN plus COALESCE keeps parents with no children
Common mistakes
Joining child tables directly and summing, causing fan-out
Adding many correlated subqueries to one large query without checking the plan
Follow-ups
How would a LATERAL join help here in PostgreSQL?
How would you add the date of the latest order?
Tips
Mention fan-out as the main risk of the join version
99.sql-0099Mediummid
How do you filter rows using a list of pairs, such as specific (student_id, course_id) combinations, in one condition?
Use a row value comparison: WHERE (student_id, course_id) IN (VALUES (1, 10), (3, 30)) or IN (SELECT ...). SQLite (since 3.15), PostgreSQL and MySQL support row values. Without them, you write OR-ed pairs of conditions or join to a small table of pairs.
Full answer
A row value is a list of columns treated as one value. Comparing row values compares the columns together, which is exactly what a composite key needs.
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);
INSERT INTO moderation VALUES (1, 10), (3, 30);
sql
SELECT student_id, course_id, marks
FROM enrolments
WHERE (student_id, course_id) IN (VALUES (1, 10), (3, 30))
ORDER BY student_id, course_id;
student_id
course_id
marks
1
10
88
3
30
80
Comparing the columns separately is a common wrong version:
sql
SELECT student_id, course_id, marks
FROM enrolments
WHERE student_id IN (1, 3) AND course_id IN (10, 30)
ORDER BY student_id, course_id;
student_id
course_id
marks
1
10
88
3
10
64
3
30
80
student_id IN (1, 3) AND course_id IN (10, 30) allows any mix of the two lists, so Chen's Databases enrolment (3, 10) matches too, giving three rows instead of the two requested pairs.
The same row value form works with a subquery, for example to find enrolments that have a moderation record:
sql
SELECT e.student_id, e.course_id, e.marks
FROM enrolments e
WHERE (e.student_id, e.course_id) IN (SELECT m.student_id, m.course_id FROM moderation m)
ORDER BY e.student_id, e.course_id;
student_id
course_id
marks
1
10
88
3
30
80
Row values also simplify keyset pagination, where (order_date, id) > (?, ?) means "after this position" in one comparison.
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);
INSERT INTO moderation VALUES (1, 10), (3, 30);
SELECT student_id, course_id, marks
FROM enrolments
WHERE (student_id, course_id) IN (VALUES (1, 10), (3, 30))
ORDER BY student_id, course_id;
SELECT student_id, course_id, marks
FROM enrolments
WHERE student_id IN (1, 3) AND course_id IN (10, 30)
ORDER BY student_id, course_id;
SELECT e.student_id, e.course_id, e.marks
FROM enrolments e
WHERE (e.student_id, e.course_id) IN (SELECT m.student_id, m.course_id FROM moderation m)
ORDER BY e.student_id, e.course_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Row values compare several columns as one unit
(a, b) IN (VALUES ...) matches exact pairs
Separate IN lists allow wrong combinations
Row values also power keyset pagination
Common mistakes
Using two independent IN lists for a pair filter
Concatenating columns into strings to compare pairs
Follow-ups
How would you write this on an engine without row values?
How does (a, b) > (x, y) compare?
Tips
Show the wrong two-list version; the extra row makes the point
100.sql-0100Mediummid
Write a query for departments whose average salary is higher than the company-wide average.
Group employees by department and compare the group's AVG(salary) with a scalar subquery for the overall average in HAVING: HAVING AVG(salary) > (SELECT AVG(salary) FROM employees). The subquery runs once; the comparison happens per group.
Full answer
The condition is about each department's group, so it belongs in HAVING, and the company figure comes from a scalar subquery.
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 ROUND(AVG(salary), 2) AS company_avg FROM employees;
company_avg
77857.14
sql
SELECT d.name, ROUND(AVG(e.salary), 2) AS dept_avg
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
HAVING AVG(e.salary) > (SELECT AVG(salary) FROM employees)
ORDER BY dept_avg DESC;
name
dept_avg
Engineering
103333.33
Only Engineering is above the overall average of 77857.14. Sales and Support are below it.
Two choices worth stating. Lena's NULL salary is ignored by both averages, and she has no department, so her NULL group has a NULL average and drops out (NULL > anything is UNKNOWN). And the comparison is between department averages and the employee-weighted company average. If the question meant "above the average department", you would compare with the average of department averages instead, which can give a different list.
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 ROUND(AVG(salary), 2) AS company_avg FROM employees;
SELECT d.name, ROUND(AVG(e.salary), 2) AS dept_avg
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
HAVING AVG(e.salary) > (SELECT AVG(salary) FROM employees)
ORDER BY dept_avg DESC;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Per-group conditions go in HAVING
A scalar subquery supplies the company-wide value
NULL groups drop out of the comparison
Clarify employee-weighted versus department-weighted averages
Common mistakes
Putting the aggregate comparison in WHERE
Comparing with the average of department averages without saying so
Follow-ups
How would you show the difference from the company average for every department?
How would you write this with a window function?
Tips
Ask which average the business means before writing the query