SQL practice: Upserts: INSERT … ON CONFLICT

Chapter 42 · 7 questions · included in full access

  1. Question 1 · easy

    Try to insert a product with product_id 1 called Duplicate Sheet, in category ACP Sheet, unit_price 1000 and cost_price 800 — but skip it silently if that id already exists.

    Solve it in your browser
  2. Question 2 · easy

    Insert product 1 again, this time updating its unit_price to 2999 if the id already exists. Leave every other column of the existing row alone.

    Solve it in your browser
  3. Question 3 · medium

    Insert a genuinely new product with product_id 20, named Corner Bead 2m, category Accessory, unit_price 310 and cost_price 200, using ON CONFLICT DO NOTHING so it is safe to re-run.

    Solve it in your browser
  4. Question 4 · medium

    Set product 2 to a unit_price of 2500, but only if that is higher than its current price. Use an upsert with a conditional DO UPDATE.

    Solve it in your browser
  5. Question 5 · medium

    Raise the price of product 3 to 3500 with an upsert, and return the product_id and unit_price of whatever was written.

    Solve it in your browser
  6. Question 6 · hard

    In an upsert, what does EXCLUDED refer to?

    Solve it in your browser
  7. Question 7 · hard

    Use the MERGE statement to update products (aliased as p) using an inline dataset (SELECT 1 AS product_id, 3200.00::numeric AS unit_price) aliased as s, matching on product_id. When matched, update p.unit_price with s.unit_price.

    Solve it in your browser

These questions are part of full access.

The first chapters of every track are free. Full access is a one-time payment.

See pricing