INSERT with ON CONFLICT Upsert
Demonstrates INSERT statements with multiple rows, column lists, and ON CONFLICT upsert behavior for inserting or updating data atomically.
Code
INSERT INTO products (product_id, product_name, unit_price, stock_quantity, category_id)
VALUES
(101, 'Wireless Mouse', 29.99, 150, 1),
(102, 'USB Keyboard', 49.99, 80, 1),
(103, 'HD Monitor', 299.99, 25, 1),
(104, 'Webcam', 89.99, 60, 1)
ON CONFLICT (product_id)
DO UPDATE SET
product_name = EXCLUDED.product_name,
unit_price = EXCLUDED.unit_price,
stock_quantity = products.stock_quantity + EXCLUDED.stock_quantity
WHERE products.unit_price != EXCLUDED.unit_price
OR products.stock_quantity < EXCLUDED.stock_quantity;
-- Insert from a SELECT query
INSERT INTO order_summary (order_id, total_items, total_amount)
SELECT
order_id,
SUM(quantity) AS total_items,
SUM(quantity * unit_price) AS total_amount
FROM order_items
GROUP BY order_id
ON CONFLICT (order_id) DO NOTHING;How the snippet works
Several statements share this file — SELECT / INSERT / UPDATE, with products, set, order_summary and order_items among the objects involved.
The SQL constructs in play: a WHERE clause deciding which rows the statement applies to; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement.
Applying it
Point it at the products table.
Statements that matter
INSERT INTO order_summary (order_id, total_items, total_amount)
SELECT
order_id,
SUM(quantity) AS total_items,
SUM(quantity * unit_price) AS total_amount
FROM order_items
GROUP BY order_id
ON CONFLICT (order_id) DO NOTHING;
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- `products`, `set`, `order_summary`, `order_items` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.