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

  1. WITH first_10_users AS (SELECT * FROM users limit 10)
  2. SELECT user_name FROM first_10_users;
  1. WITH first_10_users AS (SELECT * FROM users limit 10),
  2. first_5_users AS (SELECT * FROM first_10_users limit 5)
  3. SELECT user_name FROM first_5_users;
  1. WITH avg_distance AS (select avg(trip_distance) average FROM trips)
  2. SELECT pickup_datetime, trips.trip_distance > avg_distance.average longer_than_average
  3. FROM trips CROSS JOIN avg_distance;