Advanced · Lesson 5 of 18

Introduction to CTEs

CTEs (Common Table Expressions) name a subquery for reuse.

WITH high_earners AS (
    SELECT * FROM employees WHERE salary > 90000
)
SELECT * FROM high_earners;

Benefits:

  • More readable than nested subqueries
  • Can reference multiple times
  • Self-documenting code
  • Easier to debug

Start with WITH, name your CTE, define it in parentheses.

Check your understanding

Use a CTE to find employees earning more than average.

Examples run on the employees sample database. Open any of them in the playground to experiment.