For experienced SQL developers, interview queries go beyond basic SELECT statements and focus on advanced query patterns, performance tuning, and problem-solving under constraints. You should expect questions on window functions, complex joins, recursive CTEs, query optimization, and handling real-world data anomalies. This article breaks down the most common categories of SQL interview queries for experienced roles, with concrete examples and explanations to help you prepare.
Why Experienced SQL Interviews Differ
Entry-level SQL interviews test syntax and basic joins. Experienced interviews test your ability to write efficient, maintainable queries that handle large datasets and edge cases. Interviewers want to see that you understand how the database engine executes a query, not just that you can get the right result. They often present a schema and ask you to write a query that would perform well on millions of rows, or to debug a query that returns incorrect results due to NULL handling or duplicate records.
Another key difference is the emphasis on problem-solving. You may be given a vague business question like “find the top 3 products by revenue per region” and must clarify assumptions, choose the right functions, and explain your logic. Experienced interviews also probe your knowledge of indexes, execution plans, and when to use subqueries versus joins.
Window Functions: The Core of Advanced Queries
Window functions (also called analytic functions) are a staple in experienced SQL interviews. They allow you to compute values across a set of rows related to the current row without collapsing them into a single output row. Common functions include ROW_NUMBER(), RANK(), DENSE_RANK(), LAG(), LEAD(), and aggregate functions like SUM() with an OVER() clause.
A typical question: “For each department, find the employee with the highest salary.” The solution uses ROW_NUMBER() partitioned by department and ordered by salary descending, then filters to the first row. For example:
WITH ranked AS (
SELECT employee_id, department_id, salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
FROM employees
)
SELECT * FROM ranked WHERE rn = 1;
Another common query is calculating running totals: “Show monthly revenue and a cumulative total.” That uses SUM(revenue) OVER (ORDER BY month). Interviewers also test the difference between RANK() and DENSE_RANK() when there are ties. RANK() leaves gaps (1,1,3), while DENSE_RANK() does not (1,1,2).
Recursive CTEs for Hierarchical Data
Recursive Common Table Expressions (CTEs) are used to query hierarchical or graph-like data, such as employee-manager relationships, bill of materials, or organizational charts. A recursive CTE has two parts: an anchor member (the base query) and a recursive member that references the CTE itself, joined with a UNION ALL.
Example: “List all employees under a given manager, including indirect reports.” Given a table employees(id, manager_id), the query would be:
WITH RECURSIVE emp_tree AS (
SELECT id, name, manager_id, 1 AS level
FROM employees
WHERE id = 1 -- starting manager
UNION ALL
SELECT e.id, e.name, e.manager_id, et.level + 1
FROM employees e
JOIN emp_tree et ON e.manager_id = et.id
)
SELECT * FROM emp_tree;
Interviewers may ask you to avoid infinite loops when cycles exist in the data. A common technique is to track the path in a separate column and stop when a node repeats. They may also ask about performance implications, since recursive CTEs can be expensive on large datasets; you might suggest using a materialized path or adjacency list with indexes.
Complex Joins and Set Operations
Experienced queries often require joining multiple tables with non-obvious conditions. You should be comfortable with inner, left, right, full outer, and cross joins, as well as self-joins. A classic self-join question: “Find employees who earn more than their manager.” That requires joining the employees table to itself on e.manager_id = m.id and comparing salaries.
Set operations—UNION, INTERSECT, EXCEPT—are also tested. For example, “Find customers who placed orders in both 2023 and 2024” can be solved with INTERSECT on the customer IDs from each year. Interviewers may ask about the difference between UNION and UNION ALL: UNION removes duplicates, which requires sorting, so UNION ALL is faster when duplicates are acceptable.
Another common scenario is joining on ranges, like finding all orders that fall within a promotion period. That uses a non-equi join: ON o.order_date BETWEEN p.start_date AND p.end_date. Be ready to discuss how such joins affect performance and how you might optimize them with indexes or by pre-aggregating.
Query Optimization and Indexing
Interviewers often ask you to optimize a slow query. They may show you an execution plan and ask what indexes you would create. Key concepts: index selectivity, covering indexes, composite index column order, and avoiding functions on indexed columns (e.g., WHERE YEAR(order_date) = 2024 prevents index usage; use order_date >= '2024-01-01' AND order_date < '2025-01-01' instead).
A typical question: “Given a query that filters on status and created_at, what index would you create?” The answer is a composite index on (status, created_at) because the equality column should come first, then the range column. You should also know when to use a covering index (all columns needed in the index) to avoid table lookups.
Another optimization topic is rewriting subqueries as joins or using EXISTS instead of IN when the subquery returns many rows. For example, WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) is often faster than WHERE c.id IN (SELECT customer_id FROM orders) because EXISTS stops at the first match. However, modern optimizers may treat them the same, so it’s good to mention that you would check the execution plan.
Handling NULLs and Data Quality Issues
Experienced SQL developers know that NULLs are not just “missing values”—they behave differently in comparisons, aggregations, and joins. Interviewers test this with questions like “Count the number of orders where the discount is NULL” versus “where the discount is not NULL.” You must remember that COUNT(column) ignores NULLs, while COUNT(*) does not.
Another common problem is duplicate detection and removal. A question like “Delete duplicate rows from a table, keeping the one with the smallest id” requires a self-join or a window function. Using ROW_NUMBER() is a clean approach:
WITH numbered AS (
SELECT id,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM users
)
DELETE FROM users WHERE id IN (SELECT id FROM numbered WHERE rn > 1);
Interviewers may also ask about data cleaning: converting strings to dates, handling inconsistent formats, or splitting comma-separated values. For splitting, you might use STRING_SPLIT in SQL Server or SPLIT_PART in PostgreSQL, and you should be aware of version differences.
Pivoting and Unpivoting Data
Transforming rows to columns (pivot) or columns to rows (unpivot) is a common business requirement. In SQL Server, you can use the PIVOT operator, but many interviewers prefer a conditional aggregation approach because it’s more portable. For example, “Show total sales per product per quarter” can be done with:
SELECT product_id,
SUM(CASE WHEN quarter = 'Q1' THEN sales ELSE 0 END) AS Q1,
SUM(CASE WHEN quarter = 'Q2' THEN sales ELSE 0 END) AS Q2,
SUM(CASE WHEN quarter = 'Q3' THEN sales ELSE 0 END) AS Q3,
SUM(CASE WHEN quarter = 'Q4' THEN sales ELSE 0 END) AS Q4
FROM sales
GROUP BY product_id;
Unpivoting is less common but may appear if you have a table with columns like jan_sales, feb_sales, etc., and you need to normalize it. In SQL Server, you can use UNPIVOT, or you can use UNION ALL to stack the columns. Interviewers may ask about the performance trade-offs and when to use each method.
Common Pitfalls and Misconceptions
One frequent misconception is that SELECT DISTINCT is always bad. It’s not inherently bad, but it can mask poor joins or indicate data quality issues. Experienced developers know to investigate why duplicates exist rather than just adding DISTINCT.
Another pitfall is relying on implicit type conversion. For example, comparing a string column to a number can cause full table scans. Always use explicit casts and ensure data types match. Also, beware of using OR conditions on indexed columns; they can prevent index usage. Rewriting as a UNION ALL of two queries may be faster.
Finally, many developers forget about the HAVING clause versus WHERE. WHERE filters rows before aggregation, HAVING filters groups after. A classic mistake is using WHERE COUNT(*) > 10 which is invalid; you must use HAVING.
Frequently Asked Questions
What is the difference between RANK and DENSE_RANK?
RANK assigns a unique rank to each row, but if there are ties, it leaves gaps in the sequence. For example, if two rows tie for first, the next rank is 3. DENSE_RANK also assigns the same rank to ties, but the next rank is 2, with no gaps. Use RANK when you want to know the exact position (like a competition), and DENSE_RANK when you want a compact ranking (like top N distinct values).
How do I find the second highest salary in a table?
A common solution is to use a subquery: SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees). Alternatively, use DENSE_RANK() and filter for rank = 2. The window function approach is more flexible if you need the third or fourth highest, and it handles ties correctly.
What is a covering index and why is it useful?
A covering index is an index that contains all columns needed to satisfy a query, so the database doesn’t have to look up the actual table rows. This reduces I/O and speeds up queries. For example, if you frequently run SELECT name FROM users WHERE age > 30, an index on (age, name) would be covering because both columns are in the index.
Should I use IN or EXISTS for subqueries?
In modern databases, the optimizer often treats them the same, but historically EXISTS was faster for large subqueries because it short-circuits. IN can be slower if the subquery returns many rows because it may materialize the entire list. If the subquery is small, IN is fine. Always check the execution plan to see which is more efficient for your data.
How do I handle pagination in SQL?
Use the OFFSET and FETCH clauses (in SQL Server, PostgreSQL, and others) or LIMIT and OFFSET in MySQL. For example: SELECT * FROM products ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY. For large datasets, keyset pagination (using a WHERE clause on the last seen value) is more efficient than OFFSET because it avoids scanning skipped rows.
What is the difference between a temporary table and a CTE?
A CTE is a named subquery that exists only for the duration of a single query. A temporary table is physically created and can be indexed, and it persists for the session. CTEs are useful for readability and recursive queries, but if you need to reference the same result multiple times or add indexes, a temporary table may be better.
Related
- Auto Sum Shortcut in Excel: Quick Keys & Steps
- Computer Data Entry Job Vacancy: Real Answers
- How to Select a Cell and Everything Below It in Excel
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Row Height and Column Width: Make Cells SquareYes. To make an Excel cell square, make its column width and row height occupy the same number…
- Excel Print a Certain Area: Set a Print AreaTo print only part of a worksheet in Excel for Microsoft 365 on Windows, select the cells you…
- Google Sheets IF Function: Syntax, Examples, and TipsThe Google Sheets IF function checks whether a condition is true and returns one value if it is,…
- Excel Row Count Limit: Maximum Rows and What It MeansIn current versions of Microsoft Excel, a worksheet can contain up to 1,048,576 rows. That is the limit…
- Save an Excel File as a Copy: Step-by-Step InstructionsTo save an Excel file as a separate copy in Microsoft 365 for Windows, open the workbook and…
- Append Tables in Excel Without Power Query: Best MethodsYes. To append tables in Excel without Power Query, copy the data rows from one table and paste…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.