## The analyst SQL screen, and why it is really five patterns
The first SQL question in an analyst interview rarely feels difficult, and that is precisely why it is dangerous. It arrives in plain English, on a small table you can hold in your head, with twenty minutes on the clock and an interviewer who is watching not only whether the query runs, but how you think when the obvious version is almost, but not quite, right. Candidates who have written SQL for years in dashboards and notebooks stumble here not because they lack syntax, but because the screen is testing something narrower and less forgiving than everyday work: whether you can translate a business sentence into the exact order in which a database evaluates it, whether you notice the duplicate, the missing value and the tie hiding inside a tidy request, and whether you can explain your reasoning while you write. The good news, and the organising idea of this set, is that underneath the endless variations in wording, company and industry, the analyst screen keeps returning to the same five patterns. Learn to recognise the pattern before you reach for the syntax, and the question that looked novel becomes familiar work.

The first family is filtering and NULL logic. These are the questions about who counts and who does not: customers who placed an order but never returned one, employees whose manager is missing from the table, records where a field was never filled in rather than filled in with zero. They test WHERE clauses, certainly, but their real subject is the three-valued logic of SQL, in which a comparison with NULL is not false but unknown, and unknown rows quietly disappear from results. A candidate who treats a missing value as just another value will produce a query that looks plausible and returns the wrong people.
The second family is joins. Almost every analyst question that involves more than one table is, at heart, a question about what happens to rows that do not match. An inner join keeps only the pairs that exist on both sides. A left join keeps every row from the left table and fills the rest with NULLs when there is no partner. Choosing between them is not a stylistic preference. It is a decision about whether the business question is about activity that happened or about a population that should be accounted for even when nothing happened. Screens probe this relentlessly, because in real work the difference is the difference between reporting on active customers and reporting on all customers.
The third family is aggregation with GROUP BY and HAVING, the subject of the first question in this set. These questions ask you to collapse many rows into one row per group and then to filter at two different levels: filtering individual rows before they are grouped, and filtering the groups themselves after an average, a count or a sum has been calculated. The confusion between those two levels is so common, and so revealing, that interviewers return to it again and again.
The fourth family is window functions and ranking. Once a question contains words such as top, latest, first, highest per group, or running total, it has usually left the world of plain aggregation and entered the world of windows, where a calculation can look across rows without collapsing them. ROW_NUMBER, RANK and DENSE_RANK look interchangeable until ties appear, and ties always appear. The second question in this set, on the Nth-highest salary, belongs to this family even when it is first solved without a window function, because its difficulty is entirely about how ranking should treat equal values.
The fifth family is multi-step logic built with common table expressions, subqueries and, occasionally, self-joins. These are the questions that cannot be answered in one breath: find the departments that meet a condition, then find the people inside them; find each customer’s first order, then measure what happened next; compare every row with another row from the same table. A CTE does not give SQL new powers, but it gives the writer a way to name each step, test it, and show an interviewer a chain of reasoning instead of a single dense block.
This set is organised around those five families rather than around syntax in the abstract. Each of the ten questions is presented the way it would be posed in a room, followed by a discussion of what the interviewer is actually listening for, a worked answer that is meant to be read line by line, and an account of the common wrong answer, because in a screen the wrong answer is rarely random. It is usually the right idea applied one step too early, or the right function applied to the wrong level of the data. Where a question naturally invites a harder version, a variant or follow-up closes the section. Interviewers use follow-ups to separate a memorised answer from an understood one, and preparing for the follow-up is often worth more than preparing for the original question.
Throughout the set, every question uses the same small company, described here once so that no time is wasted relearning a schema in each section.
- The employees table, called employees, holds one row per employee. Its columns are id, a unique integer identifier for the employee; name, the employee’s full name as text; department_id, an integer that refers to a department; salary, a numeric column giving annual salary, which may occasionally be NULL for contractors whose pay is recorded elsewhere; manager_id, an integer that refers to the id of another employee, and is NULL for the most senior person; and hire_date, the date the employee started.
- The departments table, called departments, holds one row per department. Its columns are id, a unique integer identifier; and name, the department name as text, such as Engineering, Sales, Marketing or Support.
- The orders table, called orders, holds one row per order placed. Its columns are id, a unique integer identifier for the order; customer_id, an integer that refers to a customer; order_date, the date the order was placed; and amount, a numeric column giving the order total.
- The customers table, called customers, holds one row per customer. Its columns are id, a unique integer identifier; name, the customer’s name as text; and signup_date, the date the customer first signed up.
The schema is deliberately ordinary. No question in this set depends on a trick column name or an obscure data type. When a query joins employees to departments, it does so on employees.department_id equals departments.id. When it counts orders per customer, it groups orders by customer_id. Keeping the ground familiar puts the weight where interviewers put it: on logic, edge cases and clarity.
How should you study from the set? Read the question first and stop. Write your own query, on paper or in an editor, before you read the worked answer, even if you are unsure, because the gap between your version and the worked version is the lesson. Then read what the question is really testing and compare it with what you assumed it was testing; that mismatch, more than any syntax error, predicts trouble in a live screen. Run the common wrong answer in your head against a tiny invented example, with three or four rows that include a duplicate, a NULL and a tie, and watch where it fails. Finally, attempt the variant without looking back. If you can adapt the pattern to the variant, you own it. If you can only reproduce the original, you have memorised it, and memorised answers tend to dissolve the moment an interviewer changes a number, adds the words per department, or asks what happens if two people share the same salary.
One more habit is worth building from the start. Before writing any query in a screen, say, in one sentence, what one row of the result should represent. One row per department. One row per customer. One row per employee. That sentence decides whether you need GROUP BY, whether a join will multiply your rows, and whether a count is counting the thing you think it is counting. Most wrong answers in this set can be traced back to a result whose rows were never clearly defined. Most strong answers begin, quietly, with that definition.
## Question 1: WHERE vs HAVING — finding groups that clear a bar
### The question
This question usually arrives in two parts, and interviewers often ask the second part only after the first has been answered, to see whether the same idea transfers to a different table.
Part one: Write a query that returns the name of each department whose average employee salary is greater than 80,000, together with that average salary. Only employees whose salary is known should contribute to the average.
Part two: Write a query that returns the id and name of each customer who has placed more than five orders, together with the number of orders each such customer has placed.
In both parts, if it helps, you may assume the schema described at the start of this set. The interviewer will sometimes add a small twist while you are writing: for part one, only consider employees hired before 2023; for part two, only consider orders placed in the last year. Hold that twist in mind, because it is where the question reveals its purpose.
### What they are really testing
On the surface, this is a question about GROUP BY. Underneath, it is a question about timing — about which filter is applied before grouping and which is applied after, and whether you understand that a database does not evaluate a query in the order in which you type it.
The logical order in which SQL processes a standard select statement is fixed, and once it is internalised, WHERE and HAVING stop being two interchangeable filtering keywords and become two different moments in a pipeline. First, FROM and any JOINs assemble the working set of rows. Second, WHERE filters those individual rows, discarding any that do not meet its conditions, before any grouping has happened. Third, GROUP BY collapses the surviving rows into groups, one group for each distinct combination of the grouping columns. Fourth, HAVING filters those groups, using aggregate values that only exist once the groups have been formed. Fifth, SELECT decides which columns and expressions appear in the output, and any aliases defined there become available. Finally, ORDER BY sorts the result and LIMIT, if present, trims it.
That order explains everything about this question. An average salary does not exist at the WHERE stage, because at that stage there are no groups and no averages, only individual employee rows. A condition on an average therefore cannot live in WHERE. It must live in HAVING. Conversely, a condition on an individual row, such as an employee’s hire date or an order’s date, belongs in WHERE, where it can remove rows before they distort a count or an average. Interviewers are listening for whether you place each condition at the level where the value it refers to actually exists.
There is a second, quieter thing being tested: whether you understand what COUNT counts. In part two, COUNT with an asterisk counts rows in the group, while COUNT of a column counts non-NULL values of that column in the group. On the orders table, grouped by customer, either will usually give the same number, because each order row is an order. But after a left join from customers to orders, the difference becomes decisive, and candidates who have only ever counted rows often produce a confident one for a customer who has placed no orders at all. A strong answer to this question names its counting choice rather than drifting into it.
Finally, the question tests whether you group by the right key. In part one, the result should have one row per department, so the grouping must be by department, and because two departments could in principle share a name in a messier schema, grouping by the department id and selecting the name is the safer habit. In part two, the result should have one row per customer, so the grouping is by the customer’s id, with the name carried alongside. Interviewers notice when a candidate groups by name alone and thereby merges two different customers who happen to share one.
### The worked answer
Begin with part one, without the twist. The result is one row per department. The average is calculated over employee salaries within each department, and the filter on that average belongs in HAVING.
```sql
SELECT
d.name AS department_name,
AVG(e.salary) AS average_salary
FROM employees AS e
JOIN departments AS d
ON d.id = e.department_id
GROUP BY
d.id,
d.name
HAVING AVG(e.salary) > 80000;
```
Read the query in logical order, not in written order. The FROM and JOIN clauses first pair every employee with the department that employee belongs to. There is, as yet, no WHERE clause, so no rows are removed at the row level; the note in the question that only employees whose salary is known should contribute needs care, because AVG already ignores NULL values by definition in standard SQL. An employee with a NULL salary does not drag the average down and is not counted in its denominator. Naming that fact out loud is a small but telling moment in an interview: it shows you are not about to add a redundant filter out of anxiety, and it shows you know how aggregate functions treat missing values. If the interviewer instead wanted departments calculated only over employees with known salaries and wanted those employees excluded from every other part of the calculation as well, an explicit condition that salary is not NULL in WHERE would be the clear way to say so.
GROUP BY then collapses the joined rows into one group per department. Within each group, AVG works over the salary values in that group. HAVING keeps only the groups where that average is greater than 80,000. SELECT finally presents the department name and the average under readable aliases. The aliases cannot be used inside HAVING in standard SQL, because HAVING is logically evaluated before SELECT; that is why the worked answer repeats the expression AVG of salary in the HAVING clause instead of referring to average_salary. Some database systems relax that rule as a convenience, but writing the portable version signals that you understand the order rather than relying on a dialect’s generosity.
Now add the twist: only consider employees hired before 2023. That is a condition on individual employee rows, so it belongs in WHERE, where it removes later hires before any average is formed.
```sql
SELECT
d.name AS department_name,
AVG(e.salary) AS average_salary
FROM employees AS e
JOIN departments AS d
ON d.id = e.department_id
WHERE e.hire_date < ‘2023-01-01’
GROUP BY
d.id,
d.name
HAVING AVG(e.salary) > 80000;
```
Notice what did not change. The HAVING clause is untouched, because the bar for the group is the same; only the population entering the groups has narrowed. Candidates who understand the pipeline find this edit trivial. Candidates who have memorised a shape often try to force the hire date into HAVING, where a bare hire_date no longer has a single meaning, because a department group contains many hire dates.
Part two follows the same skeleton on different tables. The result is one row per customer. The count is formed per customer, and the condition of more than five orders is a condition on that count, so it belongs in HAVING.
```sql
SELECT
c.id AS customer_id,
c.name AS customer_name,
COUNT(o.id) AS order_count
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.id
GROUP BY
c.id,
c.name
HAVING COUNT(o.id) > 5
ORDER BY order_count DESC;
```
An inner join is correct here, and it is worth saying why. The question asks only for customers who have placed more than five orders. A customer with no orders cannot qualify, so there is no need to preserve orderless customers through the join; they would be filtered out by the HAVING condition in any case. Counting o.id, the order identifier, counts order rows within each customer group. Counting with an asterisk would give the same result on this inner join, but counting the joined table’s key is the habit that survives the day the join becomes a left join. The ORDER BY clause, evaluated last, can use the alias order_count, because by sorting time the SELECT aliases exist.
Add the corresponding twist, only orders placed in the last year, and once again the new condition is a row-level condition, placed in WHERE, before grouping. In portable terms, relative to a given reference date, that might be written as a condition that order_date is on or after a stated cutoff date. The count then counts only recent orders, and HAVING still applies the same threshold of more than five. The separation is the whole lesson: WHERE decides which orders are eligible to be counted; HAVING decides which customers, having been counted, clear the bar.
A brief word on presentation helps in a live setting. Round an average only if the interviewer asks for it, and if you do, apply the rounding in SELECT, around the average, rather than changing the value that HAVING compares, unless the business rule is explicitly about the rounded figure. A department whose true average is 80,000.40 clears a bar of greater than 80,000; rounding it for display should not be allowed to change whether it appears.
### The common wrong answer
The classic wrong answer puts the aggregate in WHERE.
```sql
-- This does not work
SELECT
d.name AS department_name,
AVG(e.salary) AS average_salary
FROM employees AS e
JOIN departments AS d
ON d.id = e.department_id
WHERE AVG(e.salary) > 80000
GROUP BY
d.id,
d.name;
```
Most database systems reject this outright, with an error saying that aggregate functions are not allowed in WHERE, and that error is itself instructive. The database is not being pedantic. At the moment WHERE is evaluated, rows have not yet been grouped, so there is no average to compare. In an interview, writing this version is recoverable if you catch it yourself and can explain why it fails and move the condition to HAVING. It becomes damaging when a candidate responds to the error by trying workarounds that preserve the same misunderstanding — wrapping the whole query in a subquery without being able to say why that works, or filtering on individual salaries instead, keeping only employees paid more than 80,000 and then averaging what remains. That second workaround runs, which makes it more dangerous than the error. It answers a different question: it finds departments where the average among already highly paid employees is high, which is nearly guaranteed, and it discards every employee below the threshold before the average is taken. The result looks like an answer and is not one.
A second common failure, in part two, is to filter on the count in WHERE in the same way, or to write a condition such as a check that a single order row somehow represents more than five orders. A third, subtler failure is to use a left join out of habit and then count with an asterisk, so that a customer with no orders receives a count of one, because the left join manufactures one row for that customer with NULLs on the order side, and counting rows counts that manufactured row. The fix is either to use the inner join the question calls for, or, if a left join is genuinely needed to show all customers, to count a column from the right-hand table, such as o.id, which is NULL on the manufactured row and therefore not counted. Interviewers who set this question often have that trap loaded and ready, even if the version they asked does not spring it.
There is also a grouping error worth naming. Grouping part one by department name alone, or part two by customer name alone, will pass on clean sample data and fail in the real world the moment two departments or two customers share a name. Group by the identifier; carry the name. It costs one extra line and removes an entire class of silent error.
### The follow-up
The standard follow-up is a request that changes the level of the answer: return not only the departments whose average salary exceeds 80,000, but also how many employees in each such department earn more than 100,000 individually. That addition forces you to hold two levels in one query — a group-level filter in HAVING, and a conditional count inside the group, counting employees whose own salary clears a separate bar. In many dialects that conditional count can be written as a sum over a case expression that returns one when the salary condition holds and zero otherwise, grouped exactly as before, with the original HAVING condition unchanged. The candidates who do well on the follow-up are the ones who do not rebuild the query from scratch. They recognise that the grouping has not changed, the HAVING bar has not changed, and only one more per-group calculation has been requested. That recognition — knowing which parts of a query a new requirement touches and which it leaves alone — is, in miniature, the skill the whole question was designed to find.
## Question 2: The Nth-highest salary — distinct values, ties and the meaning of next
### The question
Write a query that returns the third-highest salary in the employees table.
That is the whole question as it is usually posed, and its brevity is the point. Before writing anything, a strong candidate asks, or at least decides explicitly, three things. First, does third-highest mean the third-highest distinct salary value, or the salary of the third employee when employees are ordered by pay? Second, what should happen when two or more employees share a salary — do they occupy one rank or several? Third, what should the query return if there are fewer than three distinct salary values in the table — no rows, a NULL, or something else?
The conventional interpretation, and the one this answer adopts unless an interviewer says otherwise, is the third-highest distinct salary value. If the salaries in the table are 120,000, 110,000, 110,000, 100,000 and 90,000, the distinct values in descending order are 120,000, 110,000, 100,000 and 90,000, and the third-highest distinct salary is 100,000. The two employees earning 110,000 share the second-highest value; they do not push 100,000 down to fourth place. Stating that interpretation before you code is not hedging. It is the answer’s foundation, because every solution below implements it, and a different interpretation would require a different solution.
The interviewer may also generalise the question while you work: not third, but Nth, where N is given. A good solution should make clear where N enters, so that changing three to five is a small edit rather than a new invention.
### What they are really testing
This question is a test of precision about ranking. Most candidates can order salaries from highest to lowest. Far fewer can say, without prompting, what should happen at a tie, and fewer still notice that the most intuitive tools encode different answers to the tie question.
There are three ranking ideas in play, and they diverge only when values repeat, which is why this question cannot be understood on data without duplicates. ROW_NUMBER assigns a unique position to every row, one, two, three, four, with ties broken arbitrarily unless a secondary ordering is specified; under ROW_NUMBER, the two employees at 110,000 would take positions two and three in some order, and the employee at 100,000 would be fourth. RANK assigns the same rank to tied rows and then skips ahead, so the salaries above would be ranked one, two, two, four; the employee at 100,000 is fourth, and there is no third rank at all. DENSE_RANK assigns the same rank to tied rows and does not skip, giving one, two, two, three; the employee at 100,000 is third. Only DENSE_RANK, applied to distinct values or to rows with the understanding that tied rows share a rank, matches the conventional interpretation of Nth-highest distinct salary.
The question also tests whether you think about the empty case. A query that returns no rows when there is no third-highest value is making one defensible choice. A query that returns a single row containing NULL is making another, and some well-known versions of this problem, particularly those built around a scalar subquery in SELECT, do exactly that. Neither choice is self-evidently correct; the interviewer wants to hear that you noticed the case exists and chose deliberately.
Finally, the question tests range. Interviewers ask it expecting that a candidate might know one method. Presenting more than one method, and being able to say when each is preferable — readability, portability across database systems, performance on a large table, ease of generalising to Nth per group — turns a puzzle into a demonstration of judgement. The three solutions below are not three ways of showing off. They are three genuinely different tools, and the comparison between them is part of the answer.
### The worked answer
The first solution is the oldest and most portable. It uses a subquery to peel away the values above the one you want. The third-highest distinct salary is the largest salary that is smaller than the second-highest, which is itself the largest salary smaller than the highest. Written directly for the third-highest value, the logic nests.
A cleaner way to express the same idea for a fixed N is to find the maximum salary among salaries that have fewer than N distinct salary values strictly above them. For the third-highest value, that condition is that the number of distinct salaries greater than it is exactly two, or, in the maximum formulation, that we take the largest salary for which that count is less than three. The classic nested MAX version for third place makes the peeling explicit and is worth being able to write without hesitation.
```sql
SELECT MAX(salary) AS third_highest_salary
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
)
);
```
Work through it from the inside out. The innermost subquery returns the highest salary in the table, 120,000 in our example. The middle subquery returns the highest salary that is less than that, which is 110,000; note that because the comparison is strictly less than, both employees earning 110,000 are treated as holders of a single value, and the subquery returns that value once. The outer query returns the highest salary less than 110,000, which is 100,000. Distinctness is not added as an extra step; it falls out of using strict inequality on values rather than counting rows. That elegance is the method’s charm, and its weakness is visible in the same code: for the fifth-highest salary you would nest five deep, and for a variable N the nesting cannot be written at all. The method also returns a single row with NULL when there are too few distinct values, because MAX over an empty set is NULL; whether that is the behaviour you want should be a stated decision.
The second solution uses a window function and states the ranking rule directly. It is the version most interviewers hope to see from a candidate who will use modern SQL at work.
```sql
SELECT DISTINCT salary AS nth_highest_salary
FROM (
SELECT
salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
WHERE salary IS NOT NULL
) AS ranked
WHERE salary_rank = 3;
```
Here the inner query attaches to every employee row a dense rank based on salary in descending order. The highest value receives rank one, the next distinct value rank two, the next rank three, regardless of how many employees share each value. The outer query keeps only rows at rank three and, because several employees might share that salary, selects the distinct salary value so the result is the single value the question asked for. Excluding NULL salaries in the inner query matters: without that condition, a NULL could be ranked depending on the database system’s default ordering of NULLs, and a salary question should not quietly become a question about missing data. Changing three to N is a one-character edit to the final condition, and the structure survives that change intact, which is exactly what a generalisable answer should do. If there is no third distinct value, this version returns no rows, a contrast with the MAX version that is worth mentioning if you present both.
The third solution sorts the distinct values and skips to the one required, using OFFSET with a limit on the number of rows returned. It is often the shortest correct answer, and the easiest to explain to a non-technical listener.
```sql
SELECT DISTINCT salary AS nth_highest_salary
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
```
DISTINCT first reduces the salaries to their distinct values conceptually; ORDER BY places those values from highest to lowest; OFFSET two skips the first two distinct values; and the limit of one row returns the next value, the third-highest. For the Nth-highest value, the offset is N minus one, a formula worth saying aloud because off-by-one errors are the natural hazard of this method. The syntax for limiting rows varies by system — some use a fetch-first formulation rather than LIMIT — and on a very large table, sorting all distinct values can cost more than a ranking approach tuned to the task, but for clarity in an interview this version is hard to beat. Like the window version, it returns no rows when there are too few distinct values.
Set the three side by side and the trade-offs are plain in prose. The nested MAX version works almost everywhere, including on older systems without window functions, and it teaches the distinct-value logic most nakedly, but it does not generalise gracefully. The DENSE_RANK version names the ranking rule, generalises to any N, and extends naturally to ranking within groups, at the price of requiring window-function support and a slightly longer explanation. The OFFSET version is the most readable for a single overall value and the most fragile in dialect and in off-by-one handling. A candidate who can offer the window version as the main answer and mention one alternative, with its trade-off, has answered both the question asked and the question behind it.
### The common wrong answer
The most common wrong answer orders individual employees, rather than distinct salary values, and takes the third row.
```sql
-- Answers a different question when salaries repeat
SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
```
On data with no repeated salaries, this returns the correct value, which is why it survives practice on tidy examples. On the example used in this section — 120,000, 110,000, 110,000, 100,000, 90,000 — it returns 110,000, because the third row in the ordering is the second employee earning 110,000. The query has answered the question, what does the third-highest-paid employee earn, under an arbitrary ordering of the tied employees, rather than, what is the third-highest salary. The missing word in the candidate’s thinking is distinct, and the missing test is a duplicate deliberately placed in the data. If you practise this question only on unique values, you will never see the fault. Practise it, always, with a tie at the second-highest value, because that single case separates the two interpretations completely.
A close relative of that error uses ROW_NUMBER where DENSE_RANK is required, or uses RANK and then discovers, on tied data, that no row carries rank three at all and concludes the table has no third-highest salary. Both errors come from treating the three ranking functions as synonyms with different spellings. They are not synonyms. They are three different policies for ties, and this question exists to make you choose a policy and defend it.
A third failure is to count rows in a subquery instead of counting distinct values above the target — for instance, keeping salaries for which a count of employees earning more is less than three. With two employees at the top salary, that condition misclassifies the next value, because it counts people where it should count values. Wherever the phrase highest salary appears, the unit being ranked is the value, not the person holding it, unless the interviewer explicitly redefines the question in terms of people.
There is, finally, the silent NULL failure. If salaries can be NULL and the query does not address that fact, some systems will place NULLs first in a descending sort, so that a query seeking the highest values returns a missing value as though it were the largest pay in the company. Excluding NULLs explicitly, or stating the assumption that the column contains no NULLs and checking whether the interviewer accepts it, closes that hole.
### The follow-up
The follow-up that almost always comes next adds two words: per department. Find the second-highest salary in each department. Those two words rule out the simple OFFSET version in its original form, because a single global ordering can no longer deliver one answer per group, and they reward the window approach, which was built for exactly this extension. The ranking must now be partitioned by department, so that ranks restart within each department, while the rest of the logic stays the same.
```sql
SELECT
department_id,
salary AS second_highest_salary_in_department
FROM (
SELECT
department_id,
salary,
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_rank
FROM employees
WHERE salary IS NOT NULL
) AS ranked
WHERE salary_rank = 2;
```
PARTITION BY is doing the conceptual work. It tells the window function to rank salaries separately inside each department, so the highest salary in Engineering and the highest salary in Sales both receive rank one in their own partitions, and the condition that rank equals two then selects the second distinct salary value in every department that has one. Departments with only one distinct salary value simply contribute no rows, which is again a behaviour to state rather than to stumble over; if the business wanted every department listed, with a blank where no second-highest value exists, the ranked result would need to be joined back to the full list of departments, and saying so shows you can hear the difference between a ranking question and a reporting question. If the interviewer further asks for the names of the employees who earn that second-highest departmental salary, rather than the salary value alone, the same ranked subquery can be kept and joined or filtered at the row level instead of selecting distinct salaries, because the ranking was calculated per employee row in the first place. That adaptability is the deepest reason to lead with the window solution: it is not merely an answer to the question that was asked, but a platform for the three questions that are likely to follow it, and interviewers, who spend their days listening for exactly that quality, tend to notice.
## Question 3: NULL Traps
### The question
You are given three tables. The `employees` table has columns `id`, `name`, `department_id`, `manager_id`, `salary`, and `bonus`. The `departments` table has `id` and `department_name`. The `orders` table has `id`, `customer_id`, `employee_id`, `order_date`, `amount`, and `discount_amount`.
The interviewer asks you to work through five short tasks, all involving missing values, and to explain what each query returns and why:
First, find all employees whose `manager_id` is NULL — that is, employees with no manager recorded.
Second, find all departments that have no employees, using a list of department IDs drawn from the `employees` table.
Third, for each department, count how many employees it has and how many of those employees have a recorded bonus.
Fourth, write a query that returns each employee’s bonus as zero when no bonus is recorded, and that can safely compare salaries between two employees even when one salary is missing.
Fifth, calculate the average discount percentage on orders, defined as `discount_amount` divided by `amount`, without the query failing when an order amount is zero.
There is no single query to write here. There are five traps to avoid, and the interviewer wants to hear you name each one before you write the code that sidesteps it.
### What they are really testing
This question looks like a syntax check. It is not. It is a test of whether you understand that NULL in SQL does not mean zero, does not mean an empty string, and does not mean false. NULL means unknown, absent, or not applicable — and SQL treats it with a logic that has three values instead of two. Every comparison involving NULL can be true, false, or unknown, and a `WHERE` clause keeps only the rows where its condition is true. Unknown is discarded exactly as firmly as false is discarded, and that single fact explains almost every surprising result a new analyst meets in their first year.
Interviewers return to NULL again and again because the damage in real work is quiet. A query that uses the wrong comparison does not raise an error. It returns an empty result set, or a count that is a little too low, or a list of departments that is mysteriously incomplete, and the analyst who wrote it often ships the number without noticing. A dashboard that undercounts bonuses, a churn list that omits customers, a finance report whose denominator silently excludes the very rows it should highlight — none of these announce themselves. The interviewer is therefore not listening for whether you can recite a definition. They are listening for whether you reach instinctively for the tools that are safe around missing data: `IS NULL` and `IS NOT NULL` for testing absence, `NOT EXISTS` instead of `NOT IN` when a subquery might contain a NULL, `COALESCE` for supplying a working default, `IS DISTINCT FROM` for comparisons that need to treat two missing values as equal, and `NULLIF` for turning a dangerous zero into a NULL before it can break a division.
There is a second layer to the test. Strong candidates distinguish between the places where NULL should be preserved and the places where it should be replaced. Replacing a missing bonus with zero is correct when you are summing what the company actually paid. Replacing a missing salary with zero is almost never correct when you are averaging what the company pays, because it drags the average down with people whose pay you simply do not know. The interviewer wants to hear that judgement, not just the functions. Anyone can memorise `COALESCE`. Fewer analysts can say, in plain language, when coalescing clarifies a report and when it corrupts one.
Finally, this question tests whether you know that aggregate functions and counting functions treat NULL differently from each other, and differently again from the way a `WHERE` clause treats it. `COUNT(*)` and `COUNT(column)` sound interchangeable to a beginner. To an experienced analyst they answer different questions, and choosing the wrong one in a left join is one of the most common reasons a report shows one order for a customer who has placed none. That specific confusion returns in the next question, and interviewers set the two questions side by side on purpose.
### The worked answer
Start with the first task, because it contains the root of all the others. To find employees with no manager, the comparison must use `IS NULL`.
```sql
SELECT id, name, department_id, salary
FROM employees
WHERE manager_id IS NULL;
```
The step that matters is the one you do not write. The following query returns no rows at all, on any database, no matter how many employees have a missing manager:
```sql
-- This returns zero rows. Always.
SELECT id, name, department_id, salary
FROM employees
WHERE manager_id = NULL;
```
The reason is mechanical once you see it. The expression `manager_id = NULL` asks whether an unknown value equals another unknown value. SQL cannot answer yes, because it does not know either side. It cannot answer no for the same reason. It answers unknown, and the `WHERE` clause drops unknown rows. The same logic applies to `manager_id <> NULL`, to `salary > NULL`, and to any ordinary comparison where either side might be missing. If you need to test for absence, you test with `IS NULL`. If you need to test for presence, you test with `IS NOT NULL`. There is no third form that works, and no setting that makes `= NULL` behave the way a spreadsheet user expects.
The second task is subtler, and it is the trap that catches experienced analysts, not just beginners. Suppose you want departments that no employee belongs to. A natural first attempt lists the department IDs that do appear in `employees` and asks for departments outside that list:
```sql
-- Dangerous: this can return zero rows for the wrong reason.
SELECT id, department_name
FROM departments
WHERE id NOT IN (
SELECT department_id
FROM employees
);
```
If even one employee has a NULL `department_id` — a new hire not yet assigned, a contractor whose record was loaded incompletely, a chief executive whose department was never set — then the subquery list contains a NULL. Now consider what `NOT IN` has to prove for a given department, say department 7. It has to show that 7 is not equal to any value in the list. It checks 7 against the first ID, the second ID, and so on, and each check succeeds — until it reaches the NULL. Is 7 equal to an unknown value? Unknown. `NOT IN` requires every comparison to be true before it will keep the row. One unknown in the list poisons the whole test, the condition becomes unknown rather than true, and the row is dropped. Because that NULL sits in the subquery for every outer row, every department is dropped. The query returns nothing, and it does so without an error, on a table where the correct answer might be three departments.
The safe rewrite uses `NOT EXISTS`, which asks a different and sturdier question — not “is this value absent from a list” but “does any matching row exist at all”:
```sql
SELECT d.id, d.department_name
FROM departments d
WHERE NOT EXISTS (
SELECT 1
FROM employees e
WHERE e.department_id = d.id
);
```
Walk through why this survives the same data. For department 7, the subquery looks for an employee row whose `department_id` is 7. An employee with a NULL `department_id` never satisfies `e.department_id = d.id`, because that comparison is unknown, not true, so that row simply does not count as a match — which is exactly right, since an unassigned employee is not evidence that department 7 has staff. If no other employee matches, the subquery finds nothing, `NOT EXISTS` is true, and department 7 is correctly returned. NULLs in the data cannot poison the test because the test never builds a list to compare against. As a habit, many senior analysts use `NOT EXISTS` for every “not in this set” question, whether or not they expect NULLs, because data changes and a query that is safe today can become silently wrong the day an upstream load starts leaving a foreign key blank. If you are ever handed a `NOT IN` query you cannot rewrite — in a view you do not own, for example — the defensive patch is to filter the subquery with `WHERE department_id IS NOT NULL`, but the rewrite is the better answer and the one the interviewer is hoping to hear.
The third task separates two counts that beginners merge into one. For each department, you need the number of employees and the number of employees with a recorded bonus:
```sql
SELECT
department_id,
COUNT(*) AS employee_count,
COUNT(bonus) AS employees_with_bonus,
COUNT(*) - COUNT(bonus) AS employees_without_bonus
FROM employees
GROUP BY department_id;
```
The distinction is precise. `COUNT(*)` counts rows, whatever their contents. `COUNT(bonus)` counts rows where `bonus` is not NULL, because aggregate functions other than `COUNT(*)` skip NULL inputs entirely. `SUM`, `AVG`, `MIN`, and `MAX` all behave the same way: a missing value is not treated as zero, it is treated as if the row were not there for that calculation. That behaviour is a gift when you understand it. `AVG(salary)` correctly averages the salaries you actually know, rather than punishing the average with invented zeros. It is a trap when you forget it. `AVG(bonus)` averages bonuses only across employees who received one, which is a very different number from the average bonus cost per employee across the whole company. If the business question is the second one, you must make the missing values explicit before you average, which leads directly to the fourth task.
`COALESCE` takes a list of expressions and returns the first one that is not NULL. It is the standard way to supply a working value where data is absent:
```sql
SELECT
id,
name,
bonus,
COALESCE(bonus, 0) AS bonus_for_payroll,
salary + COALESCE(bonus, 0) AS total_cash_recorded
FROM employees;
```
Notice what this does and what it refuses to do. `bonus_for_payroll` treats a missing bonus as zero, which is right for a payroll total: if nothing was recorded as paid, nothing should be added to the payout sum. But `total_cash_recorded` is carefully named, because if `salary` itself is NULL, the whole addition is still NULL — `salary + 0` where salary is unknown is unknown — and that is honest. Coalescing the salary to zero would produce a neat, complete, and false total. In an interview, say that out loud. State which column you are coalescing and why, and state which column you are deliberately leaving alone. `COALESCE` also generalises beyond a single fallback: `COALESCE(preferred_name, legal_name, ‘Name not recorded’)` walks down a chain of preferences, and it works across types that can be sensibly converted, which makes it useful for cleaning reporting fields drawn from several source systems.
The comparison problem in the fourth task needs a different tool. Suppose you need to find employees whose salary differs from a colleague’s salary, or rows where a current salary differs from a previous salary in an audit table, and missing values should count as “the same” when both sides are missing and “different” when only one side is missing. Ordinary `<>` fails you here, because `NULL <> NULL` is unknown and `50000 <> NULL` is unknown too, so both rows vanish from your results even though they are exactly the rows you want. The null-safe comparison operators solve this:
```sql
SELECT id, name, salary, manager_id
FROM employees
WHERE salary IS DISTINCT FROM 75000;
SELECT a.id AS employee_id,
a.name AS employee_name,
b.name AS comparison_name
FROM employees a
JOIN employees b
ON b.id = a.manager_id
WHERE a.salary IS DISTINCT FROM b.salary;
```
`IS DISTINCT FROM` behaves like `<>` for ordinary values, but it treats NULL as a comparable value: two NULLs are not distinct, and a NULL and a number are distinct. Its partner, `IS NOT DISTINCT FROM`, behaves like `=` with the same null-safe property, and in several dialects it is the cleanest way to join or match on a column that can be missing on both sides — matching, for example, orders where both records have no discount code recorded. Not every dialect spells these operators identically, and part of a strong answer is acknowledging that the idea matters more than the spelling: you need a comparison that decides what two missing values mean, instead of one that gives up and returns unknown.
The fifth task, the division, is where NULL becomes your ally instead of your enemy. Dividing by zero raises an error in most dialects and stops the query. `NULLIF` takes two expressions and returns NULL when they are equal, and its first expression otherwise. That makes it the standard guard for a denominator:
```sql
SELECT
id,
customer_id,
amount,
discount_amount,
discount_amount / NULLIF(amount, 0) AS discount_rate
FROM orders;
```
Step through it row by row. When `amount` is 500 and `discount_amount` is 50, `NULLIF(500, 0)` returns 500, and the rate is 0.1, as expected. When `amount` is 0, `NULLIF(0, 0)` returns NULL, and `discount_amount / NULL` evaluates to NULL instead of raising an error. The row survives, the rate is honestly unknown, and the rest of the result set is unaffected. You can then decide, as a reporting choice, whether to display that NULL, exclude it from an average — which `AVG` will do automatically — or coalesce it for presentation. A complete answer often combines both guards, protecting the denominator and presenting a readable result:
```sql
SELECT
customer_id,
COUNT(*) AS order_count,
AVG(discount_amount / NULLIF(amount, 0)) AS avg_discount_rate,
COALESCE(
SUM(discount_amount) / NULLIF(SUM(amount), 0),
0
) AS overall_discount_rate
FROM orders
GROUP BY customer_id;
```
The second rate is worth explaining if you use it, because it is not the same measure as the first. The average of individual rates weights a small order and a large order equally. The ratio of the sums weights by size, which is usually what a finance reader means by an overall discount rate. Showing both, and naming the difference, signals that you think about what a number means and not merely how to produce it. Two cautions complete the task. First, `NULLIF` guards only the exact value you pass it; a denominator that is an expression, such as `amount - discount_amount`, must be guarded as a whole, as `NULLIF(amount - discount_amount, 0)`. Second, a denominator that is already NULL needs no guard at all — the division already returns NULL — so the guard is specifically about zero, and saying so shows you are not applying the function by superstition.
### The common wrong answer
The most common wrong answer is the first trap restated with confidence: writing `WHERE manager_id = NULL`, watching the query return no rows, and concluding that every employee has a manager. Candidates do this under time pressure because `=` is the comparison they use for everything else, and because in many programming languages a check against a null value works in roughly that shape. The interviewer will usually let the candidate sit with the empty result for a moment. What rescues the answer is not embarrassment; it is diagnosis. If you catch yourself, name the three-valued logic, switch to `IS NULL`, and explain why the first version could never return a row, you have turned a mistake into the strongest moment of your answer. If you instead start adding joins or questioning the data, the interviewer learns that you debug by guessing.
The second wrong answer is reaching for `NOT IN` without asking what the subquery can contain. This one is more dangerous in the interviewer’s eyes precisely because the query is idiomatic and often correct. It passes on clean sample data, it passes in most tutorials, and it fails only when a single NULL appears in the list — which, in production data with incomplete loads and optional foreign keys, is a matter of when rather than if. A related wrong answer is trying to repair `NOT IN` by changing it to `IN` with a negation outside, or by wrapping the column in a `COALESCE` inside the subquery without thinking through which value you have invented. Coalescing `department_id` to -1 inside the subquery happens to work if -1 is guaranteed never to be a real department, but it is a fragile fix that buries an assumption in the code. `NOT EXISTS` carries no such assumption.
The third wrong answer is treating the counting functions as synonyms. Candidates write `COUNT(bonus)` when they mean the headcount, report that a department has nine employees when it has fourteen people and five missing bonus records, and then cannot explain the discrepancy when the interviewer shows them `COUNT(*)` alongside it. The mirror-image error is just as common: a candidate who has learned that aggregates skip NULLs will coalesce everything on sight, writing `AVG(COALESCE(salary, 0))` and producing an average salary that no one in the company actually earns. Both errors come from the same root — applying a function without asking what question it answers.
The fourth wrong answer is hand-rolling the division guard with a `CASE` expression that handles zero but forgets NULL, or worse, filtering out the offending rows in the `WHERE` clause to make the error go away. Filtering changes the population of the report: an average discount rate computed after deleting zero-amount orders is a rate for a different set of orders than the one the reader thinks they are looking at. `NULLIF` keeps the row, marks the one uncomputable value as unknown, and leaves the population intact. That difference — fixing the value versus deleting the evidence — is exactly the instinct this question exists to measure.
**Variant and follow-up.** Interviewers who are satisfied with the five traps usually extend the question in one of two directions. The first is sorting: they ask where employees with a missing salary appear when you order by salary, and the honest answer is that the default differs by database — some systems place NULLs first on an ascending sort, others place them last — so a production query should state its intention explicitly with `NULLS FIRST` or `NULLS LAST` where the dialect supports it, rather than relying on a default a future migration might change. The second extension is uniqueness: they ask whether a column with a unique constraint can hold more than one NULL. In most systems it can, because NULLs are not considered equal to each other for uniqueness either, though the details vary by vendor and are worth checking before you rely on them. Both follow-ups test the same underlying habit as the main question. Missing values are not an edge case to be cleaned away before the real work starts. In analytical SQL they are part of the data, they follow consistent rules, and the analyst who has internalised those rules writes queries that stay correct on the messy tables that every real company actually has.
## Question 4: Customers Who Have Never Placed an Order
### The question
You are working with two of the shared tables. The `customers` table has columns `id`, `customer_name`, `email`, `city`, and `signup_date`. The `orders` table has columns `id`, `customer_id`, `employee_id`, `order_date`, `amount`, and `discount_amount`. Every order belongs to a customer through `orders.customer_id`, which references `customers.id`. Some customers in the table have placed many orders. Some have placed exactly one. Some signed up, browsed, perhaps even spoke to a salesperson, and have never placed an order at all.The interviewer asks for three things.
First, write a query that returns every customer who has never placed an order — name, email, city, and signup date — with one row per customer.
Second, write the same result a different way, without using a join.
Third, extend the query so that it returns every customer, not just the ones with no orders, together with the number of orders each customer has placed. Customers with no orders must appear in the results with a count of zero, not be missing from the report and not show a count of one.
The interviewer adds one condition at the end, almost as an afterthought: the business is especially interested in dormant customers in Chicago, so be ready to adapt your queries to return only never-ordered customers whose city is Chicago.
That afterthought is not an afterthought. It is where this question is won or lost.
### What they are really testing
On the surface this is the most standard question in analytical SQL. The anti-join — find the rows in one table with no matching row in another — appears in onboarding documents, certification exams, and almost every data analyst interview loop. Interviewers keep asking it because the business need behind it is permanent. Every company needs its list of customers who never bought, employees who never completed training, products that never sold, departments with no staff, patients who never returned after a first appointment. The shape of the problem never changes, and neither does the commercial value of getting the list exactly right: a win-back campaign, a churn investigation, or an onboarding review built on the wrong list wastes money and misleads everyone who reads it.
What the interviewer is really testing is whether you understand what a left join actually produces. A left join does not filter anything out. It preserves every row from the left table and attaches matching rows from the right table where they exist, filling every right-table column with NULL where they do not. That padded NULL is the signal this whole question turns on, and it is fragile in a specific way: almost anything you write afterwards — a filter, a count, a well-meant tidy-up — can destroy the signal or misread it. The interviewer wants to see whether you handle the padded rows with care all the way to the end of the query, or whether you build the join correctly and then undo your own work in the next clause.
The second thing being tested is whether you have more than one way to solve the same problem, and whether you know when each way is appropriate. The left join anti-join and the `NOT EXISTS` anti-join return the same rows, but they are not interchangeable in every context. The join version extends naturally into the third task, where you need a count for every customer. The `NOT EXISTS` version is cleaner when you need only the customer columns, it is immune to the row-multiplication problem that joins can introduce, and — as the previous question established — it is safe around NULLs in a way that its cousin `NOT IN` is not. An interviewer who asks for the second method is checking that your knowledge is structural rather than memorised: that you understand the problem as “no matching row exists” and can express that idea in whatever form the surrounding query requires.
The third layer of the test is counting discipline, and it connects directly to the counting trap in the previous question. When a customer has no orders, the left join produces exactly one row for them, with every order column set to NULL. A careless count of that row reports that the customer has placed one order — the single most embarrassing number a dormant-customer report can contain, because it converts the very people the report exists to find into apparently active customers. The interviewer is watching for whether you count rows or count matches, and whether you know that after an outer join those are different numbers.
Woven through all three layers is a subtler habit: keeping the conditions that belong to the left table separate from the conditions that belong to the right table. The Chicago condition at the end tests exactly that separation. Filtering on the customer is safe. Filtering on the order, in the wrong clause, quietly converts your outer join back into an inner join and returns an empty or wrong result. Candidates who understand join order — who know that a condition in the `ON` clause participates in the matching, while a condition in the `WHERE` clause filters the already-joined result — navigate this without thinking. Candidates who treat the two clauses as interchangeable storage for conditions fail it every time, usually without noticing.
### The worked answer
Begin with the left join anti-join, and build it in two stages so that your reasoning is visible. First, join every customer to their orders, preserving customers who have none:
```sql
SELECT
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date,
o.id AS order_id,
o.order_date,
o.amount
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id;
```
Read the result before you filter it. A customer with three orders appears three times, once per order, with real order values on each row. A customer with one order appears once, with real order values. A customer with no orders also appears once — the left join guarantees them their row — but on that row `order_id`, `order_date`, and `amount` are all NULL, because there was nothing to attach. That single padded row is the fingerprint of a customer who has never ordered, and the anti-join is simply the act of keeping only the rows that carry the fingerprint. The column you test should be a column that can never be NULL on a real order row, which is why the order’s primary key is the right choice: a genuine order always has an `id`, so a NULL `id` after the join can only mean the join found nothing.
```sql
SELECT
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id
WHERE o.id IS NULL;
```
That is the complete first answer. Every row it returns is a customer with no matching order, each customer appears exactly once because a customer with no orders generates exactly one padded row, and the select list contains only customer columns because the order columns carry no information once you have used them as a test. Note the form of the test: `IS NULL`, never `= NULL`, for the same three-valued-logic reason covered in the previous question. Note also what you did not do: you did not group, you did not deduplicate, and you did not need to, because the structure of the anti-join already guarantees one row per qualifying customer. If an interviewer asks whether the query could return a customer twice, the correct answer is no, and the reason is worth stating — duplication in a join comes from multiple matches, and these customers by definition have zero matches.
The second method asks for the same result with no join at all. State the problem in its plainest form — return customers for whom no order exists — and the SQL almost writes itself:
```sql
SELECT
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);
```
The subquery is correlated: it runs, in effect, once per customer, looking for any order whose `customer_id` matches that customer. The `SELECT 1` is a convention worth explaining if asked. `EXISTS` cares only whether the subquery returns at least one row; it does not read the values, so selecting a constant makes that indifference explicit and avoids implying that a particular column matters. As soon as one matching order is found, the subquery has done its job and the customer is excluded. If the search completes with nothing found, `NOT EXISTS` is true and the customer is returned. This version has three practical virtues. It cannot duplicate a customer, no matter how the underlying tables evolve, because it never multiplies rows in the first place. It cannot be poisoned by a NULL in `orders.customer_id` — an order with a missing customer reference simply never matches any customer, which is the correct treatment, since an unattributed order is not evidence that a particular customer ordered. And it reads the way the business question is phrased, which makes it easier to review, easier to hand over, and easier to adapt when the definition of an order narrows — for example, if the business later decides that cancelled orders should not count, the condition goes inside the subquery, where it belongs:
```sql
SELECT
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
AND o.order_date >= DATE ‘2025-01-01’
);
```
That adapted version returns customers with no orders since the start of 2025, a quietly different population that includes formerly active customers who have gone quiet — often the more valuable list, and a natural thing to point out in the interview room.
It is worth pausing on the method you should not reach for, because many candidates offer it as their second way. `NOT IN` can express the same idea:
```sql
-- Correct only if orders.customer_id can never be NULL.
SELECT id, customer_name, email, city, signup_date
FROM customers
WHERE id NOT IN (
SELECT customer_id
FROM orders
);
```
If a single order row has a NULL `customer_id` — entirely possible in real data, where an order might be loaded before its customer record is resolved — the list contains a NULL, every comparison in the `NOT IN` test becomes unknown for the reason worked through in the previous question, and the query returns no customers at all. A dormant-customer report that silently returns empty is worse than one that errors, because an empty report looks like good news. In the interview, the strongest move is to volunteer this caveat before the interviewer raises it: name `NOT IN`, explain the condition under which it fails, and say that `NOT EXISTS` is your default for exactly that reason.
The third task changes the shape of the answer. Now every customer must appear, with their order count beside them, and the never-ordered customers must show zero. The left join returns, because you need information from both tables for every customer — but the counting must respect the padded rows:
```sql
SELECT
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date,
COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id
GROUP BY
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date
ORDER BY order_count ASC, c.signup_date ASC;
```
The load-bearing choice is `COUNT(o.id)`. Recall the rule from the previous question: `COUNT(column)` counts only rows where that column is not NULL, while `COUNT(*)` counts rows unconditionally. For a customer with three orders, the join produced three rows with real order IDs, and `COUNT(o.id)` returns three. For a customer with no orders, the join produced one padded row whose order ID is NULL, and `COUNT(o.id)` returns zero — the honest answer. The ordering is a small professional touch: sorting by count ascending, then by signup date, puts the longest-dormant customers at the top of the report, which is how the reader will actually use it. The same query extends naturally if the business wants spending alongside the count. `SUM(o.amount)` for a never-ordered customer is NULL rather than zero, because a sum over no values is unknown, so a report that should display zero spending wraps it as `COALESCE(SUM(o.amount), 0)`. Mentioning that distinction unprompted — count gives zero on its own, sum needs help — shows the interviewer that your NULL knowledge is connected rather than compartmentalised.
Finally, the Chicago condition, which separates the two clauses of the query. The customer’s city lives on the left table, the table the join preserves, so filtering on it in the `WHERE` clause is completely safe in either version of the anti-join:
```sql
SELECT
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date
FROM customers c
WHERE c.city = ‘Chicago’
AND NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);
```
Nothing about the anti-join logic changes, because the city filter removes whole customers before the existence test is ever considered, and removing customers is precisely what a filter on the preserved table is supposed to do. Keep that safety in mind, because the next section is about the filter that does not share it.
### The common wrong answer
The classic wrong answer to the third task is a single character’s worth of carelessness: writing `COUNT(*)` instead of `COUNT(o.id)`. The query runs, the results look plausible, every active customer shows the right number — and every customer who has never ordered shows a count of one. The padded row, which exists only because the left join refused to abandon that customer, is counted as if it were an order. The report then contains no zeros at all, and a reader who trusts it concludes the company has no dormant customers. The error survives code review more often than any other in this set, because reviewers check whether the join is a left join and then stop reading. In the interview, the defence is to narrate the padded row as you write the count: say, out loud, that the never-ordered customer contributes one row and zero order IDs, and that the count must be taken over the IDs. Interviewers award the point for the narration as much as for the code, because the narration proves the code was not luck.
The second wrong answer is the one the Chicago afterthought is designed to expose, and it generalises far beyond this question. Suppose the business interest shifts slightly: instead of dormant customers in Chicago, they want customers who have no orders above a certain value, or no orders in a given period, and the candidate implements the condition by filtering the right table in the `WHERE` clause:
```sql
-- Wrong: this no longer finds customers with no orders.
SELECT
c.id,
c.customer_name,
c.email,
c.city
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id
WHERE o.id IS NULL
AND o.amount > 100;
```
This query can never return a row, and tracing why is the whole lesson. The padded row for a never-ordered customer has `o.amount` set to NULL. The condition `o.amount > 100` on a NULL amount is unknown, not true, so the `WHERE` clause discards the padded row — the only row the anti-join existed to keep. Meanwhile every row with a real order above 100 fails the `o.id IS NULL` test, because its ID is not NULL. The two conditions each destroy the other’s survivors, and the result is empty. The broader form of the same mistake appears without the anti-join test at all: a candidate builds the counting query, adds `WHERE o.amount > 100` to focus on significant orders, and does not notice that the condition also deletes every padded row, silently converting the left join into an inner join. The customer list shrinks to active customers only, the zeros disappear, and the report still looks finished. Any condition on a right-table column in the `WHERE` clause, other than an `IS NULL` test, has this effect, because it demands a real value from rows whose defining feature is that they have none.
The correct home for a condition on the right table is the `ON` clause, where it shapes which rows count as matches instead of filtering the joined result:
```sql
SELECT
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date,
COUNT(o.id) AS orders_over_100
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id
AND o.amount > 100
GROUP BY
c.id,
c.customer_name,
c.email,
c.city,
c.signup_date;
```
Now the logic matches the business question. A customer whose orders are all small matches nothing under this join condition, so they receive a padded row and a count of zero orders over 100 — which is true, and usefully different from having no orders at all. A customer with two large orders and one small one counts two. Every customer survives, because nothing in the `WHERE` clause is waiting to discard them. The rule to carry out of the interview is simple to state and worth stating verbatim: conditions on the preserved table go in the `WHERE` clause; conditions that define a match go in the `ON` clause; and after any outer join, read your `WHERE` clause once more and ask of every condition whether it would keep a row full of NULLs. If it would not, and you needed that row, the condition is in the wrong place.
The third wrong answer is quieter. Candidates sometimes solve the first task with an inner join to a grouped subquery, or with a `HAVING` clause counting orders per customer, and then filter for customers who appear in that result — never realising that customers with no orders cannot appear in any result built from the orders table joined inward, because there is nothing to join to. Others reach for `NOT IN` as their only method and cannot produce a second way when asked. Both answers reveal the same gap: the candidate knows a pattern that sometimes works, rather than the principle that always works. The principle is that finding absence requires either preserving the rows and testing for the padding, or testing directly for non-existence. Every correct anti-join in SQL is one of those two ideas, and every incorrect one is usually an inner join wearing a filter as a disguise.
**Variant and follow-up.** The follow-up interviewers favour most takes the same structure one step further: find customers whose most recent order was more than six months ago, alongside customers who have never ordered, as a single at-risk list. The strong answer treats the two groups as one query rather than two glued together. A left join with `MAX(o.order_date)` gives every customer a last-order date, which is NULL for the never-ordered group, and a single condition — the maximum date `IS NULL`, or earlier than the cutoff — captures both groups at once, with a `CASE` expression labelling which group each customer belongs to, since the business will treat a never-buyer and a lapsed buyer differently. A second common follow-up reverses the direction: products that have never been ordered, departments with no employees, or employees who have never handled an order through the `employee_id` column of the same orders table. Nothing in the technique changes, which is the point the interviewer is making by asking. A third variant adds a performance question — which anti-join is faster — and the mature answer is that on modern optimisers the left join and `NOT EXISTS` forms are usually planned identically, that an index on `orders.customer_id` matters more than the choice between them, and that you would check the execution plan on the real data rather than argue from folklore. Candidates who close with that answer leave the interviewer with the impression the whole question was designed to create: this analyst finds the missing rows, counts them honestly, and knows why every clause in the query is standing where it stands.## Question 5: Finding and Removing Duplicate Rows
### The question
You are given a table called `customers` with columns `customer_id`, `first_name`, `last_name`, `email`, `city`, and `created_at`. The table has no primary key enforced on it, and a faulty import has loaded some customers more than once. The interviewer asks you to do three things, in order. First, find the duplicate rows. Second, explain how you would remove them while keeping one copy of each customer. Third, say which copy you would keep, and why.
A few minutes into most interviews, a follow-up arrives: another table, `orders`, has duplicates too, but there the rows are not identical in every column. Two rows can share the same `customer_id`, the same `product_id`, and the same `order_date`, yet carry different `order_id` values and slightly different `amount` values because one of them is a corrected re-entry. Are those duplicates? How would you find them, and how would your answer change?
This question looks mechanical, and many candidates treat it that way. It is not. It is the question that separates analysts who can write a query that returns the right-looking rows on a clean practice table from analysts who can be trusted with a real table that other people depend on. Deleting data is irreversible in a way that a wrong SELECT is not. A wrong SELECT produces a wrong number in a meeting, and the number can be corrected. A wrong DELETE removes rows that may have taken months to collect, may be referenced by other tables, and may not be recoverable at all if nobody took a backup first. Interviewers know this, and they listen for caution as carefully as they listen for syntax.
The schema used across this set is worth restating here, because the duplicate discussion depends on it. The `employees` table carries `employee_id`, `first_name`, `last_name`, `department_id`, `salary`, and `hire_date`. The `departments` table carries `department_id` and `department_name`. The `customers` table is as described above, and `orders` carries `order_id`, `customer_id`, `product_id`, `amount`, `order_date`, and in some questions a category reached through a products table. Duplicates can appear in any of them, and the right treatment differs by table — which is exactly the point the interviewer is making.
### What they are really testing
The first thing being tested is whether you understand that “duplicate” is a definition, not a fact you can read off the table. A row is only a duplicate relative to a set of columns you have chosen to define identity. If you choose every column, you are hunting for exact duplicates: rows that agree on every single value. If you choose a smaller set — an email address, or a customer and product and date — you are hunting for business-key duplicates: rows that represent the same real-world thing even though some of their stored values differ. Those are different problems, they need different queries, and they lead to different deletions. A candidate who starts typing before asking which definition applies has already given the interviewer useful information, and not the kind they hoped for.
The second thing being tested is the difference between hiding duplicates and removing them. Many candidates reach immediately for DISTINCT. DISTINCT changes what a query returns. It does not change what is stored. The interviewer wants to hear that distinction stated plainly, because in a working analytics team the confusion between the two causes real damage: a dashboard built on DISTINCT looks clean for months while the underlying table keeps accumulating duplicate rows, every downstream join keeps multiplying them, and storage, performance, and every non-DISTINCT query keep paying the price. The day someone builds a new report without DISTINCT, the numbers double and nobody understands why.
Third, the interviewer is testing whether you can find duplicates before you touch them. The professional sequence is always the same: count, inspect, sample, decide, back up, delete, verify. A candidate who jumps straight to a DELETE statement, however elegant, is signalling that they would do the same thing on a production table at 4 p.m. on a Friday. A candidate who first writes a query that shows how many duplicate groups exist, how many excess rows they contain, and what a few of those groups actually look like is signalling the opposite — and that signal is worth more than any single function name.
Fourth, they are testing whether you understand that keeping “one copy” is a decision with consequences. If the copies are truly identical, it does not matter which one survives. If they differ — one has a corrected email, one has a later timestamp, one has a non-null phone number where the other has a blank — then the choice of survivor changes the data the business keeps. “Keep the lowest id” and “keep the latest row” are the two answers interviewers hear most, and both can be right, but only when the candidate explains what each choice assumes. The lowest id usually assumes the first record created is the original and later copies are re-imports. The latest row usually assumes corrections arrive as new rows, so the most recent version is the most accurate. Neither assumption is universally true, and saying which one you are making, and how you would check it, is the substance of a strong answer.
Finally, this question tests whether you know that the tool for ranking rows inside a group — a window function — is also the tool for choosing a survivor. Candidates who learned ROW_NUMBER only as a trick for top-N questions often fail to see that deduplication is the same shape of problem: partition the rows into groups that are duplicates of each other, order each group by your survival rule, keep number one, remove the rest. Recognising that the two questions share a skeleton is the mark of someone who understands the function rather than memorising its uses.
### The worked answer
Start with the simplest case: exact duplicates in `customers`, where the same customer has been loaded twice with every value the same except possibly `customer_id`, which the import regenerated. The finding query groups by every column that defines a customer and counts.
```sql
SELECT
first_name,
last_name,
email,
city,
COUNT(*) AS row_count
FROM customers
GROUP BY
first_name,
last_name,
email,
city
HAVING COUNT(*) > 1
ORDER BY row_count DESC;
```
Walk through it slowly, because the interviewer is listening to the reasoning, not just reading the code. GROUP BY collapses all rows that agree on the four listed columns into a single group. COUNT(*) counts how many original rows fell into each group. HAVING filters after grouping, which is why the count condition belongs there and not in WHERE — WHERE runs before any grouping happens, so at WHERE time there is no group count to test. A group with a count greater than one is, by the definition chosen here, a duplicated customer. Ordering by the count descending puts the worst offenders first, which matters in a real investigation: a customer appearing twice suggests a double load, while a customer appearing forty times suggests something structurally wrong, such as a join upstream that fanned out before the import.
Notice what this query deliberately does not do. It does not group by `customer_id`. If the import generated a fresh id for each copy, then grouping by id would put every row in its own group of one and the query would report no duplicates at all — a technically correct answer to the wrong question. Choosing the grouping columns is the analysis. Email is usually the strongest single signal for a customer table, because two different people rarely share one email address, while one person can easily appear with a name spelled two ways. In many real answers the cleanest definition is email alone, with the other columns inspected rather than grouped. Say that out loud. A strong candidate often presents the query in two passes: first group by email alone to find suspect accounts, then look at the full rows inside a few suspect groups to see whether the names and cities agree or whether the shared email is a household or a company inbox legitimately used by two people.
That inspection step deserves its own query, and offering it unprompted is a differentiator.
```sql
SELECT *
FROM customers
WHERE email IN (
SELECT email
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
)
ORDER BY email, created_at;
```
This returns every row belonging to a duplicated email, sorted so the copies sit next to each other with the earliest first. Now you can see what kind of duplicate you actually have. If the rows are identical apart from id and timestamp, it is a load problem. If the later row has a different city, it may be a genuine update — the customer moved, and the system recorded the move by inserting rather than updating. If the names differ, it may not be a duplicate at all. Each of those findings leads to a different fix, and none of them can be distinguished by the counting query alone. Interviewers reward the candidate who looks before deleting, every time.
Now for removal. There are two broad approaches, and a complete answer describes both and says when each is appropriate.
The first approach ranks the copies inside each duplicate group and deletes every row ranked second or worse. In dialects that allow a window function inside a deletable common table expression — SQL Server is the classic example, and the pattern is widely recognised — it looks like this:
```sql
WITH ranked AS (
SELECT
customer_id,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at ASC, customer_id ASC
) AS rn
FROM customers
)
DELETE FROM ranked
WHERE rn > 1;
```
The PARTITION BY email clause restarts the numbering for each email address, so every distinct email gets its own row number one. The ORDER BY inside the window decides which copy earns that number one: here, the earliest `created_at`, with `customer_id` as a deterministic tiebreaker in case two copies share a timestamp. Every later copy receives two, three, and so on. Deleting where the rank exceeds one therefore keeps exactly one row per email — the earliest — and removes the rest. If your survival rule were “keep the latest correction,” you would change a single word, ordering by `created_at DESC`, and the most recent copy would survive instead. Naming that choice, and the assumption behind it, is part of the answer, not a decoration on it.
The second approach avoids dialect-specific delete-from-CTE behaviour and works almost everywhere, including MySQL and standard PostgreSQL workflows. You compute the id of the survivor for each group, store those ids, and delete everything not in the survivor set — or, more cautiously, build a clean table and swap it in.
```sql
CREATE TABLE customers_deduped AS
SELECT *
FROM (
SELECT
c.*,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at DESC, customer_id DESC
) AS rn
FROM customers c
) AS ranked_customers
WHERE rn = 1;
```
Here the inner query numbers the copies with the latest row first, the outer filter keeps only number one from each group, and the result is written to a new table. The cautious workflow around this pattern is what interviewers really want to hear described: you compare the row count of the new table against the count of distinct emails in the old one, and those numbers must match. You sample a dozen formerly duplicated emails and confirm the survivor is the row you intended to keep. You check that no other table’s counts change unexpectedly — if `orders` references customers, you confirm every `customer_id` in `orders` still finds its customer, or you remap the deleted ids to the surviving id first. Only then do you rename the tables, keeping the original under a dated backup name until the business has run on the cleaned table long enough to trust it. In a live interview you will not perform all of these steps, but naming them takes twenty seconds and changes how the interviewer scores your judgement.
That remapping point deserves emphasis, because it is where careless deduplication does its worst damage. Suppose customers 1042 and 2097 are the same person, you keep 1042, and you delete 2097 — but forty orders point at 2097. Depending on the database settings, the delete either fails on a foreign key, succeeds and orphans the orders, or cascades and deletes the orders too. None of those outcomes is acceptable to discover after the fact. The professional order of operations is to update the referencing table first, pointing every order at the surviving id, then delete the losing customer row, then verify the order count is unchanged. If the interviewer gives you a schema with no enforced keys, say you would check for references manually before deleting. That sentence alone puts you ahead of most candidates.
For the follow-up about `orders`, the definition changes, and the answer must change with it. Two order rows sharing `customer_id`, `product_id`, and `order_date` but differing in `order_id` and `amount` are business-key duplicates: they claim to record the same purchase event, but they disagree about the details. The finding query is the same shape with different grouping columns.
```sql
SELECT
customer_id,
product_id,
order_date,
COUNT(*) AS row_count
FROM orders
GROUP BY
customer_id,
product_id,
order_date
HAVING COUNT(*) > 1
ORDER BY row_count DESC;
```
But here, deleting all but one blindly would be wrong, and a thoughtful candidate says why. A customer can legitimately order the same product twice on the same day — two separate purchases, a gift and one for themselves, a re-order after a failed payment that actually succeeded. The differing amounts are a warning sign: they might mark a corrected re-entry, in which case the later amount is right and the earlier row should go; or they might mark two genuine orders at different prices, a discount applied to one and not the other, in which case deleting either row understates revenue. The honest analyst answer is that the query finds suspects, not verdicts. You would look for corroborating evidence — timestamps minutes apart suggest a double submission, timestamps hours apart suggest separate purchases; a matching payment reference settles the question outright — and you would take the definition back to whoever owns the orders data before removing revenue-bearing rows. Interviewers ask this follow-up precisely to see whether success on the clean `customers` case has made you reckless. It should make you more careful, not less: the technique is identical, but the stakes of a wrong deletion have gone up, and your process should visibly tighten to match.
One more distinction completes the answer. A pure DELETE removes rows from the existing table and is the right tool when the table is live, referenced, and indexed, and the duplicate count is modest. Building a deduplicated copy and swapping it in is often cleaner when duplicates are a large share of the table, when the table has no key to delete by safely, or when you want an untouched original to fall back on. Neither is universally better. Stating the trade-off — in-place delete is surgical but harder to undo, table rebuild is safer to verify but needs a maintenance window and care with permissions, indexes, and references — shows the interviewer you have done this on real systems rather than only on exercise tables.
### The common wrong answer
The most common wrong answer is a single word: DISTINCT. A candidate writes `SELECT DISTINCT * FROM customers`, shows that the output contains no repeated rows, and declares the duplicates removed. Nothing has been removed. The table still holds every duplicate row; only this one query’s output hides them. The next analyst who queries the table without DISTINCT inherits the problem, every COUNT(*) is still inflated, and any join from `customers` to `orders` still fans out and double-counts revenue for duplicated customers. Worse, DISTINCT on a wide table is expensive, because the database must sort or hash every column of every row to decide uniqueness. The correct use of DISTINCT is narrow and honest: you understand the source may contain duplicates, you cannot fix the source today, and for this specific analysis you deliberately want one row per combination of the selected columns. Used that way, with the limitation stated, it is a legitimate tool. Offered as a deletion method, it fails the question.
The second common wrong answer is grouping by every column including the unique id, finding nothing, and concluding there are no duplicates. As shown above, if each copy received a fresh `customer_id`, no two rows can ever group together, so the query is guaranteed to return empty. The error is subtle because the SQL is valid and the logic sounds thorough — “I checked all the columns” — but including an identifier that differs by construction destroys the test. Duplicates are defined by the columns that should be the same, never by the column designed to be different.
The third wrong answer is deleting by a non-unique condition, typically something like deleting every row whose email appears more than once. That removes all the copies, including the one that should have survived, and the customer vanishes entirely. It is the single most destructive mistake available in this question, and it comes from skipping the ranking step: finding the groups and choosing the survivor are two separate operations, and collapsing them into one condition deletes the survivor along with the duplicates. A related version deletes where `customer_id` is greater than the minimum id for the email but forgets that this pattern, while it does keep the earliest id, silently assumes the earliest id is the best record — an assumption that fails whenever corrections arrive as later rows with better data.
The fourth wrong answer is confidence without verification: running a DELETE, seeing “rows affected: 1,384,” and moving on without checking whether 1,384 was the number the finding query predicted. The finding query told you how many excess rows existed — total rows minus distinct groups. If the delete affects a different number, something in your logic differs from your analysis, and that moment, before anyone else touches the table, is the cheapest time to discover it. Candidates who state the expected count before deleting, and compare afterwards, demonstrate the habit that prevents nearly every data-loss story an interviewer has personally lived through.
**Variant and follow-up.** A frequent variant moves the same problem into `employees`: a payroll import has duplicated some employees, and you must keep, for each person, the row with the highest salary, on the theory that the higher figure is the corrected one. The shape is unchanged — PARTITION BY the columns that identify the person, in this case first name, last name, and department or, better, a shared email or national identifier if the table carries one — but the ORDER BY inside the window now ranks by salary descending, so row number one is the highest-paid copy and the deletion removes the rest. The follow-up interviewers love is to ask what you would do if the two copies have the same salary but different hire dates, which forces you to add a secondary ordering — earliest hire date, say — and to admit that at some point the surviving choice between two near-identical rows is a business decision, not a technical one. A second common follow-up is preventive rather than corrective: how would you stop duplicates returning next month? The strong answer names a unique constraint or primary key on the business key, an idempotent import that checks before inserting, and a scheduled version of the fi## Question 6: Top N per Group — The Three Highest-Paid Employees in Each Department
### The question
Using the `employees` table — `employee_id`, `first_name`, `last_name`, `department_id`, `salary`, and `hire_date` — and the `departments` table with `department_id` and `department_name`, write a query that returns the three highest-paid employees in each department, showing the employee’s name, the department name, and the salary.
The interviewer then adds a complication, because there is always a complication. In the Sales department, the salaries at the top are 120,000, 115,000, 110,000, and 110,000 — two employees are tied at exactly the third-highest figure. Do both of them belong in the answer, or only one? Does your query return three rows for Sales, or four? And can you explain, in plain language, what decides that?
A final twist follows in stronger interviews. Suppose the business changes its mind and asks instead for everyone paid at one of the top three salary levels in their department, regardless of how many people sit at each level. Is that a small edit to your query or a different query altogether? Candidates who have merely memorised a top-N snippet discover, at exactly this moment, that they cannot adapt it. Candidates who understand ranking functions adapt it in one line — by changing one function name — and can explain precisely what changed and why it matches the new wording.
### What they are really testing
The central skill being tested is whether you can rank rows inside groups rather than across a whole table. A beginner hears “three highest-paid” and reaches for ORDER BY salary DESC with LIMIT 3. That returns the three highest-paid employees in the entire company — one group, one ranking, three rows. The question asks for three per department, so the ranking must restart every time the department changes. That restarting behaviour is what PARTITION BY provides, and recognising that “per group” in a question is the verbal signature of PARTITION BY in the answer is one of the most reliable patterns in all of SQL interviewing. It appears in top-N questions, in deduplication, in running totals, in latest-record-per-customer questions — learn to hear it once and you will hear it everywhere.
The second thing being tested is whether you understand the three ranking functions as different answers to the question “what should happen when values tie?” ROW_NUMBER, RANK, and DENSE_RANK all number rows in an order you specify. They differ only in their treatment of equals — and in real salary data, equals are not an edge case. Salaries cluster on round numbers, on pay bands, on standardised offer templates. Any department of a few hundred people will contain ties, so the choice of function is not a stylistic preference; it determines who appears in the answer and who does not, and if the answer feeds a bonus list, a promotion review, or a layoff consultation, that determination has human consequences. Interviewers press on ties because production data always has them, even when practice tables politely do not.
Third, the question tests whether you understand the logical order in which a SQL query is evaluated — specifically, why a window function cannot be filtered in the WHERE clause of the same query. This is the single most common mechanical failure on this question. Candidates write a perfectly good ROW_NUMBER expression, add WHERE rn <= 3 on the same level, and are genuinely surprised when the database rejects it. Understanding why — WHERE is evaluated before the window functions are computed, so at WHERE time the row number does not yet exist — converts a memorised workaround into actual knowledge, and interviewers can hear the difference in about ten seconds.
Fourth, the question tests determinism. If two employees tie at the boundary and your chosen function must pick one of them, what decides which one? If nothing in your ordering distinguishes them, the database is free to choose either, and it may choose differently tomorrow, after an index change, or on a different execution plan. A query whose answer can change without the data changing is not an answer a business can rely on. The interviewer is listening for a tiebreaker — hire date, employee id, anything stable — and for the awareness that needing one is a property of the question, not an optional polish.
Finally, this question tests translation: turning an ambiguous English phrase, “top three,” into a precise specification before coding it. Top three rows, top three people, or top three salary levels are three different requests that share two words. The professional move is to state which interpretation you are implementing and to name the alternative — ideally before writing any code. Analysts do this translation every day with stakeholders who will never see the SQL, and the interview is simulating exactly that conversation.
### The worked answer
Begin with the interpretation that matches the most literal reading of the question: exactly three employees per department, with ties at the boundary broken by a stated rule. The solution has two layers — an inner query that computes a row number for every employee within their department, and an outer query that keeps only numbers one to three and joins in the department name.
```sql
WITH ranked AS (
SELECT
e.employee_id,
e.first_name,
e.last_name,
e.department_id,
e.salary,
e.hire_date,
ROW_NUMBER() OVER (
PARTITION BY e.department_id
ORDER BY e.salary DESC, e.hire_date ASC, e.employee_id ASC
) AS rn
FROM employees e
)
SELECT
r.first_name,
r.last_name,
d.department_name,
r.salary
FROM ranked r
JOIN departments d
ON d.department_id = r.department_id
WHERE r.rn <= 3
ORDER BY d.department_name, r.salary DESC;
```
Take it piece by piece. PARTITION BY `department_id` divides the employees into one group per department and restarts the numbering in each group, so every department gets its own number one — its highest-paid employee. ORDER BY salary DESC inside the OVER clause defines what the numbering follows: the highest salary receives one, the next receives two, and so on down the department. The two extra ordering terms are the deterministic tiebreakers. If two employees share a salary, the one hired earlier ranks first — a defensible rule, since longer service is a reason a business might genuinely prefer — and if they also share a hire date, the lower employee id decides, which guarantees the ordering is fully determined by the data and can never flip between runs. The outer query then filters to row numbers of three or less and joins `departments` to translate the id into the name the question asked for. Note that the join can sit in the outer query or the inner one; placing it outside keeps the ranking layer focused purely on employees, which makes the query easier to explain and to modify — and in an interview, a query you can modify calmly under follow-up questions beats a marginally shorter one you cannot.
Now the question every candidate hits: why must the filter live in an outer query at all? Why not write the window function in a SELECT and filter it in the same WHERE? Because of the order in which the database logically processes the statement. The sequence runs roughly as follows, and it is worth listing in full because it explains several apparently unrelated SQL puzzles at once:
- FROM and JOIN assemble the rows the query will work on.
- WHERE filters those rows, one by one.
- GROUP BY and HAVING collapse and filter groups, if the query groups.
- Window functions are computed, over the rows that survived the earlier steps.
- SELECT chooses the output columns, and DISTINCT removes duplicates among them.
- ORDER BY sorts the final result, and LIMIT or TOP trims it.
WHERE sits near the beginning of that sequence and window functions sit near the end. When the database evaluates WHERE rn <= 3, the row number has not been calculated yet — the alias does not refer to anything that exists at that stage — so the statement fails. Wrapping the window function in a subquery or a common table expression gives the inner query a chance to finish, materialising rn as an ordinary column, after which the outer query’s WHERE can filter it like any other column. This is not a quirk or a limitation to apologise for; it follows directly from what a window function is. A window function describes a row’s position relative to other rows, and a row’s relatives cannot be known until the set of rows has been settled by the earlier clauses. Once a candidate explains it that way, the interviewer knows the CTE in their answer is understanding, not ritual.
With the mechanics settled, work the tie example properly, because this is where the three functions part company. Take a department with five salaries, in descending order:
- 120,000 — one employee
- 115,000 — one employee
- 110,000 — two employees, tied
- 105,000 — one employee
Apply each function to that ordering and follow the numbers by hand. ROW_NUMBER assigns a unique, unbroken sequence in the order given: 1, 2, 3, 4, 5. The two employees at 110,000 receive 3 and 4, in whichever order the tiebreakers place them. Filtering to three or less therefore returns exactly three employees, and one of the two people earning 110,000 is excluded by the tiebreaker rule. RANK assigns the same number to equal values and then skips ahead by the size of the tie: 1, 2, 3, 3, 5. Both employees at 110,000 receive rank 3, and the employee at 105,000 receives rank 5, because four employees are ranked ahead of or level with the position above. Filtering RANK to three or less returns four employees — the two tied at third place both appear. DENSE_RANK also gives equals the same number but never skips: 1, 2, 3, 3, 4. Filtering it to three or less likewise returns four employees for this department, but the difference from RANK shows up in what a filter of four or less would mean — under DENSE_RANK it would add the 105,000 employee, since that salary is the fourth distinct level, while under RANK it would add nobody, because no one holds rank 4.
Those three behaviours map onto three different English requests, and a strong answer names the mapping explicitly. If the business wants exactly three people — three seats at a dinner, three interview slots, three names on a list — ROW_NUMBER with a fair, stated tiebreaker is the honest implementation, and you should say out loud that one tied employee misses out and that the tiebreaker is what decides it, so the business can overrule the rule if it wants a different one. If the business wants everyone who placed in the top three positions, ties included, RANK is the natural choice, accepting that the result may contain more than three rows per department. If the business wants everyone at the top three salary levels — the top three distinct pay grades, however many people occupy them — DENSE_RANK is the precise tool, and the result can contain many more than three people in a department where a pay band is crowded. None of the three is “the correct function.” Each is correct for one meaning of the question, and the interviewer’s real test is whether you ask, or at least state, which meaning you are serving.
The salary-band version of the query differs from the first version by exactly one word, which is worth showing because it demonstrates how small the mechanical change is compared with the conceptual one:
```sql
WITH ranked AS (
SELECT
e.employee_id,
e.first_name,
e.last_name,
e.department_id,
e.salary,
DENSE_RANK() OVER (
PARTITION BY e.department_id
ORDER BY e.salary DESC
) AS dr
FROM employees e
)
SELECT
r.first_name,
r.last_name,
d.department_name,
r.salary
FROM ranked r
JOIN departments d
ON d.department_id = r.department_id
WHERE r.dr <= 3
ORDER BY d.department_name, r.salary DESC;
```
Notice what disappeared along with the function change: the tiebreakers in the window’s ORDER BY are gone, deliberately. Under DENSE_RANK, employees with equal salaries must receive equal ranks, so the ordering should be salary alone — adding hire date would split the tie and defeat the purpose of choosing this function. That detail, mentioned in passing, signals to an interviewer that you understand the functions rather than reciting them. Notice also what did not change: the partition, the two-layer structure, the join, the filter position. The skeleton of a top-N-per-group answer is stable; only the ranking rule flexes to fit the wording. Presenting the answer that way — skeleton first, rule second — is the clearest structure an interview answer on this topic can have.
Two smaller points round out a complete performance. First, departments with fewer than three employees simply return what they have — one or two rows — and no special handling is needed; candidates sometimes reach for padding logic that the question never asked for. Mentioning that the query degrades gracefully costs one sentence and pre-empts a common follow-up. Second, if the interviewer asks about performance on a very large table, the honest answer is that the database must sort each partition by salary, that an index on department and salary in that order can let it avoid much of that sorting, and that for a one-off interview question this is a footnote rather than a concern — but knowing the footnote exists is the difference between an analyst and a query typist.
### The common wrong answer
The most common wrong answer is ORDER BY with LIMIT and no partition: sort all employees by salary descending, take three. It answers “who are the three highest-paid people in the company?” — a question nobody asked — and typically returns three employees from whichever department pays most, leaving every other department unrepresented. The failure is conceptual, not syntactic: the candidate never registered the words “in each department” as a structural requirement. Interviewers see this often enough that many now choose department names and salaries specifically so the wrong answer looks plausible at a glance, with the company’s top three all sitting in one department. Reading the question for its grouping words before touching the keyboard is the entire defence.
The second wrong answer is filtering the window function in WHERE on the same query level, as discussed above. On its own it is a small mechanical error, and most interviewers will hint at it once. What turns it into a failing answer is the recovery: candidates who respond by moving the expression into HAVING, or by wrapping it in a MAX, or by guessing at syntax until something runs, reveal that they never understood the evaluation order and are pattern-matching under pressure. The candidate who pauses and says “the window function is computed after WHERE, so I need to compute it in a subquery and filter outside” recovers completely — the initial slip is forgotten and the explanation is remembered. In interviews, as in debugging, a correct diagnosis is worth more than never having erred.
The third wrong answer uses GROUP BY with MAX(salary), sometimes nested three deep in an attempt to find the top three values per department. This family of solutions can, with enough self-joins and correlated subqueries, be wrestled into producing the top salary levels — but it loses the employees. MAX returns a salary figure, not the person earning it; when two employees share that salary, the query cannot say which of them, or how many of them, it refers to; and extending the pattern from the top one to the top three produces some of the ugliest SQL an interviewer will read all month. The deeper problem is a category error: grouping collapses rows, while this question needs every individual row preserved and merely labelled with its position. Ranking is a labelling operation, and window functions exist precisely so that rows can be labelled without being collapsed. A candidate who articulates that contrast — GROUP BY reduces, a window function annotates — has understood something that organises a great deal of SQL, far beyond this one question.
The fourth wrong answer is a silent one: using ROW_NUMBER with salary as the only ordering term on data that contains a tie at the boundary, and never mentioning the tie at all. The query runs, returns three tidy rows per department, and is non-deterministic — run it twice under different conditions and the third seat in Sales can swap between the two employees earning 110,000. Nothing in the output warns anyone. Interviewers regard this as worse than an outright error, because an outright error gets fixed, while a quietly arbitrary answer gets pasted into a slide. The fix costs a few words — add a tiebreaker and say what it is — and the habit of looking for the boundary case, the exact place where a clean rule meets messy data, is the habit this whole question was designed to detect.
**Variant and follow-up.** The standard variant changes the subject while keeping the skeleton: find the top three products by revenue in each category. Revenue is not a stored column, so the problem gains a first stage — aggregate `orders` to one row per product and category, summing `amount` as revenue — and only then can the ranking stage partition by category and order by that revenue descending. The strongest candidates narrate it as two questions wearing one coat: first “what did each product earn?”, a GROUP BY question, then “which products lead their category?”, a ranking question, and they keep the two stages in separate CTEs so each can be checked on its own. Ties matter here just as they did with salaries — two products can post identical revenue in a small category — so the same ROW_NUMBER, RANK, and DENSE_RANK conversation applies unchanged, tiebreakers included. A second follow-up asks for the top earner in each department only, and interviewers watch to see whether you simplify gracefully — the same query with the filter set to one — rather than rewriting from scratch or, worse, switching to a GROUP BY MAX approach that breaks on ties. A third asks what changes if the business wants the top three per department per year; the answer is one more column, the year of the hire or of the salary record, added to the PARTITION BY, and nothing else — the surest sign that the pattern, and not just t## Question 7: Running Totals and Month-over-Month Change
### The question
Using the `orders` table — `order_id`, `customer_id`, `order_date`, and `amount` — show total sales for each month, the running total of sales from the first month in the table up to and including that month, the previous month’s sales, and the month-over-month percentage change. Order the result chronologically. The interviewer may phrase it more loosely — “give me a monthly sales trend with cumulative revenue and growth” — but those four output columns are what they want to see, and they will usually follow up by asking what happens when two sales land on the same day, or why your first month shows no percentage change at all.
Expect the question to evolve as you answer it. Many interviewers start at the daily grain — a running total over individual orders, ordered by `order_date` — and only then ask you to roll it up to months. Others start at the monthly grain and probe the daily version as a trap. A complete answer handles both grains deliberately, because the window-function behaviour that matters most in this question changes completely depending on which grain you choose, and naming that difference out loud is often the moment the interviewer decides you actually understand window functions rather than having memorised a pattern.
### What they are really testing
This question tests four separate skills at once, and a strong answer names each one as it arrives rather than hoping the interviewer notices.
First, it tests aggregation before windowing. A window function operates on the rows that survive grouping, so monthly sales have to be built in a common table expression or subquery first, and only then can a running total or a `LAG` be applied to one row per month. Candidates who try to compute everything in a single pass over raw orders usually tangle themselves up, because at the raw grain there is no single “previous month” to lag to.
Second, it tests whether you understand window frames — the difference between `ROWS` and `RANGE`, what the default frame actually is when you write an `ORDER BY` inside `OVER`, and why peer rows share a value under one frame and not the other. This is the technical heart of the question, and it is where memorised answers fall apart.
Third, it tests `LAG` and defensive arithmetic: pulling a value from the preceding row, accepting that the first row has no predecessor, and guarding a division with `NULLIF` so a previous month of zero does not crash the query or produce nonsense.
Fourth, and most quietly, it tests date handling. Grouping sales “by month” sounds trivial until you ask what happens to January 2024 and January 2025. The interviewer wants to hear that a month is a year plus a month, not a month number, and that truncating a date to its month is the clean way to express that.
### The worked answer
Start by building the monthly grain. Nothing else in the query can be correct until there is exactly one row per month, with that month represented by a real date value that sorts properly across year boundaries.
```sql
WITH monthly AS (
SELECT
date_trunc(’month’, order_date) AS sales_month,
SUM(amount) AS monthly_sales
FROM orders
GROUP BY date_trunc(’month’, order_date)
)
SELECT
sales_month,
monthly_sales,
SUM(monthly_sales) OVER (
ORDER BY sales_month
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total,
LAG(monthly_sales) OVER (
ORDER BY sales_month
) AS previous_month_sales,
100.0 * (monthly_sales - LAG(monthly_sales) OVER (
ORDER BY sales_month
)) / NULLIF(LAG(monthly_sales) OVER (
ORDER BY sales_month
), 0) AS pct_change
FROM monthly
ORDER BY sales_month;
```
Walk through it step by step.
**Step one: truncate, do not extract.** `date_trunc(’month’, order_date)` collapses every timestamp in January 2025 to the single value 2025-01-01, every timestamp in February 2025 to 2025-02-01, and so on. The result is still a date, so it sorts chronologically, formats cleanly, and can be joined to a calendar table later. Grouping by that truncated value therefore produces one row per year-month pair, which is exactly the grain the rest of the query needs.
Contrast that with `EXTRACT(MONTH FROM order_date)`, which returns only the number 1 through 12. Group by the extracted month alone and January 2024 and January 2025 fall into the same bucket and are summed together. In a table holding several years of orders — and production orders tables almost always do — that is not a rounding error, it is a completely wrong trend line in which every January in history appears to be one enormous month. If an interviewer hands you data spanning more than a year and you reach for `EXTRACT(MONTH ...)` as your only grouping key, you have failed the hidden part of the question. Extracting both year and month and grouping by the pair does work, and is a fair answer in dialects without `date_trunc`, but the truncated date is cleaner: one column, one sort order, no risk of sorting December 2024 after January 2025 because the month number was sorted before the year.
**Step two: the running total.** `SUM(monthly_sales) OVER (ORDER BY sales_month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)` says: for each row, sort the months in order, then add up every monthly total from the very first month through the current row. Because the CTE already guarantees one row per month, each step adds exactly one month’s sales, and the running total climbs in clean monthly increments. Writing the frame out in full, rather than relying on the default, is deliberate — it makes the query’s intent survive being read by someone else, and it protects the query if the ordering column ever changes.
**Step three: `LAG` for the previous month.** `LAG(monthly_sales) OVER (ORDER BY sales_month)` reaches back exactly one row in the ordered set and returns that row’s sales. On every row except the first, that is the previous month. On the first row there is no preceding row, so `LAG` returns null — which is not an error to be suppressed but the honest answer: the earliest month in the data has no predecessor, so it has no month-over-month change. A polished answer leaves that null visible, or coalesces it only for display, and says why. Inventing a zero predecessor would manufacture a meaningless growth figure for month one.
**Step four: percentage change with a guarded denominator.** The arithmetic is `(this month - last month) / last month`, multiplied by 100 to express it as a percentage. The guard is `NULLIF(previous, 0)`, which returns null when the previous month’s sales were exactly zero, and the previous value otherwise. Dividing by that guarded value gives null instead of a division-by-zero error or an infinite percentage — the right outcome, because growth from a zero base is undefined, not enormous. Two smaller details separate careful answers from sloppy ones here. Multiplying by `100.0`, with the decimal, forces decimal arithmetic in dialects that would otherwise do integer division and truncate every percentage to a whole number or to zero. And in a production query you would compute `LAG` once — by nesting this select inside another CTE or outer query — rather than repeating the expression three times as shown above; the repeated form is used here only so each piece can be explained in place. Saying that out loud shows you write queries for maintenance, not just for the whiteboard.
**Step five: the daily version, and the frame trap.** Now drop back to the raw grain, because this is where `ROWS` and `RANGE` stop being trivia and start changing results:
```sql
SELECT
order_id,
order_date,
amount,
SUM(amount) OVER (
ORDER BY order_date
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total_range,
SUM(amount) OVER (
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total_rows
FROM orders
ORDER BY order_date, order_id;
```
When you write `SUM(amount) OVER (ORDER BY order_date)` and specify no frame at all, the standard default frame is `RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`. The word to dwell on is `RANGE`. A `RANGE` frame is defined by values, not by physical row positions: the frame extends to include every row whose ordering value is a peer of the current row — every row tied with it on the `ORDER BY` key. So if two sales land on the same day, each of those rows sees a frame that already includes the other one. Both rows report the same running total, and that total already contains both sales. Neither row shows the intermediate figure after only the first of the day’s sales, because under `RANGE` there is no “first” — the peers arrive as a group.
A `ROWS` frame, by contrast, counts physical rows. `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` stops at the current row itself, so the first of the two same-day sales gets a running total containing only its own amount, and the second gets one containing both. The totals differ row by row even though the ordering values are identical, and the order in which the tied rows are processed is not guaranteed unless you add a tiebreaker such as `order_id` to the window’s `ORDER BY`.
Which behaviour is correct depends entirely on the business question, and a strong candidate says so. If the running total is a daily bank-balance-style figure — “how much had we sold by the end of this day” — the `RANGE` behaviour is arguably the honest one, because a day is the grain and intraday order may be arbitrary or unknown. If the running total tracks individual transactions in sequence, `ROWS` with an explicit tiebreaker is correct, because each transaction must move the total by its own amount. The interview failure is not picking the “wrong” one; it is not knowing the two differ, shipping the default without realising it was `RANGE`, and then being unable to explain why two rows on the same day show identical cumulative figures in a stakeholder’s report. Interviewers probe exactly this because it has caused real reporting bugs: a finance team reconciles a cumulative column, finds duplicate totals on busy days, and assumes data is missing, when in fact the query was grouping peers all along.
One more refinement earns credit at the monthly grain. `LAG` reaches back one row, not one calendar month. If a month has no orders at all, it produces no row in the CTE, and `LAG` for the following month reaches back to the last month that did have sales — silently presenting a two-month gap as a one-month change. The robust fix is to join the monthly aggregates to a calendar spine — a generated series of months from the first to the last — and coalesce missing months to zero sales before applying `LAG`. You do not need to write the full spine in most interviews, but naming the gap problem, and the spine as its remedy, signals that you have shipped monthly reporting against real, gappy data rather than only against tidy exercise tables.
### The common wrong answer
The most frequent wrong answer groups by `EXTRACT(MONTH FROM order_date)` alone, for the reason covered above: it merges the same calendar month across every year in the table. On the single-year sample data in an exercise it looks perfect, which is precisely why it is dangerous — it passes the visible test and fails the first January in production.
The second classic error is trying to use an aggregate inside its own comparison or window in one flat query — writing something like a running total as `SUM(SUM(amount))` without a grouping layer, or attempting a self-join of orders to orders on “every earlier date” as the primary technique. The self-join can be made to work, but it re-reads the table for every row, grows quadratically, and collapses into ambiguity on tied dates; the window function exists to replace it, and interviewers set this question partly to see whether you reach for the modern tool.
The third error is an unguarded, integer-truncated percentage: `(monthly_sales - previous) / previous * 100`, written with no `NULLIF` and no decimal literal. That version errors or misbehaves on a zero-sales month, returns zero for almost every real change in integer-division dialects because the fraction is truncated before the multiplication, and returns null silently everywhere if the candidate does not understand that `LAG` on the first row is null rather than zero.
Finally, candidates often sort the monthly output by month name or month number for presentation and accidentally sort the window the same way, scrambling the running total. The window’s internal `ORDER BY` must always be the chronological truncated date, whatever the outer display order happens to be.
**Variant and follow-up.** The standard follow-up partitions the same machinery: “now give me the running total per customer, restarting for each customer, and a three-month moving average of monthly sales.” The running total simply gains a partition — `SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)` — so the cumulative sum resets at each customer’s first order. The moving average swaps the frame’s start to `ROWS BETWEEN 2 PRECEDING AND CURRENT ROW` around an `AVG` of monthly sales, which is the natural moment to repeat the frame lesson in miniature: on monthly data with one row per month, `2 PRECEDING` means the current month and the two before it, while on daily data a “three-month” average needs a `RANGE` frame over an interval, not a row count, because months do not contain a fixed number of rows. An interviewer who asks this variant is checking that the frame knowledge transfers, rather than having been recited for one question only.
## Question 8: Earning More Than Your Department’s Average — and Being the Highest Paid in It### The question
Using the `employees` table — `employee_id`, `employee_name`, `department_id`, and `salary` — together with `departments` — `department_id` and `department_name` — answer two related questions. First, list every employee whose salary is greater than the average salary of their own department, showing the employee, their salary, their department, and that department’s average for comparison. Second, find the highest-paid employee in each department. Interviewers love pairing these two because they look like cousins and are not: the first compares each row against a group statistic, while the second asks for a whole row back — a named person — for each group, and the technique that answers the first cleanly will not, by itself, answer the second at all.
### What they are really testing
The first part tests whether you can hold two grains in one query: the employee grain, one row per person, and the department grain, one average per department, and bring them together without collapsing the employee rows. That single idea — comparing a row to its group’s aggregate — recurs constantly in analyst work, in questions about orders above the average order value, students above their class average, or products priced above their category average, so the interviewer is really checking for a transferable pattern, not one memorised query.
It also tests whether you know there are several correct ways to express that pattern, and can talk honestly about their trade-offs. The correlated subquery, the window function, and the join to a grouped subquery all produce the same result on clean data, and an interviewer who asks “is there another way?” — they almost always do — wants a comparison, not a shrug.
The second part tests a subtler and more valuable distinction: the difference between finding a maximum value and finding the row that carries it. `GROUP BY department_id` with `MAX(salary)` returns the top salary in each department and nothing else — no name, no employee ID, no way to know who earns it or what to do about ties. Recovering the person requires ranking within groups, or joining the maximum back to the table, and handling the case where two employees share the top salary. How a candidate handles ties, unprompted, is one of the most reliable signals in the whole set.
### The worked answer
Here are the three standard solutions to the first part, in the order an interviewer typically hears them, followed by the ranking solution to the second part.
**Version one: the correlated subquery.** This is the most literal translation of the English sentence into SQL, which is why so many candidates reach for it first and why it remains worth knowing.
```sql
SELECT
e.employee_id,
e.employee_name,
e.department_id,
e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id
)
ORDER BY e.department_id, e.salary DESC;
```
The inner query is correlated because it references `e.department_id` from the outer row: for each employee being examined, it computes the average salary of that employee’s department, and the outer `WHERE` keeps the employee only if their salary exceeds it. Read aloud, it says exactly what the question says, and on a small table it performs perfectly well. Its cost appears at scale: conceptually, the average is evaluated again for every employee row, even though employees in the same department all need the identical number. Good optimisers often decorrelate this pattern and compute each department’s average once, but you cannot count on that in every dialect or every query shape, and the query as written gives the optimiser less help than the alternatives. It is the clearest version to explain and the least clear about its own inefficiency — a fair summary is that it optimises for the reader of a short query, not for a large table.
**Version two: the window function.** This computes every department average once, attaches it to each employee row without collapsing any rows, and then filters.
```sql
SELECT employee_id, employee_name, department_id, salary, dept_avg
FROM (
SELECT
employee_id,
employee_name,
department_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS dept_avg
FROM employees
) AS with_avg
WHERE salary > dept_avg
ORDER BY department_id, salary DESC;
```
`AVG(salary) OVER (PARTITION BY department_id)` is the key move, and the contrast with `GROUP BY` is the point to articulate: `GROUP BY department_id` would crush the employees down to one row per department, destroying the very rows the question asks about, whereas the windowed average leaves every employee row intact and simply writes the department’s average alongside each one. The filter has to live in an outer query, because window functions are evaluated after `WHERE` in logical query processing — you cannot reference `dept_avg` in the same query’s `WHERE` clause, and candidates who try learn that from an error message rather than from understanding. Wrapping the windowed select in a subquery or CTE and filtering outside is not a workaround; it is the correct shape, and naming the reason earns more credit than the query itself. This version is usually the best interview answer for the first part: one pass, the comparison value visible in the intermediate result for easy debugging, and the department average already present when the question asks you to display it — as this one does.
**Version three: join to a grouped subquery.** This builds the department grain explicitly as its own little table, then joins it back.
```sql
SELECT
e.employee_id,
e.employee_name,
e.department_id,
e.salary,
d.dept_avg
FROM employees e
JOIN (
SELECT department_id, AVG(salary) AS dept_avg
FROM employees
GROUP BY department_id
) AS d
ON d.department_id = e.department_id
WHERE e.salary > d.dept_avg
ORDER BY e.department_id, e.salary DESC;
```
The derived table has exactly one row per department, so the join cannot multiply employee rows — each employee matches precisely one average. That guarantee is worth stating, because fear of join duplication is what pushes many candidates away from this version unnecessarily; duplication happens when the joined side has multiple rows per key, and a `GROUP BY` on the key rules that out by construction. This version is often the most readable for analysts who think in tables rather than windows, it lets you join `departments` for the department name in the same breath, and it is the easiest of the three to extend — the same derived table can carry the department’s headcount, maximum, and median alongside its average if the follow-up asks for them. Its performance is typically comparable to the window version, since both compute each average once; the honest comparison is that the window version is more compact and keeps the average attached without a join key to get wrong, while the join version is more transparent about the intermediate table, reuses that table for several statistics at once, and works in older dialects or engines with weak window support. The correlated version trails both on large data unless the optimiser rescues it. An interviewer is rarely marking one version right and the others wrong — they are listening for whether you know all three exist and can say when each earns its place.
Two edge cases apply to all three versions, and raising either unprompted helps. An employee whose `department_id` is null belongs to no department, has no department average, and is correctly excluded by every version — the comparison against a null average is never true — but a thoughtful candidate notes the exclusion rather than letting it pass silently, because in real HR data an unassigned department is a data-quality finding, not a person to disappear. And “greater than the average” must stay strictly greater: an employee earning exactly the department average does not qualify, and in a one-person department the sole employee earns exactly their own average and so never qualifies — a small, correct consequence worth mentioning before the interviewer springs it as a trap.
**The second part: the highest-paid employee in each department.** Rank within each department, then keep the top rank.
```sql
SELECT employee_id, employee_name, department_id, salary
FROM (
SELECT
employee_id,
employee_name,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rn
FROM employees
) AS ranked
WHERE rn = 1
ORDER BY department_id;
```
Step by step: `PARTITION BY department_id` restarts the ranking inside each department, `ORDER BY salary DESC` puts the largest salary first within each partition, and `ROW_NUMBER` stamps the top earner in every department with 1. The outer filter keeps exactly those rows, and because the window preserves whole rows, the result carries the employee’s name and ID — the actual answer to the question as asked, not just a salary figure.
The tie decision is where this answer is won or lost. `ROW_NUMBER` always breaks ties somehow — if two employees share the top salary, one of them gets 1 and the other gets 2, and which one wins is arbitrary unless you add a deterministic tiebreaker such as `employee_id` to the window’s ordering. That may be exactly what the business wants — one name for a report — but it must be a decision, not an accident. If the question means every employee who earns the department’s maximum, swap `ROW_NUMBER` for `RANK`: tied top earners both receive rank 1, both survive the filter, and the next salary after them is ranked 3, reflecting the tie. `DENSE_RANK` also keeps both tied earners at 1 but ranks the next salary 2. A complete answer states which function was chosen and why, and asks — or at least flags — whether a tie should return one person or all of them. The alternative join-back technique, joining `employees` to a per-department `MAX(salary)` subquery on both department and salary, naturally returns all tied earners, and is a perfectly good answer; it is also a neat mirror of version three above, and pointing that out shows the two halves of the question connecting in your mind rather than sitting as separate memorised recipes.
### The common wrong answer
The canonical wrong answer for the first part is `WHERE salary > AVG(salary)` in a flat query. Aggregate functions cannot appear in a `WHERE` clause, because `WHERE` filters rows before any grouping or aggregation happens — the average does not exist yet at that point in logical processing. Candidates who write it usually reach next for `HAVING`, which fails differently: `HAVING` filters groups, not individual rows, so it can answer “which departments have a high average” but can never return individual employees. Knowing why both fail — not just that they fail — is the understanding the question is fishing for.
For the second part, the canonical wrong answer is `SELECT department_id, MAX(salary) FROM employees GROUP BY department_id`, presented as though it answered the question. It returns a number per department, not a person. The follow-up error is trying to fix it by adding `employee_name` to the select list or the `GROUP BY`: grouping by name as well changes the grain to one row per employee, so the “maximum” of each one-row group is just that employee’s own salary and every employee comes back. A related broken fix selects the name alongside the maximum in dialects that permit loose grouping, returning an arbitrary employee’s name next to the top salary — an answer that can look right on sample data while naming entirely the wrong person.
A quieter error, in the join version of the first part, is joining the grouped subquery on salary or on a non-unique key, or grouping the derived table by something finer than department, which reintroduces multiple rows per employee and duplicates people in the output. Every version of this question rewards the same habit: state the grain of each piece — one row per employee here, one row per department there — and check that the combination preserves it.
**Variant and follow-up.** The natural variant flips the comparison up a level: “list the departments whose average salary is higher than the company-wide average salary.” Now the grain of the answer is the department itself, so `GROUP BY` and `HAVING` — the tools that were wrong for the employee-level question — become exactly right, and recognising that reversal is the point of the variant.
```sql
SELECT
d.department_name,
AVG(e.salary) AS dept_avg
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING AVG(e.salary) > (
SELECT AVG(salary)
FROM employees
)
ORDER BY dept_avg DESC;
```
The scalar subquery in the `HAVING` clause is uncorrelated this time: the company average is a single number, computed once, against which each department’s average is tested after grouping. Note how naturally `departments` joins in here to supply the name, since the answer is a list of departments rather than people. Strong follow-up discussion includes weighting: the company average is an average over employees, so a large department pulls it toward itself far more than a small one does, and a department can beat the company average while sitting below the simple average of department averages — two different benchmarks that casual phrasing conflates. If the interviewer then asks for each above-average department’s top earner, you are simply composing the two halves of the original question: filter departments with this `HAVING` logic, rank employees within departments as before, and keep rank 1 — a closing move that demonstrates the whole question was one connected toolkit, not two tricks.## Question 9: Self-joins — finding managers and department peers
### The question
Using the shared schema — employees with employee_id, first_name, last_name, department_id, manager_id, salary and hire_date, and departments with department_id and department_name — write two queries. First, list every employee together with the name of their manager. Every employee must appear in the result, including the most senior person in the company, who has no manager. Second, list pairs of employees who work in the same department, with each unordered pair appearing only once.
### What they are really testing
A self-join looks like a trick the first time you meet it and like ordinary work every time after that, which is exactly why interviewers like it. Almost every real organisation stores its hierarchy in a single table. People report to other people who are rows in the same table, teams sit inside the same roster, and referrals, mentors, buddies and approvers all point back into the same list of names. If you can only join two different tables, you cannot answer the most natural management questions a business asks: who reports to whom, who sits alongside whom, where does a chain of command actually run.
The first part tests whether you understand that a table can play two roles at once. The employees table is both the list of workers and the list of managers, because managers are employees too. The only thing that changes is the role each copy plays in the query, and you signal that role with a table alias. Interviewers watch for clear aliases here more than they watch for anything else. Names like e for the employee and m for the manager make the query readable at a glance. Names like a and b, or worse, no aliases at all with repeated column names, force the reader to reverse-engineer your thinking, and in an interview the reader is scoring that thinking in real time.
The first part also quietly tests your join choice. The senior person at the top of the hierarchy has a NULL in manager_id, because there is nobody above them in the table. An inner join compares that NULL against every employee_id, finds no match, and drops the row entirely. The query runs, it returns plausible-looking results, and it is wrong in the most instructive way possible: the one person a leadership report most needs to include has vanished. Choosing a LEFT JOIN is therefore not a stylistic preference. It is the difference between a complete roster and a roster with the chief executive silently missing.
The second part tests a different skill: generating combinations without drowning in duplicates. Joining employees to employees on department produces, by default, every ordered pairing, including an employee paired with themselves, and both directions of every genuine pair. The interviewer wants to see whether you can reason about that explosion before it happens and tame it with a single inequality condition. The standard device, requiring the first employee_id to be strictly less than the second, kills self-pairs and mirror pairs in one move. Candidates who reach for DISTINCT at the end to clean up the mess reveal that they are treating symptoms rather than causes, a theme that runs through this whole set.
Finally, the question tests composure. Many candidates have joined many tables but have never joined a table to itself, and the unfamiliar shape can rattle them even though the underlying logic is identical. Saying out loud, calmly, that you will use the table twice under two aliases is often half the marks. The interviewer is hiring someone who will face unfamiliar query shapes on ordinary Tuesdays, and the self-join is a safe way to watch how you behave in the first thirty seconds of not recognising something.
### The worked answer
Start with the manager listing. Use employees twice: once as the employee whose row you are reporting, and once as the lookup table for the manager’s name. Join on the employee’s manager_id equalling the manager copy’s employee_id, and make it a LEFT JOIN so employees with no manager survive with NULLs in the manager columns. Concatenating first and last names keeps the output shaped the way a stakeholder would actually read it, though returning the four name columns separately is equally correct and sometimes safer, because it leaves formatting to the reporting layer.
```sql
SELECT
e.employee_id,
e.first_name || ‘ ‘ || e.last_name AS employee_name,
m.first_name || ‘ ‘ || m.last_name AS manager_name,
e.department_id
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id
ORDER BY e.department_id, e.last_name;
```
Walk through what happens row by row. For a junior analyst whose manager_id is 104, the join finds employee 104 in the manager copy and fills in that person’s name. For a department head whose manager is the chief executive, the same thing happens one level up. For the chief executive, manager_id is NULL, the ON condition never evaluates to true — remember that NULL never equals anything, not even another NULL — and the LEFT JOIN preserves the employee row anyway, padding the manager columns with NULL. If you want the output to read more kindly, you can wrap the manager name in a COALESCE that substitutes a label such as Top of hierarchy, but raise that as a presentation choice rather than burying it in your first draft; some interviewers prefer the honest NULL because downstream systems handle it predictably.
If your dialect uses a different concatenation operator, adapt without fuss. MySQL commonly uses CONCAT with the two name columns and a space between them. SQL Server uses the plus operator for strings in older style and CONCAT in modern style. The join logic, which is what is being tested, does not change at all across dialects, and saying so shows you know which part of the query is portable and which part is local decoration.
Now the pairs query. Join employees to itself again, this time on department, and add the inequality that enforces each pair once.
```sql
SELECT
a.employee_id AS employee_one_id,
a.first_name || ‘ ‘ || a.last_name AS employee_one,
b.employee_id AS employee_two_id,
b.first_name || ‘ ‘ || b.last_name AS employee_two,
a.department_id
FROM employees a
JOIN employees b
ON a.department_id = b.department_id
AND a.employee_id < b.employee_id
ORDER BY a.department_id, a.employee_id, b.employee_id;
```
The department equality does the grouping work: only colleagues in the same department can pair. The strict inequality does the deduplication work, and it is worth being able to explain precisely why. Without it, an employee joins to themselves because their department matches their own department, producing useless self-pairs. Without it, Ana paired with Ben and Ben paired with Ana both appear, because both rows satisfy the department condition, doubling your result and misleading anyone counting collaboration pairs or potential mentor matches. With the less-than condition, only the ordering in which the smaller identifier comes first survives, so each genuine pair appears exactly once and no one is paired with themselves. Note that this is an inner join by design: you only want pairs that genuinely exist, so there is no outer row to preserve. Contrasting the join choice here with the LEFT JOIN in the first part, unprompted, is the kind of detail that moves an answer from correct to convincing.
A useful sanity check to offer verbally: a department with n people should produce n multiplied by n minus one, divided by two, pairs. A department of four produces six pairs. If your query returns twelve, you have kept both directions. If it returns sixteen, you have kept self-pairs too. Offering that arithmetic before anyone asks tells the interviewer you test your own work rather than trusting that a query which runs must be right.
### The common wrong answer
The classic failure is the inner join version of the manager query. It looks clean, it is syntactically perfect, and it drops the top of the hierarchy.
```sql
-- Wrong: silently drops the employee who has no manager
SELECT
e.first_name, e.last_name,
m.first_name AS manager_first_name,
m.last_name AS manager_last_name
FROM employees e
JOIN employees m
ON e.manager_id = m.employee_id;
```
The fix is one word, but the lesson is large: whenever a foreign key can legitimately be NULL, ask yourself whether the unmatched rows still belong in the answer. Org charts, category trees and approval chains all have roots, and roots always have NULL parents. A second frequent failure is forgetting aliases altogether and writing ambiguous column references that the engine rejects, or worse, qualifying everything with the same table name so the query cannot distinguish the two roles. A third is solving the pairs problem with DISTINCT after the fact. DISTINCT cannot rescue the pairs query, because Ana-with-Ben and Ben-with-Ana are genuinely different rows in the result — different values in different columns — so there is nothing duplicate for DISTINCT to remove. Candidates who propose it reveal they have not visualised the intermediate result. A fourth, subtler error is using less-than-or-equal in the inequality, which quietly re-admits every self-pair. Each of these mistakes is small on the page and large in what it signals, which is why this question has survived so long in interview loops.
**Variant.** Expect the follow-up that turns one level into many: list each employee with their manager and their manager’s manager, or find everyone who ultimately reports up to a given executive. The two-level version is just a second self-join chained onto the first — join a third copy of employees on the manager copy’s manager_id, again with a LEFT JOIN so short chains do not vanish — and you should be able to write it without hesitation. The unlimited-depth version needs a recursive common table expression, which anchors on the root, then repeatedly joins employees whose manager is in the set built so far. You may not be asked to write the recursion in a first screen, but naming it as the right tool, and noting that the fixed self-join only reaches as far as the joins you wrote, shows you know where this technique ends and the next one begins.
## Question 10: Conditional aggregation — pivoting monthly revenue by genre
### The question
A video rental business tracks its catalogue in a films table with film_id, title and genre, and its transactions in a rentals table with rental_id, film_id, rental_date and amount. Write a query that produces one row per month, with total rental revenue for each month broken out into a separate column for each major genre — Action, Comedy and Drama — plus a column for all other genres combined and a column for the month’s total revenue.
### What they are really testing
Conditional aggregation is the technique experienced analysts reach for weekly and beginners often do not know exists. Business stakeholders rarely want a long, skinny table with one row per month per genre that they must then reshape in a spreadsheet. They want the shape they think in: months down the side, categories across the top, numbers in the middle. Producing that shape directly in SQL, without any pivot operator and without exporting the problem to another tool, is what this question examines.
Underneath the presentation, the interviewer is testing whether you understand what aggregation does to rows. A SUM with a CASE inside it does not filter rows out of the query. Every rental still flows into its month group. The CASE simply decides, row by row, whether that rental’s amount contributes to a particular column’s total or contributes nothing. Once that idea clicks — that you are sorting money into buckets within a single pass over the data rather than running separate queries per genre — the whole pattern becomes portable to dozens of situations: counts of orders by status, sign-ups by channel, tickets by priority, pass and fail counts in the same report.
The question also tests care with the edges. Months must be derived consistently from rental_date, ideally truncated to the first of the month so sorting and grouping behave. Rentals whose genre is none of the named three must not disappear; they belong in the Other column, and the total column must reconcile with the sum of the parts, which gives you a built-in correctness check. NULL handling matters too: a SUM over a CASE that returns NULL for non-matching rows works elegantly because SUM ignores NULLs, while the alternative construction using zero works equally well and some interviewers prefer it because it makes the arithmetic explicit. Knowing both, and knowing why both work, is worth more than memorising one.
There is also a quiet test of scope judgement. A relational database has no truly dynamic pivot in standard SQL: the columns of a query must be known when the query is written. If a new genre appears next quarter, someone must add a column to the query. Candidates who acknowledge that limit, and who group the long tail into Other rather than pretending they can conjure a column per genre automatically, sound like people who have maintained real reports rather than only solved exercises. Interviewers also listen for how you handle genre terminology, because messy real catalogues spell, split and merge categories over time; when a reader needs to check how genres are defined and grouped, a reference such as Film Studies Reference is the sort of place they would confirm the classification language before arguing with the numbers.
### The worked answer
Group by the month, and inside each SUM place a CASE that returns the rental amount only when the film’s genre matches that column’s genre, returning NULL otherwise. Join rentals to films to reach the genre, since the transaction table alone does not carry it.
```sql
SELECT
DATE_TRUNC(rental_date, MONTH) AS rental_month,
SUM(CASE WHEN f.genre = ‘Action’ THEN r.amount END) AS action_revenue,
SUM(CASE WHEN f.genre = ‘Comedy’ THEN r.amount END) AS comedy_revenue,
SUM(CASE WHEN f.genre = ‘Drama’ THEN r.amount END) AS drama_revenue,
SUM(CASE WHEN f.genre NOT IN (’Action’, ‘Comedy’, ‘Drama’)
THEN r.amount END) AS other_revenue,
SUM(r.amount) AS total_revenue
FROM rentals r
JOIN films f
ON r.film_id = f.film_id
GROUP BY DATE_TRUNC(rental_date, MONTH)
ORDER BY rental_month;
```
Read the query the way the engine executes the grouping. Rentals are joined to their films, so every transaction now carries a genre and a date. Rows are bucketed by month. Within each month’s bucket, each SUM scans the same rows through a different CASE lens: the Action column accumulates only Action amounts, the Comedy column only Comedy amounts, and so on. The Other column catches everything whose genre is outside the named three, so no revenue leaks. The final SUM has no CASE at all and simply totals the bucket, which means total_revenue must equal the four genre columns added together, month after month. If it ever does not, something upstream — a NULL genre, an unjoined film, a duplicated catalogue row — deserves investigation, and saying that you would run exactly that reconciliation check marks you out as careful.
Two dialect notes are worth having ready. In engines without DATE_TRUNC for months, you can group by the year and month extracted from the date, or by a formatted year-month string, keeping the same expressions in both the SELECT and the GROUP BY. In SQL Server, DATEFROMPARTS built from the year and month parts gives you the clean first-of-month value. The aggregation pattern itself never changes; only the month-truncation expression is local. Also note that a genre value of NULL falls through every comparison, including the NOT IN test, because comparisons with NULL do not return true. Production-hardened code often wraps the genre in a COALESCE that maps missing genres to a label such as Unclassified so those rentals land in Other where a human will notice them. Raising that point unprompted, even briefly, shows production instincts beyond the exercise.
The same pattern produces counts just as happily as sums. Replace the amount with a one inside the CASE and you count rentals per genre per month. Replace SUM with COUNT and a filtered condition in dialects that support it and you get the same shape another way. The SUM and CASE version remains the one to lead with, because it works in every major engine, reads clearly to anyone reviewing your code, and extends naturally when the stakeholder asks for averages, minimums or a second metric per genre in the following breath.
### The common wrong answer
The most common wrong turn is writing a WHERE clause that filters to one genre and then promising to run the query three times and stitch the results together in a spreadsheet. That is not a pivot, it loses the shared month spine — a month with no Comedy rentals simply vanishes from the Comedy run instead of showing a gap or a zero — and it triples the maintenance burden. A close cousin is grouping by both month and genre and presenting the long result as finished. That output is correct data in the wrong shape: the stakeholder asked for months as rows and genres as columns, and handing back reshaping work is a small failure of the actual job, which is delivering answers in usable form.
Another frequent error is putting the CASE in the wrong place — wrapping the whole SUM in a CASE, or filtering with CASE in the GROUP BY — which either breaks aggregation or produces one column that flips meaning row by row. And a particularly revealing mistake is reaching for three separate subqueries or self-joins, one per genre, joined on month. That construction can be made to work, but it scans the data repeatedly, risks mismatched months across the branches, and collapses the moment a fourth genre is requested, whereas the conditional aggregation answer absorbs a new genre by adding a single line. Interviewers are not only checking that you arrive; they are checking the road you took, because the road is what you will drive every day if they hire you.
**Variant.** The natural follow-up changes the grain or the measure: one row per month with columns for each payment method, or columns counting rentals alongside columns summing revenue, or percentages of the month’s total per genre instead of raw amounts. Each is a small step from the worked answer. Counts and sums can sit side by side in the same GROUP BY because they share the same grouping key. Percentages are each genre column’s expression divided by the total expression, guarded against division by zero with a NULLIF on the denominator — a detail worth mentioning even if time runs short, because divide-by-zero in a monthly report is exactly the kind of thing that surfaces in the month a store was closed. If the interviewer instead asks for the long format back, smile: grouping by month and genre is now the easy direction, and explaining when each shape serves the reader better closes the question on your terms.
## What candidates are reporting about analyst SQL screens
The themes below come from reported discussion among candidates comparing notes after screens. They are presented here as themes only — the recurring shapes of what people say tripped them, argued about, or wished they had known — and for each theme, the point is what the structured answers in this set actually show when you work them carefully.
The most frequently reported miss, by a wide margin, is the difference between WHERE and HAVING. Candidates describe answering a question about departments with an average salary above a threshold by putting the average condition in the WHERE clause, watching the query fail or silently misbehave, and realising the distinction only in the corridor afterwards. The frustration in these accounts is rarely that the concept is hard; it is that under time pressure the two clauses blur into one idea of filtering. What the structured answers in this set show is a discipline that prevents the blur: decide, before writing anything, whether a condition talks about individual rows or about groups. Row conditions — this department, this hire date, this salary band — belong in WHERE and are applied before any grouping happens. Group conditions — averages, totals, counts — can only be evaluated after groups exist, so they belong in HAVING. The worked answers here also show the habit of using both in the same query without apology: WHERE narrows the population first, which is both clearer and cheaper, and HAVING then judges the groups that remain. Candidates who narrate that order out loud, even in one sentence, report that interviewers stop probing the point, because the narration itself is the evidence of understanding.
The second theme is the NOT IN trap when a subquery can return NULL. Candidates recount confident answers to questions of the form find customers who never ordered, or employees in no project list, that collapsed when a single NULL sat in the comparison list. The logic is unforgiving and worth restating plainly: NOT IN asks whether a value differs from every value in the list, and if one list member is NULL, the comparison against that member is neither true nor false, so the whole condition can never be true and the query returns nothing. What the answers in this set show is a preference for constructions that do not carry the trap. NOT EXISTS tests for the absence of a matching row and is indifferent to NULLs in the data. A LEFT JOIN followed by a check that the joined key IS NULL reaches the same answer through the join machinery candidates already trust. The lesson candidates draw in discussion, and the one borne out here, is not never use NOT IN — on a column guaranteed non-nullable it is perfectly fine — but know what your columns permit, and reach for the NULL-proof shape when you do not know or cannot guarantee it.Tie-handling in Nth-highest salary questions generates more argument than any other single topic. Discussion threads split into camps: those who used a dense rank and defended shared places, those who used a row number and picked an arbitrary winner among equals, and those who used a LIMIT with an offset and discovered that two people sharing second place broke their counting entirely. What the structured answers in this set show is that there is no disagreement about SQL here at all — there is a disagreement about what the question means, and the professional move is to surface it. If the business means the second distinct salary value, dense ranking is the honest tool. If it means a specific person in a specific row position, the tie must be broken by some stated rule or the answer is arbitrary. The set’s worked answer therefore clarifies the meaning, implements the distinct-value reading, and names the alternative — and candidates report that interviewers reward exactly that sequence, because real stakeholder questions arrive ambiguous in precisely this way every week.
A fourth recurring confession is using DISTINCT to hide a join fan-out. The story repeats with small variations: a join to a table with multiple rows per key multiplies the result, totals inflate, and DISTINCT gets sprinkled on top until the row count looks plausible again. Sometimes it even produces the expected rows while leaving every aggregate quietly wrong, because the duplication happened before the summing. What the answers in this set show is the diagnostic habit that replaces the sprinkle: when rows multiply, ask which side of the join carries duplicates and why. Check the grain of each table — one row per what? — before joining. Fix the problem at its source by aggregating the many-side table down to the join grain first, or by joining on the additional column that makes the match unique. DISTINCT has legitimate uses, and this set uses it where counting distinct values is genuinely the question, but as a repair for a misunderstood join it treats the symptom and corrupts the numbers, and interviewers who spot it tend to dig exactly there.
The final theme is running-total frame confusion. Candidates describe window queries that returned the grand total repeated on every row, or a total that reset unpredictably, and only later learning that the frame — the set of rows each row’s calculation can see — was the culprit. The default frame behaviour differs in ways that surprise people, especially once an ORDER BY enters the window definition and quietly changes what the default frame includes. What the structured answers in this set show is explicitness as the cure: write the frame out in full, rows between unbounded preceding and current row for a cumulative total, so the query says what it means in every engine rather than relying on a default you half-remember. The broader point candidates take away, and the point this set keeps making across all five themes, is that screens rarely fail people on exotic syntax. They fail on a small set of precise ideas — filtering order, NULL logic, ties, grain, frames — applied under pressure. Those ideas are learnable, they are all on display in the ten answers here, and they repay deliberate practice far more than another hour of skimming question lists.
## Three interview rooms
The three scenarios below are illustrative examples — composite situations built from the kinds of moments candidates describe, not accounts of particular people or particular companies. Each is worked through to the lesson it carries.
**Room one: the screen that turned on a single clause.** Consider a candidate who is doing well twenty minutes into a hiring-manager screen for a retail analytics role. The questions have covered joins and grouping comfortably, and then comes a plain request: show each department and its average salary, but only for departments where that average exceeds ninety thousand. The candidate writes a tidy query, groups by department, and places the average condition in the WHERE clause alongside a filter on location. The engine rejects the aggregate in WHERE, the candidate frowns, moves the condition around almost at random, tries it inside the SELECT, and burns four minutes while the interviewer watches the confidence drain. Nothing about the candidate’s knowledge was actually missing — asked afterwards, they explain grouping perfectly. What failed was retrieval under pressure: the two-stage picture of a query, rows filtered first and groups judged second, was not automatic enough to surface when nerves rose. The lesson is not to memorise a rule but to install a reflex. Before writing any aggregate condition, say the sentence: this is about groups, so it goes after grouping. Practising that narration on homework problems, out loud, is what makes it available in the room. The candidate in this scenario also recovers points in the final minute by calmly stating the correct structure even after the syntax has been tidied by the interviewer — a reminder that explaining the model counts, and that a screen is lost by panic more often than by a single misplaced clause.
**Room two: the answer that was right twice.** Consider a candidate who is asked for the second-highest salary and answers quickly with a dense rank window function, filtering to rank two. The interviewer nods and then asks: and if I wanted it without window functions? Many candidates hear this as a correction and begin apologising for a correct answer. This candidate hears it accurately, as a request to see the same idea from another angle, and writes the correlated version: the second distinct salary is the largest salary that is smaller than the overall maximum, or equivalently the value where exactly one distinct salary sits above it. The conversation that follows — about how each version treats two employees tied at the top, about which reads better to a future maintainer, about performance on a large table — is the best five minutes of the interview, and it happens because the candidate treats the follow-up as curiosity rather than judgement. The lesson generalises well beyond this question. Interviewers routinely ask for a second method, not because the first failed, but because the second method reveals depth: whether you understand the problem or merely remember a pattern. Preparing two routes to the flagship questions — a window route and a subquery route for ranking, a join route and an EXISTS route for absence — is therefore one of the highest-return habits in this whole area. It also protects you on engines or legacy systems where your first-choice feature does not exist.
**Room three: the messy table, live.** Consider a candidate who is handed a shared screen with an orders table that, the interviewer mentions almost casually, came from a system migration. The task is total revenue by customer. The candidate sums the amounts, groups by customer, and presents the result — and the interviewer asks whether they trust it. The strong move, and the one this candidate makes after a pause, is to stop calculating and start checking: count rows, count distinct order identifiers, and compare them. The counts disagree. The migration duplicated some orders, so revenue summed naively is inflated for exactly the customers whose orders were copied. The candidate then rebuilds the answer on a deduplicated base — selecting distinct orders first, or grouping the orders to one row per order identifier before summing — and states the assumption plainly for the interviewer to confirm. The lesson is that live exercises are often data-quality tests wearing a SQL costume. The syntax was never the hard part; the hard part was noticing that the grain of the table did not match the grain of the question. Building a ten-second grain check into your routine — what does one row mean here, and can it repeat? — will save you in real jobs far more often than in interviews, which is precisely why interviewers plant it. Notice, too, what the candidate did not do: they did not hide the duplication under a DISTINCT on the final output and hope. They found the duplication, named it, fixed it at the level where it occurred, and left the interviewer with more trust than a flawless first attempt would have built.
## A seven-day study plan
Work through the set in this order, writing every query by hand before running it, and keep a running list of every mistake you make — the list, reviewed on day seven, is the real curriculum.
- **Day 1 — Selection, filtering and sorting.** Rebuild the foundations until they are boring: SELECT with WHERE conditions combining AND, OR and NOT, BETWEEN and IN, pattern matching with LIKE, NULL checks with IS NULL and IS NOT NULL, and ORDER BY on multiple columns. Finish by writing ten small predicates from plain-English descriptions without looking anything up.
- **Day 2 — Aggregation and the two filters.** GROUP BY with COUNT, SUM, AVG, MIN and MAX. Drill the WHERE-versus-HAVING distinction with paired exercises: the same business question answered once with a row condition and once with a group condition, until choosing the clause feels automatic.
- **Day 3 — Joins.** Inner joins across employees, departments and orders; then LEFT JOIN and the discipline of asking which side’s rows must all survive. End the day on the self-join from Question 9, written twice from memory, once for managers and once for pairs.
- **Day 4 — Subqueries and set logic.** Scalar subqueries, IN and EXISTS, the NOT IN and NULL trap and its NOT EXISTS repair, and derived tables. Rewrite one answer from each earlier day using a subquery where you previously used a join, and note which version you would defend in review and why.
- **Day 5 — Window functions.** ROW_NUMBER, RANK and DENSE_RANK side by side on data with deliberate ties; running totals with the frame written out in full; LAG for period comparisons. This is the day the Nth-highest question should stop feeling like a puzzle and start feeling like a choice between stated meanings.
- **Day 6 — The combined techniques.** Conditional aggregation from Question 10, CASE logic inside and outside aggregates, deduplication with window functions, and one full timed mock: three questions, forty-five minutes, speaking your reasoning aloud as you type.
- **Day 7 — Review and repair.** Re-attempt every question you got wrong during the week, from a blank page. Read your mistake list and compress it into five personal rules. Do one final timed question, then stop — rest before a real screen is part of preparation, not a reward for finishing it.
One habit multiplies the value of all seven days, and it is worth a paragraph of its own. Keep a personal notebook of your own worked answers — not copied solutions, but the queries you produced, the variants you tried, and short notes on the wrong answers you personally fell for and why they tempted you. Preparation compounds when it is written down in your own words, because the act of recording a mistake in your own phrasing is what converts it into a rule you will remember under pressure, and because a notebook you build yourself becomes a revision asset no generic question list can match: it is indexed by your weaknesses, not by someone else’s syllabus. Keep it somewhere private, structured and entirely yours — VaultBook is built for exactly that kind of personal question-and-answer notebook, where each problem, your answer, its variants and your wrong-answer notes stay together and searchable — and add one entry after every practice session, however short. By the end of a single week the notebook will hold the ten answers from this set in your own hand, the five themes from the discussion section translated into your own near-misses, and the beginnings of a second set written entirely from your errors. Candidates who keep such a record report that revision stops feeling like starting again, because it is not: it is continuing, from exactly where their own thinking left off.
## Frequently asked questions
### Q: Does it matter whether I use LIMIT or TOP to restrict rows?
Only in the sense that you must use the one your engine speaks. LIMIT is the form in MySQL, PostgreSQL and SQLite, typically placed at the end of the query with an optional offset. TOP is the SQL Server form, placed immediately after SELECT, with its own syntax for ties and percentages. Oracle historically used ROWNUM and now supports the standard FETCH FIRST form, which PostgreSQL and newer SQL Server versions also accept. In an interview, write the dialect of the stack you are applying to, and if you are unsure which engine the company runs, say so and name the equivalent — interviewers treat dialect awareness as a plus, not a gap, because the underlying idea of ordering before restricting is identical everywhere and is the part that actually matters.
### Q: Should I memorise SQL syntax word for word before a screen?
Memorise the shapes, not the spelling of every clause. You should be able to write the skeleton of a grouped query, a joined query, a common table expression and a window function from memory without hesitation, because hesitation there reads as inexperience. Exact keyword order for rarer features, the precise punctuation of a frame clause, or a vendor function name are things working analysts look up weekly, and reasonable interviewers know it. What you cannot look up in the room is the reasoning: which join, which filter stage, which ranking function for the stated meaning. Spend memorisation effort there. If you blank on a detail mid-answer, say what you are trying to express and approximate the syntax — that recovers far more credit than silence.
### Q: When should I use a CTE instead of a subquery?
Use a common table expression when it makes the logic read in the order it happens, when you need to reference the same intermediate result more than once, or when the query is recursive, where a CTE is the only option. A named step such as ranked_salaries followed by a short final selection is easier for an interviewer to follow and easier for you to debug aloud than the same logic nested three levels deep. Use a subquery when the inner piece is small, used once, and genuinely reads as a detail of the outer question — a single maximum value in a comparison, for instance. Performance differences between the two are engine-dependent and usually smaller than candidates fear; in a screen, clarity is the deciding argument, and naming your steps clearly is also the best way to show an interviewer your reasoning as you go.
### Q: How much should I talk about performance and indexes in an analyst screen?
A little, offered at the right moment, goes a long way. Analyst screens are primarily correctness and communication tests, so lead with a query that is right and readable. Then, if time allows, one or two grounded observations earn disproportionate credit: that filtering early reduces the rows a join must carry, that an index on a join key or a frequently filtered column would matter at scale, or that selecting only needed columns beats selecting everything on a wide table. Avoid speculative optimisation speeches and avoid rewriting a clear query into a clever one in the name of speed. If the interviewer wants depth on execution plans, they will ask, and at that point the honest answer about what you would check first is worth more than confident guessing.
### Q: How can I practise if I do not have a database installed?
You have more options than you may think, and none of them require a serious setup. Free in-browser SQL environments let you create small tables, load a handful of rows and run queries immediately, which is all the ten questions in this set need. Lightweight local options such as SQLite run as a single file or a small download and handle joins, grouping, subqueries and common table expressions happily, though window function coverage depends on version. Spreadsheet knowledge helps more than expected for building intuition about grouping and pivoting, even if you write the real answers in SQL. What matters is not the platform but the loop: invent tiny datasets with deliberate edge cases — a NULL manager, a tied salary, a duplicated order — predict the result before running the query, and investigate every surprise. Prediction is where the learning lives.
### Q: Are window functions available in MySQL, PostgreSQL and SQL Server?
Yes, in all three, with the practical caveat of versions. PostgreSQL has supported the full range — ranking functions, running aggregates with frames, LAG and LEAD — for many years and is the reference implementation most tutorials quietly assume. SQL Server has equally mature support, with a small number of frame restrictions in older versions that rarely affect interview questions. MySQL gained window functions in version 8, so on MySQL 8 and later everything in this set works; on the older 5.7 line still lingering in some companies, window functions do not exist and the same answers must be built from subqueries and variables, which is one reason the second-method habit matters. If a job description names a database without a version, it is always acceptable — and often wise — to state the version your answer assumes.
### Q: What should I say when I am genuinely stuck on a question?
Say where you are, precisely, and keep working from there. A strong recovery sounds like this: state what the result should look like, name the step you are confident about, isolate the step you are unsure of, and offer your best attempt at that step while flagging it as the uncertain part. Interviewers can award a great deal of credit to a well-structured partial answer, and they routinely say that a candidate who reasons aloud gives them something to help with, while a silent candidate gives them nothing. Asking one clarifying question — about ties, about NULLs, about whether unmatched rows should appear — is never a weakness; it is frequently the moment the interviewer decides you think like an analyst. What does not recover is guessing silently, declaring a wrong answer finished with confidence, or giving up on a question you have half solved. Partial, honest and structured beats blank every time.
### Q: How does this set connect to data-engineer interview sets?
The overlap is large at the foundations and then the paths divide by emphasis. Engineers are asked the same joins, grouping, subqueries and window functions, because everyone who works with data shares that core — an engineer who cannot rank, deduplicate or aggregate conditionally cannot build reliable pipelines either. Where engineering sets go further is in scale and structure: partitioning and incremental loads, schema design and normalisation, data modelling trade-offs, query performance on very large tables, and pipeline correctness concerns such as idempotency and late-arriving data. Analyst sets, like this one, lean harder on business-shaped questions, ambiguous requirements, stakeholder-ready output shapes and explaining results in plain language. If you are interviewing for hybrid roles, treat this set as the shared trunk: master it completely, then branch into modelling and pipeline topics for the engineering side rather than starting again from zero.
## Sources and closing note
The questions, schema exercises and study structure in this set draw on the PracHub Top 50 SQL Interview Questions guide as a reference point for the topics employers return to most often, and on three full-length video walkthroughs studied alongside it: Complete Data Analyst SQL Interview Preparation 2026 by Data Science with Sushant; Top 25 SQL Interview Questions You Must Know (Explained With Data); and Top 10 SQL Interview Questions You MUST Know in 2026. The worked answers, wrong-answer analyses, discussion themes, scenarios and study plan above are written for this set, in this publication’s own words, around the shared employees, departments, orders and customers schema used throughout.
— Pinnacle Report, 2 December 2026. Last checked 2 December 2026.

