Questions 301–320 of 501 · 0 of 20 on this page marked learned
301.sql-0301Easyfresher
What does an empty OVER () compute, and how does adding ORDER BY inside it change SUM?
OVER () makes the whole result set one partition with an unordered frame, so SUM(x) OVER () is the grand total on every row. Adding ORDER BY switches the default frame to 'from the start up to the current row and its peers', so the same SUM becomes a running total.
Full answer
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, amount,
SUM(amount) OVER () AS total,
SUM(amount) OVER (ORDER BY day) AS running
FROM daily_sales ORDER BY day;
day
amount
total
running
2026-03-01
120
700
120
2026-03-02
80
700
200
2026-03-03
150
700
350
2026-03-05
90
700
440
2026-03-06
60
700
500
2026-03-09
200
700
700
The total column is 700 everywhere. The running column grows row by row, because ORDER BY inside OVER changes the frame, not just the order.
This is the most common source of surprise with window functions: adding ORDER BY to get a "nicer" window silently changes the numbers. When you want the grand total, leave the window empty or say ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
SELECT day, amount,
SUM(amount) OVER () AS total,
SUM(amount) OVER (ORDER BY day) AS running
FROM daily_sales ORDER BY day;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
OVER () is one partition, whole-set frame
SUM OVER () gives the grand total per row
ORDER BY in OVER changes the default frame
Write the frame explicitly when in doubt
Common mistakes
Adding ORDER BY to OVER () and getting running totals by accident
Thinking ORDER BY inside OVER only affects output order
Follow-ups
What is the default frame with ORDER BY?
How would you show share of total per row?
Tips
Show both columns side by side
302.sql-0302Easyfresher
What does SELECT COUNT(*) FROM employees WHERE salary > 200000 return: zero rows, one row with 0, or NULL?
One row containing 0. An aggregate query without GROUP BY always returns exactly one row, even when no input rows match, and COUNT of nothing is 0. With GROUP BY, the same filter would return no rows at all.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
sql
SELECT COUNT(*) AS n FROM employees WHERE salary > 200000;
n
0
No employee earns that much, yet the query still returns a row, because aggregates without GROUP BY summarize the whole (empty) set into one row. SUM, AVG, MIN and MAX in the same position would return NULL, not 0.
Add GROUP BY dept_id and the result has no rows, since there are no groups to report. Code that reads "the first row" must handle both shapes.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT COUNT(*) AS n FROM employees WHERE salary > 200000;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Aggregates without GROUP BY return exactly one row
COUNT of an empty set is 0
SUM, AVG, MIN and MAX of an empty set are NULL
With GROUP BY, an empty input gives no rows
Common mistakes
Expecting an empty result from an ungrouped COUNT
Expecting 0 from SUM over no rows
Follow-ups
What does SUM return in the same query?
How would you return 0 from SUM?
Tips
Contrast grouped and ungrouped results
303.sql-0303Easyfresher
Given the values 10, 20 and NULL, what do SUM, AVG, MIN and COUNT(*) return?
SUM is 30, AVG is 15.0, MIN is 10 and COUNT(*) is 3. Aggregates other than COUNT(*) skip NULLs, so AVG divides by 2, not 3, while COUNT(*) counts rows regardless of their values.
Full answer
sql
WITH t(x) AS (VALUES (10), (20), (NULL))
SELECT SUM(x) AS s, AVG(x) AS a, MIN(x) AS mn, COUNT(*) AS rows_n, COUNT(x) AS values_n FROM t;
s
a
mn
rows_n
values_n
30
15.0
10
3
2
The NULL contributes nothing to SUM, AVG or MIN. COUNT(x) counts only the two non-NULL values, while COUNT(*) counts all three rows.
If missing values should count as zero for the average, write AVG(COALESCE(x, 0)), which gives 10. Which one is right depends on whether NULL means "zero" or "unknown".
sql
WITH t(x) AS (VALUES (10), (20), (NULL))
SELECT SUM(x) AS s, AVG(x) AS a, MIN(x) AS mn, COUNT(*) AS rows_n, COUNT(x) AS values_n FROM t;
Checked on SQLite 3.46.1, run twice with identical output.
Dividing SUM by COUNT(*) and calling it the average
Follow-ups
When should a missing value count as zero?
What does COUNT(DISTINCT x) return here?
Tips
Ask what NULL means in the data
304.sql-0304Easyfresher
What does GROUP BY return for this query: SELECT city, COUNT(*) FROM students GROUP BY city, when one student has a NULL city?
The NULL cities form their own group, shown as one row with NULL in the city column. GROUP BY treats all NULLs as equal for grouping, even though NULL = NULL is not true in a WHERE clause.
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 city, COUNT(*) AS n FROM students GROUP BY city ORDER BY city;
city
n
NULL
1
Leeds
2
Pune
2
Dara has no city and appears as a separate group. SQLite sorts NULL first in ascending order; PostgreSQL sorts it last unless told otherwise.
Reports often relabel the group with COALESCE(city, 'Unknown'). Do that in the SELECT and GROUP BY both, or group by the raw column and relabel only for display.
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, COUNT(*) AS n FROM students GROUP BY city ORDER BY city;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
GROUP BY puts all NULLs in one group
The group key shows as NULL
NULL sort position differs between engines
Relabel with COALESCE for display
Common mistakes
Expecting rows with NULL keys to disappear
Assuming NULL groups sort the same on every engine
Follow-ups
How do you put the NULL group last on SQLite?
Does DISTINCT treat NULLs the same way?
Tips
Mention the sort-order difference
305.sql-0305Mediummid
What does SELECT dept_id, COUNT(*) FROM employees WHERE salary > 60000 GROUP BY dept_id return for a department where nobody earns over 60000?
Nothing: that department has no row. WHERE removes rows before grouping, so a department with no qualifying employees never forms a group. To show it with 0, start from departments and LEFT JOIN with the condition in ON, or count conditionally.
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 dept_id, COUNT(*) AS n FROM employees WHERE salary > 60000 GROUP BY dept_id ORDER BY dept_id;
dept_id
n
1
3
2
2
Support (dept 3) pays 55000 and 48000, so it vanishes from the result. Conditional counting keeps every department that has employees:
sql
SELECT dept_id, COUNT(CASE WHEN salary > 60000 THEN 1 END) AS n FROM employees WHERE dept_id IS NOT NULL GROUP BY dept_id ORDER BY dept_id;
dept_id
n
1
3
2
2
3
0
Legal still does not appear, because it has no employees at all. Starting from departments with a LEFT JOIN is the way to include 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, COUNT(*) AS n FROM employees WHERE salary > 60000 GROUP BY dept_id ORDER BY dept_id;
SELECT dept_id, COUNT(CASE WHEN salary > 60000 THEN 1 END) AS n FROM employees WHERE dept_id IS NOT NULL GROUP BY dept_id ORDER BY dept_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
WHERE filters before grouping
Groups with no qualifying rows disappear
Conditional COUNT keeps every group
Start from the parent table to include empty parents
Common mistakes
Expecting zero-count rows from a WHERE-filtered GROUP BY
Moving the condition to HAVING and changing the meaning
Follow-ups
How would you include Legal?
When is HAVING the right place?
Tips
Show the conditional-count version
306.sql-0306Easyfresher
What does SELECT MAX(name) FROM employees return?
The alphabetically last name under the column's collation, here 'Tom'. MIN and MAX work on text, comparing strings, not on the length of the value. With SQLite's default binary collation, uppercase letters sort before lowercase ones, which can surprise.
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 MIN(name) AS first_name, MAX(name) AS last_name FROM employees;
first_name
last_name
Asha
Tom
MIN returns Asha and MAX returns Tom, by string comparison. For the longest name, sort by length(name) instead.
With mixed case, binary collation would put 'zoe' after 'Tom' but 'Zoe' before 'asha'. Use MAX(name COLLATE NOCASE) in SQLite, or a linguistic collation in PostgreSQL, when case should not matter.
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(name) AS first_name, MAX(name) AS last_name FROM employees;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
MIN and MAX compare text by collation
They do not measure string length
Binary collation is case-sensitive
Use NOCASE or a linguistic collation when needed
Common mistakes
Using MAX to find the longest string
Ignoring case effects on string MAX
Follow-ups
How would you return the longest name?
What do MIN and MAX return for dates stored as text?
Tips
Separate value order from length
307.sql-0307Mediummid
What does AVG(DISTINCT x) return for the values 10, 10 and 40?
25.0. DISTINCT removes the duplicate 10 before averaging, so the average is over 10 and 40. Plain AVG would give 20.0. DISTINCT inside an aggregate changes the statistic, so use it only when duplicates are truly meaningless.
Full answer
sql
WITH t(x) AS (VALUES (10), (10), (40))
SELECT AVG(x) AS avg_all, AVG(DISTINCT x) AS avg_distinct, SUM(DISTINCT x) AS sum_distinct FROM t;
avg_all
avg_distinct
sum_distinct
20.0
25.0
50
The two 10s are separate rows, for example two orders of the same price. Removing one of them answers a different question ("average of distinct prices"), not "average order value".
SUM(DISTINCT x) is 50 for the same reason. These forms are occasionally useful, but they are a frequent wrong fix for double counting after joins, where the right fix is to aggregate before joining.
sql
WITH t(x) AS (VALUES (10), (10), (40))
SELECT AVG(x) AS avg_all, AVG(DISTINCT x) AS avg_distinct, SUM(DISTINCT x) AS sum_distinct FROM t;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
DISTINCT inside an aggregate removes duplicate values first
AVG(DISTINCT) answers a different question than AVG
Equal values can be different real events
Fix join fan-out by aggregating earlier, not with DISTINCT
Common mistakes
Using SUM(DISTINCT) to undo join duplication
Assuming equal values are duplicates
Follow-ups
When is COUNT(DISTINCT) the right choice?
How do you fix double counting after a join?
Tips
Ask whether equal values are separate events
308.sql-0308Easyfresher
What does SELECT COUNT(*) FROM employees GROUP BY dept_id HAVING COUNT(*) > 5 return?
No rows. No department has more than five employees, so HAVING removes every group, and a grouped query with no surviving groups returns an empty result, not a row with 0.
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 dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id HAVING COUNT(*) > 5;
dept_id
n
(0 rows)
The largest group is Engineering with three people. Each group failed the HAVING test, leaving nothing.
This is the grouped counterpart of the empty COUNT question: without GROUP BY the query returns one row, with GROUP BY it returns one row per surviving group, which here is none. Applications that expect at least one row should check for an empty 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');
SELECT dept_id, COUNT(*) AS n FROM employees GROUP BY dept_id HAVING COUNT(*) > 5;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
HAVING filters whole groups
If no group passes, the result is empty
Grouped queries return one row per surviving group
Handle empty results in code
Common mistakes
Expecting a 0 row from a grouped query
Confusing HAVING with WHERE
Follow-ups
How would you report 'no department over 5' explicitly?
What if GROUP BY were removed?
Tips
Count the largest group first
309.sql-0309Mediummid
What does SELECT name FROM employees ORDER BY salary DESC LIMIT 1 return when the top salary is tied between two people?
It returns one of them, and which one is not guaranteed unless the ORDER BY includes a tie-breaker. Here the top salary is unique, but for the 95000 tie, LIMIT 1 OFFSET 1 could return Ravi or Mei. Add a unique column, such as id, to the ORDER BY to make the result deterministic.
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, salary FROM employees WHERE salary < 120000 ORDER BY salary DESC, id LIMIT 1;
name
salary
Ravi
95000
With id as the tie-breaker, Ravi (id 2) comes before Mei (id 3), every time. Without it, the engine may return either, and the choice can change with a new index or a different plan.
If the question is "who earns the most", including all tied people with WHERE salary = (SELECT MAX(salary) ...) or RANK() = 1 is usually the better answer than picking one.
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, salary FROM employees WHERE salary < 120000 ORDER BY salary DESC, id LIMIT 1;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
LIMIT with ties returns an arbitrary tied row
Add a unique tie-breaker to ORDER BY
Plans can change which tied row comes first
Use RANK or a MAX subquery to return all tied rows
Common mistakes
Relying on the current plan to pick the same tied row
Answering 'top earner' with LIMIT 1 when ties are possible
Follow-ups
What does FETCH FIRST 1 ROW WITH TIES do in PostgreSQL?
How would you return all top earners?
Tips
Always mention the tie-breaker
310.sql-0310Mediummid
What does SELECT DISTINCT dept_id FROM employees ORDER BY salary return in PostgreSQL, and why?
PostgreSQL raises an error: for SELECT DISTINCT, ORDER BY expressions must appear in the select list. Sorting by salary would be ambiguous, since each distinct dept_id comes from several rows with different salaries. SQLite accepts it and sorts by a salary from some row of each group.
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 DISTINCT dept_id FROM employees ORDER BY salary; -- error on purpose
text
Error: for SELECT DISTINCT, ORDER BY expressions must appear in select list
SQLite is lenient:
sql
SELECT DISTINCT dept_id FROM employees ORDER BY salary;
dept_id
NULL
3
2
1
SQLite returned NULL, 3, 2, 1 here, but the order depends on which salary it picks for each group, which is not a documented rule, so the same query could order differently after a data change. To sort departments by a salary statistic, say which one: SELECT dept_id FROM employees GROUP BY dept_id ORDER BY MAX(salary) DESC.
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 DISTINCT dept_id FROM employees ORDER BY salary;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
DISTINCT plus ORDER BY needs the sort column in the SELECT list (PostgreSQL)
Each distinct value can come from rows with different sort values
SQLite accepts it with an undefined choice
Use GROUP BY with an explicit aggregate for the sort
Common mistakes
Sorting DISTINCT results by a hidden column
Trusting SQLite's lenient result
Follow-ups
How would you sort departments by average salary?
What is DISTINCT ON in PostgreSQL?
Tips
Name the aggregate you want to sort by
311.sql-0311Easyfresher
What does SELECT 'A' || NULL || 'B' return, and what does CONCAT('A', NULL, 'B') return?
The || version returns NULL, because any NULL operand makes the whole concatenation NULL. CONCAT treats NULL as an empty string and returns 'AB'. SQLite 3.44+ and PostgreSQL both support CONCAT.
Full answer
sql
SELECT 'A' || NULL || 'B' AS pipes, CONCAT('A', NULL, 'B') AS concat_fn;
pipes
concat_fn
NULL
AB
This is the string version of NULL propagation: NULL + 1 is NULL, and so is a concatenation with NULL.
Oracle is the well-known exception, because it treats the empty string as NULL and lets || skip NULLs (not run here). For portable code, wrap nullable parts in COALESCE or use CONCAT where it exists.
sql
SELECT 'A' || NULL || 'B' AS pipes, CONCAT('A', NULL, 'B') AS concat_fn;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
|| with a NULL operand returns NULL
CONCAT skips NULLs
Oracle treats '' as NULL, unlike most engines
COALESCE nullable parts for portability
Common mistakes
Building labels with || on nullable columns
Assuming Oracle behaviour elsewhere
Follow-ups
What does CONCAT_WS do?
How does NULL propagate in arithmetic?
Tips
State both results
312.sql-0312Mediummid
What is the result of SELECT 1 = 1.0, '1' = 1, and 'a' = 'A' in SQLite?
1 = 1.0 is true, because integer and real values compare numerically. '1' = 1 is false for two literals, because a text value never equals a number when no column affinity applies. 'a' = 'A' is false under the default BINARY collation.
Full answer
sql
SELECT 1 = 1.0 AS int_real, '1' = 1 AS text_int, 'a' = 'A' AS case_cmp, 'a' = 'A' COLLATE NOCASE AS nocase_cmp;
int_real
text_int
case_cmp
nocase_cmp
1
0
0
1
SQLite compares across storage classes by class first, so text and integer are never equal unless an affinity conversion happens, as it would when one side is an INTEGER column.
PostgreSQL resolves '1' = 1 by casting the untyped literal to integer, so it returns true (not run here); with a text column instead of a literal, it would raise a type error. These differences are why mixed-type comparisons are best avoided.
sql
SELECT 1 = 1.0 AS int_real, '1' = 1 AS text_int, 'a' = 'A' AS case_cmp, 'a' = 'A' COLLATE NOCASE AS nocase_cmp;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Integer and real compare numerically
Text and integer literals are not equal in SQLite
Column affinity can change that result
Default collation is case-sensitive
Common mistakes
Comparing numbers stored as text with numeric literals
Expecting case-insensitive equality by default
Follow-ups
What does PostgreSQL return for '1' = 1?
How does an INTEGER column change '1' = col?
Tips
Mention the affinity exception
313.sql-0313Mediummid
What does ROUND(123.456, -1) return, and what does ROUND(123.456, 1) return?
ROUND(123.456, 1) is 123.5 on both engines. ROUND(123.456, -1) is 120 in PostgreSQL, rounding to the nearest ten, while SQLite treats a negative precision as 0 and returns 123.0. Use ROUND(x / 10.0) * 10 for a portable round-to-tens.
Full answer
sql
SELECT ROUND(123.456, 1) AS one_dp, ROUND(123.456, -1) AS neg_precision, ROUND(123.456 / 10.0) * 10 AS to_tens;
one_dp
neg_precision
to_tens
123.5
123.0
120.0
PostgreSQL:
sql
SELECT ROUND(123.456, 1) AS one_dp, ROUND(123.456, -1) AS neg_precision;
one_dp
neg_precision
123.5
120
Negative precision is handy for report bucketing ("revenue to the nearest thousand"), but it is not portable. The divide, round and multiply form works on both engines. SQLite returns a real (120.0), while PostgreSQL's numeric ROUND returns 120 without a fractional part. If the value is shown to users, format it explicitly rather than relying on how each engine prints numbers.
sql
SELECT ROUND(123.456, 1) AS one_dp, ROUND(123.456, -1) AS neg_precision, ROUND(123.456 / 10.0) * 10 AS to_tens;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
ROUND(x, n) rounds to n decimal places
PostgreSQL accepts negative n to round to tens, hundreds
SQLite treats negative n as 0
ROUND(x / 10.0) * 10 is portable
Common mistakes
Relying on negative precision in SQLite
Rounding money stored as floats
Follow-ups
How would you round to the nearest 5?
What does TRUNC do differently?
Tips
Give the portable form
314.sql-0314Easyfresher
What does SELECT COUNT(*) FROM orders o JOIN order_items i ON i.order_id = o.id return compared with SELECT COUNT(*) FROM orders?
The join count is the number of order lines that match an order, 8 here, not the number of orders, 6. A one-to-many join repeats each order once per line. Use COUNT(DISTINCT o.id) to count orders after such a join, or count before joining.
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 (SELECT COUNT(*) FROM orders) AS orders, COUNT(*) AS joined_rows, COUNT(DISTINCT o.id) AS distinct_orders
FROM orders o JOIN order_items i ON i.order_id = o.id;
orders
joined_rows
distinct_orders
6
8
6
Orders 101 and 104 have two lines each, so they appear twice after the join. Every order has at least one line, so the distinct count matches the order count.
The same fan-out inflates SUMs of order-level columns, such as a shipping fee stored on the order. Aggregate lines per order first, then join, when mixing order-level and line-level values.
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 (SELECT COUNT(*) FROM orders) AS orders, COUNT(*) AS joined_rows, COUNT(DISTINCT o.id) AS distinct_orders
FROM orders o JOIN order_items i ON i.order_id = o.id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
One-to-many joins repeat the parent row
COUNT(*) after a join counts joined rows
COUNT(DISTINCT parent.id) counts parents
Aggregate before joining for parent-level totals
Common mistakes
Counting orders after joining to lines
Summing order-level fees after a line join
Follow-ups
How would you sum shipping fees correctly?
What if some orders had no lines?
Tips
Name the join cardinality
315.sql-0315Easyfresher
What is MIN('2026-12-01', '2026-02-15') in SQLite, and is it the earlier date?
It is '2026-02-15', which is the earlier date, because ISO-8601 text sorts in date order. The scalar min() with two arguments compares the strings. With non-ISO formats such as '15/02/2026' the string order would no longer match date order.
Full answer
sql
SELECT min('2026-12-01', '2026-02-15') AS iso_min, min('01/12/2026', '15/02/2026') AS dmy_min;
iso_min
dmy_min
2026-02-15
01/12/2026
For ISO dates, string order equals date order, so min and max work. The day-first version returns '01/12/2026' (1 December), which is the later date, because '0' sorts before '1'.
SQLite's two-argument min() and max() are scalar functions; PostgreSQL uses LEAST and GREATEST for the same purpose. This is one more reason to store dates only in ISO form: every comparison, sort and min/max then behaves like a date operation without conversion.
sql
SELECT min('2026-12-01', '2026-02-15') AS iso_min, min('01/12/2026', '15/02/2026') AS dmy_min;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
ISO date text sorts in date order
Scalar min(a, b) compares values in SQLite
Non-ISO date text breaks the ordering
PostgreSQL uses LEAST and GREATEST
Common mistakes
Comparing day-first date strings
Using MIN(a, b) syntax in PostgreSQL
Follow-ups
What do LEAST and GREATEST do with NULL?
How would you convert day-first dates?
Tips
Point out the format dependency
316.sql-0316Mediummid
Design the core tables for an online shop: customers, products, orders, order lines and payments.
Use customers, products, orders (customer, status, timestamps), order_lines (order, product, quantity, unit price paid) and payments (order, amount, method, status, provider reference). Store the price paid on each line, keep money in integer minor units or NUMERIC, and allow several payments per order for retries, partial payments and refunds.
unit_price_cents on the line is a snapshot, so price changes do not rewrite history.
status uses a CHECK or a lookup table, and transitions (pending to paid to shipped) are enforced in one place.
Payments are a separate table, because one order can have a failed attempt, a success and a later refund.
Indexes: orders(customer_id, placed_at) for a customer's order history, order_lines(product_id) for product reports.
Addresses are copied onto the order at checkout for the same snapshot reason.
Key points
Store the price paid on each order line
Use integer cents or NUMERIC for money
Allow several payments per order
Copy addresses onto orders at checkout
Index for the main access paths
Common mistakes
Computing order totals from current product prices
One payment column on the order that cannot represent refunds
Follow-ups
How would you add discounts and taxes?
How would you support multiple currencies?
Tips
Explain each snapshot decision
317.sql-0317Hardsenior
Design a schema for hotel room bookings that prevents double booking.
Store bookings with room_id, check_in and check_out as a half-open date range. Prevent overlaps in PostgreSQL with an exclusion constraint on (room_id, daterange) using &&, which handles concurrency inside the database. Without that feature, lock the room row (or use one row per room-night with a unique key) inside the booking transaction.
ALTER TABLE bookings ADD CONSTRAINT no_overlap
EXCLUDE USING gist (room_id WITH =, daterange(check_in, check_out) WITH &&)
WHERE (status <> 'cancelled');
One row per room per night: room_nights(room_id, night, booking_id, PRIMARY KEY (room_id, night)). Inserting all nights in one transaction fails on any clash. This works on any engine, including SQLite.
Application checks ("is anything overlapping?" then insert) race under concurrency unless the room row is locked first with SELECT ... FOR UPDATE.
Half-open ranges let a guest check out on the same day another checks in. Availability searches then query for rooms with no overlapping booking, using the overlap test check_in < :end AND :start < check_out.
Key points
Model stays as half-open date ranges
PostgreSQL exclusion constraints prevent overlaps
One row per room-night with a unique key works anywhere
Check-then-insert races without locking
Common mistakes
Validating availability only in application code
Using closed ranges that block same-day turnover
Follow-ups
How would you search available rooms for given dates?
How would you hold a room for 10 minutes during checkout?
Tips
Name the concurrency hazard
318.sql-0318Mediummid
How would you store chat messages for one-to-one and group conversations?
Use conversations, conversation_members (conversation, user, joined_at, last_read_message_id) and messages (id, conversation_id, sender_id, body, created_at). Treat one-to-one chats as conversations with two members. Index messages on (conversation_id, created_at, id) for paging and track read state per member rather than per message.
One model for direct and group chats keeps queries uniform.
last_read_message_id per member gives unread counts (messages with id > last_read) without a row per message per reader.
Keyset pagination on (conversation_id, created_at, id) loads history efficiently.
Soft delete (deleted_at) shows "message deleted" without breaking replies.
For a direct chat, a unique key on the ordered pair of users (smaller id, larger id) stops duplicate conversations between the same two people. At large scale, messages are often partitioned by conversation or time, but the logical model stays the same.
Key points
Model direct chats as two-member conversations
Track read state per member, not per message
Index (conversation_id, created_at, id) for paging
Prevent duplicate direct conversations with a unique pair key
Common mistakes
A read-receipt row for every message and reader
Separate tables for direct and group messages
Follow-ups
How would you compute unread counts per conversation?
How would you search message text?
Tips
Explain the unread-count design
319.sql-0319Hardsenior
What are the main ways to design a database for a multi-tenant SaaS product, and their trade-offs?
Options are a shared schema with a tenant_id column on every table, a separate schema per tenant, or a separate database per tenant. Shared tables are cheapest and simplest to operate but need strict tenant filtering, ideally enforced with row-level security. Separate schemas or databases isolate data and noisy neighbours better but multiply migrations and connections.
Full answer
Shared schema, tenant_id everywhere:
One set of tables and migrations; efficient for thousands of small tenants.
Every query must filter by tenant. PostgreSQL row-level security (CREATE POLICY ... USING (tenant_id = current_setting('app.tenant')::int)) makes forgetting impossible.
Composite keys and indexes lead with tenant_id, such as (tenant_id, created_at).
Schema per tenant:
Stronger separation and easy per-tenant export, but migrations must run N times and catalog size grows.
Database per tenant:
Strongest isolation, per-tenant backups and data residency, but connection pooling, upgrades and cross-tenant reporting get hard.
Many products mix them: shared tables for most tenants, dedicated databases for a few large or regulated ones. Whatever the choice, test that one tenant cannot read another's data.
Key points
Shared tables with tenant_id are cheapest
Row-level security enforces tenant filters
Schema or database per tenant improves isolation
Isolation costs more operational work
Hybrid models are common
Common mistakes
Relying on every developer to remember WHERE tenant_id = ?
Indexes that do not lead with tenant_id in shared tables
Follow-ups
How does row-level security work in PostgreSQL?
How would you move a large tenant to its own database?
Tips
Compare the three options on cost and isolation
320.sql-0320Mediummid
How would you implement soft delete, and what problems does it introduce?
Add a deleted_at timestamp and treat rows with a value as deleted. Every query must then exclude deleted rows, unique constraints must ignore them (a partial unique index WHERE deleted_at IS NULL), and foreign keys no longer stop references to deleted rows. A view of active rows and a retention job keep it manageable.
Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX users_email_active ON users(email) WHERE deleted_at IS NULL;
INSERT INTO users VALUES (1, 'a@x.com', '2026-01-01');
INSERT INTO users VALUES (2, 'a@x.com', NULL);
CREATE VIEW active_users AS SELECT id, email FROM users WHERE deleted_at IS NULL;
SELECT * FROM active_users;
The partial unique index lets a deleted account and a new account share an email, while two active accounts cannot. A plain UNIQUE on email would block re-registration after deletion.
Problems to plan for:
Every query needs WHERE deleted_at IS NULL; an active_users view helps.
Foreign keys still point at soft-deleted rows; cascading deletes do not happen.
Tables grow forever unless a job purges old deleted rows.
Privacy laws may require real deletion of personal data, which soft delete does not provide.
Alternatives include moving deleted rows to an archive table, or event logs that record the deletion while the row is removed.
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX users_email_active ON users(email) WHERE deleted_at IS NULL;
INSERT INTO users VALUES (1, 'a@x.com', '2026-01-01');
INSERT INTO users VALUES (2, 'a@x.com', NULL);
CREATE VIEW active_users AS SELECT id, email FROM users WHERE deleted_at IS NULL;
SELECT * FROM active_users;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
deleted_at marks rows as deleted
Partial unique indexes ignore deleted rows
Views simplify filtering active rows
Plan retention and real deletion for privacy
Common mistakes
A plain UNIQUE constraint that blocks re-registration