
SQL - Subqueries and CTEs
Scalar subqueries, correlated subqueries, EXISTS, WITH (CTE), recursive CTEs, query refactoring
1What is a subquery in SQL?
What is a subquery in SQL?
Answer
A subquery is a query nested inside another SQL query. It can appear in SELECT, FROM, WHERE, or HAVING clauses. The subquery executes first and its result is used by the outer query. This mechanism allows breaking down complex problems into successive logical steps.
2In which SQL clause can a scalar subquery be used?
In which SQL clause can a scalar subquery be used?
Answer
A scalar subquery returns exactly one value (one row, one column). Thanks to this property, it can be used in the SELECT clause as a computed column. It can also appear in WHERE for direct comparisons. Subqueries returning multiple rows cannot be used where a single value is expected.
3What is the difference between a subquery and a join?
What is the difference between a subquery and a join?
Answer
A subquery is an independent nested query that produces an intermediate result used by the outer query, while a join directly combines columns from multiple tables into a single result set. Joins are generally more performant for combining data, but subqueries are sometimes more readable for complex filters or intermediate calculations.
How to use the IN keyword with a subquery to filter results?
What is a correlated subquery?
What is the role of the EXISTS keyword in a subquery?
+17 interview questions
Master Data Analytics for your next interview
Access all questions, flashcards, technical tests and interview simulators.
Start for free