Bird
0
0

Given the table users(id SERIAL PRIMARY KEY, username TEXT UNIQUE, score INT), what will be the result of this query?

medium📝 query result Q13 of 15
PostgreSQL - Set Operations and Advanced Queries
Given the table users(id SERIAL PRIMARY KEY, username TEXT UNIQUE, score INT), what will be the result of this query?
INSERT INTO users (username, score) VALUES ('alice', 10) ON CONFLICT (username) DO UPDATE SET score = users.score + EXCLUDED.score RETURNING *;

Assuming a row with username 'alice' and score 5 already exists.
AA new row with username 'alice' and score 10 is inserted.
BThe existing row's score is updated to 15 and returned.
CThe insert fails with a duplicate key error.
DThe existing row is deleted and a new row inserted.
Step-by-Step Solution
Solution:
  1. Step 1: Understand ON CONFLICT DO UPDATE behavior

    The query updates the existing row where username='alice' because of the conflict on username.
  2. Step 2: Calculate updated score

    The update sets score = users.score + EXCLUDED.score = 5 + 10 = 15, and returns the updated row.
  3. Final Answer:

    The existing row's score is updated to 15 and returned. -> Option B
  4. Quick Check:

    ON CONFLICT DO UPDATE adds scores = 15 [OK]
Quick Trick: ON CONFLICT DO UPDATE can use existing and new values [OK]
Common Mistakes:
  • Thinking a new row is inserted despite conflict
  • Expecting an error on duplicate key
  • Assuming the row is deleted before insert

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes