Skip to content
Visual explainer 2h to learn 3 steps

Upserts, views & materialised views

Use INSERT ... ON CONFLICT and views to simplify application code.

By Invicly Tech, , in SQL & PostgreSQL. About 10 minutes to read.

Topic 12 of 30

In short

An upsert inserts a row or updates it if it already exists, in one atomic statement. Views save a query under a name; materialised views also store its results so expensive reports read instantly.

Explained simply

Upsert is short for "update or insert". You hand Postgres a row and say: if it is new, add it; if it already exists, update it. It is perfect for syncing data from another system, counting things, or saving user settings.

Without upsert you would first check whether the row exists, then decide what to do. But between the check and the action, another user might insert the same row, and one of you gets an error. Upsert does the check and the action as one step, so that gap disappears.

A view is a saved query with a name. You create it once, and from then on you can SELECT from it like a table. It hides complicated joins behind a simple name, like a shortcut on your desktop.

A materialised view goes one step further: it saves the query's results, not just the query. Reading it is very fast, like reading a printed report. The catch is that the report gets old, so you reprint it with REFRESH when needed.

Press Play on a diagram to walk through it one step at a time.

FlowINSERT ... ON CONFLICT
  1. Step 1
    Try the insert

    New row for sku 'A1'

  2. Step 2
    Unique key clash?

    Needs a unique index or constraint on sku

  3. Step 3
    No clash: insert

    Row is added as usual

  4. Step 4
    Clash: DO UPDATE

    EXCLUDED holds the values you tried to insert

CompareView vs materialised view
View
  • Stores only the query
  • Always shows fresh data
  • Runs the query each time
Materialised view
  • Stores the result rows
  • Stale until REFRESH
  • Fast reads, can be indexed
SequenceWhy check-then-insert breaks and upsert does not
Session A
Postgres
Session B
  1. 1SELECT sku 'A1'? none
    Session A to Postgres: SELECT sku 'A1'? none
  2. 2SELECT sku 'A1'? none
    Session B to Postgres: SELECT sku 'A1'? none
  3. 3INSERT 'A1': ok
    Session A to Postgres: INSERT 'A1': ok
  4. 4INSERT 'A1': duplicate key error
    Session B to Postgres: INSERT 'A1': duplicate key error
  5. 5With ON CONFLICT instead: waits for A
    Session B to Postgres: With ON CONFLICT instead: waits for A
  6. 6Row exists now: DO UPDATE applied
    Postgres to Session B: Row exists now: DO UPDATE applied

In depth

The parts of ON CONFLICT

The conflict target, such as ON CONFLICT (sku), names the columns of a unique index or constraint. Postgres needs it to know what counts as "already exists". For a constraint you can also write ON CONFLICT ON CONSTRAINT name.

DO UPDATE SET then says what to change. The special table EXCLUDED holds the row you tried to insert, and the table name refers to the row already there. You can add a WHERE to update only sometimes, for example only when the incoming data is newer: WHERE EXCLUDED.updated_at > inventory.updated_at.

RETURNING works too, so you get back the final row whether it was inserted or updated.

  • Target needs a unique index or constraint
  • EXCLUDED = proposed row; table name = existing row
  • DO UPDATE ... WHERE for conditional updates
  • One statement cannot update the same row twice

MERGE: the bigger sibling

PostgreSQL 15 added MERGE, the SQL-standard way to sync a table from a source. It compares a target with a source query and lets you say what to do WHEN MATCHED (update or delete) and WHEN NOT MATCHED (insert).

MERGE is more flexible because it can also delete, and it can match on any condition, not only a unique key. But ON CONFLICT is still the better choice for concurrent single-row upserts from an app, because it is designed to handle two sessions racing for the same key without errors. MERGE can still raise a unique violation in that situation.

CompareON CONFLICT vs MERGE
INSERT ... ON CONFLICT
  • Needs a unique index or constraint
  • Insert, or update the existing row
  • Safe for concurrent single-row upserts
MERGE (PostgreSQL 15+)
  • Matches on any condition
  • WHEN MATCHED: update or delete
  • WHEN NOT MATCHED: insert
  • Good for syncing from a source

What views are good for

A view does not store data and is not faster by itself. When you query it, Postgres pastes the view's query into yours and optimises the whole thing together, so filters you add can still use indexes.

Views shine in three places. They give a simple name to a complicated join that many queries reuse. They provide a stable interface: you can restructure tables underneath while keeping the view's columns the same. And they help security: grant a role access to a view that shows only some columns or rows, without giving access to the table itself.

Simple views on one table are automatically updatable, so INSERT and UPDATE through them work.

Keeping a materialised view fresh

REFRESH MATERIALIZED VIEW sales_summary reruns the query and replaces the stored rows. During a normal refresh, readers are blocked until it finishes. Adding CONCURRENTLY lets readers keep using the old data while the new data is built, then swaps in the differences. It requires a unique index on the materialised view and takes a bit longer.

Postgres does not refresh automatically. Teams schedule it with cron, the pg_cron extension, or a job in their app, choosing a rhythm that matches how fresh the numbers need to be: every 5 minutes for a dashboard, nightly for a monthly report.

CompareTwo ways to refresh
REFRESH MATERIALIZED VIEW
  • Reruns the query
  • Readers blocked until it finishes
  • No unique index needed
... CONCURRENTLY
  • Readers keep using old data
  • Needs a unique index on the view
  • A bit slower; swaps in differences

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Upsert with INSERT ... ON CONFLICT~40m
  2. 2
    Create views for common queries~40m
  3. 3
    Create and refresh materialised views~40m

Key points

  • ON CONFLICT (col) DO UPDATE SET x = EXCLUDED.x updates the existing row.
  • ON CONFLICT DO NOTHING silently skips duplicates.
  • Upserts avoid race conditions that a SELECT-then-INSERT pattern has.
  • REFRESH MATERIALIZED VIEW CONCURRENTLY avoids blocking readers but needs a unique index.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
INSERT INTO inventory (sku, qty)
VALUES ('A1', 5)
ON CONFLICT (sku)
DO UPDATE SET qty = inventory.qty + EXCLUDED.qty;

CREATE VIEW active_customers AS
SELECT * FROM customers WHERE deleted_at IS NULL;

CREATE MATERIALIZED VIEW monthly_sales AS
SELECT date_trunc('month', ordered_at) AS month, SUM(total) AS revenue
FROM orders GROUP BY 1;

REFRESH MATERIALIZED VIEW monthly_sales;

Counting page views with an upsert

Each visit should add 1 to today's counter for a page, creating the counter the first time. Step 1: a unique key on (page, day). Step 2: insert a row with count 1. Step 3: on conflict, add 1 to the existing count. Many users can hit the page at once and no visit is lost or causes an error.

sql
CREATE TABLE page_views (
  page  text NOT NULL,
  day   date NOT NULL,
  views bigint NOT NULL DEFAULT 0,
  PRIMARY KEY (page, day)
);

INSERT INTO page_views (page, day, views)
VALUES ('/pricing', current_date, 1)
ON CONFLICT (page, day)
DO UPDATE SET views = page_views.views + 1
RETURNING views;

A fast dashboard with a materialised view

The daily sales dashboard runs a heavy query over millions of order lines and takes 8 seconds. Step 1: save the result as a materialised view. Step 2: add a unique index so it can refresh concurrently and so lookups are fast. Step 3: schedule a refresh every 10 minutes. The dashboard now reads a few hundred stored rows in milliseconds.

sql
CREATE MATERIALIZED VIEW daily_sales AS
SELECT date_trunc('day', o.ordered_at)::date AS day,
       SUM(oi.qty * oi.unit_price)            AS revenue,
       COUNT(DISTINCT o.id)                   AS orders
FROM orders o JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'paid'
GROUP BY 1;

CREATE UNIQUE INDEX ON daily_sales (day);
-- every 10 minutes (cron / pg_cron):
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;

Quick reference

  • INSERT ... ON CONFLICT (key) DO UPDATE SET col = EXCLUDED.col;
  • INSERT ... ON CONFLICT DO NOTHING; skip duplicates quietly
  • DO UPDATE SET ... WHERE EXCLUDED.updated_at > t.updated_at (only newer data wins)
  • CREATE OR REPLACE VIEW v AS SELECT ...; a view stores the query, not rows
  • CREATE MATERIALIZED VIEW mv AS ...; REFRESH MATERIALIZED VIEW mv;
  • REFRESH ... CONCURRENTLY needs a unique index and keeps readers unblocked
  • MERGE (PG 15+) syncs a table from a source with matched / not matched rules

Common mistakes

  • ON CONFLICT on columns without a unique index, which raises an error.
  • Forgetting to refresh a materialised view, so reports show old numbers.
  • Expecting a plain view to be faster than the query it wraps.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1ON CONFLICT (email) fails with "there is no unique or exclusion constraint matching". Why?

Question 2

2In DO UPDATE SET qty = inventory.qty + EXCLUDED.qty, what is EXCLUDED.qty?

Question 3

3Is SELECT from a plain view faster than running its query directly?

Question 4

4What does CONCURRENTLY give you when refreshing a materialised view?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Insert a user with email 'ann@x.com' into users(email UNIQUE, name), but do nothing if that email already exists.

  2. Exercise 2medium

    Create a view customer_totals showing each customer's id, name, number of paid orders and paid revenue, including customers with no orders.

  3. Exercise 3hard

    Sync product prices from a staging table so that only rows whose incoming updated_at is newer overwrite the stored price, and new products are inserted. Return how each row was handled.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between ON CONFLICT and MERGE?
ON CONFLICT is a Postgres upsert built for concurrent inserts on a unique key. MERGE (PG 15+) is standard SQL for syncing from a source and can also delete, but it is less safe when sessions race for the same key.
Does a view update when the table changes?
A plain view always shows current data because it reruns its query. A materialised view only changes when you REFRESH it.
Can I index a view?
Not a plain view, but its underlying tables can be indexed. Materialised views can have their own indexes because they store rows.
ShareXLinkedInWhatsApp