Data Analytics

SQL - Subqueries and CTEs

Scalar subqueries, correlated subqueries, EXISTS, WITH (CTE), recursive CTEs, query refactoring

20 interview questions·
Mid-Level
1

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.

2

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.

3

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.

4

How to use the IN keyword with a subquery to filter results?

5

What is a correlated subquery?

6

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