JournalSQLSubqueries and CTEs3 min

WITH-queries vs. Subqueries

The WITH statement is often called a Common Table Expression or CTE. Though these expressions serve the exact same purpose as subqueries, they are more common in practice, as they tend to be cleaner for a future reader to follow the logic.

  • CTE
  • WITH
  • subquery
  • performance

You need to know about Subqueries before reading this topic, check these out:

Common Table Expressions (WITH clause)

Based on Lesson 7.11 Video: WITH:

The WITH statement is often called a Common Table Expression or CTE. Though these expressions serve the exact same purpose as subqueries, they are more common in practice, as they tend to be cleaner for a future reader to follow the logic.

From PostgreSQL Documentation:

WITH provides a way to write auxiliary statements for use in a larger query. These statements, which are often referred to as Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one query. Each auxiliary statement in a WITH clause can be a SELECT, INSERT, UPDATE, or DELETE; and the WITH clause itself is attached to a primary statement that can also be a SELECT, INSERT, UPDATE, or DELETE.

Syntax

WITH query_name (column_name1, ...) AS
     (SELECT ...)
     
SELECT ...

With is not a stand alone command like create view is: it must be followed by select. This query (and subqueries it contains) can refer to the just defined query name in their from clause.

A single with clause can introduce multiple query names by separating them with a comma (the with keyword is not repeated). Each of these queries can refer to the query names previously defined within the same with clause:

WITH query_name1 AS (
     SELECT ...
     )
   , query_name2 AS (
     SELECT ...
       FROM query_name1
        ...
     )
SELECT ...

Performance Consideration

Most databases process with-queries in the same way that they process views: they replace the reference to the query by its definition and optimize the overall query.

The PostgreSQL database is different in this regard: it optimizes each with query and the main statement independent of each other.

Example (Company Table):

 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)

Now, let us write a query using the WITH clause to select the records from the above table, as follows −

With CTE AS
(Select
 ID
, NAME
, AGE
, ADDRESS
, SALARY
FROM COMPANY )
Select * From CTE;

Result:

id  | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)

CTE vs. Subqueries

Common Table Expressions such as WITH expression_name AS (...) SELECT ... and Subqueries such as SELECT ... FROM (SELECT ...) AS subquery_name are tools for breaking up complex SQL queries, and sometimes the only way to achieve a goal. While CTEs are arguably easier to read than subqueries In Postgres they are an “optimization fence”, preventing the query optimizer from rewriting queries by moving constraints into or out of the CTE. For example this query:

SELECT
  x, count
FROM (SELECT x, count(x) count FROM big_table GROUP BY x) aggregates
WHERE x = 42;

The query could be optimized by “pushing” the WHERE clause into the subquery to avoid performing the read and count operations for every row in big_table:

SELECT
  x, count
FROM (SELECT x, count(x) count FROM big_table GROUP BY x WHERE x = 42) aggregates;

However, a CTE such as this would prevent the optimization, causing the entire table to be read, aggregated, and materialized to disk before being re-scanned from the materialized table for the x = 42 constraint:

WITH aggregates AS (SELECT x, count(x) count FROM big_table GROUP BY x)
SELECT
  x, count
FROM aggregates
WHERE x = 42;

Both Common Table Expressions and subqueries are useful, and one or the other may be more performant in a specific case.

References