Bird
0
0

How can you insert multiple rows into inventory and update the quantity by adding new values if item_id conflicts?

hard📝 Application Q9 of 15
PostgreSQL - Set Operations and Advanced Queries
How can you insert multiple rows into inventory and update the quantity by adding new values if item_id conflicts?
AINSERT INTO inventory(item_id, quantity) VALUES (1, 5), (2, 10) ON CONFLICT (item_id) DO UPDATE SET quantity = EXCLUDED.quantity * 2;
BINSERT INTO inventory(item_id, quantity) VALUES (1, 5), (2, 10) ON CONFLICT DO NOTHING;
CINSERT INTO inventory(item_id, quantity) VALUES (1, 5), (2, 10) ON CONFLICT (quantity) DO UPDATE SET quantity = EXCLUDED.quantity;
DINSERT INTO inventory(item_id, quantity) VALUES (1, 5), (2, 10) ON CONFLICT (item_id) DO UPDATE SET quantity = inventory.quantity + EXCLUDED.quantity;
Step-by-Step Solution
Solution:
  1. Step 1: Understand multi-row insert with conflict handling

    We want to add new quantities to existing ones on conflict by item_id.
  2. Step 2: Check the update expression

    INSERT INTO inventory(item_id, quantity) VALUES (1, 5), (2, 10) ON CONFLICT (item_id) DO UPDATE SET quantity = inventory.quantity + EXCLUDED.quantity; correctly adds existing quantity to new quantity using inventory.quantity + EXCLUDED.quantity.
  3. Final Answer:

    INSERT INTO inventory(item_id, quantity) VALUES (1, 5), (2, 10) ON CONFLICT (item_id) DO UPDATE SET quantity = inventory.quantity + EXCLUDED.quantity; -> Option D
  4. Quick Check:

    Use ON CONFLICT with DO UPDATE to add quantities [OK]
Quick Trick: Add quantities on conflict using existing + EXCLUDED values [OK]
Common Mistakes:
  • Using wrong conflict target column
  • Ignoring existing quantity in update
  • Using DO NOTHING which skips update

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes