The interviewer does not begin with a puzzle. In room after room, on video call after video call, the opening is almost disarmingly plain: a small table of employees, a small table of departments, and a request that sounds as if it should take ninety seconds. Find the second-highest salary. List every employee with the name of their department. Show the departments that have nobody in them. Candidates who have spent months preparing for elaborate problems relax at that moment, and that relaxation is often where the screen is lost. The questions are not hard in the way a design problem is hard. They are hard in the way a driving test is hard — familiar material, performed live, under observation, with no compiler to forgive a small slip and no second chance to quietly re-run the query and see what comes back.

That pattern has held for years across the large service companies that hire freshers and early-career engineers at scale — Tata Consultancy Services, Infosys, Wipro, Cognizant and their peers — not because their interviewers lack imagination, but because the small family of questions does a job that exotic questions do not. A handful of salary, join and grouping problems, asked the same way season after season, separates candidates who have merely read SQL from candidates who can actually write it, explain it and defend it when the interviewer changes one condition. Change “second-highest” to “second-highest in each department.” Change “list the employees” to “now show me the departments with no one in them.” The candidate who memorised a single answer collapses. The candidate who understood the idea underneath adjusts in a sentence or two and moves on. Recruiters and hiring managers who run these panels describe the same disappointment in different words: the failure is rarely on the advanced question at the end. It is on the basic question at the start, answered too quickly, with the edge case missed and the reasoning left unsaid.
This set is built around that reality. It takes ten questions that recur, in recognisable form, across service-company SQL screens, and answers each one the way a strong candidate needs to be able to answer it in the room — not just with a query that happens to return the right rows on clean data, but with an account of what the question is testing, how the answer behaves when the data is untidy, what the interviewer is likely to ask next, and why the most common wrong answer is wrong. Two of those ten are covered here in full: the second-highest salary, the single most reliable question in the entire family, and the joins question that quietly tests whether a candidate understands what happens to rows that do not match. Everything else in the set builds on the habits these two establish, so they repay slow reading. If you can answer these two completely — ties, empty departments, missing values and all — you are not merely ready for two questions. You are ready for the way the whole screen thinks.
## How the service-company SQL screen actually works
A candidate preparing for a service-company process is, without always realising it, preparing for two different tests that happen to share a subject. They reward different skills, they punish different weaknesses, and a preparation plan that treats them as one test will serve neither well. Understanding which test you are in at any given moment changes what a good answer even looks like.
The first test is the assessment. At TCS this is the National Qualifier Test, the NQT, and the other large firms run equivalents under their own names — an online, timed, proctored examination taken by very large numbers of candidates at once, in which SQL appears alongside aptitude, reasoning and coding. The SQL in an assessment is typically multiple-choice or short-output in character: a query is shown, four possible results are offered, and the candidate must predict what the query does; or a small requirement is stated and the candidate must choose, or briefly write, the query that satisfies it. There is no interviewer to impress and no partial credit for a good explanation. What the assessment rewards is speed and precision in reading. Can you trace a join in your head and count the rows it returns? Can you spot that a condition in the wrong place has changed the meaning of an outer join? Can you tell, without running anything, what a query returns when two employees share the same salary? The assessment is a filter, and it is deliberately unforgiving about exactly the details — duplicates, missing values, the difference between similar-looking functions — that a candidate can gloss over in self-study because the practice platform always showed a tidy result.
The second test is the technical interview, and it could hardly be more different in feel. Here SQL is usually one strand among several — a programming language, a project discussion, some database theory, sometimes a second technical subject from the resume — and the SQL itself is often modest in volume: two or three questions, sometimes only one, explored in depth. The candidate writes on paper, on a whiteboard, in a shared document or in a shared coding screen while the interviewer watches, and crucially, the candidate talks. “Walk me through what this does” is not small talk; it is the question underneath the question. An interviewer who asks for the second-highest salary and receives a correct query in silence has learned something. An interviewer who receives the same query with a clear account of how it treats two employees tied at the top, and what it returns if the company has only one salary level, has learned considerably more, and it is the second candidate who tends to be remembered when the panel compares notes. In the interview, the explanation is not decoration around the answer. It is a large part of the answer.
At TCS, the outcome of the combined process sorts candidates into tracks that candidates refer to constantly and prepare for unevenly: Ninja, the standard entry-level offer; Digital, a higher-paying track for stronger performers; and Prime, the highest of the three fresher tracks, aimed at candidates who perform at a distinctly higher level in the assessment and interviews. The other firms maintain their own versions of the same ladder under different names — differentiated fresher roles with higher compensation for candidates who clear a higher bar. The practical point for SQL preparation is not the labels but the gradient they create. A Ninja-level SQL performance is a correct, serviceable answer to the standard question, cleanly written. A Digital- or Prime-level performance is the same answer plus the follow-up handled without hesitation: the per-department variant produced on request, the tie case named before the interviewer names it, the alternative method offered when the first one is challenged. Interviewers calibrate quickly. The first question establishes a level; the follow-ups test whether that level was real. Candidates aiming at the higher tracks should therefore prepare not question by question but layer by layer — the standard answer, the variant, the edge case and the explanation, for every question in this set.
How the writing itself happens matters more than candidates expect. In many service-company interviews, especially in high-volume fresher drives, SQL is still written on paper or typed into a plain shared screen with no execution at all. There is no autocomplete to supply a keyword, no error message to announce a misplaced comma, and no result grid to reveal that the query returned eleven rows when it should have returned nine. Syntax must be carried in the head accurately enough to survive that setting, and the candidate must be their own executor — mentally running the query against the sample data, row by row, to catch the mistake before the interviewer does. This is a trainable skill, and it is trained in a specific way: by writing queries by hand, away from a live database, and then checking them, rather than by typing into a console that instantly forgives and corrects. Candidates who have only ever practised on auto-completing platforms often discover, in the room, that they know what a query should look like in outline but cannot reliably produce one in full. The gap is embarrassing precisely because it is so avoidable.
Against that background, what interviewers actually score becomes clearer, and it is narrower and more humane than candidates fear. First, correctness — but correctness understood properly, against the requirement as stated, including the cases the requirement implies but does not spell out. A second-highest-salary query that fails when the top salary is shared is not “almost correct”; on the data where it fails, it gives a wrong number with complete confidence, which is the most dangerous kind of wrong in production work. Second, handling of edge cases: ties, duplicate values, empty groups, and missing values — in SQL, the NULL, the marker for a value that is absent or unknown, which behaves unlike any ordinary value and silently changes the results of comparisons, counts and joins. Interviewers return to NULLs so persistently not from pedantry but because real company data is full of them: employees not yet assigned to a department, salaries not yet entered, managers not yet recorded. A candidate who never mentions NULLs is signalling that they have only ever worked with textbook data. Third, the ability to explain aloud — to state, in ordinary language, what each part of the query does and why it is there. This is scored for a practical reason the candidate should keep in mind: the job being hired for involves exactly this act, repeated daily, in discussions with colleagues and clients who will ask why a report shows what it shows. The interview is a sample of the work, not a ritual separate from it.
One further reality shapes the whole interview, and SQL preparation that ignores it is incomplete: in service-company fresher interviews, the resume is the interview. Panel members typically work from the document in front of them, and a skill listed there is an open invitation. A candidate who writes “SQL” or “MySQL” among their skills, or describes a project built on a database, should expect to be taken at their word and questioned accordingly — and the questioning will not stay at the level of the claim’s vaguest reading. If the resume names a project with a login system, expect questions about the tables behind it. If it names a specific database system, expect the dialect questions that system invites. Interviewers are not being unfair when they do this; they are testing the one thing an assessment cannot, which is whether the candidate’s account of themselves is accurate. The corollary cuts both ways. A modest resume, honestly stated and thoroughly defensible, outperforms an inflated one in these rooms, because every line of the modest resume survives questioning, while the inflated resume gives the interviewer a thread to pull for twenty minutes. Prepare SQL, by all means — but prepare it in proportion to what your own resume promises, and be ready for the screen to begin from your project and arrive at these ten questions by a route you did not choose.
## The two tables, and the ground rules for this set
Every question in this set is written against the same two tables, deliberately kept small enough to hold in the head and messy enough to expose weak answers. Real company schemas run to hundreds of columns; interview schemas do not, because the interviewer wants to test reasoning, not memory for column names. Two tables, honestly examined, are enough to test joins, grouping, ranking, subqueries and set logic — which is to say, nearly everything a fresher screen asks.
The first table is employees, with the following columns:
- emp_id — a unique number identifying each employee; no two employees share one.
- emp_name — the employee’s name, as text.
- dept_id — the number of the department the employee belongs to; this column refers to the departments table, and it may be NULL for an employee who has not yet been assigned to a department.
- salary — the employee’s salary, as a number; in the sample data these are monthly figures, though nothing in the questions depends on the period.
- manager_id — the emp_id of the employee’s manager; for the most senior person it is NULL, because there is no manager above them in the table.
- hire_date — the date the employee joined.
The second table is departments, with the following columns:
- dept_id — a unique number identifying each department.
- dept_name — the department’s name, as text.
- location — the city or site where the department is based.
The sample employees used throughout this part are as follows. Read them slowly, because the untidiness is intentional and several answers turn on it:
- Employee 101, Ananya Rao, department 10, salary 90,000, manager 105, hired 12 March 2021.
- Employee 102, Rohit Mehta, department 10, salary 90,000, manager 105, hired 28 June 2022.
- Employee 103, Sara Iqbal, department 20, salary 75,000, manager 106, hired 9 January 2020.
- Employee 104, Vikram Nair, department 20, salary 68,000, manager 106, hired 15 August 2023.
- Employee 105, Meera Pillai, department 10, salary 1,10,000, manager NULL, hired 3 February 2018.
- Employee 106, Arjun Bose, department 20, salary 95,000, manager NULL, hired 21 October 2017.
- Employee 107, Kavya Reddy, department 30, salary 60,000, manager 108, hired 7 July 2024.
- Employee 108, Nikhil Verma, department 30, salary 82,000, manager NULL, hired 30 November 2019.
- Employee 109, Divya Menon, department NULL, salary 55,000, manager 105, hired 19 April 2025.
- Employee 110, Farhan Ali, department 20, salary 75,000, manager 106, hired 11 September 2021.
The sample departments are:
- Department 10, Engineering, Bengaluru.
- Department 20, Data, Hyderabad.
- Department 30, Support, Pune.
- Department 40, Research, Chennai.
Notice what this small dataset already contains, because an interviewer who designed it this way is telling you what they care about. Two employees, Ananya Rao and Rohit Mehta, share a salary of 90,000, so any ranking question must decide what a tie means. The top salary, 1,10,000, belongs to one person alone, while the second distinct salary level, 95,000, belongs to Arjun Bose — a distinction between “the second row when salaries are sorted” and “the second-highest salary value” that Question 1 will make impossible to ignore. Department 40, Research, has no employees at all, which is what makes the joins question interesting. Divya Menon has no department yet, so she will appear and disappear from results depending on how a join is written. Three employees have no manager, so self-referencing questions later in the set have something real to bite on. Sara Iqbal and Farhan Ali share a salary of 75,000 inside the same department, which matters the moment a question is asked per department rather than across the whole company. None of this is accidental, and none of it is exotic. It is a fair miniature of production data.
Three ground rules govern every answer in the set. First, the syntax leans toward MySQL, the database most commonly named on fresher resumes and most commonly used in these screens; where SQL Server or Oracle would write the same idea differently — in limiting rows, in handling an outer join, in the names of functions — the answer notes the difference, because an interviewer who hears the dialect caveat unprompted hears a candidate who has worked in more than one environment or has at least read carefully. Second, every answer is expected to survive the sample data above, including its ties and its missing values; an answer that works only on cleaner data is presented in this set as what it is — a wrong answer waiting for the right data to expose it. Third, the set treats the spoken explanation as part of the answer throughout. Each question therefore gives the query and the reasoning together, in the order a candidate would sensibly deliver them in the room: what is being tested, the worked answer, the follow-up, and the mistake to avoid. Learn the four parts together and you will find, as candidates who prepare this way consistently report, that the interview begins to feel less like an examination and more like a conversation you have already had.
### Question 1 — Find the second-highest salary, and then the Nth-highest
The question, as it is usually put, is disarmingly short: “Write a query to find the second-highest salary in the employees table.” Sometimes the interviewer adds “and tell me who earns it.” Sometimes they say nothing more and simply watch what assumptions the candidate makes. Worked against the sample data, the correct value is 95,000 — the salary earned by Arjun Bose — because the highest distinct salary is 1,10,000, earned by Meera Pillai, and 95,000 is the next distinct level below it. Hold that word “distinct” in mind. Almost everything interesting about this question lives inside it.
#### What they are really testing
On the surface, the question tests whether the candidate can sort or compare numbers. Underneath, it tests three more valuable things. The first is whether the candidate thinks in terms of values or in terms of rows. “Second-highest salary” is a statement about values: among the different salary levels in the company, which is the second one down from the top? It is not a statement about rows: it does not ask for whoever happens to sit in the second row of a sorted list. When two employees share the top salary, those two readings give different answers, and the interviewer wants to know which reading the candidate reaches for without being prompted. In the sample data the top salary happens to be held by one person, so both readings agree here — which is precisely why a good interviewer immediately changes the data in conversation: “Suppose two people earn 1,10,000. What does your query return now, and what should it return?” The question is a trap only for candidates who never noticed there were two readings at all.
The second thing being tested is command of more than one technique. There is no single canonical solution to this problem; there are at least three respectable families of solution — a subquery built on the maximum, a ranking function, and a sorted selection with duplicates removed — and each has a setting where it is the natural choice. An interviewer who asks “is there another way?” is not filling time. They are checking whether the candidate owns the underlying idea or merely owns one memorised incantation, and whether the candidate can talk about trade-offs: which method generalises to the tenth-highest, which reads most clearly, which the older version of a database without window functions would require.
The third thing is the handling of absence. What should the query return if the table has only one distinct salary — if every employee earns the same amount? There is no second-highest salary in that company, and an honest query should say so by returning no row, or a NULL, rather than by inventing an answer. Candidates rarely consider the case until asked, and interviewers ask it because production queries face it constantly: the new department with one employee, the filtered subset where everyone sits on the same grade. A candidate who raises the case themselves, in one calm sentence, has demonstrated the habit that most distinguishes working engineers from examination candidates — asking what the data might look like before trusting the query written for it.
#### The full worked answer
Begin with the oldest and most portable method, the one that works on every database the candidate will ever meet, including versions with no window functions at all. The logic, stated in plain language first — as it should be in the room — is this: the second-highest salary is the largest salary that is smaller than the largest salary. Find the maximum; then find the maximum of everything below it.
```sql
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
```
Run against the sample data, the inner query returns 1,10,000. The outer query then considers only salaries below that figure — 90,000, 75,000, 68,000, 95,000, 60,000, 82,000, 55,000 — and returns the largest of them, 95,000. Ties are handled correctly by construction, and it is worth saying why in the room: the comparison is on values, not on positions, so if five employees shared the top salary, all five would be excluded by the same condition, and the query would still return the next level down. The single-salary case is handled correctly too, and again by construction: if every salary equals the maximum, the condition that a salary be smaller than the maximum excludes every row, and MAX over an empty set returns NULL — the database’s way of saying there is no such value. The query does not crash and does not lie. It reports, accurately, that the thing asked for does not exist. If the interviewer wants the earner as well as the amount, the same idea extends naturally: select the employees whose salary equals that computed value, which correctly returns every employee tied at the second-highest level, not just one of them.
```sql
SELECT emp_id, emp_name, salary
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees)
);
```
On the sample data this returns Arjun Bose alone. Had three employees earned 95,000, it would return all three — a detail worth volunteering, because interviewers frequently follow up with exactly that observation and reward the candidate who has already thought of it.
The second method uses a ranking function, and it is the method most interviewers now expect a prepared candidate to reach, because it generalises and because it forces the tie question into the open. SQL offers three ranking functions that look similar and behave differently precisely where it matters here. DENSE_RANK assigns the same rank to equal values and leaves no gaps: salaries of 1,10,000, 95,000, 90,000 and 90,000 receive ranks 1, 2, 3 and 3. RANK also assigns the same rank to equal values but leaves gaps after a tie: those same salaries receive 1, 2, 3 and 3, but if two employees had shared the top salary, the next salary would be ranked 3, not 2, because two rows sit above it. ROW_NUMBER ignores equality altogether and simply numbers the rows in order: 1, 2, 3, 4, with tied salaries receiving different numbers depending on an order the database is free to choose. For a question about the second-highest salary value, DENSE_RANK is the right instrument, because its ranks are ranks of distinct values.
```sql
SELECT emp_id, emp_name, salary
FROM (
SELECT emp_id, emp_name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
) AS ranked
WHERE salary_rank = 2;
```
The inner query attaches a rank to every employee; the outer query keeps those ranked second. On the sample data it returns Arjun Bose at 95,000. If the top salary were shared by two employees, both would carry rank 1, the next distinct salary would carry rank 2, and the query would still answer the question that was actually asked. Note the shape of the query, because candidates stumble on it: a window function’s result cannot be filtered in the same query’s WHERE clause, since the ranking is computed as the result is produced, so the ranked rows must be wrapped in a subquery — or, in MySQL and PostgreSQL, a common table expression — and filtered outside. Writing the filter in the wrong place and being able to explain, when challenged, why it cannot live there is a small moment that interviewers notice.
The third method is the one most candidates produce first, and it is correct only in its careful form. Sort the distinct salaries from highest to lowest, skip the first, and take the next one.
```sql
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
```
Every word of that query is load-bearing. DISTINCT collapses the salary values so that each level appears once; without it, the sorted list is a list of employees’ salaries, duplicates included, and skipping one row merely skips one employee. ORDER BY salary DESC puts the largest first. LIMIT 1 OFFSET 1 — in MySQL’s alternative spelling, LIMIT 1, 1 — then discards the first distinct value and returns the second. On the sample data: the distinct salaries in descending order are 1,10,000, 95,000, 90,000, 82,000, 75,000, 68,000, 60,000 and 55,000, so the query returns 95,000. In the single-salary case it returns no row at all, which is again the honest outcome. Dialect notes belong here, offered briefly: SQL Server writes the same idea with SELECT TOP or with OFFSET and FETCH, and requires an ORDER BY for OFFSET to make sense; Oracle historically used ROWNUM in a nested query and now also supports FETCH FIRST, with the distinct-values step just as necessary in every dialect. The idea travels; only the spelling changes.
Which method should a candidate lead with? Any of the three, delivered completely, earns the question. The strongest performance usually leads with the ranking method or the maximum-subquery method — because both visibly handle ties — and then offers the LIMIT method when asked for another way, naming its DISTINCT requirement as the price of correctness. What matters is not the order but the completeness: the method, the tie behaviour and the empty case, all present without excavation by the interviewer.#### The follow-up they ask next
The first follow-up is nearly automatic: “Now make it the Nth-highest salary.” This is where the methods separate. The maximum-subquery method does not generalise gracefully — finding the third-highest by nesting maximums produces a query of forbidding ugliness, and saying so shows judgement. The other two generalise by changing a single number. With ranking, the target rank simply becomes the requested number:
```sql
SELECT emp_id, emp_name, salary
FROM (
SELECT emp_id, emp_name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
) AS ranked
WHERE salary_rank = 3;
```
With the sorted-selection method, the offset becomes one less than the requested position: for the Nth-highest distinct salary, skip N minus 1 values and take one. A candidate who states that relationship in words — “the offset is always N minus one, because we skip every level above the one we want” — has shown they understand the mechanism rather than the example.
The second follow-up is the one that decides higher tracks: “Now find the second-highest salary in each department.” The word “each” changes the problem from a global ranking to a ranking inside groups, and the ranking method absorbs the change with a single additional phrase, PARTITION BY, which restarts the ranking independently within every department.
```sql
SELECT emp_id, emp_name, dept_id, salary
FROM (
SELECT emp_id, emp_name, dept_id, salary,
DENSE_RANK() OVER (
PARTITION BY dept_id
ORDER BY salary DESC
) AS salary_rank
FROM employees
) AS ranked
WHERE salary_rank = 2;
```
Against the sample data, this rewards careful mental execution, and a candidate should talk through at least one department aloud. In department 10, the distinct salaries are 1,10,000, 90,000 and 90,000, so the second-highest level is 90,000, earned by both Ananya Rao and Rohit Mehta — the query returns both, correctly. In department 20, the distinct salaries are 95,000, 75,000, 75,000 and 68,000, so the second-highest is 75,000, earned by both Sara Iqbal and Farhan Ali. In department 30, the salaries are 82,000 and 60,000, so the answer is Kavya Reddy at 60,000. Two subtleties deserve a spoken sentence. Divya Menon, whose dept_id is NULL, forms a partition of her own — the ranking treats all NULL department values as one group — and as its only member she has no second-highest colleague; whether the business wants her in the result at all is a question a thoughtful candidate raises. And a department with a single distinct salary, had one existed in the data, would simply contribute no row, which is the correct silence. The maximum-subquery method can also be adapted to this variant, with a correlated subquery comparing each employee against their own department’s maximum, and an interviewer may ask for it precisely to test correlation; but the partitioned ranking is the answer that shows the modern tool being used as it was designed to be used.
#### The common wrong answer
The wrong answers to this question fail in instructive ways, and an interviewer’s follow-ups are usually designed to walk a candidate into revealing which wrong answer they gave. The most common is the sorted list without DISTINCT:
```sql
SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
```
The autopsy is simple and damning. This query does not find the second-highest salary; it finds the salary of the second row in a descending sort. On the sample data it happens — happens — to return 95,000, because the top salary is held by one person, so the second row genuinely carries the second-highest value. That accident is what makes the mistake so durable in candidates’ preparation: on the tidy data of most practice sites, the wrong query and the right query return the same number, and the platform marks both correct. Change one fact — give Meera Pillai a colleague at 1,10,000 — and the query returns 1,10,000 itself, announcing the highest salary as the second-highest. A query that returns the maximum as its own runner-up has not made a small error; it has misunderstood the question. Interviewers know this, which is why the tie scenario arrives so reliably in conversation. The fix is a single word, DISTINCT, but the lesson is larger: test every ranking answer against data with a tie at the top, because that is the data the interviewer is imagining even when the sheet in front of you is clean.
The second common failure is the ranking version of the same misunderstanding — ROW_NUMBER where DENSE_RANK was required. Numbering the rows and selecting number two returns one employee, chosen arbitrarily among any tied at the top, and calls their salary the second-highest. It shares the original sin: ranking rows when the question ranks values. Its close cousin is using RANK and then being surprised, in the shared-top-salary scenario, that no row carries rank 2 at all — the ranks jump from 1 to 3 — and concluding the query is broken when in fact the function behaved exactly as documented and the choice of function was the error. Naming the three functions and their tie behaviour, unprompted, converts this entire family of traps into an opportunity: the candidate demonstrates that they chose DENSE_RANK for a reason they can state.
The third failure is quieter: returning the second-highest salary when the interviewer asked who earns it, or returning one earner’s name when several employees are tied at that level and the query silently discards the rest with an unexplained LIMIT. These are requirement errors rather than syntax errors, and panels weigh them accordingly, because in real work the difference between “the figure” and “the people at the figure” is the difference between a payroll summary and a list of employees about to be reviewed. The defence is a habit, not a technique: before writing, repeat the requirement back in a clause — “the second-highest distinct salary, and everyone who earns it” — and let that sentence choose the query. Candidates who do this aloud are, in effect, showing the interviewer their working. In a screen built on basics asked under pressure, showing the working is very often the whole game.
### Question 2 — List every employee with their department, then find the departments with no employees
The question usually arrives in two movements. First: “List every employee along with the name of their department.” Then, once that query is on the page and correct: “Now show me the departments that have no employees.” The pairing is deliberate. The first movement tests whether the candidate can combine two tables at all; the second tests whether they understand what a join does with rows that have no partner — which is where joins stop being a typing exercise and become a way of thinking about data. Against the sample tables, the first answer must account for ten employees, including one, Divya Menon, who has no department; the second answer is a single department, Research, in Chennai, which exists in the company and yet employs nobody in the data. Both answers turn on the same idea, approached from opposite sides.
#### What they are really testing
A join is, at heart, a rule for matching rows. The interviewer is testing whether the candidate holds that idea clearly enough to predict, for each kind of join, exactly which rows survive and what happens to the columns of a row that finds no match. That second clause — what happens to the unmatched row — is the soul of the question. In an inner join, the unmatched row vanishes. In an outer join, it survives, and the columns that would have come from the other table are filled with NULLs: not empty strings, not zeroes, but the explicit marker that no value exists. Candidates who describe outer joins vaguely, as “it gives everything,” usually cannot say which side’s everything, or what the padding looks like, or how to find the padded rows afterwards — and finding the padded rows afterwards is, not coincidentally, exactly what the second movement of the question asks them to do. The anti-join, as the pattern is known, is not a separate topic bolted onto joins for difficulty. It is the natural consequence of understanding NULL padding, and interviewers use it to check that the understanding is real.
The question also tests a quieter discipline: choosing the join from the requirement’s wording rather than from habit. “Every employee with their department name” contains a decision hidden in the word “every.” Does the requirement want every employee, including the one with no department, shown with a blank against her name? Or does it want every employee who has a department, with the unassigned simply absent? Both queries are legitimate answers to different requirements, and strong candidates surface the choice — often with a single clarifying sentence before writing — rather than letting a default INNER JOIN make the decision silently for them. Interviewers for service companies care about this habit out of proportion to the simplicity of the question, because so much service work consists of producing lists and reports for clients whose word “every” meant one thing while the query delivered another, a discrepancy discovered weeks later in a reconciliation nobody enjoyed.
#### The full worked answer
Start with the straightforward reading of the first movement, the list of employees who have departments, each shown with the department’s name. That is an inner join: rows from the two tables are combined where the department number in employees matches a department number in departments, and rows without a match on either side take no part in the result.
```sql
SELECT e.emp_id, e.emp_name, d.dept_name
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id;
```
On the sample data this returns nine rows. Ananya Rao, Rohit Mehta and Meera Pillai appear with Engineering; Sara Iqbal, Vikram Nair, Arjun Bose and Farhan Ali with Data; Kavya Reddy and Nikhil Verma with Support. Divya Menon does not appear, because her dept_id is NULL, and NULL never equals anything — not even another NULL — so no department can match her. Research does not appear either, because no employee matches it. The INNER keyword itself is optional in most dialects — JOIN alone means an inner join — but writing it in an interview is a small act of clarity that costs nothing. Note also the table aliases, e and d, and the qualified column names. With two tables sharing a column name, dept_id, qualification is not style; unqualified references would be ambiguous, and a candidate who qualifies automatically signals experience of queries larger than one table.
Now the other reading of “every,” in which Divya Menon must appear, with nothing where her department name would go. That requires a left outer join, which keeps every row of the table on the left — here, employees — whether or not a match exists on the right, padding the right-hand columns with NULL where there is no match.
```sql
SELECT e.emp_id, e.emp_name, d.dept_name
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id;
```
This returns all ten employees. The nine matched rows look exactly as before; Divya Menon’s row carries her name and a NULL dept_name. The order of the tables now matters in a way it did not for the inner join: employees is the preserved side because it stands on the left of the join. Swap the tables without changing the join type and the preserved side swaps with them — a fact the next part of the answer exploits. In the room, the sentence that earns confidence is the one that names the padding before the interviewer asks: “Everyone appears; the employee with no department shows NULL for the department name, because there is no department row to take it from.”
With those two in hand, the remaining join types can be explained — as they should be — through this same schema, briefly and concretely, because interviewers routinely sweep through them once the first query lands. A RIGHT JOIN is the mirror of LEFT: it preserves every row of the right-hand table. Written with departments on the right, it preserves every department, padding employee columns with NULL for a department nobody belongs to — so Research appears, with NULLs where an employee’s name and salary would be. Most practitioners prefer to rewrite a right join as a left join with the tables swapped, finding it easier to read the preserved side first, and saying so is a respectable, commonly shared preference rather than a gap. A FULL OUTER JOIN preserves both sides: every employee and every department appears, matched where possible, padded where not; on this data it would return Divya Menon with a NULL department and Research with NULL employee details, in the same result. MySQL, alone among the common systems a fresher is likely to name, has no direct FULL OUTER JOIN syntax, and the standard emulation is to combine a left join and a right join — or a left join plus the unmatched rows from the other side — with UNION, which also removes the duplicated matched rows that UNION ALL would leave behind:
```sql
SELECT e.emp_id, e.emp_name, d.dept_name
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id
UNION
SELECT e.emp_id, e.emp_name, d.dept_name
FROM employees e
RIGHT JOIN departments d
ON e.dept_id = d.dept_id;
```
SQL Server and PostgreSQL support FULL OUTER JOIN directly, and Oracle does as well; naming that contrast, without being asked, is the kind of dialect awareness this set’s ground rules are designed to build. A CROSS JOIN, by contrast, has no matching condition at all: it pairs every row of one table with every row of the other, producing the Cartesian product — here, ten employees times four departments, forty rows, most of them meaningless pairings of an employee with a department they do not belong to. Its legitimate uses are narrow — generating combinations, building test grids — and its accidental use, by forgetting the ON condition of an inner join in dialects that then treat the join as a cross join or fail outright, is a classic source of reports that return forty rows where nine were expected. Finally, a SELF JOIN is not a separate mechanism but a use of any of the above in which a table is joined to itself; this schema is built for it, since manager_id points back into employees, and a later question in the set asks for each employee alongside their manager’s name by exactly that means. Previewing it here in one sentence, when the interviewer sweeps the join types, shows the candidate connecting the schema’s design to the questions it was designed to ask.
The second movement of the question can now be answered in a single step, because the machinery is already on the page. To find departments with no employees, preserve every department, attempt to match employees to it, and keep only the departments where the match failed — which is to say, where the employee columns came back NULL. Departments must stand on the preserved side, so the join is written with departments first and a left join to employees:
```sql
SELECT d.dept_id, d.dept_name, d.location
FROM departments d
LEFT JOIN employees e
ON e.dept_id = d.dept_id
WHERE e.dept_id IS NULL;
```
On the sample data this returns exactly one row: department 40, Research, Chennai. The reasoning deserves to be spoken in full, because it is the point of the question. Engineering, Data and Support each match at least one employee, so their rows carry real employee values and are filtered out by the condition. Research matches nobody, so its single preserved row carries NULL in every employee column, including e.dept_id — and the condition e.dept_id IS NULL therefore keeps precisely it. Two details in that explanation matter. The test must be IS NULL, never an equality comparison against NULL, because NULL compared with anything, including NULL, does not evaluate to true; a candidate who writes an equals sign here has written a query that returns nothing, forever, on any data. And the column tested should be a column that cannot itself be NULL in a matched row — the joining key or the other table’s primary key — so that a NULL in it can mean only one thing: no match occurred. This pattern, a left join followed by an IS NULL test on the right-hand key, is the anti-join, and it is worth naming in the room. An alternative with the same meaning uses NOT EXISTS, asking for departments for which no matching employee exists:
```sql
SELECT d.dept_id, d.dept_name, d.location
FROM departments d
WHERE NOT EXISTS (
SELECT 1
FROM employees e
WHERE e.dept_id = d.dept_id
);
```
Many experienced practitioners prefer NOT EXISTS for clarity of intent and for its safe behaviour around NULLs, and offering it as the second way — while explaining that NOT IN, the third form candidates often reach for, carries a notorious trap when the subquery can return a NULL, since a single NULL in the compared list makes the whole condition evaluate to not-true for every row — turns a routine follow-up into evidence of depth. On this schema, employees.dept_id can indeed be NULL, thanks to Divya Menon, so the trap is not theoretical here; it is sitting in the sample data, waiting.
#### The follow-up they ask next
The standard follow-up reverses the direction: “Now find the employees who have no department.” A candidate who understood the anti-join, rather than memorising its shape, answers without pause, because only the preserved side changes. Preserve employees, join departments, and keep the rows where the department side came back NULL:
```sql
SELECT e.emp_id, e.emp_name, e.salary
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id
WHERE d.dept_id IS NULL;
```
This returns Divya Menon. The follow-up has a second layer that interviewers add when the first is handled smoothly: why does she have no department in the result — is she unassigned, or could the data be broken, pointing at a department that no longer exists? In this schema, her dept_id is NULL, which means unassigned; a dept_id of 99, matching no department, would mean something different and arguably worse, and the same query catches both, while a small variation — testing whether dept_id is NULL or testing for the unmatched non-NULL value — separates them. A candidate who volunteers that distinction has moved, in the interviewer’s assessment, from answering questions to auditing data, which is a considerable promotion within a single exchange.
Other follow-ups orbit the same centre. “How many employees are in each department, including departments with none?” combines the left join with grouping and a count that must be COUNT of an employee column rather than COUNT of rows — because the padded row for Research, if counted as a row, would falsely report one employee; that question appears in full later in this set, and its seed is planted here. “What if I want the department name for the report but the report must show the word ‘Unassigned’ instead of a blank?” invites a brief, correct use of COALESCE around the department name in the left join’s output — a small polish that real reports need constantly. Each follow-up, notice, is the original question with one condition changed. That is the design of the whole screen in miniature, and it is why this set insists on the reasoning rather than the incantation: the incantation answers one question, the reasoning answers the family.
#### The common wrong answer
The first common wrong answer is the inner join offered where the requirement needed a left join. Asked for every employee with their department, the candidate writes the inner join from habit — it is the join most tutorials teach first and most practice questions reward — and delivers nine employees while reporting, in good faith, that the list is complete. Nobody in the room may notice until the interviewer asks the gentle, lethal question: “How many employees are in the table? And how many rows did your query return?” The counts differ by one, and the missing person has a name. The autopsy is not that the candidate chose the wrong keyword; it is that they never compared the result against the source, and never let the word “every” trigger the question of what should happen to the unmatched. In production, this exact error produces the headcount report that omits new joiners not yet assigned to a team — a report that looks entirely plausible, totals neatly, and is wrong in the way that erodes trust in every other number on the page. The defence is the habit built throughout this question: state the preserved side aloud before writing. “Every employee must appear, so employees is the preserved side, so this is a left join.” Three clauses, and the error becomes almost impossible to make.
The second wrong answer is subtler, because the query looks like a left join and is written with one — and then a condition in the WHERE clause quietly converts it back into an inner join. Suppose the requirement is every employee with their department, but only for departments based in Hyderabad, with unassigned employees still shown. A candidate writes the left join and then filters on the department’s location in the WHERE clause:
```sql
SELECT e.emp_id, e.emp_name, d.dept_name, d.location
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id
WHERE d.location = ‘Hyderabad’;
```
The autopsy requires understanding the order in which a query is logically processed. The join happens first, producing all ten employees, Divya Menon padded with NULLs. The WHERE clause then evaluates the location condition row by row — and for Divya Menon’s row, the location is NULL, the comparison is not true, and her row is discarded. So is every employee outside Hyderabad, which was intended — but she was not meant to be discarded by a condition about a department she does not have. The left join’s preservation has been silently revoked by a filter applied after it. Any condition in the WHERE clause that requires a right-hand column to hold an actual value performs the same revocation, which is why experienced reviewers scan left joins for exactly this pattern. The correct placement, when the filter is meant to govern matching rather than to filter the final result, is inside the ON clause, where it restricts which department rows may match while leaving the preserved employees untouched:
```sql
SELECT e.emp_id, e.emp_name, d.dept_name, d.location
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id
AND d.location = ‘Hyderabad’;
```
Now every employee appears; only Data-department matches, Data being based in Hyderabad, bring department details with them, and everyone else shows NULLs. Whether the ON placement or the WHERE placement is right depends entirely on what the requirement means — should non-Hyderabad employees vanish, or appear without department details? — and that dependence is itself the lesson the interviewer is teaching. There is a deliberate exception that proves the rule, and it is already familiar: the anti-join’s WHERE condition testing for IS NULL is also a condition on a right-hand column, but it preserves the join’s meaning rather than revoking it, because it selects for the padding instead of against it. A candidate who can explain both placements, and why the IS NULL case is different, has understood outer joins in the only sense that matters — not as syntax, but as a sequence of decisions about rows, each of which can be stated, defended and, when the follow-up arrives, changed on purpose rather than by accident.
Taken together, the two questions in this part rehearse every habit the rest of the set will demand: read the requirement for its hidden decisions, expect ties and missing values before the interviewer supplies them, know more than one route to the answer, and be able to say, in plain sentences, what each part of the query is doing and why. The questions that follow — grouping and counting, the manager self-join, duplicates, dates and the rest — are new surfaces over the same ground. Candidates who have genuinely settled the ground, as these two questions settle it, tend to find the new surfaces surprisingly familiar. That familiarity, prepared honestly and explained calmly, is what a service-company screen is finally measuring.
### Question 3 — WHERE vs HAVING, Answered by Doing: Count Employees per Department, Show Only Departments With More Than Five Employees, Then Find the Top Three Departments by Average Salary Excluding Small Departments
#### What they are really testing
On paper this looks like a vocabulary question. Candidates walk in expecting to recite a definition, and many of them have one ready: WHERE filters rows, HAVING filters groups. The interviewer has heard that sentence hundreds of times, and it tells him almost nothing. That is why the good interviewers in TCS, Infosys, Wipro and Cognizant panels do not stop at the definition. They put a task in front of you instead.
Count the employees in each department. Now show only the departments with more than five employees. Now, from that same data, give me the three departments with the highest average salary, but do not let a tiny department with two highly paid people distort the answer.
Each step adds exactly one new idea, and each step is designed to expose a specific gap. The first step tests whether you can group at all. The second tests whether you understand that a condition on a group result cannot be handled the same way as a condition on an individual row. The third tests whether you can combine filtering, aggregation, sorting and limiting in the right order without tripping over your own logic. Candidates who memorised the definition but never practised the mechanics usually survive step one, hesitate at step two, and produce something plausible-looking but wrong at step three.
There is a deeper thing being tested as well, and it matters more in service-company work than candidates realise. In delivery projects, reporting queries are rarely written once and forgotten. A client manager asks for headcount by location this week, average cost by department next week, and attrition by grade the week after. Every one of those requests is a grouping query with a condition attached, and the condition is almost always the part the business actually cares about. Nobody asks for every department. They ask for the departments that are too big, too expensive, too concentrated in one location, or growing too fast. The ability to place a condition in the right clause, first time, without trial and error, is a daily working skill disguised as an interview question.
The interviewer is also listening for how you talk while you work. If you can explain, in plain language, why a condition belongs in one place rather than another, you sound like someone who can sit in a client call and defend a number. If you can only say that the other version gave an error, you sound like someone who fixed queries by shuffling clauses until the error went away. Both candidates might eventually produce a working query. Only one of them sounds safe to put in front of a client.
Finally, this question quietly tests whether you think about the order in which the database does its work. SQL is written in one order and executed in another, and no question reveals that gap faster than this one. Once you understand the execution order, WHERE versus HAVING stops being a rule to remember and becomes a consequence you can derive on the spot, even under pressure, even when the question is dressed up differently. That is exactly the kind of understanding interviewers are hoping to find.
#### The full worked answer
Start with the shared sample schema used throughout this set. There is an employees table with emp_id, emp_name, dept_id, salary, manager_id and hire_date, and a departments table with dept_id, dept_name and location. For the first two steps you do not even need the departments table, because the grouping key, dept_id, lives on the employee row itself. Bring the departments table in only when you need to display a department name rather than a number.
Step one: count employees per department.
```sql
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
GROUP BY dept_id;
```
Read this query the way the database executes it, not the way it is typed. The database goes to the employees table, takes every row, sorts or hashes those rows into buckets by dept_id, and then, for each bucket, counts how many rows landed in it. The SELECT list can only contain two kinds of things once a GROUP BY is present: the grouping key itself, which is dept_id, and aggregate expressions computed over each bucket, which here is COUNT(*). Anything else — an individual employee’s name, for example — has no single value per bucket, and a well-behaved database will refuse it. That refusal is not pedantry. It is the database protecting you from an ambiguous question.
A small refinement is worth making in the interview room. COUNT(*) counts rows in the group. COUNT(emp_id) counts rows in the group where emp_id is not null. In this schema emp_id is a primary key and never null, so the two are identical, but saying so out loud shows you know the difference exists. Interviewers notice. If the column you are counting can contain nulls, the choice matters, and candidates who treat the two forms as interchangeable synonyms eventually get bitten on a real project.
Step two: show only departments with more than five employees.
```sql
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;
```
One clause was added and nothing else changed. The condition COUNT(*) > 5 is a statement about a completed group. It cannot be evaluated until the bucket exists and its rows have been counted. That is the entire reason HAVING exists. HAVING runs after grouping and aggregation, so it is allowed to reference aggregate results. WHERE runs before grouping, when the database is still looking at individual rows one at a time and no count exists yet. Asking WHERE to test a count is like asking a turnstile attendant how many people are in the stadium while people are still walking in. The information simply is not available at that point in the process.
Notice what was not filtered. No individual employee was excluded in step two. A department with six employees contributes all six rows to its count, including the lowest paid and the most recently hired. The filter decided which groups survive to the output; it did not change the membership of any group. Hold on to that distinction, because step three depends on it, and because the most common wrong answer to this question, examined below, collapses precisely here.
Step three: the top three departments by average salary, excluding small departments.
```sql
SELECT d.dept_name, AVG(e.salary) AS avg_salary, COUNT(*) AS emp_count
FROM employees e
JOIN departments d
ON d.dept_id = e.dept_id
GROUP BY d.dept_id, d.dept_name
HAVING COUNT(*) > 5
ORDER BY avg_salary DESC
LIMIT 3;
```
Several decisions are packed into this short query, and a strong candidate narrates them rather than letting the interviewer guess.
First, the join. Average salary per department could be computed from employees alone, grouped by dept_id, but the business does not report department numbers, it reports department names. Joining departments in lets the output speak the client’s language. The join happens before grouping, so the grouping still operates on employee rows; each employee row now simply carries its department’s name alongside it.
Second, the grouping keys. Both d.dept_id and d.dept_name appear in the GROUP BY. In most databases, grouping by the primary key of departments is enough to make dept_name available, because the name is functionally dependent on the id. SQL Server and Oracle accept that reasoning in some forms and reject it in others, and strict modes in MySQL have changed their behaviour across versions. Listing both columns costs nothing, works everywhere, and removes an entire category of portability argument from the room. In an interview, portable and boring beats clever and version-dependent every time.
Third, the exclusion of small departments happens in HAVING COUNT(*) > 5, for the same reason as step two: the size of the department is a property of the completed group. This is doing real analytical work, not just satisfying the question. Average salary is a fragile statistic in a small group. A two-person department containing one senior architect can post a higher average than a two-hundred-person delivery unit full of associates, and ranking departments by raw average without a size floor produces a leaderboard that is technically correct and managerially useless. The HAVING clause is where you defend the ranking against that distortion.
Fourth, the ordering. ORDER BY avg_salary DESC sorts the surviving departments from highest average to lowest, referencing the alias defined in the SELECT list. ORDER BY is one of the few places where a SELECT alias is reliably available, because ordering conceptually happens after the select list has been computed. LIMIT 3 then keeps the first three rows of that sorted result. In SQL Server the equivalent ending is TOP 3 with the same ORDER BY; in Oracle and standard SQL it is FETCH FIRST 3 ROWS ONLY. The idea is identical across dialects: sort first, then cut. A limit without an order is just an arbitrary sample, and interviewers will say so if you offer one.
Now put the whole mechanism together, because this is the explanation that converts a memorised rule into understanding. The logical execution order of a query like this is:
- FROM, including any joins, assembles the working set of rows
- WHERE filters individual rows out of that working set
- GROUP BY gathers the surviving rows into buckets
- HAVING filters whole buckets out of the grouped result
- SELECT computes the final expressions and assigns aliases
- ORDER BY sorts the finished rows
- LIMIT or its dialect equivalent trims the sorted rows to the number requested
This order explains almost every confusion candidates have with this family of questions. It explains why an aggregate cannot appear in WHERE: at WHERE time there are no groups yet, so there is nothing to aggregate. It explains why a column alias defined in SELECT usually cannot be referenced in WHERE, GROUP BY or HAVING: those clauses are processed before the alias exists. And it explains why the same alias works happily in ORDER BY: ordering happens last, when the alias is already established.
The alias-in-HAVING question deserves its own moment, because interviewers who have worked across dialects love it. Can you write HAVING emp_count > 5, using the alias from the SELECT list, instead of repeating COUNT(*) > 5? In MySQL, yes — MySQL permits SELECT aliases in HAVING as a non-standard extension, and a great deal of production MySQL code relies on it. In PostgreSQL, no — the alias is not visible in HAVING and the query fails; you must repeat the aggregate expression. SQL Server also says no. Oracle also says no. The safe, portable habit is to repeat the aggregate expression in HAVING and reserve aliases for ORDER BY, where every major database accepts them. If you are writing for MySQL only and the house style uses the alias, follow the house style, but know that you are using an extension, and say so if asked. The candidate who knows which parts of his query are portable and which are dialect conveniences sounds like an experienced hand. The candidate who insists the alias version is simply how SQL works will struggle the first time the project changes databases, and service companies change databases more often than candidates expect.
One more variation separates strong answers from adequate ones. Suppose the requirement changes slightly: top three departments by average salary among employees earning more than 30,000, excluding small departments. Now two different filters are in play. The salary condition applies to individual rows before grouping, so it belongs in WHERE. The size condition applies to the group, so it stays in HAVING.
```sql
SELECT d.dept_name, AVG(e.salary) AS avg_salary, COUNT(*) AS emp_count
FROM employees e
JOIN departments d
ON d.dept_id = e.dept_id
WHERE e.salary > 30000
GROUP BY d.dept_id, d.dept_name
HAVING COUNT(*) > 5
ORDER BY avg_salary DESC
LIMIT 3;
```
Notice the subtle consequence, and mention it before the interviewer has to ask: the emp_count in this version counts only the employees who passed the WHERE filter, not every employee in the department. A department with nine employees, four of whom earn 30,000 or less, presents a count of five here and fails the HAVING test, even though the department itself has nine people. That may be exactly what the business wants — departments with more than five well-paid employees — or it may be a quiet distortion. Naming the consequence out loud shows you understand that WHERE does not merely hide rows from the output; it changes what the aggregates mean. That single observation has rescued many candidates from the follow-up trap described next.
#### The follow-up they ask next
The standard follow-up arrives within seconds of a correct answer, and it is this: I want departments with more than five employees, but only counting employees hired after 2020. Where does the date condition go, and does your count change?
The answer is that the hire-date condition goes in WHERE, because it is a property of an individual row, known the moment the row is read, long before any grouping happens.
```sql
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
WHERE hire_date >= ‘2021-01-01’
GROUP BY dept_id
HAVING COUNT(*) > 5;
```
And yes, the count changes, deliberately. The HAVING threshold now measures departments by their post-2020 hiring, not by their total size. A department of twenty people hired mostly in 2018 might show a count of three and disappear from the result, while a young department of seven recent hires survives. The interviewer is checking whether you notice that the question has quietly changed its meaning, not just its syntax. The strongest candidates answer the syntax in one breath and flag the changed meaning in the next: this query no longer finds big departments, it finds departments that have grown recently, and if the business wanted big departments filtered by something else, the query would need restructuring.
A second favourite follow-up reverses the direction. Can HAVING be used without GROUP BY? Yes. Without a GROUP BY, the entire result is treated as a single group, so a query such as selecting the average salary of the whole company only when that average exceeds a threshold is legal and occasionally useful. It rarely appears in delivery work, but knowing it exists shows your mental model is complete rather than pattern-matched.
A third follow-up, common in panels that include a database administrator, concerns performance. Is it better to filter in WHERE or in HAVING? The working rule is to filter as early as you honestly can. A condition on raw rows belongs in WHERE, where it shrinks the working set before the expensive grouping step, rather than in HAVING, where the database must group rows you were going to throw away anyway. Some optimisers will push eligible conditions down on their own, but relying on the optimiser to rescue a badly placed condition is not a habit to advertise. Place each condition at the earliest point where it can legally and truthfully be evaluated, and let the optimiser handle the rest.
#### The common wrong answer (with autopsy)
The classic wrong answer puts the aggregate in WHERE:
```sql
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
WHERE COUNT(*) > 5
GROUP BY dept_id;
```
Most databases reject this immediately with an error about aggregates not being allowed in WHERE, and in the interview room that error is actually the kind outcome, because it tells the candidate something is wrong. The autopsy matters more than the error message. The candidate wrote the condition where conditions usually go. He has written hundreds of queries in which WHERE carried every filter, and his hands reached for it automatically. What he lacks is not syntax but sequence: he has never internalised that the query is processed in an order different from the order in which it is typed. Once that is pointed out, the fix is obvious, but interviewers are not scoring the fix. They are scoring whether the understanding was there before the error forced it.
The more dangerous wrong answer produces no error at all. Faced with the small-department exclusion, a candidate reaches for a row filter instead:
```sql
SELECT dept_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY dept_id
HAVING dept_id IN (
SELECT dept_id FROM employees GROUP BY dept_id HAVING COUNT(*) > 5
);
```
This works, in the narrow sense that it runs and returns correct numbers, but it computes the grouping twice, reads awkwardly, and collapses the moment the threshold logic gets more complicated. It is the signature of a candidate who treats HAVING as a mysterious special case rather than the natural home for group conditions. The autopsy here is about economy: the direct version says the thing once, in the place designed for it. When an interviewer sees the doubled subquery, he reasonably wonders how the candidate’s code will read after six months of maintenance by somebody else.
The third wrong answer is the quietest and the worst, because it returns a confidently wrong result. The candidate, asked for departments with more than five employees, filters on something per-row that merely sounds related — for example, keeping only employees whose salary exceeds the department average via a misapplied condition, or grouping by emp_name alongside dept_id so that each group is a single person and no group can ever exceed five. Grouping by an extra high-cardinality column is the version seen most often in real panels: the candidate adds emp_name to the SELECT list because the sample output in the question paper showed names, adds it to GROUP BY to silence the error, and thereby destroys the grouping entirely. Every group now has a count of one, HAVING COUNT(*) > 5 eliminates everything, and the candidate stares at an empty result set insisting the logic was right. The lesson the autopsy teaches is permanent: every column you add to GROUP BY redefines what a group is. The group is the unit of the question. Get the unit wrong and every aggregate that follows is answering a question nobody asked.
### Question 4 — Duplicate Rows: Find Duplicate Emails and Names, Then Delete the Duplicates Keeping the Lowest emp_id
#### What they are really testing
Duplicate questions come in two halves, and interviewers weight them very differently. The first half — finding duplicates — is a grouping exercise that most prepared candidates can do. The second half — removing duplicates safely, keeping exactly one survivor per group, on a table that other people depend on — is where the question stops being about SQL syntax and starts being about professional judgement.
That split reflects real service-company work with uncomfortable accuracy. Duplicates in employee and customer tables are rarely caused by a single dramatic failure. They creep in through bulk loads run twice, migrations that merged two source systems, integrations that retried a submission after a timeout, manual entries made under slightly different spellings, and test records that escaped into production. By the time a client reports that the same person appears twice in a headcount report, the duplicates have usually been there for months, quietly inflating counts, splitting salary history across two rows, and breaking any downstream process that assumed an email address identified one person. The person sent to fix it needs more than a clever delete statement. He needs to find the extent of the problem, define precisely what counts as a duplicate, choose a survivor rule the business can agree to, and remove the rest without creating a second incident on top of the first.
That is what the interviewer is probing. When he says find duplicates, he is checking your GROUP BY. When he says delete them, keeping the lowest emp_id, he is checking whether you understand self-joins, window functions, the quirks of the database in front of you, and — most importantly — whether your instincts run toward caution or toward speed. Candidates who rush to the delete impress nobody. Candidates who instinctively select before they delete, who ask which row should survive and why, and who mention transactions unprompted, sound like people a delivery manager can trust with production data at short notice. In a TCS or Cognizant panel, that trust signal is worth more than the query itself.
There is also a definitional trap built into the question, and strong candidates surface it early. What exactly is a duplicate? Two rows with the same email are almost certainly the same person recorded twice, because email addresses in an employee table are expected to be unique per person. Two rows with the same name are a different matter entirely. Large organisations employ multiple people with identical names, and an employee table for a company the size of TCS will contain many legitimate name collisions. Treating a shared name as proof of duplication and deleting on that basis would remove real employees. The interviewer who asks about duplicate emails and names in one breath is often waiting to see whether you challenge the second half of his own question. Challenging it politely, with reasoning, is one of the highest-scoring moves available in this entire set.
#### The full worked answer
Begin by finding, not fixing. The detection query groups by the suspected key and keeps only the groups with more than one row.
```sql
SELECT emp_name, COUNT(*) AS dup_count
FROM employees
GROUP BY emp_name
HAVING COUNT(*) > 1
ORDER BY dup_count DESC;
```
The same shape works for any candidate key. In a schema extended with an email column — most real employee tables carry one even though the compact sample schema in this set omits it — the email version is identical in structure:
```sql
SELECT email, COUNT(*) AS dup_count
FROM employees
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY dup_count DESC;
```
Two habits elevate this from a correct answer to a professional one. First, order by the count descending, so the worst offenders surface first; when a client is waiting, the difference between three duplicated records and three thousand is the difference between a cleanup task and an incident, and the first query you run should reveal which situation you are in. Second, follow the summary with the detail. A count tells you how many groups are affected, but before anyone deletes anything, a human being should look at the actual rows, side by side, with every column visible:
```sql
SELECT *
FROM employees
WHERE emp_name IN (
SELECT emp_name
FROM employees
GROUP BY emp_name
HAVING COUNT(*) > 1
)
ORDER BY emp_name, emp_id;
```
Sorting the detail by name and then by emp_id places each duplicate family together, oldest record first, so the eye can compare salaries, departments, managers and hire dates across the copies. This inspection step regularly changes the plan. Sometimes the duplicates are byte-for-byte identical apart from the id, and deletion is straightforward. Sometimes the copies disagree — one has the current department, the other has the current salary — and the real task becomes merging before deleting, which is a business decision, not a SQL trick. Sometimes the supposed duplicates turn out to be two different people, and the correct delete is no delete at all. You cannot learn any of that from the count query. You learn it by looking.
Now the deletion itself, with the survivor rule stated plainly: within each duplicate group, the row with the lowest emp_id survives, and every other row in the group is removed. The lowest emp_id is the natural survivor in most tables because ids are issued in insertion order, making the lowest id the original record and the higher ids the later, accidental copies. It is also unambiguous, stable, and easy to explain to an auditor, which matters more than candidates expect.
The portable approach that works across databases uses a self-join. Join the table to itself on the duplicate key, and delete the row whose id is greater than its partner’s id:
```sql
DELETE e1
FROM employees e1
JOIN employees e2
ON e1.emp_name = e2.emp_name
AND e1.emp_id > e2.emp_id;
```
Walk through the logic slowly, because the interviewer will. For any pair of rows sharing a name, the join produces a match in which e1 is the later copy and e2 is the earlier one. The later copy is deleted. A group of three duplicates generates pairs in which the middle and highest rows each appear as e1 at least once, so both are removed, while the lowest row never satisfies the greater-than condition as e1 against any partner and therefore survives. One statement, any group size, exactly one survivor. In MySQL this multi-table delete syntax is the idiomatic solution. In SQL Server the equivalent writes DELETE e1 FROM employees e1 JOIN employees e2 with the same join condition. In PostgreSQL the shape is DELETE FROM employees e1 USING employees e2 with the condition in a WHERE clause. The spelling changes; the idea — compare each row with a partner from its own table and remove the one that loses the comparison — is constant.
The second major approach uses a window function, and on databases that support it, it is the version most experienced practitioners reach for first, because it generalises to any survivor rule, not just lowest id:
```sql
WITH ranked AS (
SELECT emp_id,
ROW_NUMBER() OVER (
PARTITION BY emp_name
ORDER BY emp_id
) AS rn
FROM employees
)
DELETE FROM employees
WHERE emp_id IN (
SELECT emp_id FROM ranked WHERE rn > 1
);
```
ROW_NUMBER restarts its numbering inside each name group, ordering by emp_id, so the survivor receives 1 and every duplicate receives 2, 3 and so on. Deleting every row numbered above 1 removes exactly the duplicates. Change the ORDER BY inside the window and the survivor rule changes with it: order by hire_date to keep the earliest hired record, or by salary descending to keep the highest paid record, if the business decides those rules make more sense. That flexibility is the argument for the window approach, and candidates should make it explicitly. In SQL Server you can delete directly through the common table expression itself; in PostgreSQL and Oracle the delete-through-CTE behaviour differs, so routing the selection through an IN list of ids, as above, is the portable pattern. In older MySQL versions without window functions — anything before MySQL 8 — the self-join delete is not merely an alternative, it is the only one of the two that exists, which is why panels for MySQL-heavy projects still insist on it.
That leads directly to the MySQL trap this question is famous for. A candidate’s first instinct is often a single-table delete with a subquery:
```sql
-- This fails in MySQL
DELETE FROM employees
WHERE emp_id NOT IN (
SELECT MIN(emp_id)
FROM employees
GROUP BY emp_name
);
```
The logic is impeccable and MySQL refuses to run it, returning the error that you cannot specify a target table for update in the FROM clause. MySQL will not let a statement modify a table while simultaneously reading from that same table in a subquery, because the read and the write would interfere as rows disappear mid-operation. Other databases allow this shape without complaint, which is why candidates who learned SQL on PostgreSQL or SQL Server walk into the error completely unprepared. The workarounds are part of the expected answer, and there are three worth knowing. The first is the self-join delete already shown, which sidesteps the restriction entirely by structuring the statement as a multi-table delete. The second is to wrap the subquery in a derived table, which forces MySQL to materialise the list of surviving ids before the delete begins:
```sql
DELETE FROM employees
WHERE emp_id NOT IN (
SELECT keep_id FROM (
SELECT MIN(emp_id) AS keep_id
FROM employees
GROUP BY emp_name
) AS keepers
);
```
The extra layer looks redundant, and functionally it is — but it changes the execution plan in exactly the way MySQL requires, converting a live read of the target table into a read of a temporary materialised result. The third workaround is the two-step approach: select the ids to delete into a temporary table, then delete by joining or matching against that table. It is the least elegant and, on very large tables or in tightly controlled production windows, sometimes the most practical, because the id list can be inspected, counted and approved before a single row is touched.
Whichever deletion shape you choose, the safety habits around it are not optional garnish; in the interviewer’s mind they are the answer. State them in this order. First, run the detection and detail selects and confirm the row count you expect to delete, then write the delete with a condition that matches that count, and compare the affected-rows number the database reports against your expectation before doing anything else. Second, wrap the work in a transaction where the database supports transactional data changes, so the delete can be rolled back after a final verification select inside the same session:
```sql
START TRANSACTION;
DELETE e1
FROM employees e1
JOIN employees e2
ON e1.emp_name = e2.emp_name
AND e1.emp_id > e2.emp_id;
-- Verify: this should now return no rows
SELECT emp_name, COUNT(*) AS c
FROM employees
GROUP BY emp_name
HAVING COUNT(*) > 1;
COMMIT;
```
If the verification surprises you, roll back instead of committing, and nothing has changed. Third, on any table that matters, take a backup of the affected rows first — a simple CREATE TABLE employees_dup_backup AS SELECT with the duplicate rows is enough — so that recovery does not depend on the transaction still being open or on a point-in-time restore. Fourth, remember that MySQL autocommits by default in many client configurations, so the transaction habit has to be deliberate rather than assumed. Candidates who recite select-first, transact, verify, back up — in that order, unprompted — have essentially answered the real question the interviewer was asking.
#### The follow-up they ask next
The first follow-up tests whether your survivor rule was a choice or an accident: what if we want to keep the most recently hired record instead of the lowest id? With the window-function version the change is a single line — order the partition by hire_date descending so the newest hire receives row number 1. With the self-join version the comparison changes to hire_date, with emp_id as a tiebreaker for records sharing a hire date, and a thoughtful candidate flags the tie problem before the interviewer does: any survivor rule built on a non-unique column needs a deterministic tiebreaker, or the database is free to keep either of two equally ranked rows and your cleanup is not reproducible.
The second follow-up moves from repair to prevention: how do you stop duplicates coming back? The honest answer has two layers. At the database layer, a unique constraint or unique index on the column that is supposed to identify a person — email, in most employee systems — makes the database itself reject the second insertion, converting a silent data-quality problem into a loud, immediate error at the point of entry. At the application layer, loads and integrations should be idempotent, so that retrying a submission updates or matches the existing record instead of inserting a fresh one. A candidate who only offers the constraint has missed that constraints get dropped during migrations and bypassed by bulk-load utilities; a candidate who only offers application care has missed that the database is the last line of defence. Interviewers want both, in that order.
The third follow-up is subtler: what if the duplicates disagree — different salaries, different departments? Then deletion alone is data loss wearing a cleanup costume. The correct sequence is to decide, with the business, which values are authoritative — usually by recency, by source system, or by field-level rules — merge those values onto the survivor row with an update, repoint any dependent records such as direct reports whose manager_id references a doomed emp_id, and only then delete the emptied copies. That last detail, the manager_id references inside this very schema, is planted deliberately. Deleting an employee row that other employees point to as their manager orphans those reports, and a candidate who notices the self-referencing foreign key before deleting has demonstrated exactly the production awareness this question exists to measure.
#### The common wrong answer (with autopsy)
The most frequent wrong answer is also the most confident one: the candidate groups by name, sees the duplicates, and immediately writes a delete keyed on the name itself:
```sql
-- Catastrophic: deletes every row in every duplicate group, survivors included
DELETE FROM employees
WHERE emp_name IN (
SELECT emp_name FROM employees GROUP BY emp_name HAVING COUNT(*) > 1
);
```
Setting aside that this exact shape also hits the MySQL same-table restriction, the logic is fatally wrong even where it runs. The condition identifies groups, not surplus rows. Every member of a duplicate group matches it — including the original record the business wanted to keep — so the statement removes the entire family and leaves nothing behind. The autopsy is instructive: the candidate never separated the two distinct jobs of identifying a duplicate group and selecting which rows inside the group are expendable. Detection logic and deletion logic are not the same logic, and reusing the first as the second is how cleanups become outages. In the interview room this answer ends the discussion of the candidate’s production readiness on the spot, and in a real project it is the reason backups and transactions are not bureaucracy.
The second wrong answer is quieter: deleting duplicates by DISTINCT reasoning. The candidate proposes selecting DISTINCT rows into a new table, truncating the original, and reloading. This can work for exact, whole-row duplicates in a small static table, and it fails almost everywhere else. It does nothing for duplicates that share a key but differ in other columns, which are the majority in real systems. It discards the original emp_id values unless they are carried through deliberately, breaking every reference from other tables. It fights with foreign keys, triggers, permissions and any process writing to the table during the swap. The autopsy: the candidate reached for the one deduplication idea he knew — DISTINCT — and applied it to a problem it does not model. Duplicates in production are a key problem, not a whole-row problem, and the fix has to operate at the level of the key.
The third wrong answer is a values failure rather than a logic failure, and panels remember it longest. The candidate produces a correct self-join delete — and offers nothing else. No prior select, no expected row count, no transaction, no backup, no pause to ask which record should survive or whether same-named rows might be different people. The query is right and the answer is wrong, because the question was never only the query. On a practice dataset the missing habits cost nothing. On a client’s live employee table, the same habits are the difference between a routine cleanup and a restore-from-backup conversation with a delivery head. Interviewers for service companies, who will be accountable for where they place you, score the caution as heavily as the code — usually more.
### Question 5 — The Self Join: List Each Employee With Their Manager’s Name, Then Find Employees Who Earn More Than Their Manager
#### What they are really testing
Every table in the earlier questions related to a different table or to itself only in the mechanical sense of grouping. This question introduces the most conceptually demanding idea in the entire screen: a table that relates to itself by meaning. The employees table contains both sides of the reporting relationship. Every row is a person, and through the manager_id column, every row also points at another row in the very same table — the person’s manager, who is himself an employee with his own row, his own salary, and possibly his own manager in turn.
Candidates stumble here for a reason that has nothing to do with intelligence. Up to this point, their mental picture of a join is two different tables being placed side by side. Confronted with one table playing two roles, many of them freeze, or produce a join between employees and departments out of habit, or ask where the managers table is. The interviewer has seen all three reactions many times, and the question exists precisely to sort candidates by whether they can make the conceptual leap: a table is not joined as a physical object, it is joined as a role. Give the same table two aliases, treat each alias as an independent character in the story, and the self join becomes no harder than any other join. Candidates who grasp that principle on this question tend to grasp views, subqueries and recursive structures later without drama. Candidates who memorise this one query as a special trick tend to collapse the moment the follow-up changes the relationship being examined.
The second thing being tested is null handling in a realistic setting rather than an abstract one. Somewhere at the top of every organisation sits a person with no manager. In the data, that person’s manager_id is null. How a query treats that single row — whether the chief executive silently vanishes from a company-wide listing or appears with an empty manager column — is a small detail with an outsized signalling effect. Reports that quietly drop the most senior person in the company are a genuine and recurring embarrassment in delivery work, and interviewers use this question to discover whether a candidate thinks about edge rows before or after someone complains about them.
The third layer is comparison across the relationship. Finding employees who out-earn their managers takes the self join and adds a condition that spans the two roles: this person’s salary against that person’s salary. It is a simple step mechanically, but it tests whether the candidate truly holds the two roles apart in his mind. Under pressure, candidates routinely compare the employee’s salary to itself, or to the wrong alias, and produce a query that runs beautifully and answers nothing. The interviewer is watching the aliases as you write, the way a driving examiner watches mirror checks — the small discipline reveals the underlying habit.
#### The full worked answer
Build the answer in the order a practitioner would: state the roles first, then write the query. The employees table will be used twice. One copy, aliased e, plays the employee. The other copy, aliased m, plays the manager. The bridge between them is that the employee’s manager_id equals the manager copy’s emp_id.
```sql
SELECT e.emp_name AS employee_name,
m.emp_name AS manager_name
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.emp_id
ORDER BY manager_name, employee_name;
```
Every part of this query earns its place. The aliases are short but the column prefixes are doing serious work: e.emp_name and m.emp_name are two different values drawn from the same column of the same table, distinguished only by which copy of the table they came through. The SELECT list labels them with clear output aliases, employee_name and manager_name, because a result set containing two columns both headed emp_name is unusable for any reader downstream. The join condition expresses the business rule directly — your manager is the employee whose id matches the manager_id recorded on your row — and reading it aloud in that form, before writing any SQL, is the habit that prevents alias confusion entirely.
The decisive choice in the query is LEFT JOIN, and it should be defended without waiting to be asked. An inner join keeps only employees who find a matching manager row. The chief executive’s manager_id is null, null matches nothing — not even another null — so the inner join discards the chief executive from the output altogether. A listing titled as every employee with their manager would then be missing the one employee whose absence is most likely to be noticed, and it would be missing him silently, with no error and no gap in the numbering to hint that anything went wrong. The LEFT JOIN keeps every row from the employee side and fills the manager columns with null where no match exists, so the chief executive appears with an empty manager_name — which is not a defect in the output but the truth about the organisation, represented faithfully. In interview terms: inner join answers who has a manager, left join answers list everyone and show the manager where there is one. The question asked for the second. Matching the join type to the exact wording of the request, rather than defaulting to inner join for everything, is one of the clearest markers of a candidate who reads requirements carefully.
A natural extension appears in stronger answers without prompting. The same structure extends upward: join the table a third time to show the manager’s manager, producing a three-level view of a reporting line in a single query:
```sql
SELECT e.emp_name AS employee_name,
m.emp_name AS manager_name,
mm.emp_name AS managers_manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.emp_id
LEFT JOIN employees mm
ON m.manager_id = mm.emp_id
ORDER BY employee_name;
```
Both additional joins are left joins for the same reason as before — each level of the chain can legitimately run out before the level below it does. Mentioning this extension, even briefly, tells the interviewer you see the pattern rather than the instance. It also sets up the honest limitation worth naming: a fixed number of self joins reaches a fixed number of levels, and a hierarchy of unknown depth calls for a recursive query, which is a different tool for a different day. Knowing where your technique stops is as valuable as the technique itself.
Now the second half of the question: employees who earn more than their manager.
```sql
SELECT e.emp_name AS employee_name,
e.salary AS employee_salary,
m.emp_name AS manager_name,
m.salary AS manager_salary
FROM employees e
JOIN employees m
ON e.manager_id = m.emp_id
WHERE e.salary > m.salary
ORDER BY e.salary - m.salary DESC;
```
Note the deliberate switch back to an inner join, and be ready to explain it, because a sharp interviewer will ask whether you changed it on purpose. Here the inner join is correct, because the comparison itself requires a manager to exist. An employee with no manager cannot earn more than his manager — the statement has no meaning for the chief executive — so excluding managerless rows is not a silent loss but the logical shape of the question. Showing both salaries in the output, not just the names, is another professional touch: it lets the reader verify the claim the query is making, and ordering by the size of the gap puts the most striking cases first, which is how such a list would actually be consumed. Results like this do occur in real organisations — a scarce specialist reporting to a generalist manager, a senior sales performer under a younger team lead, a legacy employee whose pay has compounded for decades — and the query is a standard piece of HR analytics rather than a puzzle invented for interviews.
The same result can be produced without an explicit join, using a correlated subquery, and interviewers who ask for an alternative approach expect something in this family:
```sql
SELECT e.emp_name AS employee_name,
e.salary AS employee_salary
FROM employees e
WHERE e.manager_id IS NOT NULL
AND e.salary > (
SELECT m.salary
FROM employees m
WHERE m.emp_id = e.manager_id
);
```
The subquery is correlated because it references e.manager_id from the outer row: for each employee, it looks up that employee’s manager’s salary and compares. A companion form retrieves the manager’s name in the SELECT list the same way. The correlated version is worth knowing for two reasons. First, it demonstrates that you understand the relationship itself, not just one syntax for expressing it — the lookup logic is identical, only the machinery differs. Second, it provokes the right performance conversation: the self join lets the database match the two roles in one pass using its join machinery, while the correlated subquery conceptually performs a fresh lookup per row, which the optimiser may or may not convert into the same plan. On a small employee table both are instant. On a table of hundreds of thousands, the join is the safer default, and the professional answer says exactly that — same result, join preferred at scale, subquery acceptable and sometimes clearer for single-value lookups. Candidates who present the two as rivals miss the point; candidates who present them as equivalents with different cost profiles sound like engineers.
#### The follow-up they ask next
The follow-ups for this question rotate through a small, predictable family, because each one reuses the same two-role structure with a new condition stretched across it. The first favourite: find employees who joined in the same month as their manager. The join does not change at all; only the WHERE clause grows, comparing the year and month of the two hire dates:
```sql
SELECT e.emp_name AS employee_name,
m.emp_name AS manager_name,
e.hire_date AS employee_hire_date,
m.hire_date AS manager_hire_date
FROM employees e
JOIN employees m
ON e.manager_id = m.emp_id
WHERE YEAR(e.hire_date) = YEAR(m.hire_date)
AND MONTH(e.hire_date) = MONTH(m.hire_date);
```
Comparing both year and month is the detail that matters — comparing month alone would match a January 2019 employee with a January 2024 manager, which is not the same month in any sense the business means. A refinement worth volunteering is that wrapping columns in functions prevents the database from using an index on hire_date efficiently, and that on a large table a range-based formulation would scale better; on an interview-sized table the function form is clearer, and clarity is the right trade here. Volunteering that trade-off, rather than being caught by it, is the difference between discussing performance and being examined on it.
The second favourite follow-up inverts the direction of the question: instead of looking upward from employee to manager, look downward and size each manager’s team. This is a grouping over the self relationship:
```sql
SELECT m.emp_name AS manager_name,
COUNT(*) AS team_size
FROM employees e
JOIN employees m
ON e.manager_id = m.emp_id
GROUP BY m.emp_id, m.emp_name
ORDER BY team_size DESC;
```
Only employees who have at least one report appear, because the inner join starts from employee rows. If the requirement is every manager including those whose teams have emptied out — a harder requirement, since a manager with no reports leaves no trace in the manager_id column at all — the candidate has to reason about what defines a manager in the data, which usually means returning to the questioner rather than inventing a rule. That instinct, again, is what is being scored.
The third follow-up asks for employees who have no manager in the same department, or whose manager sits in a different department — a common matrix-organisation report. The machinery is unchanged; the condition simply compares e.dept_id with m.dept_id across the join. By the third variation, the interviewer’s real conclusion is already formed: a candidate who re-derives each answer from the same stable structure understands self joins, while a candidate who treats each variation as a brand-new puzzle has memorised one query.
#### The common wrong answer (with autopsy)
The most common wrong answer uses an inner join for the first half of the question and never notices the cost:
```sql
-- Runs perfectly. Quietly deletes the chief executive from the company.
SELECT e.emp_name AS employee_name,
m.emp_name AS manager_name
FROM employees e
JOIN employees m
ON e.manager_id = m.emp_id;
```
There is no error to autopsy, which is exactly why this answer is dangerous and why interviewers prize the question. The query is syntactically flawless, the join condition is right, the aliases are right — and the output is wrong for the request as worded, missing the head of the organisation. The failure is a reading failure before it is a SQL failure: the candidate translated list each employee into a join and stopped thinking, instead of asking what happens to the row that cannot match. The permanent lesson generalises far beyond this question. Whenever a join key can be null — and in real schemas, optional relationships are everywhere — the choice between inner and outer join decides whether unmatched rows survive, and that decision belongs to the requirement, not to habit. Interviewers cannot watch you work for six months, so they compress the test into one chief executive row and watch whether you protect it.
The second wrong answer compares the wrong things. In the earn-more-than-manager half, flustered candidates write WHERE e.salary > e.salary’s natural twin — comparing the employee’s salary against itself through a mistyped alias, or joining on emp_id equals emp_id, which pairs every employee with himself and makes every comparison trivially false or trivially true depending on the operator. The output is an empty set or the whole table, and the candidate often tries to explain the result instead of questioning the join. The autopsy points at process: the candidate never stated the roles aloud before writing. Ten seconds spent saying the employee copy is e, the manager copy is m, and the bridge is e.manager_id to m.emp_id makes both errors nearly impossible, because each alias then has a meaning to check the typing against. Aliases in a self join are not decoration or shorthand; they are the only thing distinguishing the two characters in the story, and treating them casually is treating the logic casually.
The third wrong answer is subtler and appears in otherwise strong candidates: handling the null manager with a patch instead of a join decision. The candidate writes the inner join, notices the missing chief executive only when prompted, and repairs it by bolting on a UNION with a separate select for rows where manager_id is null. The union version can be made to return the right rows, and it is still the wrong answer, because it treats a one-word decision — LEFT — as a two-query construction, duplicates the column logic in two places that can drift apart under maintenance, and reveals that outer joins are not yet a natural part of the candidate’s toolkit. The autopsy is generous but firm: the candidate solved the problem in front of him, at twice the cost, with the wrong tool, after being shown the gap. Panels forgive the miss. What they record is whether the candidate, once shown, recognises the left join as the obvious instrument — because on a project, nobody will be standing by to point at the missing row.
### Question 6 — DELETE vs TRUNCATE vs DROP, and the Four Command Families
#### What they are really testing
On paper this looks like a vocabulary question. Three commands that remove things, four abbreviations to expand. In a TCS, Infosys, Wipro or Cognizant screening room, it is rarely scored that way. The interviewer is testing whether you understand what happens to the data, to the structure that held the data, to the transaction that contains your command, and to the next person who has to work with the table after you have finished.
That distinction matters because service-company work is maintenance work. You will inherit tables you did not design, on client systems you cannot afford to break, often with a change ticket that says something vague like “clean up the staging data” or “remove the test accounts before go-live.” Choosing DELETE when TRUNCATE was intended can leave a job running for hours and fill a transaction log. Choosing TRUNCATE when DELETE was intended can remove rows the client expected to keep. Choosing DROP when either of the other two was intended removes the table itself, its indexes, its constraints and, in most environments, any easy path back.
The second half of the question, the four command families, is the interviewer checking whether you can place every command you use in its proper family. If you know that CREATE and ALTER belong with DROP and TRUNCATE in one family, that INSERT, UPDATE and DELETE belong in another, that GRANT and REVOKE control who may do anything at all, and that COMMIT, ROLLBACK and SAVEPOINT govern whether work survives, then a dozen later questions become easier. Index questions, transaction questions, permission questions and recovery questions all hang on this frame. Interviewers know that, which is why this question recurs even though it appears in every preparation list ever printed.
They are also listening for precision about three specific behaviours. Can the command be rolled back? Does it accept a WHERE clause? Does it reset an identity or auto-increment counter? Those three answers, given correctly and without hedging, are usually what separate a candidate who has run these commands from a candidate who has only read about them.
#### The full worked answer
Start with the three removal commands, one at a time, each against the shared schema used throughout this set: an employees table with emp_id, emp_name, dept_id, salary, manager_id and hire_date, and a departments table with dept_id, dept_name and location.
**DELETE — removing rows, keeping the table**
DELETE removes rows from a table. The table itself remains, with its columns, constraints, indexes and permissions intact, ready to receive new rows immediately afterwards. Because it works row by row, it can be selective. The WHERE clause is the whole point.
```sql
-- Remove employees in department 40 who were hired before 2015
DELETE FROM employees
WHERE dept_id = 40
AND hire_date < ‘2015-01-01’;
```
Run without a WHERE clause, DELETE removes every row, but it still does so as a logged, row-by-row operation.
```sql
-- Remove every row, but keep the empty table
DELETE FROM employees;
```
Two consequences follow from that row-by-row nature. First, DELETE is comparatively slow on very large tables, because the database records each removed row in the transaction log so that the operation can be undone. Second, and for the same reason, a DELETE inside a transaction can be rolled back before it is committed. Until COMMIT, nothing is final.
DELETE also does not reset an identity or auto-increment counter. If employees uses an auto-generated emp_id and the highest value issued was 5,000, deleting the last hundred rows does not make the next inserted employee number 4,901. The counter remembers where it had reached, and the next value will be 5,001. Gaps in generated keys after deletions are normal, expected, and harmless, because a surrogate key carries no business meaning.
**TRUNCATE — removing every row, quickly, keeping the table**
TRUNCATE removes all rows from a table in one operation. The table structure survives, exactly as with DELETE, but the mechanism is different. Rather than processing and logging each row, the database deallocates the storage pages that held the data, which is why TRUNCATE is dramatically faster on large tables and produces a fraction of the log traffic.
```sql
-- Empty the table in one operation
TRUNCATE TABLE employees;
```
That speed comes with firm limits, and the limits are what the interviewer wants to hear. TRUNCATE accepts no WHERE clause. There is no selective truncate. It is all rows or nothing. It also resets an identity or auto-increment counter back to its seed, so the next inserted row starts again from the beginning value. And in most database systems TRUNCATE cannot be used casually on a table that is referenced by a foreign key from another table, even if that other table is empty, because emptying a parent table in bulk could silently orphan the design the constraint was there to protect. The exact restriction varies by product, but the safe interview answer names it rather than pretending TRUNCATE is simply a faster DELETE in every situation.
Rollback behaviour for TRUNCATE is the point on which preparation material most often misleads candidates, because it depends on the database product. In SQL Server and PostgreSQL, TRUNCATE can be rolled back if it runs inside an explicit transaction that has not yet committed, because those engines treat it as a logged operation at the page level. In MySQL and Oracle, TRUNCATE causes an implicit commit, so once it runs, the preceding work is committed with it and there is no rollback. The strong answer states the product you know, states the behaviour there accurately, and acknowledges that the behaviour is product-dependent. An interviewer for a project on Oracle will mark down a candidate who confidently promises rollback that Oracle will not give; an interviewer on SQL Server will mark down a candidate who insists rollback is impossible when it is not. Knowing the boundary of your own certainty is part of the test.
**DROP — removing the table itself**
DROP goes one step further than either command above. It removes the table definition as well as its data. Columns, constraints, indexes and the storage itself all go. Afterwards, the name no longer exists in the database until someone creates the table again.
```sql
-- Remove the table, its data, its indexes and its constraints
DROP TABLE employees;
```
DROP accepts no WHERE clause, for the obvious reason that there are no rows left to filter. There is no identity counter to reset because there is no counter and no table. Recovery means restoring from a backup or recreating the table from a script and reloading the data, which is why DROP is the command experienced developers type most slowly and check most carefully. In most products DROP also triggers an implicit commit where it runs inside a transaction environment that supports one, so the candidate who plans to “drop it and roll back if it looks wrong” is planning around a safety net that is usually not there.
Put side by side in words, the three commands form a ladder of destructiveness. DELETE is surgical and reversible until committed. TRUNCATE is a bulk emptying of a table you intend to keep and refill. DROP is demolition, appropriate when the object itself is being retired, a temporary table is being cleaned up at the end of its life, or a schema is being rebuilt from scripts.
**The four command families**
Every SQL command a fresher or lateral hire will meet in these interviews belongs to one of four families. Learning the families turns a scattered list of commands into a structure you can reason with.
- **DDL, Data Definition Language**
- Purpose: defines and changes the structure of database objects.
- Commands: CREATE, ALTER, DROP, TRUNCATE, and in many classifications RENAME.
- Typical use: creating the employees and departments tables, adding a column, changing a column’s length, dropping an obsolete table.
- Transaction behaviour: in Oracle and MySQL these commands cause an implicit commit; in SQL Server and PostgreSQL many of them can run inside a transaction and be rolled back. The interview-safe statement is that DDL behaviour around transactions is product-dependent, while its purpose, defining structure, is not.
```sql
-- DDL: create the departments table
CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(100) NOT NULL,
location VARCHAR(100)
);
-- DDL: add a column to an existing table
ALTER TABLE employees
ADD email VARCHAR(150);
```
- **DML, Data Manipulation Language**
- Purpose: works with the data inside tables whose structure already exists.
- Commands: INSERT, UPDATE, DELETE, and in most classifications SELECT, though some courses place SELECT in its own query category. If an interviewer insists SELECT stands apart, accept the correction gracefully; the point is that you know what SELECT does, not which drawer a textbook files it in.
- Typical use: hiring an employee, correcting a salary, removing a departed employee’s test records, reading a payroll report.
- Transaction behaviour: DML is the family that transaction control was built for. INSERT, UPDATE and DELETE can be grouped, committed together, or rolled back together.
```sql
-- DML: three statements that belong in one transaction
INSERT INTO departments (dept_id, dept_name, location)
VALUES (50, ‘Data Engineering’, ‘Pune’);
INSERT INTO employees (emp_id, emp_name, dept_id, salary, manager_id, hire_date)
VALUES (6001, ‘Ananya Rao’, 50, 720000, NULL, ‘2026-11-02’);
UPDATE employees
SET manager_id = 6001
WHERE emp_id = 6002;
```
- **DCL, Data Control Language**
- Purpose: controls who is allowed to do what.
- Commands: GRANT and REVOKE.
- Typical use: giving a reporting account read-only access to employees, allowing an application account to insert and update but not delete, withdrawing access when a team member rolls off a project.
- Why interviewers ask it: service companies work on client data under audit. A developer who has never thought about permissions is a risk on a banking or healthcare account, and the interviewer is quietly checking that you understand access is granted deliberately, in the smallest amount that does the job, and taken away when it is no longer needed.
```sql
-- DCL: a reporting user may read, and nothing more
GRANT SELECT ON employees TO reporting_user;
-- DCL: withdraw that access when it is no longer needed
REVOKE SELECT ON employees FROM reporting_user;
```
- **TCL, Transaction Control Language**
- Purpose: decides whether a unit of work becomes permanent, is undone, or is partly undone.
- Commands: COMMIT, ROLLBACK and SAVEPOINT, with some products adding RELEASE SAVEPOINT.
- Typical use: a funds transfer, a payroll update, a multi-table onboarding insert, any change where half-finished is worse than not started.
- The unit it governs: the transaction, meaning a group of statements the database treats as one indivisible piece of work.
A worked transaction pulls the families together. Suppose a new department opens and its first employee must exist in the same moment, or neither should exist at all. A departments row without its founding employee would confuse reporting; an employee pointing at a department that was never created would break the foreign key in any case, but imagine a second update, assigning that employee’s team, that must also succeed or fail as one.
```sql
BEGIN TRANSACTION;
INSERT INTO departments (dept_id, dept_name, location)
VALUES (60, ‘Cloud Support’, ‘Hyderabad’);
SAVEPOINT department_created;
INSERT INTO employees (emp_id, emp_name, dept_id, salary, manager_id, hire_date)
VALUES (6101, ‘Rohan Mehta’, 60, 680000, NULL, ‘2026-11-09’);
-- A check fails here in the real script: the salary band was wrong.
-- Undo only the work after the savepoint, keeping the department insert.
ROLLBACK TO SAVEPOINT department_created;
INSERT INTO employees (emp_id, emp_name, dept_id, salary, manager_id, hire_date)
VALUES (6101, ‘Rohan Mehta’, 60, 640000, NULL, ‘2026-11-09’);
COMMIT;
```
Read the example slowly, because interviewers probe each line. BEGIN TRANSACTION opens the unit of work. The SAVEPOINT marks a place inside it, not a commit and not an ending. ROLLBACK TO SAVEPOINT undoes the statements after that mark while leaving the earlier statements and the transaction itself alive. A full ROLLBACK, without a savepoint name, would undo everything back to BEGIN TRANSACTION. COMMIT ends the transaction and makes all of its surviving work permanent and visible to other users. Until that COMMIT, other sessions generally cannot see the uncommitted changes, which is the database protecting them from data that might still be withdrawn.
The classic second example is a salary correction that must never half-apply: a deduction from one budget row and an addition to another, or in employee terms, moving a bonus pool between two records. If the first UPDATE succeeds and the second fails because the session lost its connection, a transaction is the difference between a correct database and a quiet discrepancy that a finance team finds three months later.
**When each removal command is used on real projects**
Interviewers reward answers anchored in project situations, so attach each command to one.
DELETE is the everyday tool of application code and support work. A user closes an account and regulations require that person’s rows to go while everyone else’s stay. A batch job loaded duplicate rows for one department on one date and exactly those rows must be removed. A retention rule deletes orders older than seven years, in monthly slices, so that the log does not explode and the table stays usable while the job runs. In every case the defining feature is selectivity, and often auditability, since row-by-row logging supports recovery and, in systems with triggers or change tracking, a record of what went.
TRUNCATE is the tool of staging and reload work. An interface table is emptied and refilled from a file every night; nobody needs yesterday’s staging rows, there is no selection to make, and speed matters because the load window is fixed. A test environment is reset before a new cycle. A developer clears a scratch table before re-running a migration rehearsal. In every case the table is being kept precisely so it can be filled again, and the identity reset is either wanted or irrelevant.
DROP is the tool of retirement and rebuild. A temporary table created for a one-off reconciliation has served its purpose. A legacy table is replaced by a new design and, after migration and a retention period, removed under a change request. A build script tears down and recreates a local development database from scratch. Nobody drops a table as part of ordinary application behaviour, and saying so plainly, with the change-control point attached, is the mark of someone a client can trust near production.
#### The follow-up they ask next
The first follow-up is usually about triggers. “If a DELETE fires a trigger, does TRUNCATE?” The answer is no, in the ordinary sense that matters. DELETE processes rows, so DELETE triggers fire for the affected rows. TRUNCATE does not process rows one by one, so row-level DELETE triggers do not fire. This is a genuine production trap: a team that relies on a delete trigger to write an audit trail can empty a table with TRUNCATE and produce no audit rows at all. If the interviewer pushes further, the lesson generalises. Any mechanism that depends on per-row processing, including careful logging and some replication setups, behaves differently under a bulk operation, and that difference must be checked before the bulk operation is chosen for its speed.
The second follow-up concerns space. “You deleted ten million rows. Why is the table file the same size?” Because DELETE marks space as reusable inside the table’s storage rather than handing it back to the operating system. The table can grow into that space again without extending, which is often exactly what you want, but the disk does not shrink. Returning space is a separate administrative operation whose name and cost vary by product, and on a busy production table it is scheduled, not improvised. TRUNCATE, by deallocating pages, does release the bulk of the storage, which is one more reason it is chosen for staging tables that swing between empty and enormous.
The third follow-up is the foreign key block. “TRUNCATE failed on a table that a foreign key points to. The referencing table is empty. Why?” Because the restriction guards the relationship, not the current contents. The database cannot assume the referencing table will stay empty, and a bulk operation that bypassed row checks could leave the design in a state its constraints forbid. The practical remedies are to delete the rows with DELETE, which respects constraints row by row, or, in products and change windows that permit it, to disable and re-enable the constraint under a controlled change, never as a casual habit. What the interviewer is scoring is whether you reach for the safe remedy first.
A fourth follow-up, increasingly common, asks about the WHERE clause you would write to delete duplicates while keeping one copy, which connects this question to the ranking and grouping questions elsewhere in this set. Even a short answer helps: group by the columns that define a duplicate, keep the row with the smallest or largest emp_id according to the rule the business gives, and delete the rest, ideally inside a transaction, with a SELECT of the same condition run first so you can see exactly what is about to go. Running the SELECT twin of a DELETE before the DELETE itself is a habit worth naming out loud in any interview. It costs ten seconds and it has saved more production data than any other single practice in this entire question.
#### The common wrong answer
The common wrong answer is a memorised three-line contrast, recited flat: DELETE removes rows, TRUNCATE removes all rows, DROP removes the table; DELETE is DML, TRUNCATE and DROP are DDL; DELETE is slow, the others are fast. None of that is false, exactly, and that is what makes the answer dangerous. It earns partial credit and then collapses under the first follow-up, because almost every clause hides a condition the candidate has not understood.
The autopsy begins with the rollback clause. The memorised answer usually states, as an absolute, that DELETE can be rolled back and TRUNCATE and DROP cannot. As the worked answer above shows, that absolute is product-dependent for TRUNCATE, and a candidate who states it without naming a product is reciting, not reasoning. On a SQL Server project the statement is simply wrong. The repair is not to memorise a longer table; it is to attach each claim to the engine you know and say so. “On SQL Server, where I have worked, TRUNCATE inside an explicit transaction can be rolled back. On Oracle it commits implicitly.” That sentence survives follow-ups in either room.
The second fracture is the speed clause. “TRUNCATE is fast, DELETE is slow” is true at scale and misleading at small scale, and it tempts candidates into recommending TRUNCATE for jobs where its other properties disqualify it: any job needing a WHERE clause, any job whose deletes must fire triggers, any job on a foreign-key-referenced parent. Speed is one property among several, and it is rarely the deciding one outside staging work. Interviewers listen for the candidate who asks, in effect, “selective or all, audited or not, referenced or not,” before reaching for the faster command.
The third fracture is the identity clause, usually forgotten entirely. Asked what happens to an auto-increment counter after each command, the memorised answer has nothing to say, yet this is the detail that breaks real integrations: a downstream process that assumed new staging rows would continue from yesterday’s numbers behaves strangely after a truncate resets them to one. Naming the reset behaviour unprompted signals operational experience more convincingly than any speed comparison.
The fourth fracture belongs to the families half of the question. Candidates routinely place TRUNCATE in DML because “it manipulates data,” or GRANT in DDL because “it is administrative,” or forget SAVEPOINT entirely and describe TCL as “COMMIT and ROLLBACK.” The families are classified by what the command acts on: structure, data, access, or the transaction itself. TRUNCATE acts on the table as an object, emptying it wholesale without row processing, which is why it sits with the definition commands. A candidate who explains the principle can classify a command they have never been asked about; a candidate who memorised four lists cannot, and interviewers test exactly that by asking where RENAME or COMMENT belongs.
The deepest problem with the wrong answer, though, is tone. It treats three commands of very different destructive power as interchangeable synonyms distinguished by trivia. The candidate who gets hired talks about them the way a careful operator does: DELETE for chosen rows, TRUNCATE for a deliberate emptying, DROP for a retirement under change control, each inside a transaction where the product allows it, each preceded by a SELECT or a count that proves the target is the target. That is the whole question, really. The commands are three lines of syntax. The judgement around them is the job.
### Question 7 — UNION vs UNION ALL, and Subqueries From Scalar to Correlated
#### What they are really testing
This question bundles two topics that beginners treat as unrelated and practitioners use in the same query on the same afternoon. UNION and UNION ALL are about stacking results vertically, combining rows from two queries into one list. Subqueries are about nesting one question inside another, so that the answer to the inner question decides what the outer question returns. The interviewer who pairs them is checking whether you can think in sets rather than in single rows, because almost every real reporting task in a service company is a set task: merge the Bangalore list with the Chennai list, show me the people paid above average, show me the departments where nobody earns well, show me the employees who beat their own department, not the company as a whole.
There is a second, quieter test running underneath. UNION versus UNION ALL is, at heart, a question about duplicates and about cost, and the difference between a candidate who chooses deliberately and one who chooses by habit shows up in production as a report that quietly drops legitimate repeated rows, or a query that sorts a million rows for no reason. Subqueries are, at heart, a question about scope: does the inner query stand alone, or does it depend on the row the outer query is currently examining? Candidates who cannot feel that distinction write the department-average query wrong in a way that returns the company average with extra steps, and they cannot see why. The interviewer is watching for the moment that distinction clicks, or does not.
Finally, the EXISTS versus IN versus JOIN part of the question tests judgement under equivalence. Three constructions can produce the same answer to “which departments have at least one highly paid employee,” and they differ in readability, in behaviour around empty values, and in how the database is likely to execute them. The interviewer does not want a slogan about which is fastest. The interviewer wants a candidate who knows what each construction means, reaches for the one whose meaning matches the question, and can explain the one famous trap, involving NOT IN and a single empty value, that has produced wrong results in real systems for decades.
#### The full worked answer
**UNION and UNION ALL: stacking two lists**
Imagine the company keeps its southern and northern hiring in separate extracts, or, in terms of the shared schema, that a report needs the employees of the Chennai departments and the employees of the Pune departments presented as one list. The two source queries must produce the same number of columns, in the same order, with compatible types. The column names of the combined result come from the first query.
```sql
-- Employees based in Chennai locations
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments WHERE location = ‘Chennai’
)
UNION
-- Employees based in Pune locations
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments WHERE location = ‘Pune’
);
```
UNION combines the two results and removes duplicate rows from the combination. If the same employee row appears in both branches, perhaps because a data problem placed a department in both extracts, the final list contains that row once. To do that, the database must compare rows across the whole combined set, which in practice means a sort or a hash operation, and that work costs time and memory on large results.
UNION ALL keeps everything. Every row from the first branch and every row from the second branch appears in the output, duplicates included, and because no deduplication is required, no sorting pass is needed for that purpose.
```sql
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments WHERE location = ‘Chennai’
)
UNION ALL
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments WHERE location = ‘Pune’
);
```
The choice between them is a question about the data and about intent, and the interview answer should say so in those terms. Use UNION when duplicates across the branches are possible and would be wrong in the result, for example when merging overlapping extracts from two source systems during a migration, where the same customer or employee genuinely appears in both and the report must list each once. Use UNION ALL when the branches cannot overlap by construction, when duplicates would be meaningful and must be preserved, or when the result is so large that paying for a deduplication nobody needs is wasteful. A monthly activity report built from twelve monthly queries is the classic UNION ALL case: a row belongs to exactly one month, deduplication can only waste resources, and if two identical-looking rows exist in different months they are two events, not one event seen twice.
Two mechanical rules complete the topic. First, an ORDER BY for the whole combined result goes once, at the very end, after the last branch, and it orders the union as a whole rather than any branch separately. Second, the branches must agree in column count and compatible types position by position; the names may differ, since the first branch supplies the headings, but a salary cannot be stacked over a hire date without a conversion and a very good reason. Interviewers occasionally test this by showing a UNION whose branches select different column counts and asking what happens. The answer is an error, immediately, before any data is read.
**The scalar subquery: more than the company average**
The first subquery every candidate meets compares each employee against a single value computed from the whole table: the average salary of the company.
```sql
-- Employees earning more than the company-wide average salary
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
```
The inner query is a scalar subquery, so called because it returns exactly one row and one column, a single number. It does not mention the outer query at all. The database can evaluate it once, obtain the average, and then test every employee’s salary against that fixed number. Conceptually the execution is two steps: compute the average, then filter. If the inner query were written carelessly so that it returned many rows, for example by selecting every salary rather than the average of them, the comparison would fail with an error in most products, because a single salary cannot be greater than a list of salaries in one comparison. That error message, about a subquery returning more than one value, is one interviewers love to show in a screenshot and ask about, and recognising it as a scalar-subquery shape problem is the entire diagnosis.
A scalar subquery can also appear in the SELECT list, attaching a computed value to every output row, which is a neat way to show each employee beside the benchmark they are being compared with.
```sql
-- Each employee, with the company average alongside for context
SELECT emp_id,
emp_name,
salary,
(SELECT AVG(salary) FROM employees) AS company_average
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
```
The style is not always the most efficient on very large tables, and a strong candidate may mention that a join against a one-row aggregate or a window function can express the same report, but the subquery form is the clearest expression of the idea and the one this screen expects fluency in first.
**The correlated subquery: more than your own department’s average**
Now the question sharpens. Beating the company average is easy for an employee in a highly paid department and nearly impossible in a low-paid one, so the business asks a fairer question: who earns more than the average of their own department?
```sql
-- Employees earning more than the average of their own department
SELECT e.emp_id, e.emp_name, e.dept_id, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(inner_emp.salary)
FROM employees inner_emp
WHERE inner_emp.dept_id = e.dept_id
);
```
The inner query now refers to e.dept_id, a value from the outer query. That reference is the correlation, and it changes everything about how the query must be understood. The inner query cannot be evaluated once, because it does not have a single answer. It has one answer per department, and the right answer depends on which outer row is currently being tested.
Walk it row by row, as the interviewer hopes you will. The database takes the first employee, say emp_id 101, who sits in department 10 on a salary of 900,000. To decide her fate it runs the inner query with e.dept_id fixed at 10, averaging only department 10 salaries, and suppose that average is 780,000. Her 900,000 exceeds it, so she is kept. The database moves to emp_id 102, in department 20, salary 500,000. The inner query runs again, now averaging department 20, whose average is 460,000, and he is kept as well, even though his salary is far below the company average and below the first employee’s. A third employee in department 20 on 430,000 fails against the same 460,000 benchmark and is dropped. The benchmark travels with the row. That is the whole concept, and it is why the aliases matter: e names the outer employee being tested, inner_emp names the rows being averaged, and confusing the two produces a query that silently compares everyone against the company average while wearing the costume of a department query.
Real engines may optimise a correlated subquery into a join-like execution rather than literally re-running it per row, and a candidate may say so, but the logical meaning, the per-row benchmark, is what must be explained. The equivalent join form is worth showing because interviewers often ask for it next, and because on some workloads it performs better and reads better once the report grows extra columns.
```sql
-- The same question, expressed as a join against department averages
SELECT e.emp_id, e.emp_name, e.dept_id, e.salary
FROM employees e
JOIN (
SELECT dept_id, AVG(salary) AS dept_average
FROM employees
GROUP BY dept_id
) d ON d.dept_id = e.dept_id
WHERE e.salary > d.dept_average;
```
Both forms are correct. The subquery states the test where the reader encounters it; the join computes all the department averages once, as a set, which is often the more natural plan when the averages themselves are also needed in the output.
**EXISTS, IN and JOIN: departments with at least one employee above a threshold**
The question now flips direction. Forget employees for a moment. List the departments, from the departments table, that have at least one employee earning above 1,000,000. Three honest constructions answer it.
The JOIN construction reaches the employees through the relationship and then must deal with multiplicity, because a department with five highly paid employees would appear five times.
```sql
-- With a join: correct only once duplicates are removed
SELECT DISTINCT d.dept_id, d.dept_name, d.location
FROM departments d
JOIN employees e
ON e.dept_id = d.dept_id
WHERE e.salary > 1000000;
```
The DISTINCT is doing real work there, and forgetting it is a classic partial answer: the logic is right and the output is wrong, with popular departments repeated. The join form shines when the report also needs employee details, names, counts, the highest salary, because then the employee rows are wanted anyway and no deduplication is needed.
The IN construction tests each department’s identifier against the set of department identifiers that have a qualifying employee.
```sql
-- With IN: the department is in the qualifying set
SELECT dept_id, dept_name, location
FROM departments
WHERE dept_id IN (
SELECT dept_id
FROM employees
WHERE salary > 1000000
);
```
IN reads naturally when the subquery is short and the mental model is membership in a list. Duplicates inside the subquery do not matter, because membership is membership. The result contains each qualifying department once, since the outer query reads departments, one row each.
The EXISTS construction asks a yes-or-no question per department: does there exist at least one qualifying employee here?
```sql
-- With EXISTS: stop at the first qualifying employee found
SELECT d.dept_id, d.dept_name, d.location
FROM departments d
WHERE EXISTS (
SELECT 1
FROM employees e
WHERE e.dept_id = d.dept_id
AND e.salary > 1000000
);
```
EXISTS is a correlated subquery used as a condition. It returns true the moment one matching row is found and does not need to find the rest, which matches the question’s meaning exactly: at least one. The SELECT 1 inside is a convention; EXISTS cares only whether a row exists, not what it contains, so selecting a constant makes that indifference explicit. For this “at least one” shape of question, EXISTS is usually the clearest and often the most efficient expression, and it is the answer experienced interviewers hope to hear recommended, with the reasoning attached rather than as a bare preference.
**The NULL trap in NOT IN**
Everything above reverses when the question becomes negative: list the departments with no employee above the threshold, or the employees whose manager is not in a given list. With NOT EXISTS, the reversal is safe and symmetrical.
```sql
-- Departments with no employee above the threshold: safe form
SELECT d.dept_id, d.dept_name, d.location
FROM departments d
WHERE NOT EXISTS (
SELECT 1
FROM employees e
WHERE e.dept_id = d.dept_id
AND e.salary > 1000000
);
```
With NOT IN, a single NULL inside the subquery’s results poisons the entire comparison. The reasoning is worth stating carefully, because it is the most examinable piece of logic in this whole question. A condition of the form “x NOT IN a list” means x is not equal to the first value, and not equal to the second, and so on for every value. If one value in the list is NULL, then the comparison “x is not equal to NULL” cannot be judged true, because NULL means unknown; nothing is known to be equal or unequal to an unknown. One unknown link in a chain of AND conditions makes the whole chain unknown rather than true, and a WHERE clause keeps only rows whose condition is true. The result is not an error. It is an empty or wrongly reduced result set, returned silently, which is far worse.
In the shared schema the trap is easy to trigger, because manager_id is NULL for the most senior employee in every company, the person who manages nobody above them and reports to no one inside the table. A query asking for employees whose manager_id is NOT IN some subquery that happens to include that top manager’s row can quietly return nothing at all. The defences are two: prefer NOT EXISTS for negative existence tests, since EXISTS works in clean true-and-false terms about whether a row is present and is immune to this trap; or, if NOT IN must be used, exclude empty values explicitly inside the subquery with an IS NOT NULL condition, and understand that you are patching a fragile construction rather than choosing a sound one. Interviewers regard the NOT EXISTS preference, explained through the unknown-value logic rather than recited as folklore, as one of the most reliable signals in the entire SQL screen.
#### The follow-up they ask next
The first follow-up usually reverses the threshold question: “Now give me employees who earn more than every employee in department 30,” which introduces comparison against a whole set rather than a single average. The clean answers compare against the maximum of that department, or use ALL where the product supports it, and the candidate who reaches for the maximum shows they understand that beating every member of a set and beating its largest member are the same test. Its mirror, beating at least one member, is a comparison against the minimum, or ANY. Interviewers rarely need the syntax perfect; they are checking whether the set logic is sound.
The second follow-up asks where else a subquery can live. Candidates who have only ever placed one in a WHERE clause hesitate, so the complete answer names the other homes: in the SELECT list as a scalar value, as the worked example above showed; in the FROM clause as a derived table, as the join version of the department-average query showed; and in a HAVING clause, filtering groups by a computed benchmark, for example departments whose average salary exceeds the company average. Naming all four homes, with a one-line purpose for each, closes the topic convincingly.
The third follow-up turns to performance honesty. “Your correlated subquery is slow on ten million rows. What do you do?” The expected path is not a magic keyword. It is to check that the columns in the correlation and filter, here dept_id and salary, are indexed appropriately; to consider the join-against-aggregate form, which computes each department average once; and to look at the actual execution plan rather than guessing. The candidate who says “rewrite it and measure” beats the candidate who recites that joins are always faster than subqueries, because modern optimisers frequently transform one form into the other, and the plan, not the folklore, is the evidence.
A fourth follow-up, specific to UNION, asks how to sort the combined result by a column that exists under different names in the two branches, or how to label which branch each row came from. The labelling answer is a small professional trick worth carrying: add a constant source column to each branch, a literal such as ‘Chennai’ in the first SELECT and ‘Pune’ in the second, so the merged report can still say where each row originated. Reports that merge sources without preserving origin are a recurring source of confusion in migration work, and interviewers who have lived through one migration tend to ask.
#### The common wrong answer
The common wrong answer has two halves, matching the two halves of the question, and both halves fail in the same way: a true-sounding slogan replaces a condition the candidate never examined.
For UNION, the slogan is “UNION removes duplicates, UNION ALL does not,” delivered as though the topic were finished. The autopsy finds three missing pieces. The candidate cannot say what a duplicate means here, namely an entire row identical across all selected columns, not merely a repeated emp_id or a repeated name, so two different employees who happen to share a name and salary are not duplicates unless every selected column matches. The candidate cannot say what the deduplication costs, so they use UNION by default on enormous append-only data and pay for a sort nobody needed. And the candidate, most revealingly, uses UNION as a safety blanket to hide a join elsewhere in the query that is producing unintended duplicate rows, treating the symptom at the end of the query instead of the cause in the middle of it. Interviewers probe this by asking why the duplicates were there in the first place, and the slogan has no answer.
For subqueries, the common wrong answer is the department-average query written without correlation. It looks almost identical to the correct one, which is precisely why it is dangerous.
```sql
-- The classic wrong answer: no correlation, so the benchmark never changes
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
```
Presented as the answer to “more than their own department’s average,” this returns “more than the company average,” a different business question with a different result set. The autopsy is a lesson in reading what a query says rather than what its author intended. There is no reference from the inner query to the outer row, so the inner query has one fixed answer, so the benchmark cannot vary by department. Everything else, the AVG, the greater-than sign, the table names, is decoration around that single missing link, the condition tying inner dept_id to outer dept_id. Candidates repair this reliably once they learn to ask, of any subquery, one question: does the inner query mention the outer alias? If the business question contains the words “their own,” “its own,” or “per department,” the answer had better be yes.
The third fracture in the wrong answer concerns IN and EXISTS, where the slogan is usually “EXISTS is faster” or, from a different coaching sheet, “always use JOIN.” Both slogans collapse on the same follow-up: what does each one mean, and what happens with duplicates and empty values? The candidate who chose JOIN cannot explain why their department list repeated until DISTINCT rescued it. The candidate who chose IN cannot explain the NOT IN trap, and will, on the evidence of that interview, one day write a NOT IN against a nullable column and ship an empty report that nobody questions for a quarter. Meaning first, performance second, measured rather than assumed: that ordering is the answer the question was built to find.
### Question 8 — Keys, Constraints and Indexes
#### What they are really testing
This is the design question of the set, and it is the one that most clearly separates candidates who have only queried other people’s tables from candidates who have ever been responsible for a table’s integrity. Keys and constraints are the database’s own rules about what data is allowed to exist. Indexes are the database’s machinery for finding data quickly. Normalization is the discipline that decides how data should be spread across tables in the first place. An interviewer asking all three together is asking a single underlying question: if we gave you a blank database on a client project, would the data still be trustworthy in a year?
That matters disproportionately in service companies, because so much of the work is taking over systems where the original designers have left. The experienced hire’s daily reality is duplicate customers, orders pointing at products that no longer exist, salaries stored as text, and reports that take forty minutes because nobody indexed the column every query filters on. Each of those failures maps to a missing piece of this question. Duplicates map to a missing primary or unique key. Orphaned orders map to a missing foreign key. A salary of “eighty thousand-ish” maps to a missing type, check or not-null discipline. A forty-minute report maps to a missing index, and, just as often, a slow insert job maps to too many indexes, which is why the question insists on when indexes hurt as well as when they help.
The interviewer is also testing whether you can explain these ideas in plain language to a non-specialist, because on real projects you will have to. A business analyst will ask why the system refuses her spreadsheet import. A client manager will ask why the new screen is slower than the old one. Candidates who can only recite definitions cannot have those conversations. Candidates who can say what a B-tree is using the image of a book’s index, and why a column with only two possible values makes a poor index, usually can.
#### The full worked answer
**The keys, and what each one guarantees**
- **Primary key**
- What it is: the column, or combination of columns, chosen to identify each row of a table uniquely.
- Guarantees: no two rows share the same primary key value, and no part of it may be NULL.
- How many: exactly one primary key per table, though it may span several columns as a composite key.
- In the shared schema: emp_id on employees and dept_id on departments.
- Practical note: most production tables use a surrogate primary key, a generated number with no business meaning, because real-world identifiers change, get reused and arrive in messy formats, while a generated value never has to.
- **Unique key**
- What it is: a constraint guaranteeing that all values in a column or combination are distinct.
- Guarantees: no duplicates, but unlike a primary key, a unique column in most products may contain a NULL, and a table may carry several unique keys.
- Typical use: an employee’s company email address or a national identifier, where the value must never repeat but is not the table’s main identifier.
- The distinction interviewers want: primary key identifies the row; unique key prevents a duplicate fact. A table has one of the first and may have many of the second.
- **Foreign key**
- What it is: a column in one table whose values must match values in another table’s primary or unique key, or be NULL where the relationship is optional.
- Guarantees: referential integrity. An employee cannot be assigned to department 99 if department 99 does not exist, and the database, not the application code, enforces that on every insert and update, from every source, forever.
- In the shared schema: employees.dept_id references departments.dept_id, and employees.manager_id references employees.emp_id, a self-referencing foreign key, since a manager is also an employee.
- Behaviour on delete: the designer chooses whether deleting a parent row is blocked, cascades to the children, or sets the children’s reference to NULL, and that choice is a business decision recorded in the schema, not a detail to leave to chance.
**The other constraints, which guard single columns and single rows**
- **NOT NULL**
- Meaning: the column must carry a value in every row.
- Use it for: emp_name, dept_id and hire_date, facts without which an employee row is meaningless.
- Leave it off deliberately for: columns that are genuinely optional, such as a middle name or, in this schema, manager_id for the head of the company.
- **CHECK**
- Meaning: a condition every row must satisfy, tested on insert and update.
- Use it for: rules the type system cannot express, such as salary being greater than zero, or a status column holding only an agreed list of values.
```sql
ALTER TABLE employees
ADD CONSTRAINT chk_salary_positive CHECK (salary > 0);
```
- **DEFAULT**
- Meaning: the value the database supplies when an insert omits the column.
- Use it for: hire_date defaulting to the current date, a status defaulting to Active, a counter defaulting to zero.
- Interview precision: a DEFAULT fills an omitted column; it does not forbid NULL if a caller explicitly inserts NULL into a nullable column, which is why DEFAULT and NOT NULL are often paired.
A complete definition gathers all of these into one statement, and being able to write it without hesitation is a strong screen signal.
```sql
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(100) NOT NULL,
dept_id INT NOT NULL,
salary DECIMAL(12, 2) NOT NULL CHECK (salary > 0),
manager_id INT NULL,
hire_date DATE NOT NULL DEFAULT CURRENT_DATE,
email VARCHAR(150) UNIQUE,
CONSTRAINT fk_emp_dept
FOREIGN KEY (dept_id) REFERENCES departments (dept_id),
CONSTRAINT fk_emp_manager
FOREIGN KEY (manager_id) REFERENCES employees (emp_id)
);
```
Read it as a set of promises. Every employee has an identity and a name. Every employee belongs to a real department. No salary is zero, negative or missing. Every manager named is a real employee. An email, once used, belongs to one employee only. Those promises hold no matter which application, script, import or tired developer at midnight writes to the table, and that independence from the writer is the entire argument for constraints.
**Normalization, worked on one bad table**
Normalization is the discipline of organising tables so that each fact is stored once, in the place it belongs, so that updating it cannot leave two versions of the truth. The cleanest way to teach it, and to answer it in an interview, is to start with one bad table and repair it in stages. Suppose a project stored employee and department information together, like this described design: a single table holding emp_id, emp_name, a combined field containing several phone numbers, dept_id, dept_name, location, and the name of the department’s head, repeated on every employee row in that department.
The design fails in three visible ways before any formal rule is named. If a department moves cities, its location must be corrected on hundreds of employee rows, and any row missed leaves the database contradicting itself, which is an update anomaly. A brand-new department with no employees yet cannot be recorded at all, because there is no employee row to hang its facts on, which is an insertion anomaly. And if the last employee of a department leaves and their row is deleted, the department’s name, location and head vanish with them, which is a deletion anomaly. The three normal forms are, in order, the repairs for the structural causes of those anomalies.
- **First normal form, 1NF**
- Rule: every field holds one atomic value, and there are no repeating groups of columns.
- Violation in the bad table: several phone numbers packed into one field, which makes it impossible to search, count or validate a single number with ordinary SQL.
- Repair: one value per field. Phone numbers either become one primary phone column of a single value, or, where an employee genuinely has several numbers that matter, a separate employee_phones table with one row per number. After this step every cell can be addressed and filtered as itself.
- **Second normal form, 2NF**
- Rule: the table is in 1NF, and every non-key column depends on the whole primary key, not on part of it.
- Where it bites: tables with composite keys. Imagine the key were the combination of emp_id and dept_id for an assignment history table; emp_name depends only on emp_id, the first half of the key, so storing it there repeats it on every assignment row and invites contradiction.
- Repair: move columns that depend on part of the key into the table whose key they fully depend on. Employee facts belong in employees, keyed by emp_id alone. In the bad table, whose key is emp_id alone, this step mainly confirms that employee facts sit correctly, and sets up the real problem, which is the next form.
- **Third normal form, 3NF**
- Rule: the table is in 2NF, and no non-key column depends on another non-key column.
- Violation in the bad table: dept_name, location and the department head’s name depend on dept_id, which is a non-key column inside employees. Department facts are being carried inside an employee table, transitively, through dept_id.
- Repair: split the table. Department facts move to departments, keyed by dept_id, stored exactly once each. Employees keeps dept_id as a foreign key and nothing else about the department.
The repaired design is precisely the shared schema of this article: employees(emp_id, emp_name, dept_id, salary, manager_id, hire_date) and departments(dept_id, dept_name, location). A department’s move to a new city is now a one-row update. A department can exist before its first hire. Deleting the last employee of a department leaves the department intact. Those three sentences, offered in an interview as the payoff of the three forms, demonstrate the concept far better than the formal definitions alone, because they show the anomalies dying one by one.
Balance matters here too. A thoughtful candidate adds that real systems sometimes denormalize deliberately, copying a value into a reporting table to avoid an expensive join, but they do it knowingly, with a process that keeps the copies in step, as a performance trade made after measurement. Denormalization by accident, which is what the bad table was, and denormalization by decision are opposite things wearing similar clothes.
**Indexes: what they are, in plain language**
An index is a separate structure the database maintains alongside a table, holding the values of one or more columns in sorted order together with pointers to the rows those values belong to. The plain-language comparison that survives every interview is the index at the back of a textbook. Without it, finding every page that discusses a topic means reading the book from the first page to the last, which in database terms is a full table scan. With it, you look the topic up in an ordered list and go directly to the few pages named. The lookup is fast precisely because the list is kept sorted, and it stays fast as the book grows, because a sorted structure can be searched by repeatedly halving the remaining range rather than by reading every entry.
That sorted structure, in almost every mainstream database, is a B-tree. Explain it without mathematics: imagine the sorted values arranged as a shallow, branching tree, like a tournament bracket turned upside down. The top node holds guidepost values that divide the whole range into broad bands. Each guidepost sends the search down one branch into a smaller node, which divides its band further, until the search reaches a leaf node holding the exact value and the address of its row. Because each level multiplies the number of ranges covered, the tree stays very shallow: a table of millions of rows is typically searched in three or four steps. That shallowness is why indexed lookups feel instant at scales where scans have long since become unusable, and why the same structure serves range questions, such as salaries between two figures or hires after a date, and not only exact matches: in a sorted leaf level, a range is a starting point and a short walk forward.
An index is not free, and its price list is part of the answer. It consumes storage. It must be maintained on every insert, update and delete that touches its columns. And the optimiser is not obliged to use it; for a query returning most of the table, the database may judge a scan cheaper than millions of individual lookups, and it is usually right.
**Clustered and non-clustered indexes**
- **Clustered index**
- What it means: the table’s rows themselves are stored in the order of this index. The index is not a separate guide to the data; at its leaf level, it is the data, arranged.
- How many: one per table, for the simple reason that rows can only be physically arranged in one order at a time.
- Usual choice: the primary key, which most products cluster by default unless told otherwise.
- Consequence: range queries on the clustered column are exceptionally fast, because the rows wanted sit next to each other.
- **Non-clustered index**
- What it means: a separate sorted structure whose leaves hold the indexed values plus a pointer back to the row, rather than the row itself.
- How many: many per table, one for each access pattern worth accelerating.
- Typical examples in the shared schema: an index on dept_id for department-wise employee lists, an index on salary for pay-band reporting, an index on hire_date for joining-cohort analysis.
- Consequence: a lookup may take one extra step, from index leaf to row, a cost that is trivial for selective queries and decisive only at very large result sizes.
**Composite indexes and column order**
A composite index covers several columns together, and its column order is the single most-tested index detail in these screens, because it follows directly from the sorted structure. An index on dept_id and then salary sorts first by department, and within each department by salary, exactly as a phone book sorts by surname and then by first name. It follows that such an index serves queries filtering on dept_id alone, and queries filtering on dept_id together with salary, including salary ranges inside one department. It does not serve, or serves poorly, a query filtering on salary alone across all departments, because salary is only ordered inside each department band, not globally. Candidates express this as the leftmost-prefix principle: an index helps with conditions that begin from its first column and proceed in order.
```sql
-- Composite index: department first, salary within department
CREATE INDEX idx_emp_dept_salary
ON employees (dept_id, salary);
-- Served well by that index: one department, paid above a floor
SELECT emp_id, emp_name, salary
FROM employees
WHERE dept_id = 20
AND salary > 600000;
```
The design habit that follows is to order composite columns by how the queries actually arrive: equality-tested columns first, in the order the workload uses them, and a range-tested column last, since a range ends the useful ordering for any column after it. Getting this backwards, salary first and department second for a workload that always asks department-first questions, produces an index that exists, consumes maintenance on every write, and helps almost nobody, which is worse than no index at all because it looks like the problem was addressed.
**When indexes hurt**
The mature half of the answer, and the half that most distinguishes an experienced candidate, is knowing when not to index.
- **Write-heavy tables**
- Every index on a table must be updated on every insert, and on every update or delete touching its columns. A staging or logging table receiving thousands of inserts a second pays that tax thousands of times a second, once per index. Five indexes on such a table can turn a load that met its window into one that misses it, which is why bulk-load practice often drops or disables indexes before a load and rebuilds them after.
- **Low-cardinality columns**
- Cardinality means the number of distinct values. A column such as a yes-or-no flag, a gender code or a status with three values has very low cardinality, and an index on it divides the table into a handful of enormous groups. A query using it still has to read a large fraction of the table through the index, which is slower than scanning, so the optimiser commonly ignores such an index entirely, leaving it as pure maintenance cost. The professional phrasing is that an index earns its keep when it is selective, when a typical value picks out a small slice of the table.
- **Small tables**
- A table of a few hundred rows fits in a handful of storage pages and can be scanned completely in less time than an index lookup plus row fetch. Indexing it adds maintenance and complexity for no measurable gain.
- **Columns never used for searching or joining**
- An index on a column that no query filters, joins or sorts by is decoration with a running cost. Indexes should be designed from the workload, the actual queries the application runs, reviewed against real execution plans, and pruned when the workload changes. An index nobody uses is not harmless; it is a tax on every write, paid forever, for a benefit nobody collects.
#### The follow-up they ask next
The first follow-up is the missing-value variant of the key questions: “Can a primary key be NULL? Can a unique key?” The answers are no, and in most products yes for a single NULL, respectively, and the reasoning matters more than the answers: a key whose job is to identify a row cannot do that job with an unknown value, while a unique constraint merely forbids two rows from claiming the same known value. Some products differ on whether several NULLs may coexist in a unique column, and naming your product, as with the TRUNCATE question, is the mark of care.
The second follow-up asks how you would find duplicate emails in employees before adding a unique constraint, which tests whether design knowledge connects to data-cleaning practice. The answer groups by email, counts, and keeps groups with a count above one, then resolves those rows with the business before constraining the column, because adding a unique constraint to dirty data fails, loudly and correctly, and the failure is the database doing its job.
The third follow-up is the optimiser question: “You added the index and the query is still slow. Why?” The strong answer works through the possibilities in order: the query may return too large a share of the table for an index to help; the column order of a composite index may not match the query’s conditions; statistics about the data may be stale, leading the optimiser to a poor plan; or the real cost may be elsewhere, in a join or a sort the index was never going to fix. In every branch the next step is the same, and interviewers want to hear it: read the execution plan and measure, rather than adding a second index on a guess.
A fourth follow-up, common in lateral interviews, asks about foreign key actions: “If a department is closed, what happens to its employees?” The answer is that the schema designer chose in advance, among blocking the deletion until employees are reassigned, cascading, which here would delete the employees and is almost certainly wrong, or setting the department reference to NULL, which is only possible if the column allows it and only sensible if an employee can legitimately belong nowhere. The expected conclusion is that for employees and departments, blocking and reassigning is the business-correct behaviour, and the foreign key should be declared to enforce exactly that.
#### The common wrong answer
The common wrong answer to this question is a recital: primary key is unique and not null, foreign key links two tables, an index makes queries faster. Each clause is true and each is useless at the depth a hiring decision needs, and the autopsy shows the same pattern as the earlier questions in this set, slogans standing where conditions should be.
The first fracture appears on the unique key. Asked how it differs from a primary key, the recital repeats that both are unique, and stops. It cannot produce the three working differences: a table may have several unique keys but one primary key; a unique column may accept NULL where a primary key may not; and the primary key is the row’s identity, the target other tables’ foreign keys normally reference, while a unique key is a guard against one duplicated fact. Those differences are not pedantry. They decide real designs, such as a table whose rows are identified by a generated emp_id while email and a national identifier are each guarded separately.
The second fracture appears on normalization, where the recital offers the forms as rhymes about keys, the key, the whole key and nothing but the key, without being able to repair a design. Presented with the bad combined table, the slogan candidate cannot say which column violates which form, and cannot name a single anomaly the split prevents. The interviewer learns that the candidate has stored the vocabulary of design without the skill of design, which is the opposite of what the question exists to discover. The repair, for any candidate preparing now, is to learn normalization backwards from the anomalies: if deleting a row destroys an unrelated fact, if a fact cannot be recorded until an unrelated row exists, if one change must be typed in a hundred places, a normal form is being violated, and the fix is to give the fact a table of its own keyed by what it depends on.
The third fracture, and the most expensive in production, appears on indexes, where the slogan is simply “indexes speed up queries,” full stop. That belief, acted on, produces tables carrying a dozen indexes added one incident at a time and never reviewed, whose inserts crawl; indexes on two-value flags that no optimiser will ever use; and composite indexes in the wrong column order, present on paper and absent in every execution plan. It also produces the candidate who, told a query is slow, proposes an index before looking at the plan, the data volumes or the query itself. The complete answer holds both truths at once: an index is the most powerful performance tool in ordinary SQL work, and every index is a standing charge against writes, storage and complexity, justified only by a workload that actually uses it. Candidates who can hold both halves of that sentence are the ones this question was written to find, and they are, not coincidentally, the ones a client can safely leave alone with a production schema.
### Question 9 — Names, Missing Values and the NULL Trap: Who Starts With ‘A’, Who Has No Salary on Record, and Why Equality Fails
#### What they are really testing
On the surface this looks like the easiest question in the set. Find the employees whose names begin with a particular letter. Find the employees who have no manager. Find the employees whose salary has not been entered. Candidates who have spent a week memorising joins and window functions often relax when they hear it, and that relaxation is exactly what the interviewer is watching for.
What is being tested here is not pattern matching. It is whether a candidate understands that a database distinguishes carefully between a value that is zero, a value that is an empty string, and a value that is simply not there. In service-company work that distinction is not academic. Payroll extracts arrive with missing salaries for staff who have just joined. Organisation charts arrive with a blank manager field for the person at the top of the chart and for contractors whose reporting line lives in a different system. A report that quietly treats missing as zero will understate a department’s costs. A report that quietly drops everyone with a missing manager will lose the chief executive from the headcount. Interviewers return to this question because the production mistakes it predicts are real, frequent and expensive.
There is a second layer. The question tests whether a candidate can read a requirement precisely. “Starts with A” is not the same as “contains A.” “Has no manager recorded” is not the same as “is managed by nobody in the business,” even if the two often overlap. Strong candidates repeat the requirement back in their own words before they write, and they ask, when the setting allows it, whether the search should be case sensitive. Weak candidates write quickly and answer a slightly different question from the one that was asked.
The third layer is counting. Almost every paper that includes the NULL question also includes, somewhere nearby, a request to count employees — and the difference between counting rows and counting values inside a column sits at the heart of it. An interviewer who asks both halves together is checking whether the candidate’s mental model of the table is consistent from one line of SQL to the next.
#### The full worked answer
Begin with the pattern match, using the shared schema of employees with columns emp_id, emp_name, dept_id, salary, manager_id and hire_date, alongside departments with dept_id, dept_name and location.
To find employees whose name starts with the letter A, the LIKE operator with a percent wildcard does the work:
```sql
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE emp_name LIKE ‘A%’;
```
The percent sign means any sequence of characters, including no characters at all, after the initial A. The pattern ‘A%’ therefore means: an A in the first position, and then anything or nothing. A name consisting of a single A would qualify. So would Asha, Arjun and Ananya. A name such as Priya would not, because the A in Priya is not in the first position, and a name such as Sana would not either, even though it ends with the letter.
Contrast that with the other common patterns, because interviewers love to vary them without warning:
```sql
-- Contains the letter A anywhere
SELECT emp_id, emp_name
FROM employees
WHERE emp_name LIKE ‘%A%’;
-- Ends with the letter A
SELECT emp_id, emp_name
FROM employees
WHERE emp_name LIKE ‘%A’;
-- Second character is A
SELECT emp_id, emp_name
FROM employees
WHERE emp_name LIKE ‘_A%’;
```
The underscore matches exactly one character, no more and no less. That is why ‘_A%’ pins the A to the second position: one character of anything, then A, then anything. Candidates should be able to explain each wildcard in plain language, because the follow-up almost always asks for a variation rather than a repetition.
Case sensitivity deserves a sentence in the room. In many MySQL installations LIKE is case insensitive by default for the usual character sets, so ‘a%’ and ‘A%’ return the same rows. In PostgreSQL, LIKE is case sensitive and ILIKE is the case-insensitive form. In SQL Server the behaviour follows the collation of the column. A candidate does not need to recite every dialect, but saying “in the dialect we are using this matches both cases; if we needed to force one behaviour I would check the collation or use the case-insensitive form” signals the kind of care that production code requires.
Now the missing values. To find employees with no salary recorded:
```sql
SELECT emp_id, emp_name, dept_id, salary, hire_date
FROM employees
WHERE salary IS NULL;
```
And to find employees with no manager recorded — a group that typically includes the head of the organisation and anyone whose reporting line has not yet been loaded:
```sql
SELECT emp_id, emp_name, dept_id, manager_id
FROM employees
WHERE manager_id IS NULL;
```
The two can be combined when the requirement asks for anyone missing either piece of information:
```sql
SELECT emp_id, emp_name, salary, manager_id
FROM employees
WHERE salary IS NULL OR manager_id IS NULL;
```
And they can be narrowed to those missing both:
```sql
SELECT emp_id, emp_name, salary, manager_id
FROM employees
WHERE salary IS NULL AND manager_id IS NULL;
```
The choice between OR and AND is not a stylistic preference. OR widens the result to anyone with at least one gap. AND narrows it to those with both gaps. Reading the requirement aloud and matching the connective to it is a small discipline that prevents a large class of errors.
Why, then, does the obvious-looking version fail? Candidates write this constantly:
```sql
-- This returns no rows, ever, even when NULL salaries exist
SELECT emp_id, emp_name
FROM employees
WHERE salary = NULL;
```
It returns nothing not because the table has no missing salaries, but because the comparison itself can never be true. NULL in SQL does not mean zero and does not mean empty. It means the value is unknown or absent. A comparison asks a question — is this salary equal to that value — and when one side of the question is unknown, the database cannot honestly answer yes. It also cannot honestly answer no, because for all it knows the unknown salary might turn out to equal the value in question once it is known. So SQL works with three possible outcomes for a comparison instead of two: true, false and unknown. This is often called three-valued logic, and candidates should be able to describe it in ordinary words without reciting a textbook: true means we know it matches, false means we know it does not, and unknown means the data does not let us decide.
Follow the consequences through, because interviewers do. If salary is NULL, then salary = 60000 is unknown. Salary > 60000 is unknown. Salary <> 60000 is also unknown — the database cannot say the unknown salary is definitely different from 60000 either. And NULL = NULL is unknown as well, which surprises almost everyone the first time: two unknown values are not known to be equal, because neither of them is known at all. A WHERE clause keeps only the rows where the condition is true. Rows where the condition is false are dropped, and rows where the condition is unknown are dropped too. That single rule explains nearly every NULL surprise in SQL. A filter on salary silently excludes everyone whose salary is missing, whether the filter uses equality, inequality or a range, unless the query handles the missing case explicitly.
That is why IS NULL and IS NOT NULL exist. They are not comparisons in the ordinary sense. They are direct tests of presence and absence, and they always return true or false, never unknown. WHERE salary IS NULL asks, is the value absent. WHERE salary IS NOT NULL asks, is a value present. Both are safe to reason about.
The counting half of the question follows naturally. Suppose the interviewer asks how many employees the company has, and then how many employees have a salary recorded. The two answers can differ, and the SQL differs by one word:
SELECTCOUNT(*) AS total_employees,
COUNT(salary) AS employees_with_salary,
COUNT(manager_id) AS employees_with_manager
FROM employees;
```
COUNT(*) counts rows. It does not look inside any column, so missing values do not matter to it; every row in the table contributes one. COUNT(column), by contrast, counts the rows where that column holds an actual value. Rows where the column is NULL are skipped. If a table holds 120 employees and 7 of them have no salary loaded yet, COUNT(*) returns 120 and COUNT(salary) returns 113. Neither number is wrong. They answer different questions, and the candidate’s job is to know which question was asked. Interviewers report that this distinction, explained calmly with a small numerical example, is one of the most reliable separators between candidates who have used SQL and candidates who have only read about it.
The same logic extends to other aggregates, and a thorough answer mentions it without being prompted. SUM(salary) ignores NULL salaries rather than treating them as zero — which happens to give the same total as treating them as zero, but for a different reason. AVG(salary) divides the total of the known salaries by the count of known salaries, not by the total headcount. If seven salaries are missing, the average is the average of the 113 salaries that exist. Whether that is the average the business wants is a requirements question, and naming it as one earns credit.
Finally, reports need missing values handled gracefully rather than merely filtered. That is where COALESCE earns its place. COALESCE takes a list of expressions and returns the first one that is not NULL:
```sql
SELECT
emp_id,
emp_name,
COALESCE(salary, 0) AS salary_for_report
FROM employees;
```
In a payroll summary, COALESCE(salary, 0) lets a missing salary contribute zero to a displayed total instead of leaving a blank that a reader might misread. In a different report, showing a label such as Unassigned may be kinder than showing zero, and a CASE expression can do that when the types require it. The important point for the interview is judgement: COALESCE changes what the report displays; it does not change what is stored, and it should never be used to hide a data problem that someone needs to fix. A candidate who says “I would use COALESCE for the display, and I would also flag how many salaries were missing, because a silent zero can hide a loading failure” has understood both the function and the job.
Put together, a complete answer to Question 9 moves in order: LIKE with the wildcard in the right place, IS NULL for absence, a plain-language account of why equality against NULL can never be true, COUNT(*) for rows against COUNT(column) for present values, and COALESCE where a report needs a stand-in value. Each step is short. The understanding underneath them is what is being hired.
#### The follow-up
The follow-ups to this question are predictable enough to prepare for directly. The first is usually a variation of the pattern: names that end with a given letter, names with a given letter in the third position, names that do not start with a given letter. The NOT LIKE operator handles the last of these, but a thoughtful candidate notes that rows with a NULL name, if any exist, will not appear in either the LIKE or the NOT LIKE result, because both comparisons come back unknown for a missing name. Offering that observation unprompted is a strong signal.
The second follow-up asks for employees whose salary is missing in a particular department, which simply layers a second condition onto the first:
```sql
SELECT emp_id, emp_name
FROM employees
WHERE salary IS NULL
AND dept_id = 20;
```
The third follow-up is the trap in reverse: “Show me everyone who does not earn 60000.” A candidate who writes salary <> 60000 will lose everyone with a missing salary, because their comparison is unknown. If the business meaning of the request includes the people with no salary on record, the query must say so:
```sql
SELECT emp_id, emp_name, salary
FROM employees
WHERE salary <> 60000 OR salary IS NULL;
```
Some dialects offer a null-safe comparison operator that treats two NULLs as equal and a NULL against a value as different, and mentioning it shows breadth — but the portable, explainable form above is the one to lead with in a service-company screen, where the code may run on a client’s database rather than one’s own. The fourth follow-up replaces a missing manager with a label such as Top Level for an organisation chart. That is COALESCE with text, or a CASE expression when the types differ, and the principle is the same as in the report example: presentation is a choice, storage is a fact.
#### The common wrong answer
Three wrong answers recur so reliably that interviewers describe recognising them on sight. The first is salary = NULL, written with complete confidence. It returns an empty result, and when the interviewer says “are you sure,” many candidates check the table name and the column name rather than the comparison itself. The correction to practise until it is automatic is simple: equality compares values, NULL is the absence of a value, so absence is tested with IS NULL.
The second is treating an empty string and NULL as the same thing. In most systems an empty string is a value — a piece of text of length zero — and it is not NULL, though Oracle historically treats an empty string as NULL, which is worth knowing if the client’s estate includes Oracle. A candidate who checks only for one of the two, when the data may contain both, will miss rows. Asking which form the missing data takes is a legitimate and professional question.
The third is using COUNT(salary) when the question asked for the number of employees, then defending the smaller number as the headcount. It is not carelessness about syntax; it reveals that the candidate thinks of counting as a single operation rather than a question about rows versus values. The fix is a habit: before writing any count, say to yourself what one unit of the count is — one row, or one present value — and choose the form that matches.
### Question 10 — Window Functions: Ranking Tied Salaries, the Top Three in Each Department, and Why the Window Cannot Live in the WHERE Clause
#### What they are really testing
Every set in this series builds toward this question, and candidates for the higher tracks feel the step up when it arrives. Recruiters and interviewers describe the same dividing line in different words: a large group of candidates can filter, join and group; a smaller group can rank within groups without losing the detail of the individual rows. That second skill is what window functions provide, and it is why this question has become the recognised separator for the Digital and Prime style tracks, where the work is more likely to involve analytics, reporting and data-heavy delivery from the first year.
What is being tested is not the memorisation of three function names. It is whether the candidate understands what a window is: a set of rows, defined relative to the current row, over which a calculation runs while the rows themselves stay intact. GROUP BY collapses rows into summaries. A window function annotates rows with a result computed from their neighbours. A candidate who can state that difference in one sentence, before writing any code, has usually understood the topic. A candidate who reaches for GROUP BY to find the top three earners in each department, and then discovers that the grouping has thrown away the very names the question asked for, has not yet made the distinction — and the interviewer has learned something important in under two minutes.
The question also tests precision under ties. Real salary data ties constantly, because companies pay in bands. Any ranking method must decide what to do when two people earn the same amount, and the three ranking functions decide differently. Choosing among them is a business decision expressed in code: does the company want three rows, three salary levels, or a podium with no gaps. Interviewers are listening for that reasoning as much as for the syntax.
#### The full worked answer
Take a small department and work it by hand first, because every strong answer to this question does the arithmetic before the SQL. Suppose department 10 has five employees with these salaries: 120000, 120000, 110000, 95000 and 95000. Two people share the top salary. One person sits at the next level. Two people share the level after that.
ROW_NUMBER gives every row a distinct position, even when the values tie. It numbers the rows 1, 2, 3, 4, 5 in the order specified, and when two salaries are equal it still assigns them different numbers, in an order that is not guaranteed unless a second ordering column breaks the tie. RANK gives tied rows the same rank, then skips ahead by the size of the tie, the way an Olympic podium does when two athletes share gold and no silver is awarded. DENSE_RANK also gives tied rows the same rank, but it does not skip: the next distinct value takes the very next number.
Applied to the five salaries, ordered from highest to lowest, the three functions produce three different results:
- Salary 120000, first employee — ROW_NUMBER 1, RANK 1, DENSE_RANK 1
- Salary 120000, second employee — ROW_NUMBER 2, RANK 1, DENSE_RANK 1
- Salary 110000 — ROW_NUMBER 3, RANK 3, DENSE_RANK 2
- Salary 95000, first employee — ROW_NUMBER 4, RANK 4, DENSE_RANK 3
- Salary 95000, second employee — ROW_NUMBER 5, RANK 4, DENSE_RANK 3
Read those three columns slowly, because the whole question lives inside them. RANK jumps from 1 to 3 because two rows occupy the top. DENSE_RANK moves from 1 to 2 because it counts distinct salary levels, not rows. ROW_NUMBER counts rows and ignores the meaning of the tie entirely. None of the three is the correct one in the abstract. Each is correct for a different statement of the requirement.
In SQL, all three sit in the same shape:
```sql
SELECT
emp_id,
emp_name,
dept_id,
salary,
ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS row_num,
RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS salary_rank,
DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS salary_dense_rank
FROM employees;
```
The OVER clause defines the window. PARTITION BY dept_id restarts the calculation for each department, so every department gets its own 1, its own 2 and so on — the direct equivalent, in window terms, of grouping, except that the rows survive. ORDER BY salary DESC inside the window says what the ranking is based on and in which direction. Leave out PARTITION BY and the ranking runs across the whole company. Leave out ORDER BY and the ranking has no basis at all.
Now the request that makes the question famous: the top three salaries in each department. The phrase hides an ambiguity, and the best candidates name it before resolving it. Top three can mean three employees, or it can mean three salary levels, which may contain more than three employees when ties sit near the cut. For “the employees who earn one of the top three salary levels in their department,” DENSE_RANK is the honest tool, because it counts levels:
```sql
SELECT emp_id, emp_name, dept_id, salary
FROM (
SELECT
emp_id,
emp_name,
dept_id,
salary,
DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS dr
FROM employees
WHERE salary IS NOT NULL
) AS ranked
WHERE dr <= 3;
```
In department 10 above, that query returns all five employees, because the department has exactly three distinct salary levels: 120000, 110000 and 95000. That result surprises candidates who expected three rows, and explaining why it is right — the requirement said salary levels, and five people hold those levels — is often the moment an interview turns. If the requirement instead means exactly three employees per department, ROW_NUMBER is the tool, with a deliberate tiebreaker so the choice among equals is stable and defensible:
```sql
SELECT emp_id, emp_name, dept_id, salary
FROM (
SELECT
emp_id,
emp_name,
dept_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY dept_id
ORDER BY salary DESC, hire_date ASC, emp_id ASC
) AS rn
FROM employees
WHERE salary IS NOT NULL
) AS ranked
WHERE rn <= 3;
```
Here the earliest hire among equals comes first, and emp_id settles any remaining tie, so the same query returns the same three people every time it runs. And if the requirement follows competition ranking — joint first, then third — RANK with a filter at three returns the two top earners and the person at 110000, and no one at 95000, because there is no rank 2 in that department at all. Three readings, three queries, three different result sets from the same five rows. A candidate who walks an interviewer through that fork, and asks which reading the business intends, is demonstrating the exact judgement these tracks are hired for.
Notice the shape both queries share: the window function is computed in an inner query, and the filter on its result sits in an outer query. That shape is not a stylistic habit. It is forced by the order in which SQL processes a statement, which is the last part of the worked answer.
Window functions can also look sideways and accumulate, and a complete answer previews both, because Digital-track follow-ups reach for them quickly. A running total of salaries within a department, in hire order, uses SUM as a window function:
```sql
SELECT
emp_id,
emp_name,
dept_id,
hire_date,
salary,
SUM(salary) OVER (
PARTITION BY dept_id
ORDER BY hire_date, emp_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_salary_total
FROM employees;
```
LAG reaches for the previous row’s value within the window, and LEAD reaches for the next row’s. Together they are the standard way to do period-over-period work — the pattern behind month-over-month comparisons in sales, attrition and utilisation reporting. In an employee setting, LAG can place each person’s salary beside the salary of the person hired just before them in the same department:
```sql
SELECT
emp_id,
emp_name,
dept_id,
hire_date,
salary,
LAG(salary) OVER (
PARTITION BY dept_id
ORDER BY hire_date, emp_id
) AS previous_hire_salary
FROM employees;
```
In a monthly summary the same idea compares this month’s figure with last month’s, and the difference or the percentage change is then a plain subtraction or division in an outer query. Candidates do not need to build a full monthly report on the spot. They need to recognise that “compare each row with the one before it” is a LAG-shaped problem, and that the first row in each partition has no predecessor, so its LAG value comes back NULL — another place where the missing-value discipline from Question 9 quietly returns.
#### The follow-up
The standard follow-up is the one the worked answer has been preparing for: why can the ranking not be filtered in the same query’s WHERE clause? Candidates try it constantly:
```sql
-- This fails: window functions are not allowed in WHERE
SELECT emp_id, emp_name, dept_id, salary
FROM employees
WHERE DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) <= 3;
```
The database rejects it, and the reason is the logical order in which a query is evaluated. The WHERE clause is processed early, while the database is deciding which rows from the source tables are in play at all. Window functions are processed much later, after grouping and after the rows that will feed the SELECT list have been settled, because a window calculation needs to see the full set of rows in each partition before it can rank any of them. At the moment WHERE runs, the ranking does not yet exist. There is nothing to filter on. The remedy is the two-step shape used above: compute the rank in a subquery or a common table expression, then filter on the computed column in an outer query, where it is by then an ordinary value. A candidate who explains it as a matter of timing — “WHERE runs before the window exists, so the filter has to live one level out” — will satisfy almost any interviewer, and the same timing logic explains why window functions cannot appear in GROUP BY either.
A second follow-up swaps the direction: the lowest paid in each department, or the most recent hire. Nothing structural changes; the ORDER BY inside the window reverses or changes column. A third follow-up asks what happens when PARTITION BY is removed — the answer being that the window becomes the whole result set, so the ranking is company-wide. A fourth asks for the second-highest salary using a window function, which closes the circle with the earliest questions in this set: DENSE_RANK filtered to 2, in a subquery, returns every employee at the second salary level in one pass, ties included, which is precisely the behaviour the older LIMIT and MAX-based methods struggle to reproduce cleanly.
#### The common wrong answer
The most common wrong answer is reaching for GROUP BY and MAX three times, or joining the table to itself repeatedly, to approximate a top-three-per-group result. Such constructions can be made to work for the highest value and sometimes for the second, but they grow brittle with ties, they multiply quickly, and they usually lose either the employee names or the tied rows along the way. Interviewers do not mark the attempt as worthless — it shows persistence — but it answers the question the set has been asking since Question 1 with the tools of Question 1, when the whole point of Question 10 is that a better tool exists.
The second wrong answer is using ROW_NUMBER while calling it ranking, and then being unable to say what happens when salaries tie. If two people share the top salary and the requirement is about salary levels, ROW_NUMBER silently promotes the second distinct salary in a way that misstates the result — and worse, it may choose a different person on a different run when no tiebreaker is given, because the order among equals is unspecified. An unstable answer to a payroll question is not a small flaw.
The third wrong answer is placing the window function in WHERE and then, when the database objects, trying it in GROUP BY, and then in HAVING, in a descending tour of the clause order. Each attempt teaches the interviewer that the candidate knows the function names but not the sequence in which SQL thinks. The candidate who instead writes the subquery first, without experimenting, and can say why it has to be that way, has converted the hardest question in the set into the strongest answer of the interview.
### What candidates are discussing — and what the record shows
Spend any week in the places where candidates compare notes after these screens — the comment threads under preparation videos, the forums where freshers trade recollections of their papers, the group chats that form around a single hiring drive — and the same five arguments surface again and again. They are worth taking seriously, because each contains a fragment of truth, and each, taken whole, leads candidates to prepare for the wrong test. What follows paraphrases the themes as they circulate, without attributing them to any individual, and sets each against what the documented pattern of these interviews actually shows.
The first and most persistent belief is that the assessment and the interview are the same test in two rooms. Candidates who have cleared an online assessment built around aptitude, reasoning and a coding or SQL section often arrive at the interview expecting a harder edition of the same paper: more questions, tighter time, the same right-or-wrong scoring. The preparation that follows from that belief is more of the same — larger question banks, faster solving, less talking.
The record points the other way. The assessment is a filter. It processes very large numbers of applicants for a small number of interview slots, and it is designed to be machine-scored, standardised and defensible at scale. The interview is a probe. It takes a much smaller number of candidates and asks a different question altogether: not merely whether this person can produce an answer, but whether this person can explain an answer, defend it when it is varied, and recognise when it is wrong. That is why interviewers in these processes so often take a question the candidate has just answered correctly and change one word of it — highest becomes second-highest, inner becomes left, three rows becomes three levels. A filter cannot do that. A conversation can. Candidates who prepare only for the filter arrive fluent in answers and silent in explanations, and interviewers describe that silence, repeatedly, as the reason otherwise strong papers do not convert into offers. The practical consequence is a division of labour in preparation: timed sets for the assessment, spoken walkthroughs for the interview. Anyone who has never said a query aloud, start to finish, with reasons, has prepared for only half the process.
The second argument is the claim that the second-highest-salary question is a trick that has had its day — that it was asked so often, and mocked so often, that panels have retired it. The claim has an appealing logic. Surely, candidates reason, no serious interviewer still asks the most famous SQL question in the world.
Candidate reports and preparation guides keep listing it among the most frequent questions anyway. It appears in collections of questions candidates say they were actually asked, in the syllabi of preparation courses updated for current drives, and in the recollections posted after recent interview rounds. The reason for its survival is not a lack of imagination on the panel’s side. The question is a compact instrument. In two minutes it reveals whether a candidate can use a subquery, whether they understand what MAX does inside a condition, whether they think about ties at all, and whether they can produce a second method — a LIMIT with an offset, a dense ranking — when the first is challenged. Interviewers keep instruments that measure several things at once. Candidates should also notice what the persistence of the question implies about its cousins: the third-highest variant, the per-department variant and the tied-salaries variant all travel with it. Preparing the famous question in its single textbook form, with no thought for ties or departments, is preparing for the version of it that panels moved beyond years ago, even as they kept the question itself.
The third theme is anxiety about the medium itself: paper versus screen. In many of these processes the technical conversation still involves writing SQL by hand — on paper, on a whiteboard, or in a plain document without an editor — and candidates who have only ever written queries inside a tool that colours the syntax, completes the keywords and runs the query at a keystroke find the blank page disproportionately frightening. The fear is understandable and, in the telling, often exaggerated into a belief that handwriting is a separate skill being tested out of spite.
It is not a separate skill, but it does expose a real dependency. A candidate who has always relied on the editor to catch a missing comma, or to suggest the next keyword, has never had to hold the whole query in their head. The preparation that answers it is unglamorous and effective: write the same queries out longhand, on paper, without running them, and then check them. The first attempts are slow and error-prone, which is the point. The habit of writing a query from its logic rather than from its autocomplete is the same habit the interview room rewards, and it is built in the same place: a blank page, a pen, and a willingness to be wrong in private before being tested in public.
The fourth debate is the liveliest: whether project questions matter more than SQL. One camp, often the candidates who have done well on the written test, insists that the database questions are the gate — get through them and the rest follows. The other camp, often those who have built things, insists that the project discussion is where offers are actually made, because a candidate who can explain a real system they built demonstrates judgement that no set of syntax questions can reach.
The broader pattern is that the two halves do different jobs, and a candidate needs both. SQL functions as the gate: it is the part of the process that can be scored quickly and fairly across thousands of applicants. The project discussion is where the interview becomes a conversation, and where the candidate who has genuinely built something can separate from the candidate who has only memorised. The candidates who do best treat the SQL screen as the price of admission and the project as the place where the offer is won — and they prepare for both with the same seriousness, rather than betting everything on one half of the process.
The fifth theme concerns the video walkthroughs candidates lean on, and here the discussion is large and largely undifferentiated. Long-form worked examples — the kind where an instructor solves a query slowly, aloud, from first principles — are consistently recommended, and for good reason: they show the thinking, not just the answer. The risk is subtler. A candidate who has watched dozens of hours of such walkthroughs can mistake familiarity for competence, and can find, in the interview room, that recognition is not the same as production. The antidote is the same as for the paper test: pause the video before the answer, attempt the query yourself, and only then watch the solution. The walkthrough is a mirror, not a substitute for practice.
Taken together, the five themes resolve into a single piece of advice that no individual thread quite states: prepare for explanation, expect the famous questions in their modern variants, practise on paper as well as on screen, treat SQL as the gate and the project as the conversation, and use long worked examples to learn reasoning rather than to collect answers. Candidates who do those five things are, by the accounts of the panels themselves, recognisably different in the room.
### Three rooms, three lessons
The scenarios that follow are illustrative examples. Each is a composite, drawn from the patterns interviewers describe rather than from any single candidate’s experience, and each is worked through to the lesson it carries.
Consider a candidate who has prepared well and knows it. The paper in front of her asks for the third-highest salary in the company. She writes the familiar nested form — the maximum salary below the maximum salary below the maximum — and begins to relax. Then the interviewer, who has been reading as she writes, asks a quiet question: the top salary in this company is earned by two people; does your answer still give the third-highest salary, or does it give something else? She looks again. Her construction counts salary values, because each MAX step moves to a lower distinct value, so the two people at the top consume only one step of her nesting, and her answer does land on the third distinct salary level. She says so — and then, to her credit, she catches the second half of the lesson herself: if the question had meant the third-highest paid employee, her answer would be wrong in a different way, because three levels and three people are not the same request when ties sit at the top. The interviewer nods and asks her to write the version that returns everyone at the third salary level. She reaches for a dense ranking in a subquery, filters it to the third level, and the exchange ends with the panel having learned more from her correction than from her first answer. The lesson is not that ties are a trap laid for the unwary. It is that the phrase highest salary is ambiguous in the presence of ties, that strong candidates surface the ambiguity instead of concealing it, and that an interviewer who probes a correct answer is usually offering a chance to display exactly that awareness. A candidate who defends the first answer without engaging the tie has failed a question she had, moments earlier, answered correctly.
Consider a candidate who is asked for every department and the number of employees in it, including departments with no employees at all. He correctly chooses a LEFT JOIN from departments to employees — he even says, as he writes it, that the left join is what protects the empty departments. His query counts employees by department, and the interviewer asks him to add one condition: show only departments where the employees earn more than 50000. He appends the salary condition to the WHERE clause and presents the result. The interviewer asks what happened to the department with no employees. He studies his own query and finds it: the salary condition cannot be true for a department with no employees, because there is no salary to test — the extended row the left join produced carries a NULL salary, the comparison comes back unknown, and the WHERE clause discards the row, which is precisely the row the left join existed to preserve. His left join has been silently converted into the behaviour of an inner join, not by changing the join, but by filtering on a column from the right-hand table in the WHERE clause. The repair, once seen, is straightforward: a condition on the joined table that must not eliminate the preserved rows belongs in the ON clause of the join, where it governs matching rather than survival, or the filtering must be done in a way that explicitly keeps the no-match rows. He makes the repair and explains it back correctly. The lesson generalises well beyond this question. Any WHERE condition on a column from the nullable side of an outer join risks undoing the join, and the failure is silent — the query runs, the numbers look plausible, and only a department that vanishes betrays it. Interviewers return to this pattern because production reports fail in exactly this way, quietly, for months. The habit that prevents it is a question asked of every outer join before the query is offered: which rows must survive even when nothing matches, and does anything I have written since the join put their survival at risk?
Consider a candidate who is applying for a Digital-track role and whose early answers have gone well. His joins are clean, his grouping is correct, and he handles the missing-value question without stumbling. Then comes the ranking question: the top three salaries in each department. He writes a solution using ROW_NUMBER, filters it to three, and presents it confidently. The interviewer asks what happens in a department where the second and third salaries are tied with the fourth. He answers, honestly, that one of the tied employees will be shown and the other will not. The interviewer asks whether that is what the business asked for. He concedes it may not be. The interviewer asks which function he would use if the requirement were the top three salary levels. There is a pause, and then an admission: he knows the names RANK and DENSE_RANK, he has seen them in a list, but he cannot say with confidence which one skips numbers and which one does not, and he has never worked the same tied example through all three. The interview does not collapse — his fundamentals are sound, and for many roles they would be enough. But the track he applied for is the one where ranking, cohort and period-over-period questions are the daily work, and the panel’s note writes itself: basic answers fine, separator question not yet answered. The lesson is the most actionable in this set. The difference among the three ranking functions can be learned completely, with one five-row example, in less than an hour — and it must be learned as an explanation, not as a slogan. A candidate who can say that ROW_NUMBER counts rows and breaks ties arbitrarily, that RANK counts rows but honours ties and leaves gaps, and that DENSE_RANK counts distinct values and leaves none, and who can show all three on the same salaries, has converted the separator question from a threat into the strongest evidence in the room that they belong on the higher track.
### Keeping a notebook that compounds
There is a familiar pattern in how preparation materials accumulate. A candidate watches a walkthrough and saves the link. A forum thread contains a clever solution, and it is bookmarked. A handwritten page holds the ranking example that finally made the three functions clear, and it goes into a folder whose exact location is forgotten by the following week. By the time the interview is a fortnight away, the candidate owns a great deal of preparation and can find very little of it. Review becomes re-searching, re-searching becomes re-reading from the beginning, and the sense of progress that repetition should create never arrives, because nothing is ever encountered for the second time in the same place.
The alternative is a single notebook, kept deliberately, in which every question from sets like this one earns a page written in the candidate’s own words: the question as asked, the answer as they would give it, the follow-up they were caught by, and the wrong answer they now know to avoid. Such a notebook compounds. The NULL page sits beside the counting page, where it belongs, because the two ideas explain each other. The ranking page holds the five-salary example that settles the three functions, ready to be rehearsed the night before a Digital-track interview. A candidate building that kind of personal question-and-answer record — the practice behind VaultBook — is not collecting material but converting it, and the conversion is the learning. Ten minutes spent writing a page after each study session will, over a month, produce the single most useful revision document the candidate owns, precisely because no one else could have written it: it contains their errors, in their words, with their corrections attached.
The discipline matters more than the tool. Keep one page per question. Write the explanation before the code, because the explanation is what the interview tests. Record every follow-up as a question in its own right, with its own answer, because follow-ups are where offers are decided. Date each page, and when a later session improves an earlier answer, amend the page rather than starting a new one, so the notebook shows its own history. Reviewed this way, in short passes, the notebook turns scattered preparation into a structure that survives the journey to the interview centre — and, not incidentally, becomes the foundation of the reference the candidate will wish they had in their first months on the job, when the same questions return wearing production data.
### Seven days to ready
A week is enough to become genuinely ready for this screen if the week is spent in the right order: foundations first, famous questions second, variations and spoken explanation last. The plan below assumes roughly two focused hours a day. Candidates with less time should protect the order and shorten the sessions rather than skipping ahead to the window functions, because every later topic in this set leans on an earlier one.
- **Day 1 — Rows, filters and honest reading.** Work through SELECT, WHERE, comparison operators, AND and OR, and ORDER BY on the employees and departments tables. For every query, write one sentence in plain language stating what one row of the result means before running or finalising it. Finish with LIKE patterns: starts with, contains, ends with, and a fixed position using the underscore. End the session on paper, away from the screen, with five short queries written by hand and read aloud.
- **Day 2 — Missing values and counting.** Devote the whole session to NULL: why equality against NULL never returns true, the three outcomes a comparison can produce, IS NULL and IS NOT NULL, and the silent way ordinary filters exclude missing values. Then counting and aggregates: COUNT(*) against COUNT(column), and what SUM and AVG do with missing values. Close with COALESCE in report-style queries, and write the notebook pages for Questions 9’s ideas while the examples are fresh.
- **Day 3 — Joins without fear.** Practise inner joins between employees and departments until department names and locations arrive without hesitation, then spend the larger half of the session on LEFT JOIN: which rows must survive, what the NULL-extended rows look like, and how a WHERE condition on the joined table can silently undo the join. Rewrite the second scenario from this article from memory, then compare it with the original.
- **Day 4 — Grouping and the famous questions.** GROUP BY and HAVING, department-wise counts, totals and averages, and the difference between filtering rows before grouping and filtering groups after it. Then the canonical set: highest salary, second-highest salary by at least two methods, and highest salary per department. For the second-highest question, write out what each method does when two employees share the top salary.
- **Day 5 — Subqueries, sets and self-joins.** Employees earning more than their manager, employees earning above the department average, and correlated against independent subqueries — when each is appropriate and how each reads aloud. Add the employee-manager self-join, displaying each employee beside their manager’s name, including the handling of the employee at the top whose manager is NULL.
- **Day 6 — Window functions, the separator day.** Give this topic a full day, because it carries disproportionate weight for the higher tracks. Work the five-salary tied example through ROW_NUMBER, RANK and DENSE_RANK by hand until the three result columns can be produced without hesitation. Then top three per department in both readings — three rows and three levels — running totals with SUM as a window function, and a first pass at LAG for comparisons with the previous row. Finish by explaining, aloud and in writing, why a window function cannot sit in WHERE.
- **Day 7 — The rehearsal.** Sit a timed, mixed paper: ten questions drawn from across the set, at least two of them varied from their familiar forms, written by hand with no editor. Mark it harshly, especially on ties, NULL handling and any filter placed on a window result. Spend the second hour speaking: take three questions and explain each answer start to finish as if to an interviewer, including the follow-up you most fear. Record the gaps in the notebook, sleep, and do no new material the following morning.
One part of the process sits outside SQL altogether, and Day 6 or Day 7 is the right place for it. Candidates in these processes are repeatedly asked not only to produce answers but to write and explain — short written responses, structured reasoning set down under time pressure, and explanations that a reader must be able to follow without the author in the room. That is a trainable skill, and it transfers: the discipline of stating a claim, supporting it in order and closing it cleanly is the same discipline that makes a spoken SQL explanation land. A timed drill such as Citizen Kane essay practice used honestly for what it is — structured-writing practice against the clock, on a set subject, rather than anything to do with databases — gives candidates a low-stakes way to rehearse organising an answer under time pressure before the day when the answer that needs organising is a query. Twenty focused minutes of it, once in the week, is enough; the point is the habit of structure under time, not the subject matter.
### Frequently asked questions
### Q: How much SQL is enough for the Ninja-level screen, and how much more do the Digital and Prime tracks expect?
For the entry-level screen, the honest answer is the first eight questions of a set like this one, done reliably: filtering, pattern matching, joins, grouping, subqueries and the highest-salary family, with NULL handled correctly. For the higher tracks, add Question 10 without apology — ranking functions, top values per group in both readings, running totals and a working grasp of LAG — plus the ability to explain every choice aloud. Depth of explanation matters at every level; the higher tracks simply extend the territory that explanation must cover.
### Q: Will the test be on paper, on a shared screen, or in an online editor?
It varies by drive, by location and by round, and candidates should prepare for the least forgiving version: writing complete queries by hand, with no syntax highlighting, no autocomplete and no ability to run the query. Anyone who can do that can also work comfortably in an editor. Anyone who has only ever worked in an editor may find the blank page harder than the questions on it. A few handwritten sessions in the final week remove most of that risk.
### Q: Which SQL dialect should I learn — MySQL, PostgreSQL, Oracle or SQL Server?
Learn the concepts in one dialect, thoroughly, and learn the handful of places where dialects differ: how the top rows are limited, whether LIKE is case sensitive, how missing values and empty strings are treated, and the exact names of the ranking functions, which are reassuringly standard. In the room, name the dialect you are writing in, and if the interviewer works in another, say how the query would change. Panels hire for transferable understanding, not for loyalty to a vendor.
### Q: The interviewer wants a different method from the one I know. What should I do?
Say what your method does, acknowledge theirs, and attempt it — talking as you go. If you know the second-highest salary through a subquery and the interviewer asks for a ranking approach, that request is usually an invitation, not a rejection: they have accepted the first answer and are testing range. If you genuinely do not know the other method, say so plainly, describe what it would need to accomplish, and offer the method you have. Inventing syntax confidently is the one response that reliably damages an otherwise good interview.
### Q: What about edge cases — a department with one employee, a table where everyone earns the same, an empty department?
Raise them yourself, briefly, before the interviewer does. A department with one employee has that employee at the first, second and every other rank only in the sense that there is no second salary level at all, and a good query returns nothing for a request for the second level rather than inventing one. If everyone earns the same, there is one salary level, and level-based questions should say so through their results. An empty department tests outer joins, not ranking. Naming an edge case and stating what your query does with it is among the cheapest credibility available in these interviews.
### Q: I am an experienced hire, not a fresher. Does the set change?
The core questions recur, because they test fundamentals that experience is supposed to have settled, but the centre of gravity shifts. Experienced candidates should expect the follow-ups to run longer and deeper — performance of a query at scale, indexing on the join and filter columns, what happens when the employees table holds tens of millions of rows, and how a report requirement was clarified with a client before code was written. A wrong fundamental answer is also judged more harshly with experience, which is an argument for rehearsing the basics rather than assuming them.
### Q: If I fail a drive, can I try again, and what should I do differently?
Reapplication windows and cooling-off periods are set by each company’s current hiring policy for each drive, and they change, so candidates should check the terms of the specific drive they sat rather than relying on anything general said here. What does not change is the value of the interval: the candidates who convert a second attempt are, by every account, the ones who identified the exact questions that beat them the first time, rebuilt those topics from the explanation outward, and kept the notebook from the first attempt rather than starting again from a blank page.
### Q: Should I memorise answers to the famous questions word for word?
Memorise the reasoning, not the wording. A memorised answer survives only until the interviewer changes one condition — a tie at the top, a department added, a level instead of a row — and interviewers change one condition as a matter of routine, because that is how they distinguish understanding from recall. A candidate who has understood the second-highest question can answer its five nearest variants. A candidate who has memorised it can answer one question, and the panel will find the boundary within two follow-ups.
### Sources and coverage
This set synthesises the questions that candidate guides and interview reports keep listing as recurring across service-company SQL screens, among them Campus Monk’s TCS NQT question collection, InterviewQuery’s TCS software engineer guide, synthesised from 102 candidate reports, and Freshers Blog’s service-company SQL list, checked 25 November 2026. The questions here are original variants written in the recurring patterns, not copied question banks, and the worked answers were prepared for this publication’s readers preparing for TCS, Infosys, Wipro and Cognizant-style screens.
— Pinnacle Report

