PostgreSQL の WITH 句(共通テーブル式、CTE とも呼ぶ)は、SELECT の前に名前を付けた問い合わせを書いておき、あとの SELECT でテーブルのように使う書き方です。サブクエリを入れ子にせずに、上から順に読める SQL が書けます。
with 名前 as ( select ... ) select * from 名前;
例は、次の表を使います。
create table orders (order_id int, customer_id int, amount int, order_date date); insert into orders values (1, 1, 1000, '2026-11-01'), (2, 1, 3000, '2026-11-02'), (3, 2, 500, '2026-11-02'), (4, 3, 8000, '2026-11-03'), (5, 2, 2500, '2026-11-04'); create table employees (emp_id int, name text, boss_id int); insert into employees values (1, '社長', null), (2, '部長A', 1), (3, '部長B', 1), (4, '課長A', 2), (5, '担当A', 4); create table orders_archive (like orders);
基本の書き方
お客さまごとの合計を WITH で作ってから、3000 以上だけを出します。
appdb=# with totals as (
appdb(# select customer_id, sum(amount) as total
appdb(# from orders
appdb(# group by customer_id
appdb(# )
appdb-# select * from totals where total >= 3000 order by customer_id;
customer_id | total
-------------+-------
1 | 4000
2 | 3000
3 | 8000
(3 rows)
複数の WITH をつなげる
カンマで区切って複数書けます。後ろの WITH から、前の WITH を使えます。
appdb=# with totals as (
appdb(# select customer_id, sum(amount) as total from orders group by customer_id
appdb(# ), ranked as (
appdb(# select customer_id, total, rank() over (order by total desc) as rnk from totals
appdb(# )
appdb-# select * from ranked where rnk <= 2;
customer_id | total | rnk
-------------+-------+-----
3 | 8000 | 1
1 | 4000 | 2
(2 rows)
VALUES と組み合わせて、その場で表を作る
表を作らずに、試しのデータを WITH の中に書けます(VALUES リスト)。
appdb=# with wktbl as (
appdb(# select * from (values
appdb(# (1, '山本', 'yamamoto'),
appdb(# (2, '中嶋', 'nakajima'),
appdb(# (3, '川本', 'kawamoto')
appdb(# ) as t(lno, name, roma)
appdb(# )
appdb-# select * from wktbl order by 1;
lno | name | roma
-----+------+----------
1 | 山本 | yamamoto
2 | 中嶋 | nakajima
3 | 川本 | kawamoto
(3 rows)
再帰の WITH(WITH RECURSIVE)
WITH RECURSIVE と書くと、WITH の中で自分自身を使えます。UNION ALL の前が最初の行、後ろがくり返して足す行です。連番や、上司と部下のような階層を出すときに使います。
appdb=# with recursive nums(n) as (
appdb(# select 1
appdb(# union all
appdb(# select n + 1 from nums where n < 5
appdb(# )
appdb-# select n from nums;
n
---
1
2
3
4
5
(5 rows)
上司と部下の表から、組織の階層をたどります。
appdb=# with recursive tree as (
appdb(# select emp_id, name, boss_id, 1 as level, name::text as path
appdb(# from employees where boss_id is null
appdb(# union all
appdb(# select e.emp_id, e.name, e.boss_id, t.level + 1, t.path || ' > ' || e.name
appdb(# from employees e join tree t on e.boss_id = t.emp_id
appdb(# )
appdb-# select emp_id, level, path from tree order by path;
emp_id | level | path
--------+-------+------------------------------
1 | 1 | 社長
2 | 2 | 社長 > 部長A
4 | 3 | 社長 > 部長A > 課長A
5 | 4 | 社長 > 部長A > 課長A > 担当A
3 | 2 | 社長 > 部長B
(5 rows)
PostgreSQL では RECURSIVE が必要です(Oracle は付けなくても再帰できます)。付け忘れると、次のエラーになります。
-- RECURSIVE を付け忘れると
appdb=# with nums(n) as (
appdb(# select 1
appdb(# union all
appdb(# select n + 1 from nums where n < 5
appdb(# )
appdb-# select n from nums;
ERROR: relation "nums" does not exist
LINE 4: select n + 1 from nums where n < 5
^
DETAIL: There is a WITH item named "nums", but it cannot be referenced from this part of the query.
HINT: Use WITH RECURSIVE, or re-order the WITH items to remove forward references.
MATERIALIZED:先に結果を作るか
PostgreSQL 12 から、1 回しか使わない WITH は、ふつうのサブクエリと同じように外側の条件と合わせて最適化されます。materialized を付けると、WITH の結果を先に作ってから使います(11 までの動き)。逆に、2 回以上使う WITH を展開させたいときは not materialized を付けます。
-- 1 回しか使わない WITH は、ふつうのサブクエリと同じに扱われる
appdb=# explain (costs off) with t as (select * from orders) select * from t where customer_id = 1;
QUERY PLAN
-----------------------------
Seq Scan on orders
Filter: (customer_id = 1)
(2 rows)
-- MATERIALIZED を付けると、先に WITH の結果を作ってから絞る
appdb=# explain (costs off) with t as materialized (select * from orders) select * from t where customer_id = 1;
QUERY PLAN
-----------------------------
CTE Scan on t
Filter: (customer_id = 1)
CTE t
-> Seq Scan on orders
(4 rows)
WITH の中で更新する(DELETE … RETURNING)
PostgreSQL では、WITH の中に INSERT・UPDATE・DELETE を書けます。RETURNING で返した行を、あとの SQL で使えます。古い注文を削除して、そのまま別の表に移す例です。
appdb=# with moved as (
appdb(# delete from orders where order_date < '2026-11-03' returning *
appdb(# )
appdb-# insert into orders_archive select * from moved;
INSERT 0 3
appdb=# select count(*) from orders;
count
-------
2
(1 row)
appdb=# select count(*) from orders_archive;
count
-------
3
(1 row)
削除と追加が 1 つの SQL なので、途中で失敗しても、片方だけが実行されることはありません。
例は PostgreSQL 18.7 の psql で実行しています。