In SQL, a Common Table Expression (CTE) is a useful tool that lets you combine multiple SQL queries.

More specifically, you can create a SELECT query and use its values in a second query. It's similar to creating a temporary view that you can use in a query.

CTEs are extremely versatile, and are used in:

  • Working with data with different granularity (e.g. find the number of sales per city, state and country)
  • Breaking down a complex query into multiple steps
  • Recursive queries

and more!

Syntax

Use the WITH keyword to name a query, then use its values and columns in another query.

Syntax using WITH and AS. The CTE should be within a set of brackets "( )".

To use values and columns from your first query, make use of FROM or JOIN

Usage Example

Write a query:

From a dataset looking at F1 Car Races, select the all time fastest ever lap time

Name and store that query (making sure to remove the ';' at the end):

Name the previous query as "FastestLapTime_Table"

Then use your first query inside another query.

The all time fastest lap time (0:55.404), has been added to the table.

In this example, we've used a CTE to add an aggregated scalar number (a single value for the MIN()/fastest ever recorded lap time) to a table.