0
0
PostgreSQLquery~5 mins

INSERT ON CONFLICT (upsert) in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the INSERT ON CONFLICT clause do in PostgreSQL?
It allows you to try inserting a new row but if a conflict occurs (like a duplicate key), you can specify an alternative action such as updating the existing row instead of failing.
Click to reveal answer
beginner
What keyword is used with INSERT ON CONFLICT to update existing rows when a conflict happens?
The keyword DO UPDATE is used to update the existing row when a conflict occurs during an insert.
Click to reveal answer
beginner
Explain the purpose of the ON CONFLICT (column_name) DO NOTHING clause.
It tells PostgreSQL to skip the insert if a conflict happens on the specified column, leaving the existing row unchanged and avoiding an error.
Click to reveal answer
intermediate
In the statement INSERT INTO users (id, name) VALUES (1, 'Alice') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;, what does EXCLUDED.name mean?
EXCLUDED.name refers to the value that was attempted to be inserted for the name column. It is used to update the existing row with the new value.
Click to reveal answer
beginner
Why is INSERT ON CONFLICT called an "upsert" operation?
Because it combines "update" and "insert": it inserts a new row if no conflict exists, or updates the existing row if a conflict happens.
Click to reveal answer
What happens if you use ON CONFLICT (id) DO NOTHING and a row with the same id already exists?
AThe existing row is deleted.
BThe existing row is updated.
CAn error is thrown.
DThe insert is skipped and no error occurs.
Which clause lets you update an existing row during an insert conflict?
ADO UPDATE
BDO NOTHING
CON DUPLICATE KEY
DREPLACE
In ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, what does EXCLUDED represent?
AThe row that caused the conflict
BA temporary table
CThe new values attempted to insert
DThe existing row in the table
Can INSERT ON CONFLICT be used to insert multiple rows at once?
ANo, only single-row inserts are supported.
BYes, it works with multi-row inserts.
COnly if you use a transaction.
DOnly with a trigger.
What is the main benefit of using INSERT ON CONFLICT?
AIt prevents duplicate rows and allows updating existing data in one command.
BIt speeds up SELECT queries.
CIt automatically creates indexes.
DIt deletes conflicting rows.
Describe how the INSERT ON CONFLICT clause works in PostgreSQL and give an example use case.
Think about inserting data that might already be there.
You got /4 concepts.
    Explain the difference between DO NOTHING and DO UPDATE in the context of INSERT ON CONFLICT.
    One ignores conflict, the other fixes it.
    You got /3 concepts.