Ira SQL ProIra SQL Pro

PostgreSQL UPSERT (ON CONFLICT)

advancedpostgresql
2 min read

What is UPSERT?

UPSERT is a combination of INSERT and UPDATE. In PostgreSQL it is implemented with INSERT ... ON CONFLICT. If an insert would violate a unique constraint, you can update the existing row or do nothing.

Syntax

INSERT INTO table_name (columns) VALUES (values)
ON CONFLICT (conflict_column)
DO UPDATE SET column = EXCLUDED.value;

INSERT INTO table_name (columns) VALUES (values)
ON CONFLICT (conflict_column)
DO NOTHING;

When to Use

  • Syncing data from an external source (insert new, update existing)
  • Idempotent operations that should not fail on duplicates
  • Incrementing counters on duplicate keys
  • Handling race conditions in concurrent inserts

Key Points

  1. EXCLUDED — In DO UPDATE, EXCLUDED refers to the values proposed for insertion.
  2. Conflict Target — Specify the unique column(s) or constraint.
  3. DO NOTHING — Silently skip the row on conflict.
  4. DO UPDATE — Update the existing row with new values.
  5. WHERE in DO UPDATE — You can add a WHERE clause to conditionally update.
  6. RETURNING — Combine with RETURNING to see the result.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

PostgreSQL UPSERT (ON CONFLICT) Challenge

Write a query that solve this task: insert a student or update their name if the email already exists.

Expected result

If email exists, updates name and age. If not, inserts. Returns the resulting row.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What is UPSERT?

Initializing database...Each run starts from fresh sample data.

More Examples

Skip duplicates with DO NOTHING

Insert products and silently skip duplicates.

Initializing database...Each run starts from fresh sample data.

Increment a counter on conflict

Increment a view count when a duplicate page is recorded.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

What does EXCLUDED mean in ON CONFLICT?
EXCLUDED is a special table reference containing the values originally proposed for insertion.
Can I upsert on multiple columns?
Yes. Specify multiple columns: ON CONFLICT (col1, col2). They must have a unique constraint or index.

Related Topics