Insert or update with ON CONFLICT
PostgreSQL 19.0
Use an upsert when a key should identify the same record across repeated writes.
On this page
Define the conflict key
The existing enrollment for student 1 and course 1 has a two-column primary key. ON CONFLICT finds that row. EXCLUDED.enrolled_on is the date proposed by INSERT. ROLLBACK restores the original date after the example.
BEGIN;
INSERT INTO enrollments (student_id, course_id, enrolled_on)
VALUES (1, 1, DATE '2026-01-08')
ON CONFLICT (student_id, course_id) DO UPDATE
SET enrolled_on = EXCLUDED.enrolled_on
RETURNING student_id, course_id, enrolled_on;
ROLLBACK;
Choose whether to skip a conflict
Use DO NOTHING when an existing record should be kept as it is. A skipped row is not returned by RETURNING. Use DO UPDATE when you have a defined rule for changing the existing record.
INSERT INTO enrollments (student_id, course_id, enrolled_on)
VALUES (1, 1, DATE '2026-01-10')
ON CONFLICT (student_id, course_id) DO NOTHING
RETURNING student_id, course_id, enrolled_on;