INSERT with ON CONFLICT Upsert

Demonstrates INSERT statements with multiple rows, column lists, and ON CONFLICT upsert behavior for inserting or updating data atomically.

SqlData Integrity

Code

snippet
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;