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.

SqlData Integrity

Code

snippet
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

FAQ

Which tables does the SQL touch?
`customer_tags`, `set`, `upserted`, `customers`, combined through a join.