WITH keyword

Name one or several sub-queries to be used within the main query.

This clause makes it easy to simplify large or complex statements which involve sub-queries, particularly when such sub-queries are used several times.

Syntax#

Flow chart showing the syntax of the WITH clause

Where:

  • subQueryName is the alias for the sub-query
  • subQuery is a SQL query (e.g SELECT * FROM table)
  • mainQuery is the main SQL query which involves the subQuery using its alias.

Examples#

Single alias
WITH first_10_users AS (SELECT * FROM users limit 10)
SELECT user_name FROM first_10_users;
Using recursively
WITH first_10_users AS (SELECT * FROM users limit 10),
first_5_users AS (SELECT * FROM first_10_users limit 5)
SELECT user_name FROM first_5_users;
Flag whether individual trips are longer or shorter than average
WITH avg_distance AS (select avg(trip_distance) average FROM trips)
SELECT pickup_datetime, trips.trip_distance > avg_distance.average longer_than_average
FROM trips CROSS JOIN avg_distance;