Advanced SQL Queries for Interview: 9 Patterns

How-to basics · Updated November 23, 2026

Advanced SQL queries for interviews test your ability to solve real data problems using window functions, recursive CTEs, and clever joins—not just your memory of syntax. The core skill interviewers look for is translating a business question into a set-based SQL statement that is correct, efficient, and readable. This article covers the exact query patterns that appear most often in data analyst, data engineer, and backend developer interviews, with concrete examples you can adapt.

Why Interviewers Ask Advanced SQL

SQL is the universal language for working with relational data, and advanced queries reveal how you think about data relationships, performance, and edge cases. A candidate who can write a query that handles duplicates, NULLs, and ties demonstrates practical experience beyond basic SELECT-FROM-WHERE. Interviewers also use advanced SQL to gauge your ability to read and explain complex logic, because in a real job you will spend more time debugging other people’s queries than writing your own. Common advanced topics include window functions, common table expressions (CTEs), recursive queries, pivot/unpivot, and query optimization techniques like using indexes and avoiding correlated subqueries when a join works better.

Window Functions: The Most Tested Topic

Window functions (also called analytic functions) compute a value across a set of rows related to the current row, without collapsing them into a single output row. The syntax is function() OVER (PARTITION BY col ORDER BY col ROWS/RANGE frame). The most common ones are ROW_NUMBER(), RANK(), DENSE_RANK(), SUM() as a running total, LAG() and LEAD() for comparing rows, and NTILE() for bucketing. Example: to find the top 3 highest-paid employees per department, use ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) and then filter where rn <= 3 in an outer query. Unlike GROUP BY, window functions preserve all rows, which is why they are perfect for rankings, moving averages, and year-over-year comparisons. A common mistake is using RANK() when you want ROW_NUMBER()—RANK() gives ties the same number and skips the next, while ROW_NUMBER() always gives a unique number.

Common Table Expressions (CTEs) and Recursive Queries

A CTE (WITH clause) lets you name a subquery and reference it multiple times, making complex queries readable and modular. For example, WITH high_sales AS (SELECT * FROM orders WHERE amount > 1000) SELECT customer_id, COUNT(*) FROM high_sales GROUP BY customer_id;. Recursive CTEs are the advanced twist: they call themselves to traverse hierarchical data like employee-manager chains, bill-of-materials, or category trees. The syntax is WITH RECURSIVE cte AS (anchor_query UNION ALL recursive_query) SELECT * FROM cte;. A typical interview question: given an employees table with manager_id, list all subordinates of a given manager at any depth. The anchor selects the manager, the recursive part joins employees to the CTE on manager_id, and you add a depth column to avoid infinite loops. Recursive queries are supported in PostgreSQL, SQL Server, and MySQL 8+; older MySQL versions require a different approach.

Advanced Joins and Set Operations

Beyond inner and left joins, interviewers test self-joins, cross joins, and anti-joins. A self-join pairs a table with itself—for example, to find employees whose salary is higher than their manager, join employees e1 to employees e2 on e1.manager_id = e2.id and compare salaries. An anti-join finds rows in one table that have no match in another; use LEFT JOIN ... WHERE right_table.id IS NULL or NOT EXISTS. Set operations like UNION, INTERSECT, and EXCEPT (MINUS in Oracle) combine results from two queries. A common question: find customers who bought product A but not product B—use SELECT customer_id FROM purchases WHERE product='A' EXCEPT SELECT customer_id FROM purchases WHERE product='B'. Remember that UNION removes duplicates by default; UNION ALL keeps them and is faster. Correlated subqueries (a subquery that references the outer query) are often slower than a join, so interviewers may ask you to rewrite one for performance.

Pivoting and Unpivoting Data

Pivoting turns rows into columns, and unpivoting does the reverse. In PostgreSQL you use the crosstab() function from the tablefunc extension; in SQL Server you use the PIVOT operator; in MySQL you use conditional aggregation with CASE or SUM(IF()). For example, to convert monthly sales rows into columns for Jan-Dec, you write SELECT product, SUM(CASE WHEN month='Jan' THEN sales END) AS Jan, ... FROM sales GROUP BY product;. Unpivoting in SQL Server uses UNPIVOT, while in other databases you use UNION ALL of separate SELECTs. Interviewers ask this to see if you can reshape data for reporting or dashboard tools. A practical tip: know your database’s specific syntax because the standard SQL has no built-in PIVOT—this is a place where many candidates stumble.

Handling Duplicates, NULLs, and Ties

Advanced queries often involve cleaning messy data. To find duplicate rows, use SELECT col1, col2, COUNT(*) FROM table GROUP BY col1, col2 HAVING COUNT(*) > 1;. To delete duplicates keeping the lowest ID, use a window function: DELETE FROM table WHERE id NOT IN (SELECT MIN(id) FROM table GROUP BY col1, col2); (but be careful with large tables—a CTE with ROW_NUMBER() is safer). NULL handling is critical: use COALESCE() to replace NULLs, IS NULL in WHERE, and remember that NULL is not equal to anything, even another NULL. For ties in ranking, decide whether you want RANK() (gaps) or DENSE_RANK() (no gaps). A classic question:

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.