← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 7 of 26

Want the full pack? Interview packs · Mock interview · Mentora

Page 7 of 26

Questions 121–140 of 501 · 0 of 20 on this page marked learned

121.sql-0121Hardsenior

Why does LAST_VALUE(salary) OVER (ORDER BY salary) return the current row's salary instead of the highest salary?

With ORDER BY and no frame clause, the frame ends at the current row (and its peers). LAST_VALUE takes the last row of that frame, which is the current row. Extend the frame with ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or use FIRST_VALUE with the opposite sort order.

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,
       FIRST_VALUE(salary) OVER (ORDER BY salary) AS first_val,
       LAST_VALUE(salary)  OVER (ORDER BY salary) AS last_val
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary, name;
namesalaryfirst_vallast_val
Omar480004800048000
Diego550004800055000
Sara620004800062000
Tom700004800070000
Mei950004800095000
Ravi950004800095000
Asha12000048000120000

FIRST_VALUE looks right: the frame always starts at the first row, the lowest salary. LAST_VALUE just echoes the current salary, because the default frame stops at the current row. For Ravi and Mei it shows 95000, which happens to be both their own salary and the last peer in their frame.

Extend the frame to the whole partition:

sql
SELECT name, salary,
       LAST_VALUE(salary) OVER (ORDER BY salary
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS highest
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary, name;
namesalaryhighest
Omar48000120000
Diego55000120000
Sara62000120000
Tom70000120000
Mei95000120000
Ravi95000120000
Asha120000120000

An equivalent and often clearer version avoids LAST_VALUE entirely: FIRST_VALUE(salary) OVER (ORDER BY salary DESC) or simply MAX(salary) OVER ().

The same frame issue affects NTH_VALUE. Whenever a window function's answer depends on rows after the current one, check the frame.

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,
       FIRST_VALUE(salary) OVER (ORDER BY salary) AS first_val,
       LAST_VALUE(salary)  OVER (ORDER BY salary) AS last_val
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary, name;

SELECT name, salary,
       LAST_VALUE(salary) OVER (ORDER BY salary
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS highest
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary, name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Default frame with ORDER BY ends at the current row
  • LAST_VALUE returns the last row of the frame, not the partition
  • Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  • FIRST_VALUE with reversed order or MAX() OVER () are simpler alternatives

Common mistakes

  • Trusting LAST_VALUE without a frame clause
  • Thinking the bug is in the data because values 'look random'

Follow-ups

  • How would you show each employee's salary next to the lowest and highest in their department?
  • What does NTH_VALUE(salary, 2) return with the default frame?

Tips

  • Name the default frame when explaining the result
122.sql-0122Mediummid

How do you split students into four equal-sized groups by marks? Explain NTILE.

NTILE(4) OVER (ORDER BY marks) deals rows into 4 buckets as evenly as possible, in order. If the row count is not divisible by 4, the first buckets get one extra row. NTILE splits by row count, not by value, so tied marks can land in different buckets.

Full answer
sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
SELECT student_id, course_id, marks,
       NTILE(4) OVER (ORDER BY marks DESC, student_id, course_id) AS quartile
FROM enrolments
WHERE marks IS NOT NULL
ORDER BY marks DESC, student_id, course_id;
student_idcourse_idmarksquartile
120921
110881
330802
210752
320713
310643
520554

Seven marks into four buckets: 7 = 2 + 2 + 2 + 1, so buckets 1 to 3 get two rows and bucket 4 gets one. NTILE always assigns by position in the sorted order.

That has a consequence with ties. If two students had the same mark at a bucket boundary, they could be placed in different buckets, which looks unfair in a report. For value-based groups, compute boundaries from the values instead, for example with PERCENT_RANK or fixed cut-offs in a CASE.

The NULL mark is excluded by the WHERE clause. Left in, it would sort first in SQLite (NULLs sort low) and take a place in bucket 1.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT student_id, course_id, marks,
       NTILE(4) OVER (ORDER BY marks DESC, student_id, course_id) AS quartile
FROM enrolments
WHERE marks IS NOT NULL
ORDER BY marks DESC, student_id, course_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • NTILE(n) deals rows into n buckets by position
  • Extra rows go to the first buckets
  • Ties can be split across buckets
  • Exclude or place NULLs deliberately

Common mistakes

  • Calling NTILE buckets 'percentiles' of value
  • Leaving NULLs in and having them fill the first bucket

Follow-ups

  • How would you label the top 25 percent of students?
  • How is PERCENT_RANK different from NTILE?

Tips

  • Do the 7 = 2 + 2 + 2 + 1 arithmetic out loud
123.sql-0123Mediummid

What do PERCENT_RANK and CUME_DIST return, and how do they differ?

PERCENT_RANK is (rank - 1) / (rows - 1): the share of other rows that rank strictly below, from 0 for the first row to 1 for the last. CUME_DIST is (rows with a value at or before the current one) / (total rows): the share of rows at or below the current value, from above 0 up to 1. Ties share the same value in both.

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,
       ROUND(PERCENT_RANK() OVER (ORDER BY salary), 3) AS pct_rank,
       ROUND(CUME_DIST()    OVER (ORDER BY salary), 3) AS cume_dist
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary, name;
namesalarypct_rankcume_dist
Omar480000.00.143
Diego550000.1670.286
Sara620000.3330.429
Tom700000.50.571
Mei950000.6670.857
Ravi950000.6670.857
Asha1200001.01.0

With seven salaries in ascending order:

  • Omar is lowest. PERCENT_RANK is 0, because no one ranks below him. CUME_DIST is 1/7, because one of seven rows is at or below his salary.
  • Ravi and Mei tie at 95000. Their RANK is 5, so PERCENT_RANK is (5 - 1) / (7 - 1) = 0.667. Six of seven salaries are at or below 95000, so CUME_DIST is 6/7 = 0.857 for both.
  • Asha is highest: PERCENT_RANK 1 and CUME_DIST 1.

Use CUME_DIST for statements like "this salary is at or above 85.7 percent of salaries". Use PERCENT_RANK when you want the first row at exactly 0, for scales from 0 to 100.

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,
       ROUND(PERCENT_RANK() OVER (ORDER BY salary), 3) AS pct_rank,
       ROUND(CUME_DIST()    OVER (ORDER BY salary), 3) AS cume_dist
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary, name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • PERCENT_RANK = (rank - 1) / (n - 1)
  • CUME_DIST = rows at or before current / n
  • Ties share the same value
  • PERCENT_RANK starts at 0; CUME_DIST never does

Common mistakes

  • Calling PERCENT_RANK a percentile of the value itself
  • Forgetting NULL handling; NULLs are ranked too unless filtered

Follow-ups

  • How would you find the median with these functions?
  • How would you report each student's percentile within their course?

Tips

  • Work one tied row through both formulas
124.sql-0124Hardsenior

Can you use COUNT(DISTINCT ...) as a window function, for example a running count of distinct customers?

PostgreSQL rejects DISTINCT in window aggregates, and SQLite rejects it too. A common workaround is to mark each customer's first appearance with ROW_NUMBER() OVER (PARTITION BY customer ORDER BY date) = 1 and then take a running SUM of those flags. For a non-running distinct count per partition, DENSE_RANK forwards plus backwards minus 1 is a known trick.

Full answer

"How many distinct customers have we had up to each date?" sounds like a running COUNT(DISTINCT). Both engines refuse:

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 order_date, COUNT(DISTINCT customer_id) OVER (ORDER BY order_date) FROM orders;  -- error on purpose
text
Error: DISTINCT is not supported for window functions
sql
SELECT order_date, COUNT(DISTINCT customer_id) OVER (ORDER BY order_date) FROM orders;  -- error on purpose
text
Error: DISTINCT is not implemented for window functions

The workaround marks the first order of each customer, then runs a normal SUM over those marks:

sql
WITH firsts AS (
  SELECT id, order_date, customer_id,
         CASE WHEN ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) = 1
              THEN 1 ELSE 0 END AS is_first
  FROM orders
  WHERE customer_id IS NOT NULL
)
SELECT order_date, customer_id,
       SUM(is_first) OVER (ORDER BY order_date, id) AS distinct_customers_so_far
FROM firsts
ORDER BY order_date, id;
order_datecustomer_iddistinct_customers_so_far
2026-01-0511
2026-02-1111
2026-02-1422
2026-03-0133
2026-03-0923

A customer contributes 1 only on their first order, so the running sum counts each customer once. Ana's second order on 11 February adds 0. The guest order with no customer is excluded in WHERE.

For "distinct values in the whole partition" (not running), DENSE_RANK() OVER (ORDER BY x) + DENSE_RANK() OVER (ORDER BY x DESC) - 1 gives the distinct count on every row. It works because the two ranks of any value add up to the number of distinct values plus one.

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);

-- error on purpose
SELECT order_date, COUNT(DISTINCT customer_id) OVER (ORDER BY order_date) FROM orders;

WITH firsts AS (
  SELECT id, order_date, customer_id,
         CASE WHEN ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) = 1
              THEN 1 ELSE 0 END AS is_first
  FROM orders
  WHERE customer_id IS NOT NULL
)
SELECT order_date, customer_id,
       SUM(is_first) OVER (ORDER BY order_date, id) AS distinct_customers_so_far
FROM firsts
ORDER BY order_date, id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • COUNT(DISTINCT) is not allowed as a window function in SQLite or PostgreSQL
  • Flag first appearances with ROW_NUMBER, then SUM the flags
  • The DENSE_RANK up plus down minus 1 trick gives a partition distinct count
  • Exclude NULL keys explicitly

Common mistakes

  • Using COUNT(DISTINCT) OVER on an engine that does not support it and rewriting with a slow self join
  • Counting NULL customers as one more distinct customer

Follow-ups

  • How would you compute distinct customers per month?
  • Why does the DENSE_RANK trick work?

Tips

  • Explain why each customer contributes exactly once
125.sql-0125Mediummid

Rank departments by their total salary bill. Can a window function be applied to the result of GROUP BY?

Yes. Window functions run after GROUP BY, so they can take aggregates as input: RANK() OVER (ORDER BY SUM(salary) DESC). The grouped rows become the input rows of the window.

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 d.name,
       SUM(e.salary)                         AS total,
       RANK() OVER (ORDER BY SUM(e.salary) DESC) AS rnk,
       ROUND(100.0 * SUM(e.salary) / SUM(SUM(e.salary)) OVER (), 1) AS share_pct
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
ORDER BY rnk;
nametotalrnkshare_pct
Engineering310000156.9
Sales132000224.2
Support103000318.9

The query groups employees into departments, computes SUM(salary) per group, and then ranks those group rows. SUM(SUM(salary)) OVER () in the same query adds up the grouped sums to get a grand total for the share column.

Nesting reads oddly at first, so remember the order: the inner SUM belongs to GROUP BY and produces one value per department; the outer function belongs to the window and works across department rows.

A CTE makes the two steps explicit if a team finds the nested form hard to read:

sql
WITH totals AS (
  SELECT d.name, SUM(e.salary) AS total
  FROM employees e JOIN departments d ON d.id = e.dept_id
  GROUP BY d.id, d.name
)
SELECT name, total, RANK() OVER (ORDER BY total DESC) AS rnk
FROM totals
ORDER BY rnk;
nametotalrnk
Engineering3100001
Sales1320002
Support1030003
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,
       SUM(e.salary)                         AS total,
       RANK() OVER (ORDER BY SUM(e.salary) DESC) AS rnk,
       ROUND(100.0 * SUM(e.salary) / SUM(SUM(e.salary)) OVER (), 1) AS share_pct
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
ORDER BY rnk;

WITH totals AS (
  SELECT d.name, SUM(e.salary) AS total
  FROM employees e JOIN departments d ON d.id = e.dept_id
  GROUP BY d.id, d.name
)
SELECT name, total, RANK() OVER (ORDER BY total DESC) AS rnk
FROM totals
ORDER BY rnk;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Window functions run after GROUP BY
  • They can take aggregates as arguments
  • SUM(SUM(x)) OVER () gives a grand total of group sums
  • A CTE separates the steps for readability

Common mistakes

  • Thinking a window function and GROUP BY cannot be in the same query
  • Ranking before grouping and getting one rank per employee

Follow-ups

  • How would you show only the top two departments?
  • How would you add each department's share of the total?

Tips

  • Describe the evaluation order to justify the nested aggregate
126.sql-0126Mediummid

What is the WINDOW clause, and when does it help?

The WINDOW clause names a window definition once, for example WINDOW w AS (PARTITION BY dept_id ORDER BY salary DESC), so several functions can use OVER w. It removes repetition and guarantees every function uses the same partition and order. SQLite (3.28+) and PostgreSQL support it.

Full answer

When a query computes several window functions over the same window, repeating the definition is noisy and easy to get subtly wrong. The WINDOW clause names 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 name, dept_id, salary,
       ROW_NUMBER() OVER w AS rn,
       RANK()       OVER w AS rnk,
       SUM(salary)  OVER w AS running_dept_total
FROM employees
WHERE dept_id IS NOT NULL
WINDOW w AS (PARTITION BY dept_id ORDER BY salary DESC, name)
ORDER BY dept_id, rn;
namedept_idsalaryrnrnkrunning_dept_total
Asha112000011120000
Mei19500022215000
Ravi19500033310000
Tom2700001170000
Sara26200022132000
Diego3550001155000
Omar34800022103000

All three functions use the same partition and order, defined once. A named window can also be extended: OVER (w ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) adds a frame to the base definition, as long as w itself has no frame.

The clause sits after HAVING and before ORDER BY. It changes nothing about the result; it is purely about readability and consistency. In code review, a named window makes it obvious that the rank and the running total are computed over the same ordering.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, dept_id, salary,
       ROW_NUMBER() OVER w AS rn,
       RANK()       OVER w AS rnk,
       SUM(salary)  OVER w AS running_dept_total
FROM employees
WHERE dept_id IS NOT NULL
WINDOW w AS (PARTITION BY dept_id ORDER BY salary DESC, name)
ORDER BY dept_id, rn;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • WINDOW w AS (...) names a window definition
  • Several functions can use OVER w
  • A named window can be extended with a frame
  • Placed after HAVING, before ORDER BY

Common mistakes

  • Copying slightly different window definitions into each function
  • Adding a frame to a named window that already has one

Follow-ups

  • Can a named window be based on another named window?
  • Does the WINDOW clause affect performance?

Tips

  • Use it when three or more functions share a window
127.sql-0127Easyfresher

How do UNION and UNION ALL behave differently, and which should be the default choice?

UNION combines two results and removes duplicate rows; UNION ALL keeps every row. Removing duplicates needs a sort or hash step, so UNION ALL is cheaper. Use UNION ALL unless duplicates are actually possible and unwanted.

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);

Cities of students in year 1, combined with cities of students in year 2:

sql
SELECT city FROM students WHERE year = 1
UNION ALL
SELECT city FROM students WHERE year = 2
ORDER BY city;
city
Leeds
Leeds
Pune
Pune
sql
SELECT city FROM students WHERE year = 1
UNION
SELECT city FROM students WHERE year = 2
ORDER BY city;
city
Leeds
Pune

UNION ALL returns all four rows, including Pune twice (Asha and Chen both live there). UNION keeps each distinct row once, so Pune and Leeds appear a single time.

Duplicate removal compares whole rows, not single columns, and it treats two NULLs as equal, unlike =. It also costs extra work on large inputs. A common habit is to write UNION ALL by default and switch to UNION only when the question says "distinct". When the two branches cannot overlap, for example rows from separate years tagged with a constant column, UNION does pointless work.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT city FROM students WHERE year = 1
UNION ALL
SELECT city FROM students WHERE year = 2
ORDER BY city;

SELECT city FROM students WHERE year = 1
UNION
SELECT city FROM students WHERE year = 2
ORDER BY city;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • UNION removes duplicate rows; UNION ALL keeps them
  • Duplicate detection uses whole rows and treats NULLs as equal
  • UNION ALL avoids a sort or hash step
  • Prefer UNION ALL when the branches cannot overlap

Common mistakes

  • Using UNION by habit and paying for deduplication on large data
  • Expecting UNION to deduplicate on one column only

Follow-ups

  • What rules must the two SELECT lists follow?
  • How would you tag which branch each row came from?

Tips

  • State the cost difference, not just the output difference
128.sql-0128Easyfresher

What rules must the SELECT lists on each side of a UNION follow, and where do the column names come from?

Both sides need the same number of columns, and matching positions need compatible types. Columns are matched by position, not by name. The result takes its column names from the first SELECT, and ORDER BY applies to the whole combined result.

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 name AS who, 'student' AS kind FROM students WHERE id <= 2
UNION ALL
SELECT title AS title, 'course' FROM courses WHERE id = 10
ORDER BY kind, who;
whokind
Databasescourse
Ashastudent
Benstudent

The output column is called who because that alias is on the first branch. The second branch's alias title is ignored. Columns line up by position, so swapping column order in one branch silently mixes data rather than raising an error.

A different column count is an error on both engines:

sql
SELECT name, city FROM students
UNION
SELECT title FROM courses;
-- error on purpose
text
Error: SELECTs to the left and right of UNION do not have the same number of result columns
sql
SELECT name, city FROM students
UNION
SELECT title FROM courses;
-- error on purpose
text
Error: each UNION query must have the same number of columns

Types are handled differently. SQLite has dynamic typing and accepts text and integers in one output column:

sql
SELECT name FROM students WHERE id = 1
UNION ALL
SELECT credits FROM courses WHERE id = 10
ORDER BY 1;
name
4
Asha

PostgreSQL requires compatible types per column and rejects the same query:

sql
SELECT name FROM students WHERE id = 1
UNION ALL
SELECT credits FROM courses WHERE id = 10;
-- error on purpose
text
Error: UNION types text and integer cannot be matched

One ORDER BY at the end sorts the combined result. To sort or limit a single branch, wrap it in a subquery.

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 name AS who, 'student' AS kind FROM students WHERE id <= 2
UNION ALL
SELECT title AS title, 'course' FROM courses WHERE id = 10
ORDER BY kind, who;

-- error on purpose
SELECT name, city FROM students
UNION
SELECT title FROM courses;

SELECT name FROM students WHERE id = 1
UNION ALL
SELECT credits FROM courses WHERE id = 10
ORDER BY 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

  • Same number of columns on every branch
  • Columns match by position, not name
  • Names come from the first SELECT
  • One ORDER BY at the end sorts the whole result

Common mistakes

  • Listing columns in a different order in one branch
  • Putting ORDER BY inside a branch without a subquery

Follow-ups

  • How would you limit each branch separately?
  • Why does PostgreSQL reject text UNION integer?

Tips

  • Mention that the first branch names the columns
129.sql-0129Easyfresher

Write a query that finds students enrolled in both Databases (10) and Algorithms (20) using a set operation.

INTERSECT returns rows present in both results: SELECT student_id FROM enrolments WHERE course_id = 10 INTERSECT SELECT student_id ... WHERE course_id = 20. It removes duplicates, like UNION. A self join or GROUP BY with HAVING COUNT(DISTINCT course_id) = 2 gives the same answer.

Full answer
sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
SELECT student_id FROM enrolments WHERE course_id = 10
INTERSECT
SELECT student_id FROM enrolments WHERE course_id = 20
ORDER BY student_id;
student_id
1
3

Asha (1) and Chen (3) took both courses. Ben took only Databases and Eli only Algorithms.

The GROUP BY version scales better to "all of these N courses", because only the list and the count change:

sql
SELECT student_id
FROM enrolments
WHERE course_id IN (10, 20)
GROUP BY student_id
HAVING COUNT(DISTINCT course_id) = 2
ORDER BY student_id;
student_id
1
3

INTERSECT is concise for two or three sets. For "students who took every course in a list", the HAVING form is easier to extend. Both forms compare whole rows, so select only the key columns you want to match on.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT student_id FROM enrolments WHERE course_id = 10
INTERSECT
SELECT student_id FROM enrolments WHERE course_id = 20
ORDER BY student_id;

SELECT student_id
FROM enrolments
WHERE course_id IN (10, 20)
GROUP BY student_id
HAVING COUNT(DISTINCT course_id) = 2
ORDER BY student_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • INTERSECT keeps rows found in both results
  • It removes duplicates by default
  • GROUP BY with HAVING COUNT(DISTINCT ...) generalizes to N values
  • Select only the columns that define a match

Common mistakes

  • Writing WHERE course_id = 10 AND course_id = 20, which matches nothing
  • Intersecting full rows that include columns that differ, such as marks

Follow-ups

  • How would you find students in either course but not both?
  • How would you return student names instead of ids?

Tips

  • Show both forms and say when each fits
130.sql-0130Easyfresher

Which customers have never placed an order? Solve it with EXCEPT.

SELECT id FROM customers EXCEPT SELECT customer_id FROM orders returns customer ids missing from orders. EXCEPT is NULL-safe because set operations treat NULLs as equal, which avoids the NOT IN trap. Oracle calls the operator MINUS.

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 id FROM customers
EXCEPT
SELECT customer_id FROM orders
ORDER BY id;
id
4

Dev (4) has no orders. Note that orders contains a guest order with a NULL customer_id. That NULL would break NOT IN:

sql
SELECT id FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders)
ORDER BY id;
id

(0 rows)

NOT IN returns nothing, because 4 NOT IN (1, 2, 3, NULL) evaluates to unknown. EXCEPT compares rows with "is not distinct" semantics, so the NULL does no harm.

To show names, join back or use NOT EXISTS, which most engines also plan as an anti join:

sql
SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
ORDER BY c.name;
name
Dev
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

SELECT id FROM customers
EXCEPT
SELECT customer_id FROM orders
ORDER BY id;

SELECT id FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders)
ORDER BY id;

SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
ORDER BY c.name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • EXCEPT returns rows in the first result but not the second
  • Set operations treat NULLs as equal
  • NOT IN with a NULL in the list returns no rows
  • Oracle uses MINUS for EXCEPT

Common mistakes

  • Using NOT IN against a nullable column
  • Putting the larger set second and reversing the meaning

Follow-ups

  • How would you return the customer names?
  • How do EXCEPT and NOT EXISTS differ in handling duplicates?

Tips

  • Point out the NULL guest order before choosing an approach
131.sql-0131Hardsenior

Does SQLite support INTERSECT ALL and EXCEPT ALL? What do they return where they exist?

PostgreSQL supports both: they keep duplicates according to counts. EXCEPT ALL removes one matching row from the left side for each row on the right, so a value appearing 3 times minus 1 time leaves 2. SQLite does not support the ALL forms and raises a syntax error.

Full answer

A bag of product names from all order lines, minus a bag from cancelled orders:

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);

PostgreSQL:

sql
SELECT product FROM order_items
EXCEPT ALL
SELECT oi.product FROM order_items oi JOIN orders o ON o.id = oi.order_id WHERE o.status = 'cancelled'
ORDER BY product;
product
Bag
Bag
Lamp
Notebook
Notebook
Pen
Pen

Pen appears in three order lines and in one cancelled line, so EXCEPT ALL leaves two Pens. Plain EXCEPT would remove Pen completely, because it works on distinct rows.

SQLite rejects the ALL form:

sql
SELECT product FROM order_items
EXCEPT ALL
SELECT product FROM order_items WHERE order_id = 103;
-- error on purpose
text
Error: near "ALL": syntax error

To emulate EXCEPT ALL on SQLite, count each value on both sides and subtract:

sql
WITH a AS (SELECT product, COUNT(*) AS n FROM order_items GROUP BY product),
     b AS (SELECT oi.product, COUNT(*) AS n FROM order_items oi
           JOIN orders o ON o.id = oi.order_id WHERE o.status = 'cancelled' GROUP BY oi.product)
SELECT a.product, a.n - COALESCE(b.n, 0) AS remaining
FROM a LEFT JOIN b ON b.product = a.product
WHERE a.n - COALESCE(b.n, 0) > 0
ORDER BY a.product;
productremaining
Bag2
Lamp1
Notebook2
Pen2
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);

-- error on purpose
SELECT product FROM order_items
EXCEPT ALL
SELECT product FROM order_items WHERE order_id = 103;

WITH a AS (SELECT product, COUNT(*) AS n FROM order_items GROUP BY product),
     b AS (SELECT oi.product, COUNT(*) AS n FROM order_items oi
           JOIN orders o ON o.id = oi.order_id WHERE o.status = 'cancelled' GROUP BY oi.product)
SELECT a.product, a.n - COALESCE(b.n, 0) AS remaining
FROM a LEFT JOIN b ON b.product = a.product
WHERE a.n - COALESCE(b.n, 0) > 0
ORDER BY a.product;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • EXCEPT ALL and INTERSECT ALL respect duplicate counts
  • EXCEPT ALL subtracts counts; INTERSECT ALL takes the minimum count
  • PostgreSQL supports both; SQLite does not
  • Counting and subtracting emulates them

Common mistakes

  • Assuming EXCEPT removes only one copy of a duplicate
  • Writing EXCEPT ALL in SQLite and getting a syntax error

Follow-ups

  • How would you emulate INTERSECT ALL?
  • When would bag semantics matter in a reconciliation report?

Tips

  • Use a small count example to show the arithmetic
132.sql-0132Mediummid

In what order are UNION, INTERSECT and EXCEPT evaluated when combined in one query?

In the SQL standard and PostgreSQL, INTERSECT binds tighter than UNION and EXCEPT, which are evaluated left to right. SQLite gives all three equal precedence and evaluates strictly left to right. The same query can therefore return different results, so use parentheses or CTEs to make intent explicit.

Full answer
sql
CREATE TABLE a (x INTEGER); CREATE TABLE b (x INTEGER); CREATE TABLE c (x INTEGER);
INSERT INTO a VALUES (1),(2); INSERT INTO b VALUES (2),(3); INSERT INTO c VALUES (3);

The query is {1,2} UNION {2,3} INTERSECT {3}.

sql
SELECT x FROM a UNION SELECT x FROM b INTERSECT SELECT x FROM c ORDER BY x;
x
3
sql
SELECT x FROM a UNION SELECT x FROM b INTERSECT SELECT x FROM c ORDER BY x;
x
1
2
3

SQLite reads it left to right: ({1,2} UNION {2,3}) INTERSECT {3} = {3}. PostgreSQL follows the standard and evaluates the INTERSECT first: {1,2} UNION ({2,3} INTERSECT {3}) = {1,2,3}.

SQLite does not allow parentheses around compound SELECT branches, so the portable way to fix the order is a CTE or subquery for the part that should run first:

sql
WITH bc AS (SELECT x FROM b INTERSECT SELECT x FROM c)
SELECT x FROM a UNION SELECT x FROM bc ORDER BY x;
x
1
2
3
sql
CREATE TABLE a (x INTEGER); CREATE TABLE b (x INTEGER); CREATE TABLE c (x INTEGER);
INSERT INTO a VALUES (1),(2); INSERT INTO b VALUES (2),(3); INSERT INTO c VALUES (3);

SELECT x FROM a UNION SELECT x FROM b INTERSECT SELECT x FROM c ORDER BY x;

WITH bc AS (SELECT x FROM b INTERSECT SELECT x FROM c)
SELECT x FROM a UNION SELECT x FROM bc ORDER BY x;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Standard: INTERSECT binds tighter than UNION and EXCEPT
  • SQLite: all set operators have equal precedence, left to right
  • The same text can give different results on different engines
  • Use CTEs or subqueries to fix the order

Common mistakes

  • Mixing set operators without making the order explicit
  • Assuming parentheses around branches work in SQLite

Follow-ups

  • How would you rewrite the query to force left-to-right order in PostgreSQL?
  • Are UNION and EXCEPT associative?

Tips

  • Give a concrete three-set example
133.sql-0133Easyfresher

Write a query that labels each employee's salary as 'high' (100000 or more), 'mid' (60000 to 99999) or 'low', and says 'unknown' when the salary is missing.

Use a searched CASE: CASE WHEN salary IS NULL THEN 'unknown' WHEN salary >= 100000 THEN 'high' WHEN salary >= 60000 THEN 'mid' ELSE 'low' END. Branches are tested in order and the first true one wins, so ordered thresholds need only a lower bound.

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,
       CASE
         WHEN salary IS NULL    THEN 'unknown'
         WHEN salary >= 100000  THEN 'high'
         WHEN salary >= 60000   THEN 'mid'
         ELSE 'low'
       END AS band
FROM employees
ORDER BY id;
namesalaryband
Asha120000high
Ravi95000mid
Mei95000mid
Tom70000mid
Sara62000mid
Diego55000low
LenaNULLunknown
Omar48000low

The first true WHEN wins, so the mid branch does not need AND salary < 100000: any salary that high already matched high.

The NULL check comes first on purpose. If it were left out, Lena's NULL salary would fail every comparison and land in ELSE as low, which is wrong. Without an ELSE at all, CASE returns NULL when nothing matches.

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,
       CASE
         WHEN salary IS NULL    THEN 'unknown'
         WHEN salary >= 100000  THEN 'high'
         WHEN salary >= 60000   THEN 'mid'
         ELSE 'low'
       END AS band
FROM employees
ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Searched CASE tests conditions in order
  • The first true branch wins
  • Without ELSE, unmatched rows get NULL
  • Handle NULL explicitly before comparisons

Common mistakes

  • Letting NULL fall into the ELSE branch
  • Writing overlapping ranges in the wrong order

Follow-ups

  • How would you count employees per band?
  • What is the difference in syntax between simple and searched CASE?

Tips

  • Order thresholds from highest to lowest
134.sql-0134Mediummid

What does CASE dept_id WHEN NULL THEN 'none' ELSE 'has dept' END return for an employee with no department?

It returns 'has dept'. A simple CASE compares with =, and NULL = NULL is unknown, so the WHEN NULL branch never matches. Use a searched CASE with WHEN dept_id IS NULL instead.

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, CASE dept_id WHEN NULL THEN 'none' ELSE 'has dept' END AS label
FROM employees WHERE id IN (1, 7) ORDER BY id;
namelabel
Ashahas dept
Lenahas dept

Lena's dept_id is NULL, yet she gets has dept. The simple form CASE expr WHEN value is shorthand for CASE WHEN expr = value, and NULL = NULL is not true.

The searched form fixes it:

sql
SELECT name, CASE WHEN dept_id IS NULL THEN 'none' ELSE 'has dept' END AS label
FROM employees WHERE id IN (1, 7) ORDER BY id;
namelabel
Ashahas dept
Lenanone

PostgreSQL behaves the same way:

sql
SELECT name, CASE dept_id WHEN NULL THEN 'none' ELSE 'has dept' END AS label
FROM employees WHERE id IN (1, 7) ORDER BY id;
namelabel
Ashahas dept
Lenahas dept

The same trap appears with DECODE in Oracle, which is documented to treat NULLs as equal (not run here). That difference is one reason to prefer explicit IS NULL checks everywhere.

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, CASE dept_id WHEN NULL THEN 'none' ELSE 'has dept' END AS label
FROM employees WHERE id IN (1, 7) ORDER BY id;

SELECT name, CASE WHEN dept_id IS NULL THEN 'none' ELSE 'has dept' END AS label
FROM employees WHERE id IN (1, 7) ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Simple CASE compares with =
  • WHEN NULL in a simple CASE never matches
  • Use WHEN col IS NULL in a searched CASE
  • Behaviour is the same in SQLite and PostgreSQL

Common mistakes

  • Writing WHEN NULL in a simple CASE
  • Assuming CASE treats NULLs as equal like GROUP BY does

Follow-ups

  • How does COALESCE relate to CASE?
  • Which other constructs compare with = and miss NULLs?

Tips

  • Rewrite the simple CASE as the searched one to explain
135.sql-0135Mediummid

How do you turn rows into columns, for example one row per student with a column per course mark?

Use conditional aggregation: group by the row key and write one MAX(CASE WHEN course_id = 10 THEN marks END) per output column. The CASE keeps only the matching value and NULL elsewhere, and MAX picks it. This works on every engine, unlike vendor PIVOT syntax.

Full answer
sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
SELECT student_id,
       MAX(CASE WHEN course_id = 10 THEN marks END) AS databases,
       MAX(CASE WHEN course_id = 20 THEN marks END) AS algorithms,
       MAX(CASE WHEN course_id = 30 THEN marks END) AS statistics
FROM enrolments
GROUP BY student_id
ORDER BY student_id;
student_iddatabasesalgorithmsstatistics
18892NULL
275NULLNULL
3647180
5NULL55NULL

Each CASE returns the mark for its course and NULL for other rows. MAX ignores NULLs, so it returns the single mark per student, or NULL when the student did not take the course. Ben has a row for Statistics with a NULL mark, which also shows as NULL.

Dara does not appear, because she has no enrolments. Start from students with a LEFT JOIN to include her.

The column list is fixed in the query text. For a dynamic set of columns, generate the SQL in application code, or use vendor features such as SQL Server's PIVOT or PostgreSQL's crosstab from the tablefunc extension (not run here).

PostgreSQL also accepts MAX(marks) FILTER (WHERE course_id = 10), and SQLite 3.30+ supports FILTER too.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT student_id,
       MAX(CASE WHEN course_id = 10 THEN marks END) AS databases,
       MAX(CASE WHEN course_id = 20 THEN marks END) AS algorithms,
       MAX(CASE WHEN course_id = 30 THEN marks END) AS statistics
FROM enrolments
GROUP BY student_id
ORDER BY student_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Conditional aggregation pivots rows into columns
  • CASE returns the value for one column and NULL otherwise
  • MAX or SUM collapses each group
  • Columns are fixed; dynamic pivots need generated SQL

Common mistakes

  • Forgetting GROUP BY and getting one row per enrolment
  • Using SUM where a missing value should stay NULL and not become 0 after COALESCE

Follow-ups

  • How would you unpivot columns back into rows?
  • How would you include students with no enrolments?

Tips

  • Explain why MAX is safe here
136.sql-0136Mediummid

How do you unpivot a table with one column per quarter into one row per quarter?

Use UNION ALL with one SELECT per column, each returning the key, a label and that column's value. Alternatively, cross join with a small list of labels and pick the value with CASE. PostgreSQL can also unpivot with a VALUES list in a LATERAL join.

Full answer
sql
CREATE TABLE targets (team TEXT PRIMARY KEY, q1 INTEGER, q2 INTEGER, q3 INTEGER, q4 INTEGER);
INSERT INTO targets VALUES ('north',10,12,12,15),('south',8,9,NULL,11);
sql
SELECT team, 'q1' AS quarter, q1 AS target FROM targets
UNION ALL SELECT team, 'q2', q2 FROM targets
UNION ALL SELECT team, 'q3', q3 FROM targets
UNION ALL SELECT team, 'q4', q4 FROM targets
ORDER BY team, quarter;
teamquartertarget
northq110
northq212
northq312
northq415
southq18
southq29
southq3NULL
southq411

Each branch reads the table once. With four columns that is four scans, which is fine for small tables. The CROSS JOIN version scans once and multiplies rows by the label list:

sql
WITH q(quarter) AS (VALUES ('q1'),('q2'),('q3'),('q4'))
SELECT t.team, q.quarter,
       CASE q.quarter WHEN 'q1' THEN t.q1 WHEN 'q2' THEN t.q2
                      WHEN 'q3' THEN t.q3 ELSE t.q4 END AS target
FROM targets t CROSS JOIN q
ORDER BY t.team, q.quarter;
teamquartertarget
northq110
northq212
northq312
northq415
southq18
southq29
southq3NULL
southq411

PostgreSQL's LATERAL VALUES form is compact:

sql
SELECT t.team, v.quarter, v.target
FROM targets t
CROSS JOIN LATERAL (VALUES ('q1', t.q1), ('q2', t.q2), ('q3', t.q3), ('q4', t.q4)) AS v(quarter, target)
ORDER BY t.team, v.quarter;
teamquartertarget
northq110
northq212
northq312
northq415
southq18
southq29
southq3NULL
southq411

All three return the same eight rows. Wide tables with repeating columns (q1, q2, q3...) often signal a design that should store one row per period; unpivoting is how you read such data in a normalized shape.

sql
CREATE TABLE targets (team TEXT PRIMARY KEY, q1 INTEGER, q2 INTEGER, q3 INTEGER, q4 INTEGER);
INSERT INTO targets VALUES ('north',10,12,12,15),('south',8,9,NULL,11);

SELECT team, 'q1' AS quarter, q1 AS target FROM targets
UNION ALL SELECT team, 'q2', q2 FROM targets
UNION ALL SELECT team, 'q3', q3 FROM targets
UNION ALL SELECT team, 'q4', q4 FROM targets
ORDER BY team, quarter;

WITH q(quarter) AS (VALUES ('q1'),('q2'),('q3'),('q4'))
SELECT t.team, q.quarter,
       CASE q.quarter WHEN 'q1' THEN t.q1 WHEN 'q2' THEN t.q2
                      WHEN 'q3' THEN t.q3 ELSE t.q4 END AS target
FROM targets t CROSS JOIN q
ORDER BY t.team, q.quarter;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • UNION ALL with one branch per column unpivots
  • CROSS JOIN with a label list and CASE scans once
  • PostgreSQL can use LATERAL VALUES
  • Repeating columns usually mean the table should be long, not wide

Common mistakes

  • Using UNION instead of UNION ALL and losing equal values
  • Forgetting the label column that says which column a value came from

Follow-ups

  • How would you skip NULL quarters?
  • How would you pivot the result back?

Tips

  • Mention the normalization angle
137.sql-0137Mediummid

What happens when CASE branches return different types, such as THEN salary ELSE 'n/a'?

PostgreSQL resolves all branches to one common type, here integer, so the literal 'n/a' fails to convert and the query errors. SQLite has dynamic typing, so each row keeps whatever type its branch produced. Keep branches the same type, for example by casting the number to text or returning NULL instead of a marker string.

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SQLite accepts the mixed CASE and returns integers for some rows and text for others:

sql
SELECT name, CASE WHEN salary IS NOT NULL THEN salary ELSE 'n/a' END AS pay,
       typeof(CASE WHEN salary IS NOT NULL THEN salary ELSE 'n/a' END) AS t
FROM employees WHERE id IN (1, 7) ORDER BY id;
namepayt
Asha120000integer
Lenan/atext

typeof shows the mix. Sorting or comparing such a column later gives surprising results, because SQLite orders all integers before all text.

PostgreSQL refuses the same query:

sql
SELECT name, CASE WHEN salary IS NOT NULL THEN salary ELSE 'n/a' END AS pay
FROM employees WHERE id IN (1, 7) ORDER BY id;
-- error on purpose
text
Error: invalid input syntax for type integer: "n/a"

Two portable versions: cast the number so every branch is text, or return NULL and let the display layer print a placeholder.

sql
SELECT name, CASE WHEN salary IS NOT NULL THEN CAST(salary AS TEXT) ELSE 'n/a' END AS pay
FROM employees WHERE id IN (1, 7) ORDER BY id;
namepay
Asha120000
Lenan/a
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, CASE WHEN salary IS NOT NULL THEN salary ELSE 'n/a' END AS pay,
       typeof(CASE WHEN salary IS NOT NULL THEN salary ELSE 'n/a' END) AS t
FROM employees WHERE id IN (1, 7) ORDER BY id;

SELECT name, CASE WHEN salary IS NOT NULL THEN CAST(salary AS TEXT) ELSE 'n/a' END AS pay
FROM employees WHERE id IN (1, 7) ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • PostgreSQL needs one common result type for all branches
  • SQLite lets each row keep its own type
  • Mixed types cause odd sorting and comparisons
  • Cast explicitly or return NULL for missing values

Common mistakes

  • Returning a marker string like 'n/a' from a numeric CASE
  • Testing only on SQLite and failing on PostgreSQL

Follow-ups

  • How does COALESCE(salary, 'n/a') behave on each engine?
  • Where should placeholders for missing values be produced?

Tips

  • Keep data typed in SQL and format at the edge
138.sql-0138Mediummid

A report uses SUM(CASE WHEN status = 'shipped' THEN 1 END) to count shipped orders per customer, and Dev shows NULL instead of 0. Why, and what is the fix?

A CASE without ELSE returns NULL for non-matching rows, and SUM of only NULLs is NULL. For Dev, the LEFT JOIN produced one row with NULL status, so the sum is NULL. Add ELSE 0, or use COUNT(CASE WHEN ... THEN 1 END), which returns 0 when nothing matches.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
SELECT c.name, SUM(CASE WHEN o.status = 'shipped' THEN 1 END) AS shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
nameshipped
Ana2
BilalNULL
Chloe1
DevNULL

Bilal's orders are cancelled and pending, so none matches; his SUM is NULL too. Dev has no orders, so his only row comes from the LEFT JOIN with all order columns NULL.

Two fixes, both giving 0:

sql
SELECT c.name,
       COUNT(CASE WHEN o.status = 'shipped' THEN 1 END)      AS shipped_count,
       SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped_sum
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
nameshipped_countshipped_sum
Ana22
Bilal00
Chloe11
Dev00

COUNT counts non-NULL values and returns 0 for an empty set, so it needs no ELSE. SUM with ELSE 0 also works. COALESCE(SUM(...), 0) is a third option, but fixing the expression itself is clearer.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

SELECT c.name, SUM(CASE WHEN o.status = 'shipped' THEN 1 END) AS shipped
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;

SELECT c.name,
       COUNT(CASE WHEN o.status = 'shipped' THEN 1 END)      AS shipped_count,
       SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped_sum
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CASE without ELSE yields NULL
  • SUM over only NULLs returns NULL, not 0
  • COUNT(CASE ...) returns 0 when nothing matches
  • ELSE 0 makes SUM return 0

Common mistakes

  • Assuming SUM of nothing is 0
  • Wrapping everything in COALESCE instead of fixing the expression

Follow-ups

  • What does AVG(CASE WHEN ... THEN 1 ELSE 0 END) compute?
  • How would FILTER express the same count?

Tips

  • Explain which rows are NULL and why
139.sql-0139Mediummid

Can CASE be used inside UPDATE, and how would you give different raises to different departments in one statement?

Yes. SET salary = salary * CASE dept_id WHEN 1 THEN 1.05 WHEN 2 THEN 1.10 ELSE 1 END updates every row in one pass with per-row logic. Add a WHERE clause so rows that should not change are not touched, which avoids needless writes and trigger calls.

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
UPDATE employees
SET salary = CAST(salary * CASE dept_id WHEN 1 THEN 1.05 WHEN 2 THEN 1.10 END AS INTEGER)
WHERE dept_id IN (1, 2);
SELECT name, dept_id, salary FROM employees ORDER BY id;
namedept_idsalary
Asha1126000
Ravi199750
Mei199750
Tom277000
Sara268200
Diego355000
LenaNULLNULL
Omar348000

Engineering got 5 percent and Sales 10 percent. Support and Lena (no department) were excluded by WHERE, so their rows were not rewritten at all. Without the WHERE, the ELSE 1 branch would still keep values the same, but every row would be written, firing triggers and generating log volume for no change.

CAST(... AS INTEGER) keeps the column integer, because multiplying by 1.05 gives a real number. One UPDATE with CASE is also atomic: there is no moment where Engineering has its raise and Sales does not.

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');

UPDATE employees
SET salary = CAST(salary * CASE dept_id WHEN 1 THEN 1.05 WHEN 2 THEN 1.10 END AS INTEGER)
WHERE dept_id IN (1, 2);
SELECT name, dept_id, salary FROM employees ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CASE works in SET expressions
  • One statement applies different logic per row
  • WHERE limits writes to rows that change
  • A single statement is atomic

Common mistakes

  • Running separate UPDATEs and leaving partial state on failure
  • Updating every row with a no-op ELSE

Follow-ups

  • How would you update from a lookup table of raise percentages instead?
  • What happens to NULL salaries?

Tips

  • Mention atomicity and needless writes
140.sql-0140Easyfresher

What does first || ' ' || last return when last is NULL, and how is CONCAT different?

The || operator returns NULL if any operand is NULL, so the whole name disappears. CONCAT, available in PostgreSQL and in SQLite 3.44+, treats NULL as an empty string. Use COALESCE around nullable parts, or CONCAT_WS to join with a separator and skip NULLs.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id,
       first || ' ' || last        AS pipes,
       CONCAT(first, ' ', last)    AS concat_fn,
       CONCAT_WS(' ', first, last) AS concat_ws
FROM contacts WHERE id IN (1, 2) ORDER BY id;
idpipesconcat_fnconcat_ws
1Asha RaoAsha RaoAsha Rao
2NULLbenben

Ben's last is NULL, so || gives NULL for him. CONCAT drops the NULL but keeps the space, leaving a trailing blank. CONCAT_WS adds the separator only between non-NULL values, which is usually what a "full name" column wants.

PostgreSQL gives the same three results:

sql
SELECT id, first || ' ' || last AS pipes, CONCAT(first, ' ', last) AS concat_fn,
       CONCAT_WS(' ', first, last) AS concat_ws
FROM contacts WHERE id IN (1, 2) ORDER BY id;
idpipesconcat_fnconcat_ws
1Asha RaoAsha RaoAsha Rao
2NULLbenben

SQL Server's + on strings also yields NULL with a NULL operand by default; MySQL uses CONCAT because || means OR there unless a mode is set (neither was run here).

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id,
       first || ' ' || last        AS pipes,
       CONCAT(first, ' ', last)    AS concat_fn,
       CONCAT_WS(' ', first, last) AS concat_ws
FROM contacts WHERE id IN (1, 2) ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • || returns NULL when any part is NULL
  • CONCAT treats NULL as an empty string
  • CONCAT_WS skips NULLs and their separators
  • Operator meaning varies by engine

Common mistakes

  • Building display names with || on nullable columns
  • Leaving double or trailing spaces after CONCAT

Follow-ups

  • How would you build 'Last, First' only when both exist?
  • Which engines use + for string concatenation?

Tips

  • Show the three variants on one NULL row