8. Common Table Expressions
PostgreSQL CTE
WITH cte_name (column_list) AS (
CTE_query_definition
)
statement;Example 1
WITH cte_film AS (
SELECT
film_id,
title,
(CASE
WHEN length < 30 THEN 'Short'
WHEN length < 90 THEN 'Medium'
ELSE 'Long'
END) length
FROM
film
)
SELECT
film_id,
title,
length
FROM
cte_film
WHERE
length = 'Long'
ORDER BY
title;
Example 2 (Joining a CTE with a table)

Example 3 (CTE with a window function)

PostgreSQL CTE advantages
Recursive query using CTEs
Example (get all subordinates of the manager with the id 2)
Last updated