Skip to content
Guest
Learn SQL · Course Syllabus Show lessons
Intermediate Queries · 8 min read · Beginner

Subqueries & Common Table Expressions (CTEs)

Break complex multi-step SQL queries into clean, readable building blocks using WITH Common Table Expressions and subqueries.

What you'll learn

  • Filter rows against an aggregate threshold using a scalar subquery
  • Structure multi-step SQL cleanly with WITH cte_name AS (...)

When a query needs two logical steps (for example, compute each track’s average score, then pick tracks above 90), WITH Common Table Expressions (CTEs) keep your SQL readable from top to bottom.

WITH track_avgs AS (
  SELECT track, ROUND(AVG(score), 1) AS avg_score
  FROM enrollments
  GROUP BY track
)
SELECT track, avg_score
FROM track_avgs
WHERE avg_score >= 90;

Fill-in-the-Blank Exercise

Define a SQL CTE

Create a CTE named high_scores using WITH ... AS and query it.

 high_scores  (
SELECT name, score FROM learners WHERE score >= 90
)
SELECT * FROM high_scores;

Try It Yourself

SQLFind Learners Above the Overall Average
Query Result (In-Browser SQLite)

Click Run SQL to execute this query against a live in-browser SQLite database.

Check Your Understanding

Score: 0 / 1

1. Which SQL keyword introduces a Common Table Expression (CTE)?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind