CTE Name Shadows Same Table
A WITH query hides any real table sharing its name: bare references read the CTE, and only a schema-qualified name reaches the actual table.
Code
-- WITH 查询名与真实表同名:主查询里裸名解析到 CTE——
-- PostgreSQL 文档:the WITH query hides any real table of the same name;
-- 只有 schema 限定(pg_temp.orders / public.orders)才能碰到真实表
CREATE TEMP TABLE orders (
order_id int PRIMARY KEY,
total numeric NOT NULL
);
INSERT INTO orders VALUES (1, 100.00);
WITH orders AS (
SELECT 42::int AS order_id, 9.99::numeric AS total
)
SELECT
o.order_id AS from_bare_name, -- 裸名 -> CTE 的 42
real_t.order_id AS from_real_table -- schema 限定 -> 真实表的 1
FROM orders o
JOIN pg_temp.orders real_t ON real_t.order_id = 1;Inside the snippet
What runs here is SELECT / INSERT / CREATE — orders and pg_temp.orders are the objects involved.
orders starts out as a session-local temp table that this file makes on the spot — nothing has to be in place first, and the session wrapping up clears it away.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
Nothing outside the file is needed: the session-local tables it touches (orders) are created by the file itself — point it at a scratch database and run the whole thing.
Core lines
WITH orders AS (
SELECT 42::int AS order_id, 9.99::numeric AS total
)
SELECT
o.order_id AS from_bare_name, -- 裸名 -> CTE 的 42
real_t.order_id AS from_real_table -- schema 限定 -> 真实表的 1
FROM orders o
JOIN pg_temp.orders real_t ON real_t.order_id = 1;
CREATE TEMP TABLE orders (
order_id int PRIMARY KEY,
total numeric NOT NULL
);
INSERT INTO orders VALUES (1, 100.00);
Interactive Tools for This Topic
FAQ
- Which tables does this file reference?
- `orders`, `pg_temp.orders` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.