Consider a table users(id SERIAL PRIMARY KEY, username TEXT UNIQUE, score INT). You run this query:
INSERT INTO users (username, score) VALUES ('alice', 10) ON CONFLICT (username) DO UPDATE SET score = users.score + 5 RETURNING score;Assuming the table initially has a row {id:1, username:'alice', score:7}, what will be the returned score?
INSERT INTO users (username, score) VALUES ('alice', 10) ON CONFLICT (username) DO UPDATE SET score = users.score + 5 RETURNING score;
ON CONFLICT updates the existing row's score by adding 5 to the current score.
The existing score is 7. The update adds 5, so the new score is 12. But the query uses users.score which refers to the old value, so the update sets score = 7 + 5 = 12. The RETURNING clause returns the updated score, which is 12.
Correction: The correct updated score is 12, so option D (15) is incorrect. The correct answer is C (12).
Given the same users table, what will be the result of this query if a user with username 'bob' already exists?
INSERT INTO users (username, score) VALUES ('bob', 20) ON CONFLICT (username) DO NOTHING RETURNING *;INSERT INTO users (username, score) VALUES ('bob', 20) ON CONFLICT (username) DO NOTHING RETURNING *;
DO NOTHING skips the insert if conflict occurs.
ON CONFLICT DO NOTHING skips the insert and returns no rows if the username already exists. So RETURNING * returns no rows.
Choose the correct query that inserts a user or updates the score only if the new score is greater than the existing score.
Use WHERE clause after DO UPDATE to conditionally update.
Option B uses the correct syntax: the WHERE clause after DO UPDATE limits the update to cases where the new score is higher.
Option B uses invalid IF syntax.
Option B is valid SQL but does not prevent update if new score is lower; it always updates.
Option B has the WHERE clause reversed but is syntactically valid; however, it is equivalent to D logically.
Between A and D, D is the canonical correct syntax.
You want to insert thousands of rows into users with ON CONFLICT to update scores. Which approach is best for performance?
Batch operations reduce overhead.
Option C is best because a single INSERT with multiple VALUES and ON CONFLICT DO UPDATE minimizes transaction overhead and uses PostgreSQL's efficient upsert.
Option C is slow due to many round-trips.
Option C adds complexity and may not be faster.
Option C risks data loss and is inefficient.
In concurrent transactions, using ON CONFLICT DO UPDATE can cause deadlocks. What is the main reason?
Think about row locking order in concurrent updates.
Deadlocks occur when concurrent transactions lock rows in different orders, causing circular waits. ON CONFLICT DO UPDATE locks the conflicting rows, so if two transactions try to update the same rows in different orders, deadlocks can happen.
Option A is false; table locks are not taken.
Option A is false; indexes are used.
Option A is false; PostgreSQL supports concurrent inserts with ON CONFLICT.