Given the table users(id INT PRIMARY KEY, name TEXT, age INT) with initial data:
id | name | age ---+-------+---- 1 | Alice | 30 2 | Bob | 25
What will be the content of the table after running this query?
INSERT INTO users (id, name, age) VALUES (2, 'Bobby', 26) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, age = EXCLUDED.age;
INSERT INTO users (id, name, age) VALUES (2, 'Bobby', 26) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, age = EXCLUDED.age;
Remember that ON CONFLICT (id) DO UPDATE updates the existing row with the new values.
The query tries to insert a row with id=2. Since that id already exists, it updates the existing row's name and age to the new values 'Bobby' and 26.
Given the table products(id INT PRIMARY KEY, name TEXT, price NUMERIC) with data:
id | name | price ---+----------+------- 1 | Chair | 49.99 2 | Table | 89.99
What will be the table content after running this query?
INSERT INTO products (id, name, price) VALUES (2, 'Desk', 99.99) ON CONFLICT (id) DO NOTHING;
INSERT INTO products (id, name, price) VALUES (2, 'Desk', 99.99) ON CONFLICT (id) DO NOTHING;
DO NOTHING means the insert is skipped if there is a conflict.
The insert tries to add a product with id=2, but since that id exists, the DO NOTHING clause skips the insert. The table remains unchanged.
Which of the following queries correctly updates only the price column on conflict for the items table?
The DO UPDATE SET clause is required after ON CONFLICT.
Option D uses the correct syntax: ON CONFLICT (id) DO UPDATE SET column = value. Other options miss keywords or have wrong order.
Consider this query:
INSERT INTO orders (order_id, product, quantity) VALUES (10, 'Book', 3) ON CONFLICT (order_id) DO UPDATE quantity = EXCLUDED.quantity;
Why does it cause a syntax error?
INSERT INTO orders (order_id, product, quantity) VALUES (10, 'Book', 3) ON CONFLICT (order_id) DO UPDATE quantity = EXCLUDED.quantity;
Check the syntax after DO UPDATE.
The DO UPDATE clause must be followed by SET before specifying columns to update. The query misses SET, causing syntax error.
Choose the correct statement about INSERT ON CONFLICT in PostgreSQL.
Think about what you must specify to use ON CONFLICT.
Option B is correct: you must specify the conflict target columns or constraint name for ON CONFLICT to work. Option B is false because it works with unique constraints too. Option B is false because EXCLUDED refers to the new row, not the existing one. Option B is false because DO NOTHING skips the insert without error.