Common Table Expression

  • CTE is a temporary result take from a SQL statement

  • A second approach to create temporary tables for query data instead of using sub queries in a FROM clause

  • CTE's are a good alternative to sub queries.

  • CTE can be referenced multiple times in multiple places in query statement

  • Lifetime of CTE is equal to the lifetime of a query.

  • Types of CTE

    • Materialized

    • Not materialized

Syntax

with cte_table ( column_list ) as (
    cte_query_definition
)

with num as (
    select *
    from generate_series(1, 5) as id
)
select *
from num;

 id 
----
  1
  2
  3
  4
  5

CTE with Join

CTE with CASE

Complex query example

CTE to perform DML

Loading Sample Data

Query

Last updated

Was this helpful?