⚡0 XP🔥0

Subqueries, CTEs and Set Operations

Lesson 6 of 10 ⏱ 6 min read ✎ 3 exercises ❓ 4-question quiz ▶ Runs SQL

Queries inside queries - scalar subqueries, IN and EXISTS, correlated subqueries, derived tables, Common Table Expressions (WITH), recursive CTEs, and UNION, INTERSECT and EXCEPT.

A subquery is a SELECT inside another statement. It lets you use the result of one question to answer another: who scored above the average? first needs what is the average?

Scalar subqueries - a single value#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

The inner query runs first and returns one value (7.83); the outer query uses it. Scalar subqueries can also appear in SELECT:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

IN and NOT IN - a list of values#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Common Mistake

NOT IN and NULL do not mix. If the subquery returns even one NULL, x NOT IN (...) is never true and you get no rows. students.dept_id contains a NULL (Om Malviya), so SELECT name FROM departments WHERE dept_id NOT IN (SELECT dept_id FROM students) returns nothing. Use NOT EXISTS instead (below), or add WHERE dept_id IS NOT NULL inside the subquery.

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

EXISTS and correlated subqueries#

A correlated subquery refers to the outer row, so it is evaluated once per outer row. EXISTS is true if the subquery returns any row:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
हिंदी में समझें

Subquery = query के अंदर query। पहले अंदर वाली query जवाब देती है (जैसे औसत CGPA), फिर बाहर वाली उसका इस्तेमाल करती है। Correlated subquery हर बाहरी row के लिए दोबारा चलती है, क्योंकि वह बाहरी row का column (जैसे s.dept_id) इस्तेमाल करती है - "अपने ही department के औसत से ज़्यादा" ऐसे सवालों के लिए।

Derived tables - a subquery in FROM#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Common Table Expressions (WITH)#

A CTE gives a subquery a name at the top of the query. Several CTEs can be chained, which makes complex reports read top-to-bottom like steps:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Tip

Write complex queries as CTEs: each step is small, has a meaningful name, and can be tested on its own by running SELECT * FROM step_name.

Recursive CTEs#

A recursive CTE refers to itself - perfect for hierarchies (org charts, categories) and generating sequences:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Set operations: UNION, INTERSECT, EXCEPT#

They combine the results of two queries with the same number and types of columns:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Operator Result
UNION rows in either query, duplicates removed
UNION ALL rows in either query, duplicates kept (faster)
INTERSECT rows in both queries
EXCEPT (MINUS in Oracle) rows in the first but not the second

Summary#

  • Scalar subqueries return one value; IN subqueries return a list; EXISTS checks for any row.
  • Correlated subqueries refer to the outer row; beware NOT IN with NULLs (prefer NOT EXISTS).
  • WITH name AS (...) (CTE) names intermediate results; WITH RECURSIVE walks hierarchies.
  • UNION, INTERSECT, EXCEPT combine query results.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Above the overall average

Show the name and cgpa of students whose CGPA is above the average CGPA of all students, highest first.

Database: college (see the tables in this lesson)
2

Students who took Machine Learning

Using a subquery with IN (no JOIN), list the name of students enrolled in the course titled Machine Learning.

Database: college (see the tables in this lesson)
3

Best in department (CTE)

Using a CTE that computes each department's maximum CGPA, show dept_id, name and cgpa of the top student(s) of each department, ordered by dept_id.

Database: college (see the tables in this lesson)

Quick Quiz

Q1.

A correlated subquery...

Q2.

What does WITH top AS (SELECT ...) SELECT * FROM top define?

Q3.

What is the difference between UNION and UNION ALL?

Q4.

WHERE dept_id NOT IN (SELECT dept_id FROM students) returns nothing even though Data Science has no students. Why?