CTE (PostgreSQL)
A
CTE, or a common table expression, is a temporary result taken from a SQL statement. This statement can containSELECT,INSERT,UPDATE, orDELETEinstructions. The lifetime of aCTEis equal to the lifetime of the query.
CTEs in PostgreSQL 12+
Starting from PostgreSQL version 12, things have changed, and two new options have been introduced for the execution of a CTE, namely
MATERIALIZEDandNOT MATERIALIZED.
Recursive CTEs
WITH RECURSIVE fib AS (
SELECT
0 as level,
0 as n,
1 as m
UNION ALL
SELECT
level + 1 as level,
m as n,
(n + m) as m
FROM fib WHERE n < 10
)
SELECT * FROM fib;
-- Outputs:
level | n | m
-------+----+----
0 | 0 | 1
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3
4 | 3 | 5
5 | 5 | 8
6 | 8 | 13
7 | 13 | 21