QA Interview Hub · Knowledge base · Quizzes · Українська

SQL

Interview tasks

write the query

Task: find the second highest salary.

The second highest salary is usually the second largest distinct value, so the condition is clarified first. The simplest way is the maximum among values below the overall maximum. The LIMIT 1 OFFSET 1 variant counts rows, not values, so it needs DISTINCT and NULL filtering (in PostgreSQL NULL comes first under DESC). For the Nth highest, DENSE_RANK fits.

SQL · Tasks

Two people share the top salary. Which one is then the "second highest"?

In an interview you get an employees table and are asked for the second highest salary. The candidate writes ORDER BY salary DESC LIMIT 1 OFFSET 1, the query runs and returns a number. The number is wrong. This lesson shows how to take such a task apart: clarify the condition, pick an approach and check it on data with repeats and NULL.

namesalary
Anna300
Bohdan300
Olha250
Ivan200
KaterynaNULL

What to clarify first. "Second highest" reads in two ways: the second value (250 is expected) or the second row of the list (300, because Bohdan also earns the maximum). Usually the unique value is meant, but say it out loud. Two more questions: what to return when there is no second one (a row with NULL or an empty result) and whether the column may hold NULL.

How it works and why. The three approaches answer the question differently. The subquery looks for "the highest among those below the maximum": repeats of the maximum do not interfere, because < drops every copy, and NULL gives UNKNOWN and falls out of the selection by itself. An aggregate without GROUP BY always returns one row, so when no row qualifies MAX gives NULL. OFFSET works with rows, not values: it sorts and skips N rows, so repeats must be removed with DISTINCT before the skip. DENSE_RANK numbers values without gaps, equal salaries get one rank, so "the N-th" becomes dr = N.

There is also a trap that depends on the DBMS. In PostgreSQL, with DESC NULL values come first by default (NULLS FIRST); in MySQL NULL counts as the smallest and ends up last. The same query can therefore give different answers on different databases.

Example: from a wrong answer to the fix. The initial query:

SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
-- 300

Diagnosis: in PostgreSQL the sorted list looks like NULL, 300, 300, 250, 200. OFFSET 1 skips NULL and LIMIT 1 takes the next row, i.e. 300. There are two defects: NULL comes first and the repeated maximum takes second place.

How OFFSET 1 skips and cuts rows

No DISTINCT, NULL first
№salary
1NULL OFFSET
2300
3300 LIMIT
4250 LIMIT
5200 LIMIT
With DISTINCT and IS NOT NULL
№salary
1300 OFFSET
2250
3200 LIMIT
Figure 1. The surviving row is the answer. On the left it is 300: the second row of the list, not the second value. On the right it is 250.

Fixed variants (on this data all return 250):

-- 1. subquery
SELECT MAX(salary) AS second_max
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- 250

-- 2. DISTINCT + OFFSET
SELECT DISTINCT salary
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
-- 250

-- 3. DENSE_RANK: change dr = N for the N-th
WITH r AS (
  SELECT salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS dr
  FROM employees
  WHERE salary IS NOT NULL
)
SELECT DISTINCT salary FROM r WHERE dr = 2;
-- 250

Why these fixes. DISTINCT turns a list of rows into a list of values, IS NOT NULL removes NULL before sorting (the alternative is ORDER BY salary DESC NULLS LAST). Without either fix the answer stays 300.

Limits and alternatives. When there is no second salary (all equal, or just one), the subquery returns one row with NULL, while variants 2 and 3 return an empty result. A test that expects NULL fails on an empty set. To always get one row, wrap the query in a scalar subquery: with no rows it yields NULL.

-- always one row, even when there is no second salary
SELECT (
  SELECT DISTINCT salary
  FROM employees
  WHERE salary IS NOT NULL
  ORDER BY salary DESC
  LIMIT 1 OFFSET 1
) AS second_max;

The DENSE_RANK variant is costlier because it ranks the whole table, but it generalises best: the third highest is dr = 3, and it works per group with PARTITION BY. For the highest or the second highest a subquery is enough. SQL Server uses OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY instead of LIMIT.

Common mistakes.

  • OFFSET 1 without DISTINCT: the second row instead of the second value when the maximum repeats.
  • Ignoring NULL: in PostgreSQL it takes first place under DESC and shifts everything.
  • MAX(salary) - 1 and similar tricks: they only work on lucky data.
  • Not agreeing on the result when there is no second salary: the test expects NULL, the query returns zero rows.

Check yourself

The table has three rows with salary = 100. What do variants 1, 2 and 3 return?

Answer

Variant 1 returns one row with NULL (an aggregate without GROUP BY always yields a row, and salary < 100 selected nobody). Variants 2 and 3 return an empty result: after DISTINCT one value is left, nothing to skip and take. Agree what counts as the right answer.

In PostgreSQL SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 returned NULL on our table. Why is it not the maximum?

Answer

For DESC PostgreSQL puts NULL first by default. The first row of the sorted list is NULL, not 300. The fix: WHERE salary IS NOT NULL or NULLS LAST. The MAX aggregate ignores NULL, so it does not have this problem.

In an interview. Junior: First I ask whether a repeat of the maximum counts. The simplest solution is the maximum salary among those below the overall maximum. The LIMIT and OFFSET variant needs DISTINCT, otherwise a repeated maximum gives a wrong answer. Middle/Senior: I also ask about NULL and what to return when there is no second salary: in PostgreSQL NULL comes first under DESC, and the subquery and OFFSET behave differently on an empty set. For the N-th highest I use DENSE_RANK, since it generalises and works inside groups.

Task: find duplicated emails.

Duplicate emails are found by grouping on a normalised value: GROUP BY LOWER(TRIM(email)) with HAVING COUNT(*) > 1. Normalisation is needed because addresses differing in case or whitespace are different for grouping. NULLs are excluded, since grouping collects them into one group and reports a false duplicate. The records themselves come from a window COUNT. Prevention is a unique index on the normalised expression, because UNIQUE(email) does not normalise case.

SQL · Tasks

The backend promises a unique email, yet the database holds several "identical" addresses. How to find them?

Email uniqueness is usually stated in the requirements, and this is where backends often slip: they compare strings literally or check "does it exist?" and only then insert. The interview task is simple: find the repeated emails. On real data, though, the simple query misses part of the duplicates and adds a spurious row.

idemail
1anna@test.com
2Anna@test.com
3'anna@test.com ' (trailing space)
4oleh@test.com
5oleh@test.com
6maria@test.com
7NULL
8NULL

How it works and why. GROUP BY email collects rows with the same value into one group, and HAVING COUNT(*) > 1 keeps the groups with more than one row. A condition on a group cannot go in WHERE: that works on single rows before grouping. The key word is "same": for grouping, rows with a different case or whitespace are different, while all NULLs land in one group (for grouping NULLs count as equal, although NULL = NULL gives UNKNOWN).

Example: from the literal query to the normalised one.

SELECT email, COUNT(*) AS cnt
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
-- oleh@test.com | 2
-- NULL          | 2

Diagnosis: anna@test.com, Anna@test.com and the record with a trailing space are three different values for grouping, so none reached the "more than one" threshold. Meanwhile two empty emails formed a NULL group, and it looks like a duplicate. For a required field that is a separate defect; for an optional field it is normal.

SELECT LOWER(TRIM(email)) AS email_norm, COUNT(*) AS cnt
FROM users
WHERE email IS NOT NULL
GROUP BY LOWER(TRIM(email))
HAVING COUNT(*) > 1;
-- anna@test.com | 3
-- oleh@test.com | 2

What each of the two queries sees

GROUP BY email
emailcnt
oleh@test.com2
NULL2
LOWER(TRIM) + NOT NULL
emailcnt
anna@test.com3
oleh@test.com2
Figure 1. The literal query misses anna (three records, none matching byte for byte) and shows NULL as a "duplicate". The normalised one sees both real groups.

To see the records themselves, not just the values, use a window count: it adds the count to every row, and an outer query filters the groups.

SELECT id, email
FROM (
  SELECT id, email,
         COUNT(*) OVER (PARTITION BY LOWER(TRIM(email))) AS n
  FROM users
  WHERE email IS NOT NULL
) x
WHERE n > 1
ORDER BY LOWER(TRIM(email)), id;
-- ids 1, 2, 3 (anna) and 4, 5 (oleh)

Limits and alternatives. In PostgreSQL TRIM removes only spaces by default, not tabs and non-breaking spaces: catch those separately with a regular expression or REGEXP_REPLACE. What counts as a duplicate is a product rule: whether addresses that differ in the case of the local part are the same, and whether a +tag makes another address. Found duplicates are a symptom; prevention lives in the database: a unique index over the normalised expression (CREATE UNIQUE INDEX … ON users (LOWER(email))). A plain UNIQUE(email) does not normalise the case and allows several NULLs.

Common mistakes.

  • Grouping by the raw email: duplicates that differ in case or whitespace stay unnoticed.
  • Without IS NOT NULL: empty emails form a NULL "duplicate".
  • WHERE COUNT(*) > 1 instead of HAVING: the query fails with an error.
  • Counting duplicates as the COUNT(*) of groups: a group of three records has two extra, not three.

Check yourself

Why does GROUP BY email HAVING COUNT(*) > 1 return a row where the email is NULL, and is it always a bug?

Answer

For grouping all NULLs fall into one group, so two empty emails give a "duplicate". It is a bug only if the field is required. If an empty email is allowed, exclude NULL with WHERE email IS NOT NULL.

The table has UNIQUE(email). Can it hold both Anna@test.com and anna@test.com?

Answer

Yes: in PostgreSQL string comparison is case-sensitive, so these are different values. Case-insensitive uniqueness needs a unique index on LOWER(email) or the citext type. A registration test with a different case exposes this defect.

In an interview. Junior: I group by email and keep the groups where the count is greater than one, using HAVING. Middle/Senior: As QA I normalise the values with LOWER and TRIM, because the backend uniqueness check often compares strings literally. I exclude NULL to avoid a false duplicate and look at the records themselves with a window COUNT. And I suggest enforcing the rule with a unique index over the normalised expression.

Task: find users who have no accounts at all.

Users with no accounts are found with NOT EXISTS or a LEFT JOIN that checks the right table's key for NULL, not with NOT IN. If the subquery contains a NULL, NOT IN returns zero rows without any error, because a comparison with NULL gives UNKNOWN. A condition on the right side, such as an active account, goes into ON or inside NOT EXISTS, not into WHERE.

SQL · Tasks

The query "users with no account" returns zero rows, yet such users exist. What is wrong?

This is a task about absence: we look for what is missing in another table. The natural thought "take the ids that are not among the accounts" leads to NOT IN. It works while the subquery has no NULL, and on real data with an orphan account that has no owner it returns an empty result without any error. The lesson shows three correct ways and why the fourth is dangerous.

users.idname
1Anna
2Bohdan
3Olha
accounts.iduser_id
101
111
123
13NULL

How it works and why. LEFT JOIN with a NULL check (anti-join): the left table is kept in full, and for a user with no match the account columns are filled with NULL. The filter WHERE a.id IS NULL keeps exactly those rows. The checked column must be one that is never NULL in a real match, i.e. the primary key of the right table. NOT EXISTS asks for each user whether at least one account exists, and handles the three logical values safely. The PostgreSQL planner runs NOT EXISTS as an anti-join. It turns LEFT JOIN … IS NULL into an anti-join when the checked column comes from the ON condition (a.user_id), and since version 19 also a NOT NULL column such as the primary key; on older versions checking a.id leaves an ordinary LEFT JOIN with a filter. On small tables the difference is invisible; on big ones EXPLAIN shows it.

LEFT JOIN keeps everyone, WHERE drops the rest

After LEFT JOIN
u.idnamea.id
1Anna10 dropped
1Anna11 dropped
2BohdanNULL
3Olha12 dropped
After WHERE a.id IS NULL
idname
2Bohdan
Figure 1. A user with no match gets NULL in the account columns, and WHERE finds him by exactly that.
SELECT u.id, u.name
FROM users u
LEFT JOIN accounts a ON a.user_id = u.id
WHERE a.id IS NULL;
-- 2 | Bohdan

SELECT u.id, u.name
FROM users u
WHERE NOT EXISTS (
  SELECT 1 FROM accounts a WHERE a.user_id = u.id
);
-- 2 | Bohdan

Example: why NOT IN stays silent.

SELECT id, name
FROM users
WHERE id NOT IN (SELECT user_id FROM accounts);
-- 0 rows, while Bohdan was expected

SELECT COUNT(*) FROM accounts WHERE user_id IS NULL;
-- 1

Diagnosis: the subquery contains NULL (account 13 with no owner). The condition id NOT IN (1, 1, 3, NULL) expands to id <> 1 AND id <> 1 AND id <> 3 AND id <> NULL. The last term gives UNKNOWN for every id, so the whole expression never becomes true. The fix is NOT EXISTS or LEFT JOIN … IS NULL, or NOT IN with a filtered subquery (WHERE user_id IS NOT NULL). The ownerless account itself is a bug-report finding if user_id was supposed to be required.

Limits and alternatives. If you need users with no active account, the status condition goes into ON (or inside NOT EXISTS), not into WHERE: in WHERE it turns the LEFT JOIN into an ordinary one. Another way is EXCEPT, for example SELECT id FROM users EXCEPT SELECT user_id FROM accounts. It treats NULLs as equal and has no NOT IN trap, but returns only the listed columns.

Common mistakes.

  • NOT IN over a subquery where NULL is possible: an empty result with no error.
  • INNER JOIN instead of LEFT JOIN: users with no match vanish before the filter.
  • Checking for NULL a column that can be NULL even in a real match: false findings.
  • A condition on the account in WHERE: the query stops finding the missing ones.

Check yourself

The query … LEFT JOIN accounts a ON a.user_id = u.id WHERE a.id IS NULL AND a.status = 'active' should find users without an active account. What does it return and why?

Answer

Nothing. For a user with no match a.status is NULL too, and NULL = 'active' gives UNKNOWN, so the row is dropped. Move a.status = 'active' into ON, and the anti-check a.id IS NULL then also finds those who have only closed accounts.

accounts has one row with user_id = NULL. Which form returns the correct result: NOT IN, NOT EXISTS or LEFT JOIN … IS NULL?

Answer

NOT EXISTS and LEFT JOIN … IS NULL are correct: the row with NULL simply matches no user. NOT IN returns zero rows.

In an interview. Junior: I LEFT JOIN users with accounts and take those whose account key is NULL. The alternative is NOT EXISTS. Middle/Senior: I do not use NOT IN: if the subquery returns a NULL, it yields zero rows without an error. Conditions on the right side (for example an active account) go into ON or into NOT EXISTS, not WHERE. An ownerless account is itself logged as a data defect.

Task: the top 3 users by the sum of completed deposits.

The top 3 by completed deposits comes from grouping by user, filtering type and status in WHERE, sorting the sum descending and LIMIT 3. Equal sums at the boundary are cut arbitrarily, so a second sort key is added, and RANK or WITH TIES shows all tied users. After every one-to-many JOIN the row count is watched, because sums get multiplied.

SQL · Tasks

Top 3 by deposits, and two users with the same sum share third place. Who gets shown?

The task combines almost all basic SQL: three tables, a filter by type and status, grouping, a sum, sorting and a limit. That is why interviewers watch whether the candidate keeps the order of query execution in mind and asks about equal sums. Below is a simplified sample of transactions after joining users, accounts and transactions.

usertypestatusamount
Annadepositcompleted300
Annadepositcompleted200
Annadepositfailed900
Annawithdrawalcompleted100
Bohdandepositcompleted400
Olhadepositcompleted300
Ivandepositcompleted300
Ivandepositpending50

How it works and why. First JOIN connects the rows, then WHERE drops transactions that are not completed deposits (the failed deposit of 900 and the withdrawal do not count), then GROUP BY builds the sum per user, ORDER BY sorts the groups and LIMIT takes the first three. The status filter sits in WHERE because it is a condition on a row, not on a group. The sums: Anna 500, Bohdan 400, Olha 300, Ivan 300 (the pending 50 is not included).

SELECT u.id, u.email, SUM(t.amount) AS total_deposits
FROM users u
JOIN accounts a     ON a.user_id = u.id
JOIN transactions t ON t.account_id = a.id
WHERE t.type = 'deposit' AND t.status = 'completed'
GROUP BY u.id, u.email
ORDER BY total_deposits DESC, u.id
LIMIT 3;

The same totals, two policies for ties

LIMIT 3
usertotal
Anna500
Bohdan400
Olha300
Ivan300 cut
RANK <= 3
usertotalrnk
Anna5001
Bohdan4002
Olha3003
Ivan3003
Figure 1. LIMIT 3 keeps exactly three rows, so the sort order decides which of the two with 300 gets cut. RANK returns both, because they share third place.

Example: what happens to ties. The query above returns Anna, Bohdan and Olha (Olha has a lower u.id than Ivan). Ivan has the same sum as Olha but is cut: LIMIT 3 knows nothing about equality, and the extra key u.id only makes the selection deterministic. Without it a different one of the two could stay on each run. If the requirement is to show everyone sharing third place, there are two ways.

-- 1. RANK over the totals
WITH s AS (
  SELECT u.id, u.email, SUM(t.amount) AS total_deposits
  FROM users u
  JOIN accounts a     ON a.user_id = u.id
  JOIN transactions t ON t.account_id = a.id
  WHERE t.type = 'deposit' AND t.status = 'completed'
  GROUP BY u.id, u.email
), r AS (
  SELECT *, RANK() OVER (ORDER BY total_deposits DESC) AS rnk
  FROM s
)
SELECT * FROM r WHERE rnk <= 3;

-- 2. PostgreSQL 13+: WITH TIES, no u.id in ORDER BY
-- ... ORDER BY total_deposits DESC
-- FETCH FIRST 3 ROWS WITH TIES;

WITH TIES judges equality by the ORDER BY columns: if you add u.id there, there are no ties any more and the result is three rows again. Both variants return four rows on our sample.

Limits and alternatives. Users with no completed deposit are not in the result: that follows from the INNER JOIN and the filter. To see them with zero you need a LEFT JOIN with the conditions in ON. Sums in different currencies must not be added: group by currency as well. The most dangerous case is one more join to another one-to-many table (for example the user's cards): each transaction multiplies by the number of cards and the sums come out inflated.

Common mistakes.

  • LIMIT 3 without a second sort key: with equal sums the result floats between runs.
  • No status filter: failed and pending payments get into the sum (and a condition on t.status in HAVING without an aggregate fails, because the column is not in GROUP BY).
  • An extra one-to-many join: the sums multiply.
  • Sorting by SUM without DESC: the top turns into the "smallest".

Check yourself

A JOIN cards c ON c.user_id = u.id was added to the query, and Anna has two cards. What happens to Anna's total_deposits?

Answer

Each of her deposits joins with both cards, so there are twice as many rows and the sum becomes 1000 instead of 500. This is a fan-out: after every one-to-many JOIN the row count must be checked. Cards are not needed in this task, so the join should go.

Why does FETCH FIRST 3 ROWS WITH TIES stop working if u.id is added to ORDER BY?

Answer

Equality is judged over all ORDER BY columns. With a unique u.id no two rows are equal, so there are no ties and exactly three rows come back.

In an interview. Junior: I join users, accounts and transactions, filter completed deposits in WHERE, group by user, sort by the sum in descending order and take three. Middle/Senior: I ask what to do with equal sums at the boundary: LIMIT cuts arbitrarily, so I add a second sort key, and if everyone tied must be shown I take RANK or WITH TIES. I watch the row count after every JOIN and the currencies.

Task: the number and sum of transactions by month.

Count and sum by month use grouping on DATE_TRUNC('month', created_at) with the status filter in WHERE. Grouping does not create groups absent from the data, so a month with no transactions disappears. To show it with zero, a calendar is generated and joined with LEFT JOIN with conditions in ON, counting COUNT(t.id). The report's time zone is agreed, because it shifts transactions at month boundaries.

SQL · Tasks

The quarterly report has no September. Did the month with no transactions simply vanish?

A "count and sum by month" report appears in every project with payments, and QA reconciles it with data from other sources. The interview task checks two things: whether the candidate can group time by a period and whether they know that grouping does not create groups that are absent from the data. The doubts here usually come from time zones and empty months.

idcreated_atamountstatus
12026-08-05100completed
22026-08-2050completed
32026-08-2570failed
42026-10-02200completed
52026-10-1530completed

How it works and why. DATE_TRUNC('month', created_at) truncates a point in time to the start of the month: every August date becomes 2026-08-01 00:00, and these values are equal, so they can be grouped. The filter status = 'completed' sits in WHERE and works before grouping. A group is built from rows that passed the filter, so a month with none does not appear in the result. This is not a DBMS bug but a property of grouping.

SELECT DATE_TRUNC('month', created_at)::date AS month,
       COUNT(*)    AS tx_count,
       SUM(amount) AS volume
FROM transactions
WHERE status = 'completed'
GROUP BY 1
ORDER BY 1;
-- 2026-08-01 | 2 | 150
-- 2026-10-01 | 2 | 230

In MySQL the counterpart is DATE_FORMAT(created_at, '%Y-%m'). August gives 2 and 150, because the failed transaction of 70 is filtered out. September is absent.

Example: align the report with a calendar. The months must be generated separately and the transactions joined to them with a LEFT JOIN. Conditions on the right side, including the status, go in ON: in WHERE they would drop the empty months and bring the same problem back. Count with COUNT(t.id), not COUNT(*): for an empty month COUNT(*) would give 1 (the one calendar row), while COUNT(t.id) gives 0.

SELECT m.month::date AS month,
       COUNT(t.id) AS tx_count,
       COALESCE(SUM(t.amount), 0) AS volume
FROM generate_series(timestamp '2026-08-01',
                     timestamp '2026-10-01',
                     interval '1 month') AS m(month)
LEFT JOIN transactions t
  ON t.created_at >= m.month
 AND t.created_at <  m.month + interval '1 month'
 AND t.status = 'completed'
GROUP BY m.month
ORDER BY m.month;
-- 2026-08-01 | 2 | 150
-- 2026-09-01 | 0 | 0
-- 2026-10-01 | 2 | 230

Groups exist only where rows exist

GROUP BY
monthcntvolume
2026-08-012150
2026-10-012230
Calendar + LEFT JOIN
monthcntvolume
2026-08-012150
2026-09-0100 added
2026-10-012230
Figure 1. September is not in the first result at all, rather than "with zero". A report reading it will skip the month silently.

COALESCE replaces the NULL sum of the empty month with zero. The month boundaries are a range [start; start + 1 month) rather than BETWEEN, so the last day is not lost.

Limits and alternatives. A typical source of mismatches with a report is the time zone. If created_at is timestamptz, DATE_TRUNC works in the session time zone. A transaction from 31 October 23:30 UTC in a session with the Europe/Kyiv zone (after daylight saving ends this is UTC+2) lands in November, while in UTC it stays in October. So agree which zone the report uses and set it explicitly: DATE_TRUNC('month', created_at AT TIME ZONE 'UTC'). On bigger tables grouping by an expression reads everything, so ranges over an indexed column are faster.

Common mistakes.

  • Assuming an empty month will appear: groups come only from existing rows.
  • A filter on the right table in WHERE after a LEFT JOIN: the empty months vanish again.
  • COUNT(*) instead of COUNT(t.id) in the aligned report: an empty month shows 1.
  • Not fixing the time zone: the sum on a month boundary differs from the report.

Check yourself

In the aligned query COUNT(t.id) was replaced with COUNT(*). What does September show?

Answer

A count of 1 instead of 0. For September the LEFT JOIN gives one row: the calendar row with NULL in the transaction columns. COUNT(*) counts rows, COUNT(t.id) only those where the id is not NULL.

A transaction was created at 2026-10-31 23:30 UTC, the column is timestamptz, the session zone is Europe/Kyiv. Which month does DATE_TRUNC('month', created_at) put it in?

Answer

In November: in Kyiv it is already 1 November 01:30 (UTC+2). If the report is computed in UTC, the transaction belongs to October. The zone must be fixed in the requirements and in the query.

In an interview. Junior: I truncate the date to the month with DATE_TRUNC, group by it and count the number and the sum. I put the status filter in WHERE. Middle/Senior: I point out that months without transactions will not appear: if they are needed with zeros, I generate a calendar with generate_series and attach it with a LEFT JOIN with the conditions in ON. I also ask which time zone the report is computed in.

Task: employees who earn more than their manager.

Employees who earn more than their manager are found with a self join: the table is taken twice under aliases and joined on m.id = e.manager_id. The filter e.salary > m.salary goes in WHERE. INNER JOIN fits, since an employee without a manager has nobody to compare with, and a NULL salary makes the comparison unknown. One result row is checked against the table, because a reversed join gives a plausible but wrong answer.

SQL · Tasks

The manager and the subordinate sit in the same table. How to compare their salaries?

In the employees table a manager is an employee too: the manager_id column points to the id of another row of the same table. To compare an employee's salary with the manager's, both rows must be in one row of the result. A self join does this: it joins the table to itself.

idnamesalarymanager_id
1Maria5000NULL
2Taras40001
3Olena45002
4Petro30002
5IrynaNULL2

How it works and why. One table is taken twice under different aliases: e plays the employee, m plays the manager. Without aliases the DBMS could not tell which of the two copies a column belongs to. The join condition m.id = e.manager_id reads as "the manager is the row whose id is stored in the employee's manager_id". The filter e.salary > m.salary sits in WHERE and works on the already joined pairs.

SELECT e.name AS employee, e.salary,
       m.name AS manager,  m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
-- Olena | 4500 | Taras | 4000

Self join, then WHERE

After JOIN
employeesalmanagermsal
Taras4000Maria5000
Olena4500Taras4000
Petro3000Taras4000
IrynaNULLTaras4000
After WHERE
employeesalmanagermsal
Olena4500Taras4000
Figure 1. Maria never entered the join: she has no manager. Iryna fell out at the comparison: NULL > 4000 is UNKNOWN.

INNER JOIN is appropriate here: an employee without a manager (Maria) cannot earn more than him, so losing that row is correct. A LEFT JOIN would be needed for another question: "show all employees and their managers' names where they exist".

Example: swapped keys. A typical self-join mistake is to swap the sides of the condition. The query below looks right, runs and returns two rows, but it answers a different question.

SELECT e.name AS employee, e.salary,
       m.name AS manager,  m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.manager_id = e.id   -- reversed
WHERE e.salary > m.salary;
-- Maria | 5000 | Taras | 4000
-- Taras | 4000 | Petro | 3000

Diagnosis: now e is the manager and m is his subordinate, but the columns are labelled "employee" and "manager". The result lists managers who earn more than their subordinates, which is the majority in any company, so it looks plausible. The check is simple: take one row of the result and look in the table whether the employee's manager_id really points to the named manager.

Limits and alternatives. The same can be written with a correlated subquery: WHERE e.salary > (SELECT m.salary FROM employees m WHERE m.id = e.manager_id). For an employee without a manager the subquery gives NULL and the row drops out the same way. A self join compares only with the direct manager. If the question is about any boss in the chain, recursion is needed: WITH RECURSIVE. NULL in salary makes the comparison unknown: an employee with an unspecified salary is not in the answer, and this is better said out loud than decided silently.

Common mistakes.

  • No aliases: an error "table name … specified more than once", and with an alias on only one copy, "column reference … is ambiguous".
  • A reversed join condition: a plausible result about managers instead of subordinates.
  • The condition e.manager_id = m.manager_id: comparison with colleagues, not with the manager.
  • LEFT JOIN without need: rows with a NULL manager salary drop out in WHERE anyway.

Check yourself

Why is Iryna (salary = NULL) not in the answer, and should she be added?

Answer

NULL > 4000 gives UNKNOWN, and WHERE keeps only true conditions. She should not be added: an unknown salary does not prove it is greater. But the very existence of an employee with no salary may be a data defect, and that is worth reporting separately.

What does the query with ON m.manager_id = e.id instead of ON m.id = e.manager_id return on our data?

Answer

Two pairs where "e" is actually the manager: Maria 5000 against Taras 4000 and Taras 4000 against Petro 3000. The pair Taras against Olena (4000 against 4500) fails the filter, and Iryna gives UNKNOWN. The result is wrong in meaning although not empty.

In an interview. Junior: It is a self join: I join the employees table to itself, where the manager is another row by manager_id, and compare the salaries. Middle/Senior: INNER JOIN fits here, because an employee without a manager cannot earn more than him, and a NULL salary gives an unknown comparison. After writing it I check one result row against the table to make sure the keys are not swapped. For an arbitrary chain of bosses I use WITH RECURSIVE.

Task: remove duplicates, leaving one record each.

Duplicates are removed by numbering rows within groups with ROW_NUMBER() OVER (PARTITION BY …) and deleting everything numbered above one. The group is the normalised email, and a tie-break order decides which record stays. NULLs are excluded, because they sit in one group. A SELECT with the same condition is reviewed first, the delete then runs in a transaction with RETURNING, and counts are compared. Child references move to the kept record.

SQL · Tasks

Duplicates must go, with one record each kept. How not to delete too much?

Finding duplicates is easy, deleting them safely is harder: DELETE has no undo button, and a mistake in the condition touches live data. So the task is solved in three steps: number the rows in the groups, look at what will be deleted, and only then delete inside a transaction.

idemailcreated_at
1anna@x.io2026-01-10
2Anna@x.io2026-02-01
3oleh@x.io2026-01-15
4anna@x.io2026-03-01
5maria@x.io2026-03-02

How it works and why. ROW_NUMBER() OVER (PARTITION BY … ORDER BY …) numbers the rows inside each group without reducing their count (unlike GROUP BY). The group is the normalised email, and the order decides who becomes first: here the oldest by created_at with a tie-break on id. The row with number 1 stays, all with a number above 1 are extra copies. The tie-break is needed so that with equal dates the choice does not depend on chance.

Numbering and what is left after DELETE

ROW_NUMBER
idemailrn
1anna@x.io1
2Anna@x.io2 delete
3oleh@x.io1
4anna@x.io3 delete
5maria@x.io1
users after DELETE
idemail
1anna@x.io
3oleh@x.io
5maria@x.io
Figure 1. Number 1 is the one we keep. The order created_at, id makes the choice deterministic: always the oldest record.

Example: the safe sequence. First look at what exactly will be deleted (a SELECT with the same condition) and count the rows. Then, inside a transaction, delete returning the deleted rows, reconcile the counters and commit.

BEGIN;

WITH ranked AS (
  SELECT id,
         ROW_NUMBER() OVER (
           PARTITION BY LOWER(TRIM(email))
           ORDER BY created_at, id
         ) AS rn
  FROM users
  WHERE email IS NOT NULL
)
DELETE FROM users
WHERE id IN (SELECT id FROM ranked WHERE rn > 1)
RETURNING id, email;
-- 2 | Anna@x.io
-- 4 | anna@x.io

SELECT COUNT(*) FROM users;   -- 3
COMMIT;                       -- or ROLLBACK

The filter WHERE email IS NOT NULL is mandatory: for PARTITION BY all NULLs sit in one group, and without the filter every row with an empty email except the first would be deleted. RETURNING shows the deleted rows at once, BEGIN … COMMIT allows a rollback if the count does not match. The count is checked twice: before (5) and after (3), and the difference equals the number of rows with rn > 1 (2).

Limits and alternatives. The biggest risk is child records. If accounts reference the duplicate, a foreign key without a cascade will refuse the delete, and with ON DELETE CASCADE the related data vanishes together with the duplicate. Before deleting, references are moved to the kept record.

UPDATE accounts a
SET user_id = k.keep_id
FROM (
  SELECT id,
         FIRST_VALUE(id) OVER (
           PARTITION BY LOWER(TRIM(email))
           ORDER BY created_at, id
         ) AS keep_id
  FROM users
  WHERE email IS NOT NULL
) k
WHERE a.user_id = k.id AND k.id <> k.keep_id;

A simpler alternative when "the oldest" coincides with "the lowest id": DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users WHERE email IS NOT NULL GROUP BY LOWER(TRIM(email))). NOT IN is safe here because MIN(id) is never NULL, but the query would also delete the rows with an empty email, so the outer filter is needed too. On a shared environment make a copy of the table before deleting (CREATE TABLE users_backup AS SELECT * FROM users). After the cleanup the rule is enforced with a unique index, otherwise duplicates come back.

Common mistakes.

  • DELETE without a preceding SELECT and without a transaction: the mistake cannot be rolled back.
  • Not filtering NULL: all empty emails except one disappear.
  • Numbering without a tie-break in ORDER BY: which of the equal ones stays is down to chance.
  • Ignoring child records: an FK error or cascading deletion of related data.

Check yourself

The table has two users with email NULL. What happens if WHERE email IS NOT NULL is removed from the ROW_NUMBER query?

Answer

For PARTITION BY all NULLs share one group, so the second and later users without an email get rn above 1 and are deleted, although they are not duplicates. The delete should touch only real matches.

Accounts with ON DELETE CASCADE reference the duplicate. What happens when the duplicate is deleted and how to avoid it?

Answer

The user's accounts vanish with him. Before deleting, the accounts' user_id must be moved to the kept record (UPDATE with FIRST_VALUE), and only then the duplicates are deleted.

In an interview. Junior: I number the rows in each duplicate group with ROW_NUMBER and PARTITION BY and delete everything with a number above one. First a SELECT of the same rows, and everything runs inside a transaction. Middle/Senior: I add a tie-break to ORDER BY, exclude NULL and look at child records: I move the references to the kept record, otherwise foreign keys refuse the delete or a cascade destroys related data. After cleanup I enforce uniqueness with an index.

Task: the percentage of failed transactions for each type.

The percentage of failed transactions per type uses conditional aggregation: failed over total, with 100.0 as the first factor. Integer division in PostgreSQL drops the fraction, so COUNT(*) FILTER (WHERE …) / COUNT(*) * 100.0 gives 0. The denominator is agreed (whether pending and NULL count), protected from zero with NULLIF, and the result checked against a manual count.

SQL · Tasks

The failed-transaction percentage came out as 0, although failed ones certainly exist. What went wrong?

The error percentage per operation type is a typical QA metric: it shows where the system breaks most often. The query consists of conditional aggregation and a division, and the division hides the trap. The test table holds 9 transactions: 4 deposits (1 failed), 3 withdrawals (1 failed), 2 transfers (none failed).

How it works and why. COUNT(*) FILTER (WHERE status = 'failed') counts only the rows of the group that satisfy the condition, while COUNT(*) counts all. Both return an integer (bigint). Dividing an integer by an integer in PostgreSQL gives an integer and drops the fraction, so 1 / 4 is 0. The order of operations matters too: an expression is evaluated left to right, so failed / total * 100.0 first divides integers (0), then multiplies zero by 100.0, and the answer is 0 for every type. For a fractional division the first factor must be a number with a decimal part: 100.0 * failed / total.

Example: from a truncated 33 to 33.33.

SELECT type,
       COUNT(*) AS total,
       COUNT(*) FILTER (WHERE status = 'failed') AS failed,
       COUNT(*) FILTER (WHERE status = 'failed') * 100 / COUNT(*) AS pct
FROM transactions
GROUP BY type
ORDER BY pct DESC;
-- withdrawal | 3 | 1 | 33
-- deposit    | 4 | 1 | 25
-- transfer   | 2 | 0 | 0

Diagnosis: the result looks plausible, and the error is masked by 25 and 0 being exactly right. Only the row with 33 for 1 out of 3 gives the truncation away. Checking against a manual calculation (1 of 3 is 33.33) shows the mismatch. The fix: the 100.0 factor first and rounding to the needed precision.

SELECT type,
       COUNT(*) AS total,
       COUNT(*) FILTER (WHERE status = 'failed') AS failed,
       ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'failed')
             / COUNT(*), 2) AS failed_pct
FROM transactions
GROUP BY type
ORDER BY failed_pct DESC;
-- withdrawal | 3 | 1 | 33.33
-- deposit    | 4 | 1 | 25.00
-- transfer   | 2 | 0 | 0.00

-- the same without FILTER (MySQL, SQL Server)
SELECT type,
       ROUND(AVG(CASE WHEN status = 'failed'
                      THEN 100.0 ELSE 0 END), 2) AS failed_pct
FROM transactions
GROUP BY type;

The same percentage, two ways to write it

failed * 100 / total
typetotalfailedpct
withdrawal3133
deposit4125
transfer200
100.0 * failed / total
typetotalfailedpct
withdrawal3133.33
deposit4125.00
transfer200.00
Figure 1. On the left integer division dropped the fraction: 33 instead of 33.33. Every row of the left table looks tidy, so the error is not visible.

Limits and alternatives. The AVG(CASE …) variant works where there is no FILTER: the average of 100 for failed and 0 for the rest equals the percentage of failed. The denominator here is all rows of the group, including NULL statuses. This is a decision about the metric, not about syntax: sometimes the percentage is counted only from final statuses (completed and failed), without pending, and then the denominator condition must be stated explicitly. If a group can be empty (for example a dictionary of types with transactions attached by LEFT JOIN), the denominator is zero and PostgreSQL raises "division by zero": wrap the denominator in NULLIF(COUNT(t.id), 0).

Common mistakes.

  • Dividing integers: the fraction disappears, and on small groups the percentage becomes 0.
  • failed / total * 100.0: the order of evaluation again puts the integer division first.
  • Counting the denominator only over filtered rows: WHERE status = 'failed' leaves only the failed, and the percentage is always 100.
  • Not agreeing whether pending and NULL belong in the denominator.

Check yourself

What does COUNT(*) FILTER (WHERE status = 'failed') / COUNT(*) * 100.0 return for the deposit type (1 of 4) and why?

Answer

0.0. First the integer division 1 / 4 runs and gives 0, then 0 * 100.0 gives 0.0. The multiplication by 100.0 comes too late. Put 100.0 as the first factor or cast to numeric.

In a types dictionary with a LEFT JOIN to transactions, the type "refund" has no transactions. What happens to the percentage and how to fix it?

Answer

The denominator COUNT(t.id) is 0 and division by zero raises an error. The fix: NULLIF(COUNT(t.id), 0) in the denominator, then the percentage for the empty type is NULL instead of an error.

In an interview. Junior: I group by type and count the total and the failed through FILTER or SUM with CASE, then divide. I multiply by 100.0 rather than 100, because dividing integers drops the fraction. Middle/Senior: I watch the order of evaluation: 100.0 must come first. I agree separately on the denominator (whether pending and NULL are included) and protect it against zero with NULLIF. I reconcile the result with a manual count on small groups.

Task: the employee with the highest salary in each department.

The highest salary with the name in each department comes from the window function RANK() with PARTITION BY department and a filter on rank 1. It is wrapped in a CTE or subquery, because it is not available in WHERE. RANK shows everyone sharing the maximum, while ROW_NUMBER with a tie-break or DISTINCT ON gives exactly one. In PostgreSQL NULL comes first under DESC, so NULLS LAST is needed.

SQL · Tasks

Not just the maximum value but the person's name is needed. Why is GROUP BY not enough here?

SELECT department, MAX(salary) FROM employees GROUP BY department returns the top salary in a department, but without a name. Adding name to the list does not work: the DBMS does not know whose name to show when it is not grouped. The task checks whether the candidate knows how to connect an aggregate with the row it came from. The sample data is below.

namedepartmentsalary
AnnaDev300
BohdanDev300
OlhaDev250
IvanQA280
KaterynaQANULL
PetroHRNULL

How it works and why. A window function RANK() OVER (PARTITION BY department ORDER BY salary DESC) numbers the rows inside a department and keeps them all, so the name stays available. Equal salaries get the same rank, so rnk = 1 returns everyone sharing the maximum. A window function cannot be placed in WHERE (it is computed after it), so it is wrapped in a CTE or a subquery and filtered outside. A JOIN with an aggregate first computes the department maximum, then finds the rows whose salary equals it. The result is the same, without window functions.

Example: when NULL stops being harmless. The classic form:

WITH r AS (
  SELECT name, department, salary,
         RANK() OVER (PARTITION BY department
                      ORDER BY salary DESC) AS rnk
  FROM employees
)
SELECT department, name, salary FROM r WHERE rnk = 1;

Diagnosis on our data in PostgreSQL: for DESC NULL comes first by default, so in QA first rank went to Kateryna with an empty salary, and Ivan with 280 got second and disappeared. It looks like a normal result until QA is checked against the table. The fix: ORDER BY salary DESC NULLS LAST or a WHERE salary IS NOT NULL filter.

RANK = 1: where NULL ends up first

Default DESC
deptnamesalary
DevAnna300
DevBohdan300
HRPetroNULL
QAKaterynaNULL wrong
DESC NULLS LAST
deptnamesalary
DevAnna300
DevBohdan300
HRPetroNULL
QAIvan280
Figure 1. In QA first place went to Kateryna with no salary, and Ivan disappeared from the result. HR shows the only employee, whose salary is unknown.

The NULLS LAST version also shows the HR department, where no salaries exist at all: the only employee with NULL. With an IS NOT NULL filter the HR department would drop out of the result. Which behaviour is right is for the requirement to decide, and it is worth saying aloud.

-- without window functions: everyone with the department maximum
SELECT e.department, e.name, e.salary
FROM employees e
JOIN (SELECT department, MAX(salary) AS max_salary
      FROM employees
      GROUP BY department) m
  ON m.department = e.department
 AND m.max_salary = e.salary;
-- Dev Anna 300, Dev Bohdan 300, QA Ivan 280

-- PostgreSQL: exactly one per department
SELECT DISTINCT ON (department) department, name, salary
FROM employees
ORDER BY department, salary DESC NULLS LAST, name;
-- Dev Anna 300, HR Petro NULL, QA Ivan 280

Limits and alternatives. The JOIN with an aggregate handles NULL correctly: MAX skips them, and in the HR department the maximum is NULL, so m.max_salary = e.salary finds nothing with NULL and HR disappears. ROW_NUMBER() instead of RANK() always gives exactly one of the equal ones (which one depends on the tie-break in ORDER BY). DISTINCT ON is PostgreSQL-specific: it keeps the first row of each group in ORDER BY order, and the name after the salary works as a tie-break. Of the three ways the window function is the most flexible: changing rnk = 1 to rnk <= 3 gives the top three.

Common mistakes.

  • SELECT name, MAX(salary) … GROUP BY department: an error, because name is not grouped.
  • Ignoring NULL in ORDER BY … DESC: in PostgreSQL NULL takes first place.
  • ROW_NUMBER where all the equal ones are needed: some people silently disappear.
  • A window function straight in WHERE: an error, a CTE or subquery is needed.

Check yourself

What does the RANK query without NULLS LAST return for the QA department on our data in PostgreSQL?

Answer

Kateryna with NULL: under DESC NULL comes first and gets rank 1. Ivan with 280 becomes second and is not in the result. The result is wrong although the query runs without error.

Exactly one person per department is needed, even if two share the maximum. How to do it?

Answer

Use ROW_NUMBER() with a tie-break in ORDER BY (for example by name) and take rn = 1, or DISTINCT ON (department) in PostgreSQL. The tie-break makes the choice reproducible.

In an interview. Junior: GROUP BY with MAX gives only the maximum salary, not the name, so I use the RANK window function partitioned by department and take rank one. An alternative without window functions is to join the table with a subquery that computes the department maximum. Middle/Senior: RANK shows everyone sharing the maximum, while ROW_NUMBER or DISTINCT ON gives exactly one, and here I ask what is needed. I also watch NULL: in PostgreSQL it comes first under DESC, so I add NULLS LAST and settle with the requirement whether to show a department with no salaries.

Finding duplicate emails

Duplicate emails are found by grouping on LOWER(TRIM(email)) with HAVING COUNT(*) > 1, and the records themselves come from a window COUNT or EXISTS. A duplicate usually means uniqueness is not enforced in the database: an existence check separate from the insert lets two simultaneous requests through, so the race is proved with two parallel registrations. The guarantee is a unique index on the normalised expression, created after cleanup.

SQL · Tasks

One address, yet two accounts. How to find out why it happened and prevent it from happening again?

In the task "find the emails that repeat" the query showed that anna is in three records and oleh in two. That is a symptom. A duplicate email in a system is rarely an accident: it is a consequence of a rule the backend did not enforce in the database. The "does this address exist?" check runs apart from the insert, case and whitespace are not normalised, and two simultaneous requests pass the check together. QA has three tasks here: show the records themselves, prove the cause and make sure the database lacks a constraint. The sample is the same: ids 1, 2, 3 are anna in three variants, ids 4 and 5 are oleh, ids 7 and 8 have email NULL.

Which exact records. Grouping gives the value and a counter, but not the ids. To open each record and compare them you need the rows.

-- which exact records (ids 1, 2, 3, 4, 5)
SELECT u.*
FROM users u
WHERE EXISTS (
  SELECT 1 FROM users d
  WHERE d.id <> u.id
    AND LOWER(TRIM(d.email)) = LOWER(TRIM(u.email))
);

The query compares each record with all the others by equality, and NULL = NULL is not true, so NULL rows stay out by themselves (grouping, by contrast, would collect them into one group). The drawback of EXISTS: it joins the table to itself, so on a big table it is heavier than grouping. PostgreSQL usually runs it as a hash join on the expression, and an index on LOWER(TRIM(email)) may let it look the match up by index, depending on the plan.

How to prevent it from happening again. A check in the application without a database constraint is unreliable. If the code first runs a SELECT "does this address exist?" and then an INSERT, two simultaneous requests both see "no" and both insert. The only guarantee is a unique index over the normalised expression. It is created after cleanup, because with duplicates present it cannot be created.

CREATE UNIQUE INDEX users_email_norm_key
  ON users (LOWER(TRIM(email)));

A repeated insert with the same address now gives a uniqueness error, which the backend must turn into a 409 response. The index allows several rows with NULL. If an empty email is forbidden, the column is made NOT NULL, and PostgreSQL 15 and newer also have UNIQUE NULLS NOT DISTINCT. Case-insensitivity can also be provided by the citext type from an extension.

How to test the race. The test sends two identical registration requests at the same moment and looks at the response codes and the number of records in the database.

const body = JSON.stringify({ email: 'race@test.com', password: 'Passw0rd!' });
const send = () =>
  fetch(`${base}/users`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body,
  });

const res = await Promise.all([send(), send()]);
console.log(res.map((r) => r.status));
// expect one 201 and one 409 in any order; two 201s mean there is no constraint

After the test the database is checked with SELECT COUNT(*) FROM users WHERE email = 'race@test.com': it must be 1. If the same request sent after the first one gets 409 while two simultaneous ones give [201, 201] and two rows, the duplicate is created by a race, not by missing validation.

Common mistakes.

  • Looking for duplicates by the raw email: variants with case and whitespace stay unnoticed.
  • Believing the backend check is enough without a unique index in the database.
  • Creating the index without removing duplicates first: the operation fails.
  • Not checking NULL: false duplicates in the report or, conversely, missed empty values.

Check yourself

Why does the EXISTS query not show records with email NULL, while the GROUP BY query without IS NOT NULL shows them as a duplicate?

Answer

GROUP BY treats all NULLs as one value and collects them into one group. EXISTS compares with =, and NULL = NULL gives UNKNOWN, so there is no match. These are two different semantics, so the results of the two queries must be interpreted differently.

After CREATE UNIQUE INDEX … ON users (LOWER(TRIM(email))) the race test still gives [201, 201]. What should be checked?

Answer

Whether the index really exists and is valid in the very database the test uses, and how many rows the database really has: if one, the backend swallows the uniqueness error and answers 201 instead of 409. Also whether the application inserts into another table or schema. The query SELECT indexdef FROM pg_indexes WHERE tablename = 'users' shows what exists.

In an interview. Junior: I find duplicates by grouping on LOWER(TRIM(email)) with HAVING COUNT above one, and then look for the cause: I check whether the database has a unique constraint. Middle/Senior: To see the records themselves I use a window COUNT or EXISTS. For QA a found duplicate often means a missing UNIQUE constraint in the database or a race with parallel requests, so I prove it with a test of two simultaneous requests and propose a unique index over the normalised expression.