0
0
PostgreSQLquery~5 mins

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

Choose your learning style9 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.