Bird
Raised Fist0
PostgreSQLquery~5 mins

Conditional INSERT with ON CONFLICT in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What does the ON CONFLICT clause do in a PostgreSQL INSERT statement?
It tells PostgreSQL what to do if the insert would cause a conflict, like a duplicate key. You can choose to do nothing or update existing data instead.
Click to reveal answer
beginner
How do you prevent inserting duplicate rows using ON CONFLICT?
Use ON CONFLICT DO NOTHING. This skips the insert if a conflict happens, so no duplicate row is added.
Click to reveal answer
intermediate
Explain the syntax to update a row if a conflict occurs during INSERT.
Use ON CONFLICT (column) DO UPDATE SET column = EXCLUDED.value. This updates the existing row instead of inserting a new one.
Click to reveal answer
intermediate
Can you use a WHERE clause with ON CONFLICT DO UPDATE? What is it for?
Yes, you can add WHERE to DO UPDATE to update only when certain conditions are true. This lets you control when to change the existing row.
Click to reveal answer
advanced
What happens if you omit the conflict target in ON CONFLICT?
PostgreSQL raises an error unless it can unambiguously infer the conflict target from the table's unique or primary key constraints.
Click to reveal answer
What does ON CONFLICT DO NOTHING do?
AUpdates the existing row on conflict
BInserts the row only if no conflict occurs
CDeletes the conflicting row
DRaises an error on conflict
Which clause specifies the column to check for conflicts in ON CONFLICT?
AON CONFLICT (column_name)
BCONFLICT TARGET
CWHERE
DDO UPDATE
What does ON CONFLICT DO UPDATE allow you to do?
AUpdate the existing row when a conflict occurs
BRollback the transaction
CDelete the conflicting row
DInsert a new row ignoring conflicts
Can you add a WHERE clause to ON CONFLICT DO UPDATE?
AOnly with DO NOTHING
BNo, WHERE is not allowed
CYes, to conditionally update rows
DOnly outside the INSERT statement
What happens if you omit the conflict target in ON CONFLICT?
APostgreSQL handles all conflicts automatically
BThe statement ignores conflicts
CThe statement inserts duplicates
DAn error is raised
Describe how to use ON CONFLICT to insert a row only if it does not already exist.
Think about skipping insert on conflict.
You got /3 concepts.
    Explain how ON CONFLICT DO UPDATE works and when you might use it.
    Consider updating data instead of inserting duplicates.
    You got /4 concepts.

      Practice

      (1/5)
      1. What does the ON CONFLICT DO NOTHING clause do in a PostgreSQL INSERT statement?
      easy
      A. It skips inserting the row if a conflict occurs on a unique key.
      B. It updates the existing row with new values on conflict.
      C. It deletes the conflicting row before inserting the new one.
      D. It raises an error and stops the insert operation.

      Solution

      1. Step 1: Understand ON CONFLICT behavior

        The ON CONFLICT DO NOTHING clause tells PostgreSQL to ignore the insert if a duplicate key conflict happens.
      2. Step 2: Compare with other conflict actions

        Unlike DO UPDATE which modifies existing rows, DO NOTHING simply skips the insert without error.
      3. Final Answer:

        It skips inserting the row if a conflict occurs on a unique key. -> Option A
      4. Quick Check:

        ON CONFLICT DO NOTHING = skip insert on duplicate [OK]
      Hint: DO NOTHING skips duplicates silently, no error thrown [OK]
      Common Mistakes:
      • Thinking DO NOTHING updates existing rows
      • Assuming DO NOTHING deletes conflicting rows
      • Believing DO NOTHING raises an error
      2. Which of the following is the correct syntax to insert a row and update the existing row on conflict for the column id in PostgreSQL?
      easy
      A. INSERT INTO table_name (id, val) VALUES (1, 'a') ON DUPLICATE KEY UPDATE val = VALUES(val);
      B. INSERT INTO table_name (id, val) VALUES (1, 'a') ON CONFLICT (id) DO NOTHING SET val = EXCLUDED.val;
      C. INSERT INTO table_name (id, val) VALUES (1, 'a') ON CONFLICT UPDATE val = EXCLUDED.val;
      D. INSERT INTO table_name (id, val) VALUES (1, 'a') ON CONFLICT (id) DO UPDATE SET val = EXCLUDED.val;

      Solution

      1. Step 1: Identify correct ON CONFLICT syntax

        PostgreSQL uses ON CONFLICT (column) DO UPDATE SET to update on conflict.
      2. Step 2: Check syntax details

        INSERT INTO table_name (id, val) VALUES (1, 'a') ON CONFLICT (id) DO UPDATE SET val = EXCLUDED.val; correctly uses EXCLUDED.val to refer to the new value and specifies the conflict column.
      3. Final Answer:

        INSERT INTO table_name (id, val) VALUES (1, 'a') ON CONFLICT (id) DO UPDATE SET val = EXCLUDED.val; -> Option D
      4. Quick Check:

        ON CONFLICT (id) DO UPDATE SET val = EXCLUDED.val [OK]
      Hint: Use ON CONFLICT (column) DO UPDATE SET col = EXCLUDED.col [OK]
      Common Mistakes:
      • Using MySQL syntax ON DUPLICATE KEY UPDATE
      • Omitting conflict target column in ON CONFLICT
      • Combining DO NOTHING with SET clause incorrectly
      3. 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.
      medium
      A. A new row with username 'alice' and score 10 is inserted.
      B. The existing row's score is updated to 15 and returned.
      C. The insert fails with a duplicate key error.
      D. The existing row is deleted and a new row inserted.

      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]
      Hint: 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
      4. Given the table products(id INT UNIQUE, name TEXT UNIQUE), identify the error in this PostgreSQL query:
      INSERT INTO products (id, name) VALUES (1, 'Pen') ON CONFLICT DO UPDATE SET name = EXCLUDED.name;
      medium
      A. Missing conflict target column after ON CONFLICT.
      B. EXCLUDED keyword is not valid in DO UPDATE.
      C. VALUES clause should be after DO UPDATE.
      D. DO UPDATE cannot be used without WHERE clause.

      Solution

      1. Step 1: Check ON CONFLICT syntax

        When using DO UPDATE, PostgreSQL requires specifying the conflict target column or constraint.
      2. Step 2: Identify missing conflict target

        The query lacks (id) or constraint name after ON CONFLICT, causing syntax error.
      3. Final Answer:

        Missing conflict target column after ON CONFLICT. -> Option A
      4. Quick Check:

        ON CONFLICT needs target column for DO UPDATE [OK]
      Hint: Always specify conflict column with DO UPDATE [OK]
      Common Mistakes:
      • Omitting conflict target column
      • Misusing EXCLUDED keyword
      • Assuming WHERE clause is mandatory
      5. You want to insert a new user with email and last_login into a table users(email TEXT UNIQUE, last_login TIMESTAMP). If the email already exists, update last_login only if the new timestamp is more recent. Which query correctly implements this conditional update?
      hard
      A. INSERT INTO users (email, last_login) VALUES ('a@b.com', '2024-01-01') ON CONFLICT DO NOTHING WHERE EXCLUDED.last_login > users.last_login;
      B. INSERT INTO users (email, last_login) VALUES ('a@b.com', '2024-01-01') ON CONFLICT (email) DO UPDATE SET last_login = users.last_login WHERE EXCLUDED.last_login > users.last_login;
      C. INSERT INTO users (email, last_login) VALUES ('a@b.com', '2024-01-01') ON CONFLICT (email) DO UPDATE SET last_login = EXCLUDED.last_login WHERE EXCLUDED.last_login > users.last_login;
      D. INSERT INTO users (email, last_login) VALUES ('a@b.com', '2024-01-01') ON CONFLICT (email) DO UPDATE SET last_login = EXCLUDED.last_login;

      Solution

      1. Step 1: Understand conditional update with WHERE clause

        PostgreSQL allows a WHERE clause in DO UPDATE to conditionally apply the update.
      2. Step 2: Check condition for updating last_login

        INSERT INTO users (email, last_login) VALUES ('a@b.com', '2024-01-01') ON CONFLICT (email) DO UPDATE SET last_login = EXCLUDED.last_login WHERE EXCLUDED.last_login > users.last_login; updates last_login only if the new timestamp is greater than the existing one, using WHERE EXCLUDED.last_login > users.last_login.
      3. Final Answer:

        INSERT INTO users (email, last_login) VALUES ('a@b.com', '2024-01-01') ON CONFLICT (email) DO UPDATE SET last_login = EXCLUDED.last_login WHERE EXCLUDED.last_login > users.last_login; -> Option C
      4. Quick Check:

        Use WHERE in DO UPDATE for conditional update [OK]
      Hint: Use WHERE in DO UPDATE to update conditionally [OK]
      Common Mistakes:
      • Forgetting WHERE clause for conditional update
      • Using DO NOTHING with WHERE incorrectly
      • Updating unconditionally without checking timestamps
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard