CTE Reuses Upsert RETURNING Keys
Chain INSERT ON CONFLICT with RETURNING inside a CTE so the guaranteed row keys feed a follow-up join in the same statement.
Code
WITH upserted AS (
INSERT INTO customer_tags (customer_id, tag, priority)
VALUES (101, 'vip', 10), (102, 'beta', 5), (103, 'vip', 10)
ON CONFLICT (customer_id, tag) DO UPDATE
SET priority = EXCLUDED.priority,
-- DO UPDATE SET 允许 = DEFAULT:冲突行重置回列默认值
boosted = DEFAULT
RETURNING customer_id, tag, priority
)
SELECT
c.customer_id,
c.email,
u.tag,
u.priority
FROM upserted u
JOIN customers c USING (customer_id)
ORDER BY u.priority DESC, c.customer_id;Inside the snippet
What runs is SELECT / INSERT / UPDATE, with customer_tags, set, upserted and customers as the object involved.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; an ORDER BY that fixes the output order; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a RETURNING clause that hands the affected rows back to the caller; DEFAULT values filling omitted columns.
Putting it to use
Run the statement against the customer_tags table.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- `customer_tags`, `set`, `upserted`, `customers`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.