← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 2 of 26

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

Page 2 of 26

Questions 21–40 of 501 · 0 of 20 on this page marked learned

21.sql-0021Easyfresher

A query meant to find Sales or Support staff earning over 65000 returns a low-paid employee. What is wrong with WHERE dept_id = 2 OR dept_id = 3 AND salary > 65000?

AND binds more tightly than OR, so the condition is read as dept_id = 2 OR (dept_id = 3 AND salary > 65000). Every Sales employee passes regardless of salary. Add parentheses around the OR, or use dept_id IN (2, 3) AND salary > 65000.

Full answer

SQL evaluates NOT first, then AND, then OR, the same way multiplication comes before addition in arithmetic. The condition as written:

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
FROM employees
WHERE dept_id = 2 OR dept_id = 3 AND salary > 65000
ORDER BY name;
namedept_idsalary
Sara262000
Tom270000

The database read it as:

text
dept_id = 2  OR  (dept_id = 3 AND salary > 65000)

So both Sales employees pass on the first half alone, and Sara's 62000 sneaks through next to Tom. Support staff are checked against the salary rule, and both of them fail it. The output looks plausible, which is why this bug survives code review.

The fix is to say what you meant with parentheses:

sql
SELECT name, dept_id, salary
FROM employees
WHERE (dept_id = 2 OR dept_id = 3) AND salary > 65000
ORDER BY name;
namedept_idsalary
Tom270000

IN expresses the same thing with less room for mistakes:

sql
SELECT name, dept_id, salary
FROM employees
WHERE dept_id IN (2, 3) AND salary > 65000
ORDER BY name;
namedept_idsalary
Tom270000

A habit worth building: whenever a WHERE clause mixes AND and OR, add parentheses even if the default precedence happens to be right. The next person to edit the query will not have to work out the precedence rules in their head.

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
FROM employees
WHERE dept_id = 2 OR dept_id = 3 AND salary > 65000
ORDER BY name;

SELECT name, dept_id, salary
FROM employees
WHERE (dept_id = 2 OR dept_id = 3) AND salary > 65000
ORDER BY name;

SELECT name, dept_id, salary
FROM employees
WHERE dept_id IN (2, 3) AND salary > 65000
ORDER BY name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Precedence is NOT, then AND, then OR
  • a OR b AND c means a OR (b AND c)
  • Parentheses or IN make the intent explicit
  • Always bracket mixed AND and OR

Common mistakes

  • Trusting that the output looks reasonable instead of checking the logic
  • Adding parentheses around the wrong pair of conditions

Follow-ups

  • How does NOT interact with AND and OR in the same expression?
  • Rewrite the condition using IN.

Tips

  • Write out how the database groups the condition before fixing it
22.sql-0022Mediummid

Is BETWEEN inclusive? Why can BETWEEN miss rows when the column stores a date and time?

BETWEEN a AND b is inclusive at both ends and means >= a AND <= b. With timestamps, BETWEEN '2026-03-01' AND '2026-03-02' excludes everything after midnight at the start of 2 March, so most of that day is missed. A half-open range, >= start AND < day after end, is the reliable pattern.

Full answer

x BETWEEN 10 AND 20 is shorthand for x >= 10 AND x <= 20, so both ends are included. With whole numbers or plain dates that is exactly what people expect.

Timestamps change the picture. Here are canteen payments with a date and time:

sql
CREATE TABLE payments (id INTEGER PRIMARY KEY, paid_at TEXT, amount INTEGER);
INSERT INTO payments (paid_at, amount) VALUES
  ('2026-03-01 09:10', 40), ('2026-03-02 00:00', 25),
  ('2026-03-02 13:45', 60), ('2026-03-03 08:00', 30);
SELECT id, paid_at, amount
FROM payments
WHERE paid_at BETWEEN '2026-03-01' AND '2026-03-02'
ORDER BY paid_at;
idpaid_atamount
12026-03-01 09:1040

The intent was "all payments on 1 and 2 March", but both 2 March payments are missing. As text, '2026-03-02 00:00' and '2026-03-02 13:45' start with '2026-03-02' and then keep going, so both are greater than '2026-03-02' and fail the <= half. Real timestamp types in PostgreSQL behave a little differently but have the same flaw: the date '2026-03-02' becomes midnight, so the midnight payment is included and everything later that day is not:

sql
SELECT id, paid_at, amount
FROM payments
WHERE paid_at BETWEEN '2026-03-01' AND '2026-03-02'
ORDER BY paid_at;
idpaid_atamount
12026-03-01 09:10:0040
22026-03-02 00:00:0025

A half-open range avoids the problem. Include the start, exclude the day after the end:

sql
SELECT id, paid_at, amount
FROM payments
WHERE paid_at >= '2026-03-01' AND paid_at < '2026-03-03'
ORDER BY paid_at;
idpaid_atamount
12026-03-01 09:1040
22026-03-02 00:0025
32026-03-02 13:4560

This form has two more advantages. Back-to-back ranges never overlap or leave gaps (March is >= '2026-03-01' AND < '2026-04-01'), and it works whatever the precision of the time part. Writing <= '2026-03-02 23:59:59' looks like a fix, but it breaks as soon as times carry fractions of a second.

NOT BETWEEN is inclusive in reverse: it means < a OR > b. And if a is greater than b, BETWEEN a AND b matches nothing, because the shorthand is not symmetric.

sql
CREATE TABLE payments (id INTEGER PRIMARY KEY, paid_at TEXT, amount INTEGER);
INSERT INTO payments (paid_at, amount) VALUES
  ('2026-03-01 09:10', 40), ('2026-03-02 00:00', 25),
  ('2026-03-02 13:45', 60), ('2026-03-03 08:00', 30);
SELECT id, paid_at, amount
FROM payments
WHERE paid_at BETWEEN '2026-03-01' AND '2026-03-02'
ORDER BY paid_at;

SELECT id, paid_at, amount
FROM payments
WHERE paid_at >= '2026-03-01' AND paid_at < '2026-03-03'
ORDER BY paid_at;

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

Key points

  • BETWEEN includes both ends
  • With timestamps, the end date means midnight, so the last day is mostly excluded
  • Use >= start AND < next_day for date-time ranges
  • BETWEEN 20 AND 10 matches nothing

Common mistakes

  • Using BETWEEN with an end date on a timestamp column
  • Patching the range with 23:59:59 and missing fractional seconds

Follow-ups

  • How would you select all orders in the current calendar month?
  • Does BETWEEN work with text values?

Tips

  • Give the half-open form as the answer you would ship
23.sql-0023Mediummid

How do the LIKE wildcards % and _ work, and how do you search for a literal percent sign or underscore?

In LIKE, % matches any run of characters (including none) and _ matches exactly one character. To match a literal % or _, declare an escape character with ESCAPE and put it before the wildcard, for example LIKE '%50\%%' ESCAPE '\'. Without ESCAPE, a search for '50%' matches '50' followed by anything.

Full answer

LIKE compares a value with a pattern that has two wildcards:

  • % matches zero or more characters. 'Ma%' matches Maya and Ma.
  • _ matches exactly one character. 'R_vi' matches Ravi but not Rvi or Raavi.
sql
CREATE TABLE names (n TEXT);
INSERT INTO names VALUES ('Ravi'),('Rvi'),('Raavi'),('Maya'),('Ma');
SELECT n,
       n LIKE 'Ma%'  AS starts_ma,
       n LIKE 'R_vi' AS r_one_vi
FROM names
ORDER BY n;
nstarts_mar_one_vi
Ma10
Maya10
Raavi00
Ravi01
Rvi00

The trouble starts when the data itself contains % or _. A coupon table has notes like "50% off" and "500 points". Searching for '%50%' cannot tell the literal percent from the wildcard:

sql
CREATE TABLE coupons (code TEXT, note TEXT);
INSERT INTO coupons VALUES ('A1','50% off'),('B2','500 points'),('C3','5 percent'),('NEW_USER','welcome'),('NEWXUSER','typo copy');
SELECT code, note FROM coupons WHERE note LIKE '%50%' ORDER BY code;
codenote
A150% off
B2500 points

Declare an escape character and put it in front of the character you want to match literally:

sql
SELECT code, note FROM coupons WHERE note LIKE '%50\%%' ESCAPE '\' ORDER BY code;
codenote
A150% off

Now \% means "a real percent sign". The same applies to underscores, which are common in codes such as NEW_USER:

sql
SELECT code,
       code LIKE 'NEW_%'               AS plain,
       code LIKE 'NEW\_%' ESCAPE '\'   AS escaped
FROM coupons
WHERE code LIKE 'NEW%'
ORDER BY code;
codeplainescaped
NEWXUSER10
NEW_USER11

Without the escape, 'NEW_%' also matches NEWXUSER, because _ matched the X. PostgreSQL uses backslash as its default escape character for LIKE, so '%50\%%' works there even without the ESCAPE clause; SQLite has no default escape, so the clause is required.

When user input goes into a LIKE pattern, escape % and _ in the input as well as passing it as a parameter. Otherwise a user typing % turns a search into "match everything".

sql
CREATE TABLE names (n TEXT);
INSERT INTO names VALUES ('Ravi'),('Rvi'),('Raavi'),('Maya'),('Ma');
SELECT n,
       n LIKE 'Ma%'  AS starts_ma,
       n LIKE 'R_vi' AS r_one_vi
FROM names
ORDER BY n;

CREATE TABLE coupons (code TEXT, note TEXT);
INSERT INTO coupons VALUES ('A1','50% off'),('B2','500 points'),('C3','5 percent'),('NEW_USER','welcome'),('NEWXUSER','typo copy');
SELECT code, note FROM coupons WHERE note LIKE '%50%' ORDER BY code;

SELECT code, note FROM coupons WHERE note LIKE '%50\%%' ESCAPE '\' ORDER BY code;

SELECT code,
       code LIKE 'NEW_%'               AS plain,
       code LIKE 'NEW\_%' ESCAPE '\'   AS escaped
FROM coupons
WHERE code LIKE 'NEW%'
ORDER BY code;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • % matches any run of characters; _ matches exactly one
  • ESCAPE declares a character that makes the next wildcard literal
  • SQLite needs an explicit ESCAPE clause
  • Escape wildcards in user search input, not only quotes

Common mistakes

  • Searching for codes with underscores and getting extra matches
  • Passing raw user input into a LIKE pattern

Follow-ups

  • Is LIKE case-sensitive on SQLite and PostgreSQL?
  • Which LIKE patterns can use a B-tree index?

Tips

  • Show a pattern with _ catching an extra row; it proves you understand the wildcard
24.sql-0024Mediummid

Which LIKE patterns can use an index, and why can a search like LIKE '%son' not?

A B-tree index stores values in sorted order, so a pattern with a fixed prefix such as 'Ma%' becomes a range scan from 'Ma' up to 'Mb'. A leading wildcard such as '%son' has no prefix to seek to, so every value must be checked. In SQLite the prefix optimisation also needs the index collation to match LIKE's case rules.

Full answer

Think of a phone book sorted by surname. Finding everyone whose name starts with "Ma" is quick: jump to the first Ma and read until the names stop starting with Ma. Finding everyone whose name ends in "son" means reading the whole book.

A B-tree index is the phone book. LIKE 'Ma%' can be turned into the range >= 'Ma' AND < 'Mb', which the index can seek to. LIKE '%son' and LIKE '%ar%' have no fixed start, so the database scans.

SQLite adds a twist. Its LIKE is case-insensitive for ASCII, but a normal index is case-sensitive, so the two orders do not agree and SQLite will not use the index for LIKE:

sql
CREATE TABLE people (id INTEGER PRIMARY KEY, surname TEXT);
CREATE INDEX idx_people_surname ON people(surname);
EXPLAIN QUERY PLAN SELECT id FROM people WHERE surname LIKE 'Ma%';
text
QUERY PLAN
SCAN people

Declare the column (or the index) with COLLATE NOCASE, and the prefix search becomes an index search:

sql
CREATE TABLE people2 (id INTEGER PRIMARY KEY, surname TEXT COLLATE NOCASE);
CREATE INDEX idx_people2_surname ON people2(surname);
EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE 'Ma%';
text
QUERY PLAN
SEARCH people2 USING COVERING INDEX idx_people2_surname (surname>? AND surname<?)

The %son search still scans, even with the right collation:

sql
EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE '%son';
text
QUERY PLAN
SCAN people2

PostgreSQL has its own rule: a plain B-tree index helps LIKE prefix searches only with the C collation or an index built with text_pattern_ops. For "contains" or "ends with" searches, PostgreSQL offers trigram indexes (the pg_trgm extension), and both engines offer full-text search for word matching. Those PostgreSQL details come from its documentation and were not run here.

A trick for "ends with" searches is to store the reversed string and index that, so '%son' becomes a prefix search for 'nos%'.

sql
CREATE TABLE people (id INTEGER PRIMARY KEY, surname TEXT);
CREATE INDEX idx_people_surname ON people(surname);
EXPLAIN QUERY PLAN SELECT id FROM people WHERE surname LIKE 'Ma%';

CREATE TABLE people2 (id INTEGER PRIMARY KEY, surname TEXT COLLATE NOCASE);
CREATE INDEX idx_people2_surname ON people2(surname);
EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE 'Ma%';

EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE '%son';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A fixed prefix turns LIKE into an index range scan
  • A leading % forces a scan
  • SQLite needs NOCASE collation (or case_sensitive_like) for LIKE to use an index
  • PostgreSQL uses text_pattern_ops for prefix LIKE, pg_trgm for contains

Common mistakes

  • Adding an index and assuming LIKE '%term%' will use it
  • Ignoring collation when checking why SQLite does not use the index

Follow-ups

  • How would you speed up a search box that matches anywhere in a product name?
  • What is a trigram index?

Tips

  • Use the phone book picture; it explains the rule in one sentence
  • Check the plan with EXPLAIN instead of guessing
25.sql-0025Easyfresher

Write a query for all orders placed in February 2026, using a range that stays correct if times are added to the dates later.

Use a half-open range: order_date >= '2026-02-01' AND order_date < '2026-03-01'. It includes every moment of February and nothing from March, whatever the time precision. Avoid wrapping the column in a function such as strftime, which blocks index use.

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, customer_id, order_date
FROM orders
WHERE order_date >= '2026-02-01'
  AND order_date <  '2026-03-01'
ORDER BY order_date;
idcustomer_idorder_date
10212026-02-11
10322026-02-14

Two choices in that query are deliberate.

The upper bound is the first day of the next month with <, not the last day of February with <=. If the column later stores '2026-02-28 18:30', the query still includes it. It also avoids working out how many days the month has.

The column is compared directly. Writing strftime('%Y-%m', order_date) = '2026-02' returns the same rows here:

sql
SELECT id, customer_id, order_date
FROM orders
WHERE strftime('%Y-%m', order_date) = '2026-02'
ORDER BY order_date;
idcustomer_idorder_date
10212026-02-11
10322026-02-14

But the function has to be computed for every row, so an index on order_date cannot be used to jump to February. With a direct range, the index can seek to the start and stop at the end. A condition the index can use this way is called sargable (from "search argument able").

ISO dates as text (YYYY-MM-DD) sort correctly as strings, which is why the text comparison works on SQLite. On PostgreSQL, use a date or timestamp column and the same range works with real date 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 id, customer_id, order_date
FROM orders
WHERE order_date >= '2026-02-01'
  AND order_date <  '2026-03-01'
ORDER BY order_date;

SELECT id, customer_id, order_date
FROM orders
WHERE strftime('%Y-%m', order_date) = '2026-02'
ORDER BY order_date;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Half-open range: >= first day AND < first day of next month
  • Correct for dates with or without times
  • Comparing the bare column keeps the condition index-friendly
  • ISO text dates sort correctly in SQLite

Common mistakes

  • Using <= '2026-02-28' and losing rows with times or on leap years
  • Wrapping the column in a date function and forcing a full scan

Follow-ups

  • How would you get the same range for any month passed as a parameter?
  • What does sargable mean?

Tips

  • Mention index use when you explain why you avoided the function
26.sql-0026Mediummid

How would you write one query for a search form where every filter (city, year) is optional?

A common pattern is WHERE (:city IS NULL OR city = :city) AND (:year IS NULL OR year = :year), so an empty filter switches itself off. It is simple and safe with bound parameters, but one cached plan must serve every combination, which can hurt on large tables. Building the WHERE clause in code from only the filters supplied, still with parameters, usually performs better.

Full answer

Each filter is written so that a missing value makes its condition true for every row:

text
(:city IS NULL OR city = :city)

If the user leaves city empty, :city IS NULL is true and the filter switches itself off. If they choose a city, only matching rows pass.

To show it without an application, the parameters come from a one-row CTE here. First with only the year set:

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
WITH params(p_city, p_year) AS (SELECT NULL, 2)
SELECT s.name, s.city, s.year
FROM students s, params
WHERE (p_city IS NULL OR s.city = p_city)
  AND (p_year IS NULL OR s.year = p_year)
ORDER BY s.name;
namecityyear
BenLeeds2
EliLeeds2

Then with both filters set:

sql
WITH params(p_city, p_year) AS (SELECT 'Pune', 1)
SELECT s.name, s.city, s.year
FROM students s, params
WHERE (p_city IS NULL OR s.city = p_city)
  AND (p_year IS NULL OR s.year = p_year)
ORDER BY s.name;
namecityyear
AshaPune1
ChenPune1

Then with neither, which returns everybody:

sql
WITH params(p_city, p_year) AS (SELECT NULL, NULL)
SELECT s.name, s.city, s.year
FROM students s, params
WHERE (p_city IS NULL OR s.city = p_city)
  AND (p_year IS NULL OR s.year = p_year)
ORDER BY s.name;
namecityyear
AshaPune1
BenLeeds2
ChenPune1
DaraNULL3
EliLeeds2

The pattern has a cost worth raising in an interview. The database sees one query text for every combination of filters, so it may reuse one plan. That plan cannot assume the city filter is active, so it may not use an index on city even when a city is given. On small tables it does not matter. On large ones, build the WHERE clause in application code, adding AND city = ? only when a city is supplied. Each combination gets its own query text and its own plan, and values still go in as bound parameters, never pasted into the string.

Never build the filter by concatenating raw user text into SQL; that is how SQL injection happens.

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

WITH params(p_city, p_year) AS (SELECT NULL, 2)
SELECT s.name, s.city, s.year
FROM students s, params
WHERE (p_city IS NULL OR s.city = p_city)
  AND (p_year IS NULL OR s.year = p_year)
ORDER BY s.name;

WITH params(p_city, p_year) AS (SELECT 'Pune', 1)
SELECT s.name, s.city, s.year
FROM students s, params
WHERE (p_city IS NULL OR s.city = p_city)
  AND (p_year IS NULL OR s.year = p_year)
ORDER BY s.name;

WITH params(p_city, p_year) AS (SELECT NULL, NULL)
SELECT s.name, s.city, s.year
FROM students s, params
WHERE (p_city IS NULL OR s.city = p_city)
  AND (p_year IS NULL OR s.year = p_year)
ORDER BY s.name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • (:p IS NULL OR col = :p) disables a filter when the parameter is empty
  • One query text can mean one plan for every combination
  • Dynamic SQL with bound parameters often gives better plans
  • Never concatenate user input into the SQL text

Common mistakes

  • Using an empty string as 'no filter' and getting zero rows
  • Building optional filters by string concatenation of user input

Follow-ups

  • What is SQL injection, and how do bound parameters prevent it?
  • How would you add an optional name search with LIKE?

Tips

  • Mention the plan-sharing cost; it separates a good answer from a basic one
27.sql-0027Mediummid

Does 'abc' equal 'abc ' (with a trailing space) in SQL?

It depends on the type and engine. In SQLite and in PostgreSQL text or varchar, trailing spaces are significant, so 'abc' = 'abc ' is false. PostgreSQL's char(n) type pads and ignores trailing spaces, so the comparison is true there. MySQL and SQL Server ignore trailing spaces in = comparisons for most collations.

Full answer

A trailing space is a real character, but some types and engines choose to ignore it when comparing.

SQLite compares strings exactly:

sql
SELECT 'abc' = 'abc ' AS equal_with_space,
       'abc' = TRIM('abc ') AS equal_after_trim,
       LENGTH('abc ') AS len;
equal_with_spaceequal_after_trimlen
014

PostgreSQL does too for text and varchar, but its fixed-width char(n) type pads values with spaces and treats trailing spaces as insignificant:

sql
SELECT 'abc'::text = 'abc '::text           AS text_equal,
       'abc'::char(5) = 'abc '::char(5)     AS char_equal,
       length('abc '::text)                 AS text_len;
text_equalchar_equaltext_len
falsetrue4

MySQL and SQL Server use "pad space" comparison rules for most collations, so 'abc' = 'abc ' is true there. That comes from their documentation and was not run here.

Where this bites in practice: data imported from a spreadsheet carries trailing spaces, a lookup by name works in one database and fails in another, or a unique constraint allows 'Pune' and 'Pune ' as two different cities. The usual fix is to clean the data on the way in with TRIM, and to add a CHECK constraint such as CHECK (city = TRIM(city)) so dirty values cannot come back.

sql
SELECT 'abc' = 'abc ' AS equal_with_space,
       'abc' = TRIM('abc ') AS equal_after_trim,
       LENGTH('abc ') AS len;

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

Key points

  • SQLite and PostgreSQL text: trailing spaces matter
  • PostgreSQL char(n): trailing spaces are ignored
  • MySQL and SQL Server usually ignore trailing spaces in =
  • Clean with TRIM on input and guard with a CHECK constraint

Common mistakes

  • Assuming string equality rules are the same on every engine
  • Using char(n) for variable-length text

Follow-ups

  • How would you find rows whose value has leading or trailing spaces?
  • Why is char(n) rarely a good choice?

Tips

  • Mention a real symptom, such as duplicate-looking city names
28.sql-0028Easyfresher

What is NULL in SQL, and how does three-valued logic change the way conditions are evaluated?

NULL means a value is missing or unknown; it is not zero and not an empty string. Any comparison with NULL gives UNKNOWN instead of true or false, and WHERE keeps only rows where the condition is true. AND and OR follow a three-valued truth table: FALSE AND UNKNOWN is FALSE, TRUE OR UNKNOWN is TRUE, and most other combinations stay UNKNOWN.

Full answer

NULL is a marker that says "no value here". An employee's salary might not be agreed yet; a student might not have a city on file. NULL is different from 0 and from '', both of which are real values.

Because NULL is unknown, comparing it with anything gives a third logical result, UNKNOWN. Is an unknown salary greater than 50000? Nobody can say. SQLite shows UNKNOWN as NULL:

sql
SELECT NULL = NULL       AS null_eq_null,
       NULL > 50000      AS null_gt,
       NULL IS NULL      AS is_null,
       NULL IS NOT NULL  AS is_not_null;
null_eq_nullnull_gtis_nullis_not_null
NULLNULL10

NULL = NULL is unknown too: two missing values are not known to be equal. To test for missing values, SQL has IS NULL and IS NOT NULL, which always return true or false.

AND and OR follow simple reasoning. If one side of AND is false, the whole thing is false whatever the unknown side is. If one side of OR is true, the whole thing is true. Otherwise the result stays unknown:

sql
SELECT (1 = 0) AND NULL AS false_and_unknown,
       (1 = 1) AND NULL AS true_and_unknown,
       (1 = 1) OR  NULL AS true_or_unknown,
       (1 = 0) OR  NULL AS false_or_unknown,
       NOT NULL         AS not_unknown;
false_and_unknowntrue_and_unknowntrue_or_unknownfalse_or_unknownnot_unknown
0NULL1NULLNULL

WHERE keeps a row only when the condition is TRUE. Unknown is treated like false for filtering, which is why rows with NULL silently drop out of both salary > 60000 and salary <= 60000:

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 (SELECT COUNT(*) FROM employees WHERE salary >  60000) AS high,
       (SELECT COUNT(*) FROM employees WHERE salary <= 60000) AS low,
       (SELECT COUNT(*) FROM employees)                       AS total;
highlowtotal
528

Seven of eight employees appear in one bucket or the other. Lena's NULL salary is in neither, so two counts that look as if they should add up to the table size do 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');

SELECT NULL = NULL       AS null_eq_null,
       NULL > 50000      AS null_gt,
       NULL IS NULL      AS is_null,
       NULL IS NOT NULL  AS is_not_null;

SELECT (1 = 0) AND NULL AS false_and_unknown,
       (1 = 1) AND NULL AS true_and_unknown,
       (1 = 1) OR  NULL AS true_or_unknown,
       (1 = 0) OR  NULL AS false_or_unknown,
       NOT NULL         AS not_unknown;

SELECT (SELECT COUNT(*) FROM employees WHERE salary >  60000) AS high,
       (SELECT COUNT(*) FROM employees WHERE salary <= 60000) AS low,
       (SELECT COUNT(*) FROM employees)                       AS total;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • NULL means unknown or missing, not 0 or ''
  • Comparisons with NULL return UNKNOWN
  • WHERE keeps only TRUE rows, so UNKNOWN rows drop out
  • FALSE AND UNKNOWN is FALSE; TRUE OR UNKNOWN is TRUE
  • Use IS NULL and IS NOT NULL to test for NULL

Common mistakes

  • Expecting a condition and its opposite to cover every row
  • Treating NULL as zero in comparisons

Follow-ups

  • Why does NOT IN behave strangely when the list contains NULL?
  • What does CHECK (salary > 0) do with a NULL salary?

Tips

  • Use the two-bucket count example; it shows the effect in numbers
29.sql-0029Easyfresher

Why does WHERE manager_id = NULL return no rows even though some rows have no manager?

Comparing anything with NULL using = gives UNKNOWN, never TRUE, so WHERE filters every row out. Use WHERE manager_id IS NULL. The same applies to <> NULL, which also returns nothing; use IS NOT NULL.

Full answer

This is one of the most common first bugs with NULL:

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 FROM employees WHERE manager_id = NULL;
name

(0 rows)

The query runs without an error and returns nothing. For each row, manager_id = NULL asks "is this value equal to an unknown value?". The answer is unknown, and WHERE only keeps rows where the answer is true.

The right test is IS NULL:

sql
SELECT name FROM employees WHERE manager_id IS NULL;
name
Asha

Asha has no manager, because she runs the company. The opposite test fails in the same silent way:

sql
SELECT COUNT(*) AS with_manager_wrong FROM employees WHERE manager_id <> NULL;
with_manager_wrong
0
sql
SELECT COUNT(*) AS with_manager FROM employees WHERE manager_id IS NOT NULL;
with_manager
7

Some engines once offered a setting that made = NULL behave like IS NULL (SQL Server's ANSI_NULLS OFF, now deprecated). Do not rely on anything like that. In application code, watch out for query builders that generate col = ? and then bind a NULL; they need to switch to IS NULL when the value is missing, or use a null-safe operator such as IS NOT DISTINCT FROM.

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 FROM employees WHERE manager_id = NULL;

SELECT name FROM employees WHERE manager_id IS NULL;

SELECT COUNT(*) AS with_manager_wrong FROM employees WHERE manager_id <> NULL;

SELECT COUNT(*) AS with_manager FROM employees WHERE manager_id IS NOT NULL;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • = NULL and <> NULL never match
  • Use IS NULL and IS NOT NULL
  • A query that returns nothing without error is the typical symptom
  • Bound parameters with NULL values need IS NULL or a null-safe comparison

Common mistakes

  • Writing col = NULL or col <> NULL
  • Binding NULL into col = ? from application code

Follow-ups

  • What is a null-safe equality operator?
  • How would you count employees with and without a manager in one query?

Tips

  • Mention the silent empty result; it is how this bug is usually found
30.sql-0030Hardsenior

Why does SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders) return no rows when one order has a NULL customer_id?

x NOT IN (a, b, NULL) expands to x <> a AND x <> b AND x <> NULL. The last comparison is UNKNOWN, so the whole condition can never be TRUE and every row is filtered out. Use NOT EXISTS, which compares row by row and is not affected by NULLs, or filter NULLs out of the subquery.

Full answer

The goal is "customers who have never ordered". Dev has no orders, so he should appear. Instead:

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, name
FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
idname

(0 rows)

One guest order (id 106) has customer_id NULL. The subquery returns 1, 1, 2, 3, 2, NULL. For Dev, 4 NOT IN (1, 1, 2, 3, 2, NULL) means:

text
4 <> 1 AND 4 <> 1 AND 4 <> 2 AND 4 <> 3 AND 4 <> 2 AND 4 <> NULL
TRUE   AND TRUE   AND TRUE   AND TRUE   AND TRUE   AND UNKNOWN   =  UNKNOWN

UNKNOWN is not TRUE, so Dev is dropped. Every other customer is dropped too, because each matches some order. The result is empty once a single NULL appears in the list, and the query gives no warning.

NOT EXISTS asks a different question for each customer: "is there an order row whose customer_id equals this customer's id?". A NULL customer_id never equals anything, so it simply does not count:

sql
SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
idname
4Dev

Filtering NULLs out of the subquery also works, but it relies on everyone remembering to add it:

sql
SELECT id, name
FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders WHERE customer_id IS NOT NULL);
idname
4Dev

A LEFT JOIN with IS NULL is a third way to write the same anti-join:

sql
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
idname
4Dev

IN (without NOT) does not have this problem, because x IN (..., NULL) is still TRUE when x matches a non-NULL value. The trap is specific to NOT IN.

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

SELECT id, name
FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);

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

SELECT id, name
FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders WHERE customer_id IS NOT NULL);

SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • NOT IN with any NULL in the list can never be TRUE
  • The query returns no rows and no error
  • NOT EXISTS is NULL-safe and is the usual fix
  • LEFT JOIN ... WHERE right.key IS NULL is an equivalent anti-join
  • Plain IN is not affected the same way

Common mistakes

  • Using NOT IN on a nullable column and testing only on data without NULLs
  • Fixing it by adding IS NOT NULL in one place and forgetting it in the next query

Follow-ups

  • Which of NOT EXISTS, NOT IN and LEFT JOIN performs best on your database?
  • Does a NOT NULL constraint on orders.customer_id remove the problem?

Tips

  • Write out the expanded AND chain; it makes the explanation obvious
  • Name NOT EXISTS as the default choice
31.sql-0031Easyfresher

Given a table with values 5, NULL, 5 and 8, what do COUNT(*), COUNT(x) and COUNT(DISTINCT x) return?

COUNT(*) counts rows, so it returns 4. COUNT(x) counts non-NULL values, so it returns 3. COUNT(DISTINCT x) counts distinct non-NULL values, so it returns 2 (5 and 8).

Full answer

The three forms answer three different questions.

  • COUNT(*): how many rows are there? NULLs do not matter, because it counts rows, not values.
  • COUNT(x): how many rows have a value in x? NULLs are skipped.
  • COUNT(DISTINCT x): how many different values does x take? NULLs are skipped, and duplicates are counted once.
sql
WITH t(x) AS (VALUES (5), (NULL), (5), (8))
SELECT COUNT(*)          AS count_star,
       COUNT(x)          AS count_x,
       COUNT(DISTINCT x) AS count_distinct_x
FROM t;
count_starcount_xcount_distinct_x
432

The gap between COUNT(*) and COUNT(x) is often useful on purpose. For example, the number of enrolments that still have no marks entered:

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 COUNT(*)                AS enrolments,
       COUNT(marks)            AS marked,
       COUNT(*) - COUNT(marks) AS waiting_for_marks
FROM enrolments;
enrolmentsmarkedwaiting_for_marks
871

COUNT(1) and COUNT('anything') behave exactly like COUNT(*), because the constant is never NULL. There is no speed difference worth arguing about in modern engines.

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

WITH t(x) AS (VALUES (5), (NULL), (5), (8))
SELECT COUNT(*)          AS count_star,
       COUNT(x)          AS count_x,
       COUNT(DISTINCT x) AS count_distinct_x
FROM t;

SELECT COUNT(*)                AS enrolments,
       COUNT(marks)            AS marked,
       COUNT(*) - COUNT(marks) AS waiting_for_marks
FROM enrolments;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • COUNT(*) counts rows
  • COUNT(col) counts non-NULL values
  • COUNT(DISTINCT col) counts distinct non-NULL values
  • COUNT(*) - COUNT(col) gives the number of NULLs

Common mistakes

  • Using COUNT(col) to count rows on a nullable column
  • Expecting COUNT(DISTINCT col) to count NULL as a value

Follow-ups

  • How do you count distinct pairs of columns?
  • What does COUNT return on an empty table?

Tips

  • Answer with the three numbers first, then the rule behind each
32.sql-0032Mediummid

Why can AVG(marks) differ from SUM(marks) / COUNT(*)? Which one is correct?

AVG ignores NULLs, so it divides the sum by the number of non-NULL values. SUM(marks) / COUNT(*) divides by all rows, treating missing marks as if they were zero. Which is correct depends on meaning: a mark that is still pending should usually be excluded, while a missed exam scored as zero should be stored as 0, not NULL.

Full answer

All aggregate functions except COUNT(*) skip NULLs. For AVG, that changes the denominator.

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

The Statistics course has two enrolments, one marked 80 and one with no mark yet:

sql
SELECT AVG(marks)                    AS avg_marks,
       SUM(marks) * 1.0 / COUNT(*)   AS sum_over_rows,
       SUM(marks) / COUNT(*)         AS integer_division
FROM enrolments
WHERE course_id = 30;
avg_markssum_over_rowsinteger_division
80.040.040

AVG(marks) is 80, because only one value exists. Dividing the sum by COUNT(*) gives 40, as though the missing mark were zero. And SUM(marks) / COUNT(*) with two integers also performs integer division, a second trap hiding in the same expression (here 80 / 2 happens to divide evenly).

Neither number is wrong by itself; they answer different questions. "What is the average of the marks entered so far?" is 80. "What is the average if we count a missing mark as zero?" is 40. The data model should make the meaning clear. If a student skipped the exam and the rule is that they score zero, store 0. Keep NULL for "not known yet".

If you do want missing values counted as zero, say so explicitly rather than relying on the division:

sql
SELECT AVG(COALESCE(marks, 0)) AS avg_missing_as_zero
FROM enrolments
WHERE course_id = 30;
avg_missing_as_zero
40.0
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 AVG(marks)                    AS avg_marks,
       SUM(marks) * 1.0 / COUNT(*)   AS sum_over_rows,
       SUM(marks) / COUNT(*)         AS integer_division
FROM enrolments
WHERE course_id = 30;

SELECT AVG(COALESCE(marks, 0)) AS avg_missing_as_zero
FROM enrolments
WHERE course_id = 30;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Aggregates other than COUNT(*) ignore NULL
  • AVG divides by the count of non-NULL values
  • SUM / COUNT(*) treats NULL as zero and may do integer division
  • Store 0 for a real zero and NULL for unknown

Common mistakes

  • Recomputing an average by hand and getting a different answer than AVG
  • Using NULL to mean zero in the data

Follow-ups

  • What does AVG return when every value is NULL?
  • How would you show the average per course with a count of missing marks?

Tips

  • Ask what NULL means in this column before choosing the formula
33.sql-0033Easyfresher

What is the result of NULL + 1, and of joining a first name with a NULL middle name using ||?

Both are NULL. Most operators return NULL when any operand is NULL, so NULL + 1 is NULL and 'Ana ' || NULL || ' Lopez' is NULL. Wrap the nullable part in COALESCE, or use CONCAT_WS, which skips NULLs in SQLite, PostgreSQL and MySQL.

Full answer

NULL spreads through expressions. If one input is unknown, the result is unknown:

sql
CREATE TABLE people (first TEXT, middle TEXT, last TEXT);
INSERT INTO people VALUES ('Ana', NULL, 'Lopez'), ('Ravi', 'K', 'Iyer'), ('Mei', NULL, 'Lin');
sql
SELECT NULL + 1 AS plus, NULL * 0 AS times_zero, 'tea' || NULL AS joined;
plustimes_zerojoined
NULLNULLNULL

That catches people building display names. A middle name column is often empty:

sql
SELECT first || ' ' || middle || ' ' || last AS full_name FROM people ORDER BY first;
full_name
NULL
NULL
Ravi K Iyer

Two rows lost their whole name because of one missing piece. Fix it by turning the NULL into something harmless before joining:

sql
SELECT first || COALESCE(' ' || middle, '') || ' ' || last AS full_name FROM people ORDER BY first;
full_name
Ana Lopez
Mei Lin
Ravi K Iyer

This also tidies the spacing: the space is only added when a middle name exists. SQLite (3.44 and later), PostgreSQL and MySQL 8 have CONCAT_WS(separator, ...), which skips NULLs and puts the separator only between real values:

sql
SELECT CONCAT_WS(' ', first, middle, last) AS full_name FROM people ORDER BY first;
full_name
Ana Lopez
Mei Lin
Ravi K Iyer

PostgreSQL gives the same result for the CONCAT_WS query:

sql
SELECT CONCAT_WS(' ', first, middle, last) AS full_name FROM people ORDER BY first;
full_name
Ana Lopez
Mei Lin
Ravi K Iyer

Plain CONCAT() treats NULL as an empty string in SQLite and PostgreSQL, but MySQL's CONCAT() returns NULL if any argument is NULL (from the MySQL documentation, not run here).

sql
CREATE TABLE people (first TEXT, middle TEXT, last TEXT);
INSERT INTO people VALUES ('Ana', NULL, 'Lopez'), ('Ravi', 'K', 'Iyer'), ('Mei', NULL, 'Lin');

SELECT NULL + 1 AS plus, NULL * 0 AS times_zero, 'tea' || NULL AS joined;

SELECT first || ' ' || middle || ' ' || last AS full_name FROM people ORDER BY first;

SELECT first || COALESCE(' ' || middle, '') || ' ' || last AS full_name FROM people ORDER BY first;

SELECT CONCAT_WS(' ', first, middle, last) AS full_name FROM people ORDER BY first;

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

Key points

  • Operators return NULL if any operand is NULL
  • || with a NULL part makes the whole string NULL
  • COALESCE replaces NULL with a default
  • CONCAT_WS skips NULLs and handles separators

Common mistakes

  • Building full names with || on nullable columns
  • Assuming CONCAT ignores NULLs on every engine

Follow-ups

  • How do aggregate functions treat NULL compared with operators?
  • How would you show 'N/A' for a missing phone number?

Tips

  • Use the name example; it is the version you will meet in real code
34.sql-0034Easyfresher

Explain COALESCE, IFNULL and NULLIF with an example of each.

COALESCE(a, b, c) returns the first argument that is not NULL, and it is standard SQL. IFNULL(a, b) is a two-argument version found in SQLite and MySQL; SQL Server calls it ISNULL. NULLIF(a, b) does the reverse job: it returns NULL when a equals b, and a otherwise, which is handy for turning placeholder values such as 0 or '' into NULL.

Full answer

These three functions convert between NULL and real values.

COALESCE walks its arguments left to right and returns the first non-NULL one. A contact table where people may give a mobile, a home phone or neither:

sql
CREATE TABLE contacts (name TEXT, mobile TEXT, home TEXT);
INSERT INTO contacts VALUES ('Ana','555-0101',NULL),('Ben',NULL,'555-0199'),('Chen',NULL,''),('Dara',NULL,NULL);
sql
SELECT name, COALESCE(mobile, home, 'no phone') AS best_phone FROM contacts ORDER BY name;
namebest_phone
Ana555-0101
Ben555-0199
Chen''
Darano phone

IFNULL(a, b) is a two-argument shortcut in SQLite and MySQL, the same as COALESCE(a, b). SQL Server's version is ISNULL(a, b), and Oracle's is NVL(a, b). Prefer COALESCE in portable code.

sql
SELECT name, IFNULL(mobile, 'no mobile') AS mobile FROM contacts ORDER BY name;
namemobile
Ana555-0101
Benno mobile
Chenno mobile
Darano mobile

NULLIF(a, b) goes the other way. If a = b it returns NULL, otherwise it returns a. Its classic use is cleaning values that mean "nothing" but were stored as something:

sql
SELECT name,
       COALESCE(mobile, home, 'no phone')               AS without_nullif,
       COALESCE(mobile, NULLIF(home, ''), 'no phone')   AS with_nullif
FROM contacts
ORDER BY name;
namewithout_nullifwith_nullif
Ana555-0101555-0101
Ben555-0199555-0199
Chen''no phone
Darano phoneno phone

Chen's empty home phone became NULL, so COALESCE could skip it. Without NULLIF, COALESCE('', 'no phone') returns the empty string, since an empty string is a value, not a NULL.

Another everyday use of NULLIF is guarding a division: total / NULLIF(count, 0) gives NULL instead of a division error when count is zero.

sql
CREATE TABLE contacts (name TEXT, mobile TEXT, home TEXT);
INSERT INTO contacts VALUES ('Ana','555-0101',NULL),('Ben',NULL,'555-0199'),('Chen',NULL,''),('Dara',NULL,NULL);

SELECT name, COALESCE(mobile, home, 'no phone') AS best_phone FROM contacts ORDER BY name;

SELECT name, IFNULL(mobile, 'no mobile') AS mobile FROM contacts ORDER BY name;

SELECT name,
       COALESCE(mobile, home, 'no phone')               AS without_nullif,
       COALESCE(mobile, NULLIF(home, ''), 'no phone')   AS with_nullif
FROM contacts
ORDER BY name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • COALESCE returns the first non-NULL argument and takes any number of arguments
  • IFNULL, ISNULL and NVL are two-argument vendor versions
  • NULLIF(a, b) returns NULL when a = b
  • NULLIF(x, '') then COALESCE handles empty strings

Common mistakes

  • Expecting COALESCE to skip empty strings
  • Using vendor-specific ISNULL or NVL in code meant to be portable

Follow-ups

  • How would you protect a percentage calculation from division by zero?
  • Does COALESCE evaluate every argument?

Tips

  • Pair NULLIF with COALESCE in your example to show both directions
35.sql-0035Mediummid

How do you avoid a division-by-zero problem when computing a ratio such as revenue per order?

Divide by NULLIF(denominator, 0), which turns a zero denominator into NULL so the result is NULL rather than an error. Wrap the result in COALESCE if a default such as 0 is wanted. Engines differ when no guard is used: PostgreSQL raises a division by zero error, while SQLite silently returns NULL.

Full answer

A per-day report divides revenue by the number of orders. On a day with no orders, the denominator is zero.

PostgreSQL stops the whole query:

sql
CREATE TABLE day_stats (day TEXT PRIMARY KEY, revenue INTEGER, orders INTEGER);
INSERT INTO day_stats VALUES ('2026-03-01', 310, 4), ('2026-03-02', 0, 0), ('2026-03-03', 250, 3);
sql
SELECT day, revenue / orders AS per_order FROM day_stats ORDER BY day;  -- error on purpose
text
Error: division by zero

SQLite does not raise an error. It returns NULL for any division by zero:

sql
SELECT day, revenue / orders AS per_order FROM day_stats ORDER BY day;
dayper_order
2026-03-0177
2026-03-02NULL
2026-03-0383

Relying on that SQLite behaviour is risky, because the same query fails after a move to PostgreSQL. NULLIF makes the intent explicit on every engine:

sql
SELECT day,
       ROUND(1.0 * revenue / NULLIF(orders, 0), 2) AS per_order
FROM day_stats
ORDER BY day;
dayper_order
2026-03-0177.5
2026-03-02NULL
2026-03-0383.33

PostgreSQL accepts the guarded query:

sql
SELECT day,
       ROUND(1.0 * revenue / NULLIF(orders, 0), 2) AS per_order
FROM day_stats
ORDER BY day;
dayper_order
2026-03-0177.50
2026-03-02NULL
2026-03-0383.33

Whether the result for an empty day should be NULL or 0 is a product decision. NULL says "not defined". A 0 says "nothing earned per order", which can mislead a chart. If the dashboard needs a number, add COALESCE(..., 0) on the outside, and label it clearly.

Compare the first SQLite result with the guarded one. Without 1.0 *, integer division truncated 77.5 to 77 and 83.33 to 83 before anyone noticed.

sql
CREATE TABLE day_stats (day TEXT PRIMARY KEY, revenue INTEGER, orders INTEGER);
INSERT INTO day_stats VALUES ('2026-03-01', 310, 4), ('2026-03-02', 0, 0), ('2026-03-03', 250, 3);

SELECT day, revenue / orders AS per_order FROM day_stats ORDER BY day;

SELECT day,
       ROUND(1.0 * revenue / NULLIF(orders, 0), 2) AS per_order
FROM day_stats
ORDER BY day;

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

Key points

  • x / NULLIF(y, 0) returns NULL instead of failing
  • PostgreSQL raises an error on division by zero; SQLite returns NULL
  • COALESCE outside the division supplies a default if needed
  • Watch for integer division in the same expression

Common mistakes

  • Testing on SQLite, where division by zero is silent, and failing in production
  • Defaulting undefined ratios to 0 without telling the reader

Follow-ups

  • How would you compute conversion rate per campaign with zero visits on some days?
  • Why does showing NULL instead of 0 matter on a dashboard?

Tips

  • Mention the engine difference; it shows you have moved queries between databases
36.sql-0036Mediummid

How do you compare two nullable columns so that NULL equals NULL? Explain IS DISTINCT FROM.

Plain = returns UNKNOWN when either side is NULL. The standard null-safe operators are IS DISTINCT FROM and IS NOT DISTINCT FROM, which treat two NULLs as equal and NULL versus a value as different, always returning true or false. SQLite also accepts IS and IS NOT for the same purpose, and MySQL uses <=>.

Full answer

A sync job compares the city stored in two systems to find changed rows. Some cities are missing in both.

sql
CREATE TABLE city_sync (id INTEGER PRIMARY KEY, old_city TEXT, new_city TEXT);
INSERT INTO city_sync VALUES (1,'Pune','Pune'),(2,'Pune','Delhi'),(3,NULL,'Leeds'),(4,NULL,NULL);
sql
SELECT id, old_city, new_city, old_city <> new_city AS changed_plain
FROM city_sync ORDER BY id;
idold_citynew_citychanged_plain
1PunePune0
2PuneDelhi1
3NULLLeedsNULL
4NULLNULLNULL

With <>, a pair where one side is NULL produces UNKNOWN, so the change from NULL to 'Leeds' is not reported. A pair where both are NULL is also UNKNOWN rather than "same".

The null-safe operator fixes both cases:

sql
SELECT id, old_city, new_city,
       old_city IS DISTINCT FROM new_city AS changed
FROM city_sync ORDER BY id;
idold_citynew_citychanged
1PunePune0
2PuneDelhi1
3NULLLeeds1
4NULLNULL0

IS DISTINCT FROM returns TRUE when the values differ (including NULL versus a value) and FALSE when they are the same (including NULL versus NULL). It never returns UNKNOWN. PostgreSQL supports it, and SQLite has accepted it since 3.39. SQLite's own shorter form a IS NOT b means the same thing.

PostgreSQL agrees:

sql
SELECT id, old_city IS DISTINCT FROM new_city AS changed FROM city_sync ORDER BY id;
idchanged
1false
2true
3true
4false

MySQL spells null-safe equality as a <=> b (from its documentation, not run here).

A caution for joins: on PostgreSQL, IS NOT DISTINCT FROM as a join condition generally cannot use a plain B-tree index the way = can. For change detection over a whole table that rarely matters; for joins on large tables, check the plan.

sql
CREATE TABLE city_sync (id INTEGER PRIMARY KEY, old_city TEXT, new_city TEXT);
INSERT INTO city_sync VALUES (1,'Pune','Pune'),(2,'Pune','Delhi'),(3,NULL,'Leeds'),(4,NULL,NULL);

SELECT id, old_city, new_city, old_city <> new_city AS changed_plain
FROM city_sync ORDER BY id;

SELECT id, old_city, new_city,
       old_city IS DISTINCT FROM new_city AS changed
FROM city_sync 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

  • = and <> return UNKNOWN when either side is NULL
  • IS DISTINCT FROM treats NULL as a comparable value
  • SQLite also has IS and IS NOT; MySQL has <=>
  • Useful for change detection between nullable columns

Common mistakes

  • Missing a change from NULL to a value because <> returned UNKNOWN
  • Writing (a <> b OR a IS NULL OR b IS NULL), which reports NULL versus NULL as a change

Follow-ups

  • How would you write the same comparison on an engine without IS DISTINCT FROM?
  • Can IS NOT DISTINCT FROM use an index?

Tips

  • Use the change-detection example; it is where this operator matters most
37.sql-0037Mediummid

Can a column with a UNIQUE constraint hold more than one NULL?

In SQLite, PostgreSQL, MySQL and Oracle, yes: NULLs are not considered equal to each other, so many rows can have NULL in a unique column. SQL Server is the exception and allows only one NULL in a unique constraint. PostgreSQL 15 and later can declare UNIQUE NULLS NOT DISTINCT to allow only one NULL.

Full answer

A unique constraint says no two rows may have equal values. Since NULL = NULL is not true, two NULLs do not violate it on most engines.

A student registry with an optional national ID:

sql
CREATE TABLE registry (id INTEGER PRIMARY KEY, name TEXT, national_id TEXT UNIQUE);
sql
INSERT INTO registry (name, national_id) VALUES ('Ana', NULL), ('Ben', NULL), ('Chen', 'X-77');
SELECT name, national_id FROM registry ORDER BY id;
namenational_id
AnaNULL
BenNULL
ChenX-77

Two students without an ID are accepted. A repeated real value is not:

sql
INSERT INTO registry (name, national_id) VALUES ('Dara', 'X-77');  -- error on purpose
text
Error: UNIQUE constraint failed: registry.national_id

PostgreSQL behaves the same by default. From version 15 you can choose the other rule, and then a second NULL is rejected:

sql
INSERT INTO registry2 VALUES (1, NULL);
INSERT INTO registry2 VALUES (2, NULL);
-- error on purpose
text
Error: duplicate key value violates unique constraint "registry2_national_id_key"

SQL Server's unique constraints treat NULLs as equal and allow only one NULL; a filtered unique index (WHERE col IS NOT NULL) is the usual workaround there. That comes from SQL Server documentation and was not run here.

For a multi-column unique constraint such as (email, deleted_at), the same rule means any row with NULL in either column escapes the check. That is a common way soft-delete designs accidentally allow duplicate active emails. A partial unique index on active rows only is a cleaner design.

sql
CREATE TABLE registry (id INTEGER PRIMARY KEY, name TEXT, national_id TEXT UNIQUE);

INSERT INTO registry (name, national_id) VALUES ('Ana', NULL), ('Ben', NULL), ('Chen', 'X-77');
SELECT name, national_id FROM registry ORDER BY id;

-- error on purpose
INSERT INTO registry (name, national_id) VALUES ('Dara', 'X-77');

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

Key points

  • Most engines allow many NULLs in a UNIQUE column
  • SQL Server allows only one NULL in a unique constraint
  • PostgreSQL 15+ offers UNIQUE NULLS NOT DISTINCT
  • NULLs in multi-column unique keys let duplicates slip through

Common mistakes

  • Using a nullable column in a composite unique key and expecting full protection
  • Assuming SQL Server rules apply to PostgreSQL or the reverse

Follow-ups

  • How would you enforce one active email per user with soft deletes?
  • What is a partial index?

Tips

  • Name the SQL Server exception; interviewers often test exactly that
38.sql-0038Easyfresher

How are NULLs treated by GROUP BY? What does a query grouping employees by department return for employees without a department?

GROUP BY puts all NULLs into one group, even though NULL = NULL is not true in a WHERE clause. So employees with no department appear together in a single row whose department value is NULL. Label it with COALESCE if the report needs a readable name.

Full answer

For grouping, SQL treats NULLs as "not distinct" from each other, the same rule DISTINCT uses. All rows with a NULL key land in one group.

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 people
FROM employees
GROUP BY dept_id
ORDER BY dept_id;
dept_idpeople
NULL1
13
22
32

Lena has no department, so she forms a group of one with dept_id NULL. If more employees lacked a department, they would all be counted in that same row, not split into separate groups.

Reports usually want a readable label. Group by the raw key and label it in the select list:

sql
SELECT COALESCE(CAST(dept_id AS TEXT), 'Unassigned') AS dept, COUNT(*) AS people
FROM employees
GROUP BY dept_id
ORDER BY dept_id;
deptpeople
Unassigned1
13
22
32

Grouping by the label instead would be risky: if a real department were ever named 'Unassigned', the two would merge into one row.

Joining to departments changes things in a different way. An inner join drops Lena entirely, because her NULL dept_id matches no department. A LEFT JOIN keeps her, with a NULL department name.

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 people
FROM employees
GROUP BY dept_id
ORDER BY dept_id;

SELECT COALESCE(CAST(dept_id AS TEXT), 'Unassigned') AS dept, COUNT(*) AS people
FROM employees
GROUP BY dept_id
ORDER BY dept_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • GROUP BY collects all NULL keys into one group
  • This differs from = in WHERE, where NULL never equals NULL
  • Use COALESCE to label the NULL group
  • An inner join to the lookup table drops NULL-key rows

Common mistakes

  • Expecting each NULL to form its own group
  • Losing the NULL group by inner joining to a lookup table

Follow-ups

  • How would you put the NULL group last in the report?
  • What does COUNT(dept_id) show for that group?

Tips

  • Compare the rule with WHERE explicitly; that contrast is the point of the question
39.sql-0039Mediummid

Why does CASE x WHEN NULL THEN 'missing' END never return 'missing'?

The simple CASE form compares with =, so WHEN NULL means x = NULL, which is UNKNOWN and never matches. Use the searched form, CASE WHEN x IS NULL THEN 'missing' ... END, or COALESCE.

Full answer

There are two ways to write CASE. The simple form compares one expression against several values:

text
CASE x WHEN 1 THEN 'one' WHEN 2 THEN 'two' END

Each WHEN is checked as x = value. When the value is NULL, the check is x = NULL, which is never true:

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,
       CASE city WHEN NULL THEN 'missing' ELSE 'has city' END AS label
FROM students
ORDER BY name;
namelabel
Ashahas city
Benhas city
Chenhas city
Darahas city
Elihas city

Dara's city is NULL, yet the label fell through to the ELSE branch. The searched form takes a full condition in each WHEN, so it can use IS NULL:

sql
SELECT name,
       CASE WHEN city IS NULL THEN 'missing'
            WHEN city = 'Pune' THEN 'local'
            ELSE 'outstation'
       END AS label
FROM students
ORDER BY name;
namelabel
Ashalocal
Benoutstation
Chenlocal
Daramissing
Elioutstation

Order matters in the searched form: the first true condition wins. Putting the NULL check first is a good habit, so later conditions can assume a value exists. For a plain "show this instead of NULL", COALESCE is shorter: COALESCE(city, 'missing').

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,
       CASE city WHEN NULL THEN 'missing' ELSE 'has city' END AS label
FROM students
ORDER BY name;

SELECT name,
       CASE WHEN city IS NULL THEN 'missing'
            WHEN city = 'Pune' THEN 'local'
            ELSE 'outstation'
       END AS label
FROM students
ORDER BY name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Simple CASE uses = for each WHEN
  • WHEN NULL can never match
  • Use the searched form with IS NULL
  • The first true WHEN wins, so check NULL first

Common mistakes

  • Writing CASE col WHEN NULL and getting the ELSE value
  • Forgetting an ELSE and getting NULL for unmatched rows

Follow-ups

  • What does CASE return when no WHEN matches and there is no ELSE?
  • Rewrite the query with COALESCE.

Tips

  • Name the two forms of CASE before explaining the bug
40.sql-0040Mediummid

What do SUM and COUNT return over zero rows, and how do you make a total show 0 instead of NULL?

COUNT over zero rows returns 0, but SUM, AVG, MIN and MAX return NULL, because there is nothing to add. Wrap the sum in COALESCE(SUM(x), 0) when a zero is the right answer. SQLite also has TOTAL(), which returns 0.0 for an empty set.

Full answer

An aggregate without GROUP BY always returns exactly one row, even when no input rows match. What goes in that row differs by function:

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

COUNT says zero rows matched. SUM says "no values to add", which SQL represents as NULL. That surprises people who expect the sum of nothing to be zero, and it shows up as a blank on dashboards or as a NULL that breaks later arithmetic.

When zero is the correct business answer, say so:

sql
SELECT COALESCE(SUM(qty), 0) AS total_qty, TOTAL(qty) AS sqlite_total
FROM order_items
WHERE product = 'Laptop';
total_qtysqlite_total
00.0

SQLite has an extra aggregate, TOTAL(), which behaves like SUM but returns 0.0 for an empty set and always returns a floating-point number.

With GROUP BY, an empty input gives no rows at all, not a row of zeros. To show every customer with a 0 count, start from the customers table and LEFT JOIN orders:

sql
SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
nameorders
Ana2
Bilal2
Chloe1
Dev0

Dev appears with 0 only because the query starts from customers. Grouping the orders table alone could never produce a row for him.

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 COUNT(*) AS n, SUM(qty) AS total_qty, MAX(qty) AS biggest
FROM order_items
WHERE product = 'Laptop';

SELECT COALESCE(SUM(qty), 0) AS total_qty, TOTAL(qty) AS sqlite_total
FROM order_items
WHERE product = 'Laptop';

SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • COUNT of no rows is 0
  • SUM, AVG, MIN, MAX of no rows are NULL
  • COALESCE(SUM(x), 0) when zero is meaningful
  • GROUP BY over no rows returns no rows; LEFT JOIN from the parent table to show zeros

Common mistakes

  • Adding NULL from an empty SUM to another number and getting NULL
  • Expecting GROUP BY to produce rows for groups that have no data

Follow-ups

  • What does AVG return over an empty set?
  • How would you list every month of the year with its revenue, including months with none?

Tips

  • Show the LEFT JOIN version; the empty-group case is the follow-up interviewers ask