Subqueries and CTEs Interview Questions for SQL
25 Subqueries and CTEs questions with answers for sql roles — 6 easy, 12 medium, 7 hard.
About Subqueries and CTEs
Break complex problems into steps with scalar, list, table and correlated subqueries and Common Table Expressions. Learn IN versus EXISTS, the NOT IN NULL trap, recursive CTEs for hierarchies, lateral joins for top N per group, and classic interview problems like Nth highest salary and duplicate removal.
What is the difference between a correlated and a non-correlated subquery?
Show answer
What is a CTE and why use it?
Show answer
Find employees earning more than the company average.
Show answer
Find the second highest salary.
Show answer
How do you approach a SQL problem you have never seen before in an interview?
Show answer
What is the difference between IN and EXISTS?
Show answer
Why is NOT IN dangerous when the subquery contains NULL?
Show answer
What is the difference between a CTE, a subquery, a temp table and a view?
Show answer
Are CTEs materialised or inlined?
Show answer
Find employees who earn more than their department average.
Show answer
Rewrite a nested query using CTEs for readability.
Show answer
Find departments where every employee earns above 40000.
Show answer
Your NOT IN query returns zero rows even though you expect results. What do you check?
Show answer
A query with a correlated subquery in SELECT runs for every row and is slow. How do you improve it?
Show answer
You need to delete duplicate rows but keep one copy of each. How do you do it?
Show answer
An interviewer asks for the Nth highest salary in a reusable way. How do you answer?
Show answer
Describe a time you reviewed someone else's SQL and suggested improvements.
Show answer
What is a recursive CTE and how does it work?
Show answer
What is a lateral join or CROSS APPLY?
Show answer
Write a recursive CTE to show an employee hierarchy with levels.
Show answer
Get the latest 3 orders for every customer using a lateral join.
Show answer
A long report query has eight nested subqueries and nobody can maintain it. How would you refactor it?
Show answer
A recursive CTE on a category tree runs forever. What is the likely cause and fix?
Show answer
Tell me about a time you set SQL coding standards for a team.
Show answer
Frequently asked questions
How important is Subqueries and CTEs in SQL interviews?
Break complex problems into steps with scalar, list, table and correlated subqueries and Common Table Expressions. Learn IN versus EXISTS, the NOT IN NULL trap, recursive CTEs for hierarchies, lateral joins for top N per group, and classic interview problems like Nth highest salary and duplicate removal.
How should I use the Subqueries and CTEs sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.