The most effective way to answer tricky SQL interview queries is to practice the specific patterns interviewers reuse: self-joins, window functions, recursive CTEs, and conditional aggregation. This article walks through 15 realistic examples of those patterns, explains the logic behind each solution, and gives you the exact SQL syntax you can adapt in an interview setting.
Why SQL Interviews Focus on Tricky Queries
Interviewers rarely ask for simple SELECT statements because those don’t reveal how you think. Tricky queries test your ability to break a problem into steps, choose the right join type, and use advanced features like window functions or common table expressions (CTEs). They also show whether you can write efficient code that scales—a key concern for production databases. Most tricky questions fall into a handful of categories: finding duplicates, comparing rows within the same table, handling gaps in data, and aggregating across multiple conditions. Once you recognize the category, the solution becomes a matter of applying the correct pattern.
Core SQL Features You Must Know
Before diving into examples, make sure you’re comfortable with these features that appear in nearly every tricky query:
- Window functions (ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM OVER) for row-level calculations without collapsing rows.
- Common table expressions (CTEs) using WITH to break complex logic into readable steps.
- Self-joins to compare rows in the same table.
- Conditional aggregation using CASE inside SUM or COUNT to pivot data.
- Recursive CTEs for hierarchical data like employee-manager chains.
These are standard in PostgreSQL, MySQL 8+, SQL Server, and Oracle. If you’re using an older MySQL version (pre-8.0), window functions aren’t available, but most interview environments use modern versions.
Example 1: Find Duplicate Rows in a Table
Given a table users(id, email), find all emails that appear more than once. The classic solution uses GROUP BY and HAVING:
SELECT email, COUNT(*) AS cnt
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
But a trickier version asks for the full rows of duplicates. Use a window function:
WITH ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM users
)
SELECT * FROM ranked WHERE rn > 1;
This returns every duplicate row except the first occurrence, which is often what the interviewer wants.
Example 2: Second Highest Salary
This classic appears in many forms. With a table employees(id, salary), find the second highest distinct salary. Use OFFSET with ORDER BY:
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
But if there are ties, DISTINCT ensures you get the second distinct value. A more robust alternative uses a subquery:
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
This works even without LIMIT, which is useful in SQL Server where TOP is used instead.
Example 3: Employees Who Earn More Than Their Manager
Given employee(id, name, salary, manager_id) where manager_id references id in the same table, find employees whose salary exceeds their manager’s. This requires a self-join:
SELECT e.name AS employee, e.salary AS emp_salary,
m.name AS manager, m.salary AS mgr_salary
FROM employee e
JOIN employee m ON e.manager_id = m.id
WHERE e.salary > m.salary;
The key is to alias the same table twice and join on the foreign key. This pattern also appears in questions about organizational hierarchy.
Example 4: Consecutive Rows (e.g., Consecutive Logins)
Find dates where a user logged in for three consecutive days. Table logins(user_id, login_date). Use LAG to compare with previous rows:
WITH dated AS (
SELECT user_id, login_date,
LAG(login_date, 1) OVER (PARTITION BY user_id ORDER BY login_date) AS prev1,
LAG(login_date, 2) OVER (PARTITION BY user_id ORDER BY login_date) AS prev2
FROM logins
)
SELECT DISTINCT user_id
FROM dated
WHERE login_date = prev1 + INTERVAL '1 day'
AND login_date = prev2 + INTERVAL '2 days';
Note: The INTERVAL syntax varies by database. In SQL Server, use DATEADD(day, 1, prev1). This pattern shows you understand window functions and date arithmetic.
Example 5: Department-Wise Top N Salaries
Given employees(id, name, salary, dept_id), find the top 3 salaries per department. Use ROW_NUMBER with PARTITION BY:
WITH ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rn
FROM employees
)
SELECT * FROM ranked WHERE rn <= 3;
If you need ties included, use DENSE_RANK instead. This is a common follow-up to test your understanding of the difference between ROW_NUMBER, RANK, and DENSE_RANK.
Example 6: Running Total and Moving Average
Calculate a running total of sales by date. Table sales(sale_date, amount). Use SUM with OVER:
SELECT sale_date, amount,
SUM(amount) OVER (ORDER BY sale_date) AS running_total
FROM sales
ORDER BY sale_date;
For a moving average over 3 days, use AVG with ROWS BETWEEN:
SELECT sale_date, amount,
AVG(amount) OVER (ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg
FROM sales;
This tests window frame specification, which is a common point of confusion.
Example 7: Pivot Rows to Columns
Given sales(month, product, revenue), show one row per month with columns for each product’s revenue. Use conditional aggregation:
SELECT month,
SUM(CASE WHEN product = 'A' THEN revenue ELSE 0 END) AS prod_A,
SUM(CASE WHEN product = 'B' THEN revenue ELSE 0 END) AS prod_B
FROM sales
GROUP BY month;
This is a manual pivot. Some databases have PIVOT (SQL Server) or crosstab (PostgreSQL), but conditional aggregation is portable and often preferred in interviews.
Example 8: Recursive Query for Employee Hierarchy
Find the full reporting chain for each employee. Table employee(id, name, manager_id). Use a recursive CTE:
WITH RECURSIVE emp_tree AS (
SELECT id, name, manager_id, 1 AS level
FROM employee
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, t.level + 1
FROM employee e
JOIN emp_tree t ON e.manager_id = t.id
)
SELECT * FROM emp_tree;
This is a standard pattern for tree structures. In SQL Server, the syntax is WITH cte AS (…) without RECURSIVE keyword.
Example 9: Find Gaps in a Sequence
Given a table numbers(n) with integers 1,2,4,5, find missing numbers. Use a recursive CTE to generate all numbers up to the max, then LEFT JOIN:
WITH RECURSIVE all_nums AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM all_nums WHERE n < (SELECT MAX(n) FROM numbers)
)
SELECT a.n AS missing
FROM all_nums a
LEFT JOIN numbers n ON a.n = n.n
WHERE n.n IS NULL;
This is a common trick to test your ability to generate sequences.
Example 10: Compare Consecutive Rows (e.g., Sales Increase)
Find days where sales increased from the previous day. Use LAG:
WITH prev AS (
SELECT sale_date, amount,
LAG(amount) OVER (ORDER BY sale_date) AS prev_amount
FROM sales
)
SELECT sale_date, amount
FROM prev
WHERE amount > prev_amount;
This pattern also applies to stock prices, temperature readings, and any time-series data.
How to Approach Tricky Queries in an Interview
When faced with a tricky query, follow a systematic process:
- Clarify the question: Ask about duplicates, ties, nulls, and expected output format.
- Sketch the tables: Write down the columns and relationships.
- Break the problem into steps: Often a CTE helps.
- Start with a simple version: Get the basic logic working, then add complexity.
- Test with a small dataset: Mentally run through a few rows.
Interviewers value a clear thought process over a perfect answer. Verbalize your reasoning as you go.
Common Pitfalls and How to Avoid Them
- Forgetting to handle NULLs: Use COALESCE or IS NULL in joins and conditions.
- Misunderstanding window function order: The ORDER BY inside OVER affects the frame, not the final output order.
- Using GROUP BY without aggregating all selected columns: Always include non-aggregated columns in GROUP BY.
- Assuming a specific database dialect: Mention your assumption (e.g., PostgreSQL) and note differences.
- Overcomplicating the solution: Often a simple join or subquery suffices.
Frequently Asked Questions
What is the difference between RANK and DENSE_RANK?
RANK leaves gaps in the ranking when there are ties. For example, if two people tie for first, the next rank is 3. DENSE_RANK gives consecutive ranks, so the next rank would be 2. Use RANK when you want to know the exact position, and DENSE_RANK when you want a compact list of top N distinct values.
Should I use a subquery or a CTE?
Both are valid. CTEs are easier to read and can be referenced multiple times, which is helpful for complex logic. Subqueries are fine for simple cases. In modern databases, performance is often similar because the optimizer rewrites them. Choose based on readability.
How do I handle ties when finding the Nth highest salary?
Use DENSE_RANK in a subquery and filter by rank. For example, to find the 3rd highest salary with ties, use SELECT * FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) WHERE rnk = 3. This returns all rows with that salary.
What if my database doesn’t support window functions?
Older MySQL (before 8.0) and some other systems lack them. You can often use correlated subqueries or self-joins instead. For example, a running total can be done with a correlated subquery: SELECT sale_date, amount, (SELECT SUM(amount) FROM sales s2 WHERE s2.sale_date <= s1.sale_date) AS running_total FROM sales s1.
How do I practice tricky SQL queries?
Use online platforms like LeetCode, HackerRank, and StrataScratch, which have real interview questions. Set up a local database (PostgreSQL or SQLite) and write your own test data. Focus on understanding the logic, not memorizing syntax.
Is it okay to ask the interviewer for a hint?
Yes, if you’re stuck. Interviewers often give hints to see how you respond to guidance. It’s better to ask a clarifying question than to go silent. Frame it as “Would it be correct to use a window function here?”
Final Tips for Success
Master these 10 patterns, and you’ll handle most tricky queries. Practice writing them from memory, because in an interview you won’t have time to look things up. Also, be ready to explain the time complexity and how your query would perform on large datasets. Finally, remember that a correct but slightly slower query is better than a fast but wrong one—interviewers look for correctness first, then efficiency.
Related
- Data Entry and Data Management: Clear Answers
- Google Sheets Percentage of Total: Easy Formula
- Java String Length: How to Get String Length
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Conditional Formatting: How to Test Rules EasilyTo test conditional formatting in Excel for Microsoft 365 on Windows, create a small set of sample values,…
- Excel Split Cells Into Multiple ColumnsTo split text from one Excel cell into separate columns, select the cells and choose Data > Text…
- How to Change View Size in Outlook Email on Any ScreenTo change the size of an email in Outlook, adjust message zoom in classic Outlook for Windows, or…
- Test Excel Data: Practical Checks for Accuracy and ErrorsTo test Excel data, check for missing values, duplicates, invalid entries, and formulas that do not match the…
- Excel Cell Won’t Move With Arrow Keys? Fixes That WorkIf an Excel cell will not move when you press an arrow key, first check whether Scroll Lock…
- Google Sheets: Duplicate a Sheet Multiple TimesYes. In Google Sheets, right-click a sheet tab and choose Duplicate to make one copy; repeat the command…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.