Skip to main content

8 posts tagged with "SQL"

View all tags

Postgres Lateral Can't See the UPDATE Target? Use a CTE

· 7 min read

In a migration pipeline for a Node.js + PostgreSQL service, a data-migration SQL using UPDATE ... FROM lateral was rejected by psql with a clear error; the same file handed to drizzle-kit migrate failed silently — exit 1, with nothing but two unrelated NOTICEs in the output.

TL;DR​

The UPDATE/DELETE target table has zero visibility inside a lateral: top-level references fail, nested ones fail too — the SELECT intuition that "a lateral sees earlier FROM items" simply does not apply here. psql states the error plainly, while drizzle-kit (postgres-js driver) swallows it into a silent exit, which left a dev database's migration ledger three versions behind. Fix: rewrite every correlated reference to the target table as a CTE with correlated subqueries, and verify complex migrations with psql -v ON_ERROR_STOP=1 before they reach the toolchain.

Symptoms: psql speaks up, drizzle-kit says nothing​

The same migration file, two execution paths, opposite behavior: psql shows the error, drizzle-kit fails quietly.

The psql-side error, verbatim:

ERROR:  invalid reference to FROM-clause entry for table "t"
LINE 1: ... UPDATE tenants AS t SET settings = t.settings FROM lateral (SELECT t.settings ...
^
HINT: There is an entry for table "t", but it cannot be referenced from this part of the query.

The first instinct was "the reference is written wrong": move the target-table reference into the lateral's select list — still rejected; wrap it one level deeper in a scalar subquery — the same error again. Two edits died on the same sentence, which is what forced a change of direction: this is not about where you place the reference. Search phrasing for the same problem varies — "postgres update from lateral", "lateral reference to the outer update table" — all pointing at the same semantic gap.

The drizzle-kit side was worse: pnpm db:migrate exited 1 on the same file, stderr holding only two unrelated NOTICEs, no error message at all. The dev database's migration ledger stayed at 0027, three later migrations never applied, and tenant settings were missing the new keys — no alert anywhere in the process.

For why migration ledgers fall behind silently and how to reconcile them at deploy time, see drizzle-kit migrate: table missing? Journal silently skipped — same lesson: never trust a green tool alone.

Root cause: the lateral has zero visibility into the UPDATE target​

The conclusion, stated hard: the UPDATE/DELETE target table cannot be referenced from a lateral at any position — not "only at the top level", but nowhere.

In SELECT, a lateral sees the FROM items before it; carried over to UPDATE ... FROM, that intuition breaks: Postgres removes the target table from the lateral's visible set entirely in UPDATE/DELETE context. The HINT says it all — the entry exists, but it cannot be referenced from this part of the query, and both the top level and nested levels count as "this part". That is exactly why moving the reference into the select list still failed: no legal position exists.

A minimal reproduction on PG 16 (temp tables suffice; both variants fail with the identical message):

BEGIN;
CREATE TEMP TABLE t0 (id int PRIMARY KEY, settings jsonb);
INSERT INTO t0 VALUES (1, '{"a":"1","b":"2"}');

-- Variant A: lateral top level references target t → rejected
UPDATE t0 AS t
SET settings = t.settings
FROM lateral (SELECT t.settings->>'a' AS va) x
WHERE t.id = 1;
-- ERROR: invalid reference to FROM-clause entry for table "t"

-- Variant B: one nested scalar subquery to "relay" the value → same error
UPDATE t0 AS t
SET settings = t.settings
FROM lateral (SELECT (SELECT t.settings->>'b') AS vb) x
WHERE t.id = 1;
ROLLBACK;

Of the two failure sources, the drizzle-kit half is the more dangerous: swallowed error → no logs → dev state lags indefinitely with no alert. The psql half at least says something every time.

Fix: move correlated reads into a CTE​

Put the reads of the target table into a plain CTE and let UPDATE ... FROM do a key join only — semantically equivalent to the original lateral intent, with no reference-position restrictions. This is the final shape of that 0029 migration:

WITH src AS (
SELECT id,
settings->>'daily_remind' AS v1,
settings->>'daily_remind_at' AS v2
FROM tenants
WHERE settings ? 'daily_remind'
)
UPDATE tenants AS t
SET settings = t.settings || jsonb_build_object('remind_time', src.v2)
FROM src
WHERE t.id = src.id;

The CTE is an ordinary SELECT — no restrictions on referencing the target table; UPDATE ... FROM src does an equality join only.

The matching minimal check (PG 16, fully self-contained — the previous block's temp table was rolled back, this one rebuilds it):

BEGIN;
CREATE TEMP TABLE t0 (id int PRIMARY KEY, settings jsonb);
INSERT INTO t0 VALUES (1, '{"a":"1","b":"2"}');

WITH src AS (
SELECT id, settings->>'a' AS va
FROM t0
WHERE settings->>'a' IS NOT NULL
)
UPDATE t0 AS t
SET settings = t.settings || jsonb_build_object('a_cte', src.va)
FROM src
WHERE t.id = src.id;
-- UPDATE 1
ROLLBACK;

Three verification passes after the rewrite: the same file verified through both the pg 8.16 node driver and psql; applied twice to the dev database — UPDATE 3 the first run, UPDATE 0 the second — idempotent; ledger reconciled after backfilling, __drizzle_migrations count equal to the migration file count.

Before you ship

  • The SELECT lateral intuition does not carry to UPDATE/DELETE FROM: rewrite correlated references to the target as CTE + correlated subqueries, never lateral.
  • Verify complex data migrations with dev psql -v ON_ERROR_STOP=1 before they reach the drizzle-kit toolchain — never trust a green tool alone.
  • After drizzle-kit migrations, reconcile the ledger count against the file count routinely; a "done" with no output counts as a failure.

FAQs​

What does 'invalid reference to FROM-clause entry for table' mean in Postgres?​

A FROM entry exists but can't be referenced from where you used it. The classic trigger: a lateral subquery in UPDATE/DELETE FROM referencing the target table — Postgres rejects every position, top level included (verified on PG 16); the HINT says cannot be referenced from this part of the query. Other common causes are join order or alias scope mistakes.

Can a lateral subquery reference the UPDATE target table in Postgres?​

No — not at any position. Unlike SELECT, where a lateral sees earlier FROM items, UPDATE and DELETE give the lateral zero visibility into the target table at any nesting depth (PG 16 verified, top level included). Move the correlated reads into a CTE and join by key.

Why does drizzle-kit migrate fail with no error output?​

The postgres-js driver swallows the error: exit 1 with nothing but two unrelated NOTICEs on stderr. It once left a dev database stuck three migrations behind with no alert. Run complex SQL through psql -v ON_ERROR_STOP=1 first.

What is the correct rewrite for UPDATE FROM lateral?​

A CTE joined by key: WITH src AS (SELECT id, settings->>'k' AS v FROM target) UPDATE target t SET ... FROM src WHERE t.id = src.id. The CTE is a plain SELECT with no reference restrictions; verified on PG 16 with UPDATE 1, and idempotent as UPDATE 3 then UPDATE 0 on a real migration.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Postgres RLS Backfill Lands 0 Rows? FORCE RLS Binds Owners

· 10 min read

While running a one-off data backfill against a multi-tenant table, the command finished normally and returned INSERT 0 0 — the baseline had 23 rows to migrate, and not one of them landed. In the same deployment, every CREATE TABLE and ADD COLUMN migration had succeeded.

TL;DR​

ENABLE ROW LEVEL SECURITY does not constrain the table owner; FORCE ROW LEVEL SECURITY removes that exemption. An owner's ops session has no app.tenant_id context, so a tenant-scoped policy evaluates to false on every row, and the SELECT source of an INSERT…SELECT is filtered to an empty set — the statement succeeds, inserts nothing, and raises no error. DDL never passes through RLS, which is why migrations stay green on the same channel. Run data backfills as a superuser (or per-tenant with SET app.tenant_id), and always verify "baseline row count vs landed row count".

The symptom​

On a FORCE-RLS multi-tenant table, an owner-session backfill silently inserts 0 rows — the statement succeeds with no error and no warning, and the command output alone reads as success. Here is how it happened for real.

The setting: a multi-tenant SaaS deployment. A batch of migrations (create table, add column) goes through the owner database channel and all succeed. Right after, an idempotent backfill moves data from legacy single-select columns into a new child table:

INSERT INTO task_assignees (tenant_id, task_id, assignee_user_id, assignee_vendor_id)
SELECT tenant_id, id, assignee_user_id, assignee_vendor_id
FROM tasks
WHERE assignee_user_id IS NOT NULL OR assignee_vendor_id IS NOT NULL
ON CONFLICT DO NOTHING;

Run as the project's owner role (app_owner for short):

INSERT 0 0

The statement exits successfully, ON_ERROR_STOP never fires, and the deployment pipeline moves on. But a superuser count shows 23 tasks with non-null legacy columns — the backfill effectively never ran. Judged by exit status alone, this step slips through silently.

The confusing part is the contrast within the same channel: in one and the same psql pipeline, CREATE TABLE and ALTER TABLE … ADD COLUMN work fine, and only this INSERT…SELECT lands 0 rows.

Root cause: FORCE RLS binds the owner too​

FORCE RLS extends policy enforcement to the owner, while the owner's ops session carries no tenant context — the policy evaluates false on every row and the SELECT is silently filtered to empty; DDL never passes through RLS, so migrations stay green on the same channel. Three layers stack into the silent chain, and each one looks reasonable on its own.

Layer 1: ENABLE and FORCE are different switches. PostgreSQL has shipped RLS since 9.5. ENABLE ROW LEVEL SECURITY turns policies on, but the table owner is exempt by default — policies only bind other roles. Multi-tenant tables usually add FORCE ROW LEVEL SECURITY to cancel that exemption:

ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tasks FORCE ROW LEVEL SECURITY; -- the owner is no longer exempt

Security-wise this is right: if the owner account ever leaks into an application connection, tenant isolation still holds. The cost is that the owner's ops channel is governed by policies too — a detail that deployment docs tend to omit.

Layer 2: current_setting with missing_ok silently returns NULL. The policy is the standard tenant-header filter:

CREATE POLICY tasks_tenant ON tasks
USING (tid = current_setting('app.tenant_id', true)::uuid);

The second argument, missing_ok = true, means "return NULL instead of raising an error when the setting is absent" — a lenient read designed for application connections. Nobody runs SET app.tenant_id in an ops session, so the policy expression becomes tid = NULL, which evaluates to NULL (not true, not false), and the row is filtered out. The session raises nothing; the query raises nothing; you simply see no rows.

Layer 3: DDL never passes through RLS. RLS evaluates row access only (SELECT visibility, write legality). CREATE TABLE, ALTER TABLE, and index builds never touch policy evaluation. So the same owner channel splits in two:

OperationOwner-channel result
Create table / add column / build index (DDL)Runs normally
INSERT…SELECT (DML, source governed by FORCE RLS)SELECT source filtered to empty, INSERT 0 0
Bare INSERT with VALUES into the governed tableError: "violates row-level security" (visible)

The second row is the dangerous one: INSERT…SELECT fails in the shape of an emptied source, not a rejected target. No row ever attempts to enter, so no violation is ever raised — a silent 0 is far harder to notice than an error.

The fix​

The way out is to make the backfill session bypass — or satisfy — the tenant policy: a superuser (first choice for one-off migrations), a dedicated BYPASSRLS role (regular corrections), or per-tenant SET (keeping isolation semantics). A minimal reproduction first, then each option in turn.

Minimal reproduction​

-- A FORCE-RLS multi-tenant table
CREATE TABLE tasks (
id INT GENERATED ALWAYS AS IDENTITY,
tid UUID NOT NULL,
title TEXT,
done BOOLEAN DEFAULT false
);
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tasks FORCE ROW LEVEL SECURITY;
CREATE POLICY tasks_tenant ON tasks
USING (tid = current_setting('app.tenant_id', true)::uuid);

-- An unguarded archive table (the backfill target)
CREATE TABLE tasks_archived (
id INT,
tid UUID,
title TEXT,
done BOOLEAN
);

-- Seed two rows as superuser
INSERT INTO tasks (tid, title) VALUES ('11111111-1111-1111-1111-111111111111', 'a'),
('22222222-2222-2222-2222-222222222222', 'b');

-- Switch to an owner-role session (no tenant context):
SELECT count(*) FROM tasks; -- 0
INSERT INTO tasks_archived SELECT * FROM tasks; -- INSERT 0 0

count(*) returning 0 is the diagnostic pivot: the SQL is not wrong, the session simply cannot see the rows.

A superuser is not subject to RLS. Hand the backfill to the postgres role:

psql -U postgres -d mydb -v ON_ERROR_STOP=1 -f backfill.sql

The same statement flips from INSERT 0 0 to INSERT 0 23. The trade-off: maximum privilege, so reserve it for controlled one-off ops and never put it into application connection strings.

Option 2: a dedicated BYPASSRLS role​

If the ops channel runs data corrections regularly, create a dedicated role:

CREATE ROLE migrator WITH LOGIN BYPASSRLS;

A BYPASSRLS role skips every policy without acquiring the rest of the superuser privilege set — a narrower surface. It still needs explicit GRANTs per table, and the role's credentials must be treated as sensitive secrets.

Option 3: set tenant context per tenant​

To keep RLS semantics intact (the migration logic itself passes through isolation rules), run tenant by tenant inside a session:

SET app.tenant_id = '11111111-1111-1111-1111-111111111111';
-- backfill statements for that tenant

Fits backfills whose logic differs per tenant; for a straight full copy, a per-tenant loop is more ceremony than bypassing outright.

Always verify row counts afterwards​

Whichever channel you pick, the acceptance criterion for a backfill is not "command succeeded" — it is row reconciliation:

-- Baseline: affected rows (counted before the backfill)
SELECT count(*) FROM tasks
WHERE assignee_user_id IS NOT NULL OR assignee_vendor_id IS NOT NULL;

-- Landed: after the backfill
SELECT count(*) FROM task_assignees; -- total = baseline
SELECT count(DISTINCT task_id) FROM task_assignees; -- distinct tasks = baseline (single-select case)

In this incident, it was exactly the "baseline 23 = landed 23" check failing to add up that exposed the problem — the owner channel had printed INSERT 0 0, and without reconciliation the deployment would have shipped an empty child table. For belt-and-suspenders, join old and new rows on the primary key and compare migrated column values: zero diffs closes the loop.

Pitfalls on database write paths are rarely syntax errors — they are deployment-order and constraint-semantics mismatches. ON CONFLICT unique-constraint matching is the same family: the SQL is right, and a mismatched migration/deploy ordering still breaks everything.

The same FORCE RLS chain has a backup-side shape too: running pg_dump as the owner produces a structure-only backup with zero rows. Which channel each data action should take, and how to design restore-drill checks that catch it, is in the companion post pg_dump backup empty? FORCE RLS blocks the table owner too.

Gotchas​

On FORCE-RLS tables, the acceptance criterion for ops actions shifts from "command succeeded" to "row counts reconcile". All four points come straight from this incident:

Gotchas

  • A silent 0 is riskier than an error: when RLS empties the source of an INSERT…SELECT, nothing is raised. Backfill-type operations need a "baseline vs landed" row-count check, not just an exit code.
  • Never infer the data path from migration success: DDL bypasses RLS, so green DDL on the same channel proves nothing about DML. Probe the channel with a real DML statement.
  • missing_ok=true is part of the silent chain: current_setting('app.tenant_id', true) returns NULL when the setting is absent (policy always false, whole table filtered); with missing_ok=false a missing setting raises immediately, which surfaces the problem sooner. The lenient read is fine for app connections — just know what it does in ops sessions.
  • Keep superuser credentials in their own lane: the postgres role is for one-off ops only; it should never appear in connection strings, app config, or CI.

FAQ​

Why does Postgres row level security not seem to apply to the table owner?​

Because ENABLE ROW LEVEL SECURITY alone never constrains the table owner — policies only bind other roles by default. Add ALTER TABLE … FORCE ROW LEVEL SECURITY and every row-access statement from the owner session goes through policy evaluation too.

What does INSERT 0 0 mean in PostgreSQL?​

The two numbers are OID and row count: the statement succeeded but inserted 0 rows. Under FORCE RLS, a policy can filter the SELECT source of an INSERT…SELECT down to an empty set — nothing violates any policy, so nothing is raised. To pinpoint it, run SELECT count(*) in the same session first; a 0 confirms visibility filtering rather than a broken statement.

How do I bypass row level security in PostgreSQL for a data migration?​

Three options: run as a superuser such as the postgres role (bypasses RLS by definition — best for one-off backfills); create a dedicated role with BYPASSRLS; or SET app.tenant_id per tenant to keep RLS semantics. Whichever you choose, follow up with a row-count check against the baseline.

Does FORCE ROW LEVEL SECURITY affect DDL statements?​

No. RLS evaluates row access only — SELECT visibility and write legality. CREATE TABLE, ALTER TABLE, and index builds never touch policy evaluation, which is why the same migration run shows all-green DDL next to a silently empty DML backfill.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Postgres 42501 on new tables? Default grants per database

· 6 min read

While creating new tables with a dedicated owner role in a multi-tenant system, every query from the application role failed with permission denied for table — old tables were fine, every freshly migrated table was unreachable.

Ran into this in a Node.js + PostgreSQL multi-tenant system (row-level security isolating tenant data).

TL;DR​

ALTER DEFAULT PRIVILEGES is not a global switch: its scope is "which role grants × which database it runs in". Running it once in the postgres database gives future tables in your app database nothing — queries fail with 42501 anyway. Fix in two moves: run it in every application database; and when DROP ROLE complains about dependencies, clear the stale entries with DROP OWNED BY in that same database.

Symptoms: old tables work, new tables fail with 42501​

A freshly created table is immediately unreadable for the application role while the same role queries every existing table without trouble — grants missing only on "tables created after migration" is the signature of missing default privileges. If you searched "postgres permission denied for table", "42501 insufficient privilege", or "granted privileges but still permission denied", it's the same problem.

-- a table the owner role just created via migration
ERROR: permission denied for table vendors
SQLSTATE: 42501

The second symptom shows up later, when cleaning up a role:

ERROR:  role "app_role" cannot be dropped because some objects depend on it
DETAIL: privileges for default privileges in database appdb

The DETAIL line is the tell: the dependency is not a table or a function, it's a stale default-privileges entry.

Root cause: ALTER DEFAULT PRIVILEGES is scoped to a role × a database​

The default-privilege rule lives in the database where you ran it, and never crosses databases. What ALTER DEFAULT PRIVILEGES records is a rule — "objects created in this database, from now on, by the role named in FOR ROLE (default: the current role), are granted to the TO role automatically". The rule is stored in the database-local pg_default_acl catalog, which means:

  • run it in the postgres database → only future objects in the postgres database are covered
  • never ran it in the app database → new tables there carry no default grants at all
  • tables get created by a different role (no FOR ROLE) → the rule doesn't match

The order of events that produced this: a tutorial-style "global" default-privilege statement ran in the postgres database first, then the app database was created. The first few tables happened to be granted manually, so everything looked fine — until migrations started creating tables automatically and 42501 errors appeared in bulk. First hypothesis: a missing GRANT statement; adding grants changed nothing. The stale entry surfaced only when dropping an unused role failed with privileges for default privileges in the DETAIL — the grants did exist, just in the wrong database.

PostgreSQL treating "where you run it" as a behavior boundary shows up elsewhere too: fe_sendauth across containers is the same logic — identical command, different execution path, completely different rules.

ALTER DEFAULT PRIVILEGES scope: one role × one database

Fix: grants go into the app database, cleanup goes into the same database​

Three steps, all organized around the database unit:

  1. Inventory which databases have default privileges. Run in each database; 0 in an application database means it was missed:
SELECT count(*) FROM pg_default_acl;
  1. Run the default grants per database. One statement for TABLES, one for SEQUENCES, FOR ROLE naming the role that actually creates tables:
-- run with psql -d <appdb>, not while connected to the postgres database
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_role;

ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO app_role;
  1. Clear stale entries. When DROP ROLE reports dependencies, connect to each database named in the DETAIL (every database holding default-privileges entries) and run:
DROP OWNED BY app_role;
DROP ROLE app_role;

For new databases, bake step 2 into the provisioning script — every grant statement in our init script is forced through -d <database>, which rules out the "ran it while connected to postgres" failure mode for good.

Default privileges only cover future objects, so tables that already exist need a one-time grant:

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_role;

Watch out

  • No FOR ROLE means the current role: run it as the superuser without FOR ROLE and the rule is attached to the superuser — it only fires when the superuser creates objects, and migrations running as the owner role still produce ungranted tables.
  • DROP OWNED drops objects too: it revokes the role's privileges in that database and drops objects it owns. Use it for dedicated roles being removed, not casually on shared roles.
  • A new database is a new grants gap: default privileges are not inherited on CREATE DATABASE. "Create database → immediately set default privileges" should be one fixed step in the provisioning script.

FAQ​

Why is ALTER DEFAULT PRIVILEGES not working for new tables?​

Its scope is one role in one database: running it in the postgres database only affects future objects created there. Run it in each application database, with FOR ROLE set to the role that actually creates tables.

What does PostgreSQL error 42501 (permission denied for table) mean?​

SQLSTATE 42501 is insufficient_privilege. When old tables query fine and only migrated tables fail, the app role is missing default grants — verify with SELECT count(*) FROM pg_default_acl; in that database (0 means none configured), then add the per-database ALTER DEFAULT PRIVILEGES.

Do I need ALTER DEFAULT PRIVILEGES FOR ROLE in every database?​

Yes — once per database per table-creating role, and it only covers future objects, so existing tables need a one-time GRANT ... ON ALL TABLES IN SCHEMA public. To drop a role blocked by "privileges for default privileges", run DROP OWNED BY in each database holding stale entries, and retry DROP ROLE once SELECT count(*) FROM pg_default_acl; returns 0 there.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

jsonb IS NOT NULL passes for JSON null? Use jsonb_typeof

· 5 min read

Filtering a jsonb field's "empty" values with IS NOT NULL lets rows whose value is JSON null sail right through — the data is empty, yet the predicate says otherwise.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. Analysis decision snapshots are stored as jsonb; rows where no rule fired get JSON null written in, which silently corrupted the "has rule output" predicate.

Symptom: IS NOT NULL doesn't catch the "empty" value​

field->'key' IS NOT NULL returns true for rows whose value is JSON null — the filter does nothing, and rows that should be excluded leak into the result set. If you searched for "jsonb is not null not working", "jsonb null filter" or "postgres json null check", this is the same issue.

Root cause: JSON null is a valid jsonb value, not SQL NULL​

PostgreSQL has two kinds of "empty" here: SQL NULL means no value exists; JSON null is a legitimate jsonb value. The -> operator retrieves what the key holds — for JSON null, that's a perfectly valid value, and IS NOT NULL answers "did I get something back?", not "is it meaningful?". Verified behavior matrix (tested on a PostgreSQL 16 container):

ExpressionResult
('{"a":null}'::jsonb -> 'a') IS NOT NULLtrue
('{"a":1}'::jsonb -> 'b') IS NULLtrue (missing key yields SQL NULL)
jsonb_typeof('{"a":null}'::jsonb -> 'a')'null' (a string)
jsonb_typeof('{"a":1}'::jsonb -> 'b')SQL NULL
'{"a":null}'::jsonb ? 'a'true
('{"a":null}'::jsonb ->> 'a') IS NULLtrue

Two combinations bite most often:

  • IS NOT NULL cannot tell JSON null from a real value — the first row, exactly where the misjudgment comes from.
  • Extracting text with ->> and testing IS NULL fails the same way — JSON null and a missing key both become SQL NULL (last row). Reaching for ->> to dodge the trap lands you right back in it.

The fix: ? for key existence, jsonb_typeof for value type​

Two different intents need two different tools:

-- "key exists": value irrelevant
SELECT '{"a":null}'::jsonb ? 'a'; -- true

-- "has a real value": assert the JSON type; 'null', missing keys all excluded
SELECT jsonb_typeof(config->'rule_output') = 'array'; -- arrays only
SELECT jsonb_typeof(config->'rule_output') = 'object'; -- objects only

-- find rows that hold a JSON null (data triage)
SELECT * FROM t WHERE jsonb_typeof(config->'rule_output') = 'null';

Our concrete case: the rule engine writes JSON null into decision snapshots when no rule fired, and a downstream count used ->'rule_output' IS NOT NULL as "has rule output" — the metric was simply wrong. The fix tightened the assertion to jsonb_typeof(...) = 'array', excluding JSON null, missing keys and every other type in one stroke.

Boundary cases: JSON null is not always wrong​

To be clear: JSON null is a legitimate design — "key exists but empty" and "key absent" are different business semantics; an API returning "extra": null is not the same as omitting extra. The data isn't wrong; the predicate is. Three intents, three spellings:

IntentExpression
Key exists (value irrelevant)jsonb ? 'key'
Real value of a given typejsonb_typeof(x) = 'array' / 'object' / ...
Value is JSON nulljsonb_typeof(x) = 'null'

A related trap lives on the update side: jsonb_set(config, '{rule_output}', 'null') writes a JSON null, while jsonb_set(config, '{rule_output}', NULL) deletes the key entirely — JSON vs SQL NULL as the argument flips the meaning. For other "query results don't match expectations" hunts, cross-query granularity mismatches causing dangling references are another frequent root cause worth comparing.

Watch out

  • Triage existing data before changing predicates: run jsonb_typeof(...) = 'null' across the table first to size up where JSON null rows come from, then decide whether to fix the query or the writer.
  • Standardize the spelling in your team: even if a field currently always holds a valid array and IS NOT NULL happens to work, use jsonb_typeof assertions uniformly — the moment the field's semantics shift, the loose spelling becomes a silent bug.
  • The same applies at the ORM/driver layer: when application code checks "JSON field is not empty", know what your driver maps JSON null to (most languages map it to a language-level null/None) — don't conflate the two kinds of empty.

FAQ​

What is the difference between JSON null and SQL NULL in Postgres jsonb?​

JSON null is a valid jsonb value; SQL NULL means the value does not exist. Tested: ('{"a":null}'::jsonb -> 'a') IS NOT NULL returns true; jsonb_typeof returns the string 'null' for the former and SQL NULL for a missing key.

Why doesn't IS NOT NULL filter out empty jsonb values?​

->'key' returns a valid jsonb value for JSON null, so IS NOT NULL is trivially true. Assert the type instead — jsonb_typeof(field->'key') = 'array' — or check key existence with the ? operator.

How do I tell a JSON null value from a missing key in jsonb?​

Use the ? operator for key existence — it returns true even when the value is JSON null. jsonb_typeof returns the string 'null' for a JSON null value and SQL NULL for a missing key, which tells the two apart.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Metrics Inflated 20x After SQL Aggregation? Never SUM Ratio Columns

· 6 min read

While aggregating daily ad data into weekly reports, the ratio metrics — PPC, CPM, ROI — jumped by tens of times: PPC went from 4.70 in the daily detail to 111.39 in the weekly report.

Encountered this while building AI Ops — LLM-powered analysis that surfaces market trends, user behavior, and sales insights to drive precise operations strategy. The ad data API returns daily detail rows, which must be aggregated to week granularity before feeding reports. The first check after launch: PPC 111.39 (daily actual 4.70), CPM 1585.9 (daily actual 68.6), ROI 169.98 (daily actual 1.82) — all 13 ratio/average columns distorted.

TL;DR​

Applying SUM directly to ratio/average columns like CTR, PPC, ROI in an aggregation query yields "the sum of daily ratios," not a mean — values inflate proportionally to the number of days aggregated. Two rules: aggregate only additive columns (impressions, clicks, cost — the totals), skipping every ratio column; recompute ratios from the totals after aggregating (cost ÷ clicks, clicks ÷ impressions). If you only have ratios without the underlying totals, take a weighted average using the denominator as weight — never a plain average.

The Symptom​

The aggregation code SUMmed "every numeric column," silently sweeping ratio columns along:

-- Wrong: SUM every column
SELECT
campaign_id,
date_trunc('week', day) AS week,
SUM(clicks) AS clicks,
SUM(impressions) AS impressions,
SUM(ppc) AS ppc, -- sum of 7 daily PPC values!
SUM(ctr) AS ctr, -- sum of 7 daily CTR values!
SUM(roi) AS roi -- sum of 7 daily ROI values!
FROM daily_ad_report
GROUP BY campaign_id, date_trunc('week', day);

Measured comparison (one campaign, one week):

MetricDaily actualSUM weeklyInflation
ppc4.70111.39~24×
cpm68.61585.9~23×
roi1.82169.98~93×

No errors anywhere: data ingested normally, reports rendered normally — only by comparing the weekly report against daily details side by side could you see values off by one to two orders of magnitude.

Root Cause​

Ratios and averages are non-additive derived quantities. Each day's ppc = cost / clicks has a different denominator; adding 7 daily PPC values mathematically yields "a sum of 7 relative values," which has no business meaning. CTR and ROI are the same.

"Sum all numeric columns" is a silent trap. Aggregation code usually loops over columns uniformly, and ratio columns slip in without error or warning — results just quietly distort. The more columns you have, the harder it is to spot by eye.

An ROI inflated 93× is actually more deceptive. It reads as "outstanding ad performance." If downstream consumers read the weekly report directly to make budget decisions, the wrong number propagates all the way into operational actions. In this incident, several read-only consumers queried the weekly table directly — until the table was corrected, every consumer was reading wrong data.

The Fix​

Step 1: Keep only additive columns in the aggregation​

CREATE VIEW weekly_ad_totals AS
SELECT
campaign_id,
date_trunc('week', day) AS week,
SUM(impressions) AS impressions,
SUM(clicks) AS clicks,
SUM(cost) AS cost,
SUM(gmv) AS gmv
FROM daily_ad_report
GROUP BY campaign_id, date_trunc('week', day);

Additive columns are counts/totals (impressions, clicks, cost, orders) — summing them across time intervals still means something.

Step 2: Recompute all ratios from totals after aggregating​

SELECT
campaign_id,
week,
impressions,
clicks,
cost,
CASE WHEN clicks > 0
THEN cost / NULLIF(clicks, 0)::numeric
ELSE 0 END AS ppc,
CASE WHEN impressions > 0
THEN clicks::numeric / NULLIF(impressions, 0)
ELSE 0 END AS ctr,
CASE WHEN cost > 0
THEN (gmv - cost)::numeric / NULLIF(cost, 0)
ELSE 0 END AS roi
FROM weekly_ad_totals;

Two details: PostgreSQL integer division truncates, so cast with ::numeric before dividing; return 0 when the denominator is 0, keeping the same convention as the daily layer.

Step 3: When you only have ratios, use a weighted average​

-- Aggregate daily CTR weighted by impressions (expanded form: SUM(ctr × impressions) / SUM(impressions))
SELECT
date_trunc('week', day) AS week,
SUM(clicks)::numeric / NULLIF(SUM(impressions), 0) AS ctr_weighted
FROM daily_ad_report
GROUP BY date_trunc('week', day);

A weighted average is essentially "reconstruct numerator and denominator, then divide" — as long as you can still access the weight column, always prefer it over a plain average.

After the fix, all 13 ratio columns in the weekly report matched the measured daily values. Historical dirty data was backfilled with the same formulas, and read-only downstream consumers became correct automatically — without changing a single line of code.

Heads up

Generic aggregation code that "sums every numeric column" is the source of this class of incident: maintain an allowlist of additive columns, explicitly excluding ratio/average columns. When adding a new metric column, first answer: "does summing this across days still mean something?"

When multiple granularities (weekly, monthly) derive from the same daily table, converge "recompute ratios from totals" into one function or view instead of copying the formula into each report SQL — metric-definition drift usually starts with copy-paste.

After fixing the aggregation logic, remember to backfill historical data: aggregation errors usually persist for many cycles, and fixing code without backfilling leaves old wrong values in the reports.

FAQ​

Can you sum percentages?​

No. Percentages and ratios are relative values with different denominators per row — SUMming them yields a sum of N relative values, inflated by the number of periods aggregated, with no business meaning. The correct approach is to skip ratio columns during aggregation and recompute from totals afterward (clicks ÷ impressions, cost ÷ clicks); when you only have ratios without totals, take a weighted average using the denominator as weight.

Can you add percentages together to get an average?​

Only when the denominators are identical. Averaging percentages with different denominators is an unweighted average that skews toward small-denominator items (extreme ratios from low-traffic days get amplified). The correct approach is to sum numerators and denominators separately, then divide — mathematically equivalent to a weighted average by denominator.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Row Exists in the Detail Query but Not the Summary? Cross-Query Predicate Granularity Mismatch

· 6 min read

While triaging a dashboard lead in an ad-data pipeline: an offer was flagged "suspected paused" in the diagnostic detail, complete with a reinvestment suggestion — yet the "suggested actions" list had no row for it. The detail page pointed at a table that didn't contain it.

Encountered this while building AI Analytics — an LLM-powered analytics platform that surfaces market trends, user behavior, and sales data; the diagnostic detail and the suggestion list come from two adjacent queries in the pipeline.

TL;DR​

Two queries defined the same business predicate ("suspected paused") at different aggregation granularity: the detail query judged at campaign×offer level — any single campaign with no spend in the last week flags it; the candidate list judged at whole-offer level — all campaigns must be spend-free to qualify. One offer still had spend (3.09) in one campaign, so the detail flagged it while the summary skipped it, leaving a dangling reference in the UI. Three fixes: unify the definition at the coarser granularity, make the predicate CTEs verbatim-identical, and verify row-set containment before cross-referencing.

Symptoms​

Two queries, each with its own definition of "suspected paused":

-- Query 4, diagnostic detail: pair granularity (campaign × offer)
WITH consumption_paused_q4 AS (
SELECT offer_id, campaign_id
FROM spend_weekly
GROUP BY offer_id, campaign_id -- each campaign judged alone
HAVING SUM(spend) FILTER (WHERE is_last_week) = 0
)

-- Query 5, suggestion candidates: offer granularity (summed across campaigns)
WITH suspected_paused_q5 AS (
SELECT offer_id
FROM spend_weekly
GROUP BY offer_id -- the whole offer judged together
HAVING SUM(spend) FILTER (WHERE is_last_week) = 0
)

The problematic offer hung under multiple campaigns, one of which still had spend (3.09) in its last week:

Query 4 (pair level):   campaign A last-week spend = 0    → flagged ✓, suggestion attached
Query 5 (offer level): summed last-week spend = 3.09 → excluded ✗
UI: detail says "see the suggestion table"; the suggestion table has no such row

No errors, plausible totals — the dangling reference only surfaces when someone follows a specific detail row.

Root Cause​

The "same source" contract had a coverage gap. The pipeline spec requires the feature-column CTEs of adjacent queries to be verbatim identical — that rule was followed to the letter. But it only covers feature columns; the predicate set (the business judgment before WHERE) was out of scope. "Suspected paused" was implemented twice, at different granularities: pair-level judgment is sensitive to "one campaign has no spend", offer-level judgment to "all campaigns have no spend". For any offer spanning both situations, the two queries must disagree — the overlap zone is mathematically guaranteed.

Cross-query referencing amplified the fork into a dangling reference: the UI treats query 4's rows as details and query 5's table as the entry point, with nobody ever checking "rows(q4) ⊆ rows(q5)". Aggregation-level inconsistency is the classic data-warehouse consistency trap — our earlier post on SUM over ratio columns inflating aggregated metrics is the same disease in another organ: aggregation happening at the wrong level.

Solution​

Step 1: Decide the canonical definition before touching SQL​

The business question has one answer: "should we keep funding this offer" is an offer-level decision, so the predicate must tighten to whole-offer granularity — every attached campaign spend-free in the last week AND no operation annotation rows. Bump the rule version so the change is traceable.

Step 2: Share the predicate CTE verbatim​

Extract the predicate CTE into one text block referenced by both queries; upgrade the contract at the same time: verbatim sharing covers the predicate set (including granularity), not just feature columns. One definition, one place to change.

Step 3: Before cross-referencing, check row-set containment​

Make "marker set ⊆ target row set" a standing check (promote it to a test):

-- Dangling detection: flagged by q4 but absent from q5
SELECT q4.offer_id
FROM consumption_paused_q4 q4
LEFT JOIN suspected_paused_q5 q5 USING (offer_id)
WHERE q5.offer_id IS NULL;

Only when this returns 0 rows does the UI earn the right to render both outputs on one page.

Step 4: Replay against history before shipping​

Replay the new definition over historical snapshots: verify every verdict flip (flagged ↔ normal) is correct, with zero collateral flips and zero dangling references, then re-run production validation.

Notes

  • "Same source" contracts must cover predicate granularity, not just feature columns; feature-column sharing cannot save you from a predicate defined twice.
  • Each business predicate (paused, hot, churning...) gets exactly one definition in the pipeline; a second implementation is an incident in waiting.
  • Before adding any cross-query reference (A's output rows pointing at B's output table), run the containment check — don't wait for a user to click a dangling link.
  • Version every definition change and replay it over historical data; "it works on new data" hides the risk of existing conclusions silently reversing.

FAQ​

Why do two SQL queries return different results on the same data?​

Three usual differences: aggregation granularity (different GROUP BY dimensions — campaign×entity vs whole entity in this case), filter logic (different WHERE/HAVING conditions), and point in time. Granularity is the sneakiest: both queries are individually correct, yet their verdicts can contradict.

When do I use HAVING vs WHERE for aggregate conditions in SQL?​

WHERE filters rows before grouping; HAVING filters groups after. But before picking the keyword, pick the granularity — "what counts as one group" determines sensitivity: finer granularity flags more easily (any group qualifies), coarser granularity is conservative (all groups must qualify). Different granularity, opposite verdicts.

How do I keep data definitions consistent across reports?​

One definition per business predicate, predicate CTEs shared verbatim across queries, containment checks (A ⊆ B) before cross-query references, and versioned definition changes replayed over history. Consistency doesn't come from convention — it comes from contracts plus checks.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

PostgreSQL migration left orphan empty tables behind? Audit schema leftovers with information_schema

· 7 min read

After switching an ads data source from daily tables to weekly tables, I found an empty table still sitting in the schema — one that was only ever CREATEd in the earliest migration, held zero rows, and was never referenced by runtime code. It even carried stale field names and unnormalized columns.

Encountered this while building AI Ops — AI-powered analytics that surfaces market trends, user behavior, and sales data to drive precise operational strategy. After this data-source switch, the write path had long since moved to the new weekly tables and a cleanup migration had already dropped the old daily table. The one thing missed was a monthly table that existed only in the baseline CREATE — it had no new writes, no corresponding DROP, and just sat dormant in the schema with its deprecated field definitions.

TL;DR​

The signature of an orphan table: only CREATEd in an early/baseline migration, zero references in current code, often with stale or unnormalized column names. Batch migrations don't touch these automatically. You have to actively list every table in the schema with information_schema.tables, compare against code references, identify the orphans, and write a DROP migration to clean them up — not just psql your way to a one-off delete.

The symptom​

A typical orphan table looks like this:

  • Zero rows — the business stopped writing to it long ago;
  • Zero runtime references — no SELECT/INSERT anywhere in code, only the CREATE in a migration file;
  • Stale fields — column names from a previous naming convention (e.g. ad_plan_id/product_id), out of step with current standards;
  • Unnormalized columns — possibly even Chinese column names that were never cleaned up.

It doesn't crash and doesn't affect production, so from a "nothing's broken online" perspective it's invisible. But the harm is implicit: it misleads newcomers into thinking it's still in use, pollutes the schema namespace, adds noise to cross-table audits, and could be read as dirty data by some mistaken SELECT *.

Root cause​

Database migrations follow a pervasive pattern: migrations are "additive".

A data-source switch typically evolves like this:

  1. An early baseline migration CREATEs a batch of tables (daily, monthly);
  2. Once the business runs, the write path starts depending on them;
  3. Requirements change, new tables (weekly) are introduced, and writes migrate over;
  4. The old daily table's writes stop, and a migration DROPs it;
  5. But the monthly table (or any table that was only ever CREATEd in the baseline and never directly used by the write path) gets no corresponding DROP.

The problem is step 5: migration attention focuses on "tables in use right now" — which ones are being written, which ones queries hit. A table that "once existed but never entered the main path" is in neither the write path nor the query path, so it never triggers a DROP and becomes an orphan. This is the same family as Airflow DAG metadata lingering after deletion: "removed the entry, forgot to clean the structure" — a high-frequency failure mode in migration work.

The fix​

Core flow: list all tables → compare references → confirm empty → write a DROP migration → verify.

Step 1: list all base tables in the schema with information_schema​

-- List all base tables in a schema (exclude views)
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'your_schema'
AND table_type = 'BASE TABLE'
ORDER BY table_name;

information_schema.tables is a SQL-standard catalog view, portable across PostgreSQL/MySQL/SQL Server with stable fields — ideal for baking into an audit script.

Step 2: grep the codebase to confirm runtime references​

For each candidate table, search for references in the codebase, excluding migration files themselves:

# Search runtime code references, excluding the migrations directory
grep -rn "ad_product_monthly_stats" src/ --include="*.py" \
| grep -v "migrations/"
# 0 lines of output → no runtime reference, it's a candidate

Zero references is the key evidence for an orphan. Make sure to exclude the migration directory — the CREATE in the baseline doesn't count as a "reference".

Step 3: confirm it's empty​

SELECT count(*) FROM your_schema.ad_product_monthly_stats;
-- 0 → confirmed no data, safe to clean up

Be extra careful with tables that have data: first confirm they're truly abandoned (not just recently unwritten), and back up logically if in doubt.

Step 4: write a DROP migration (not a manual delete)​

-- db-migrations/{project}/027_drop_ad_product_monthly_stats.sql
DROP TABLE IF EXISTS your_schema.ad_product_monthly_stats;

Always go through a migration file: it's version-controlled, replayed consistently across environments (dev/staging/prod), and leaves an audit trail. A one-off psql delete only works on the current machine — on another box, the table grows back.

Step 5: verify the drop​

SELECT to_regclass('your_schema.ad_product_monthly_stats');
-- Returns NULL → the table no longer exists

to_regclass() is the standard way to check whether a relation exists; NULL confirms the drop succeeded.

Batch audit: sweep same-prefix siblings at once​

After dropping one table, list all same-prefix siblings and walk through each — avoid "dropped one, missed its siblings":

-- List all tables under a prefix, run steps 2-5 on each
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'your_schema'
AND table_name LIKE 'ad_%'
ORDER BY table_name;

Caveats

  • Back up / snapshot before DROP: dropping a production table is irreversible. For any table with data, confirm it's abandoned and export a logical backup first (e.g. CREATE TABLE ... AS SELECT into an archive schema).
  • Check foreign-key dependencies: if another table has a FK pointing at it, DROP TABLE fails. Confirm dependencies are resolved, or deliberately use CASCADE — but CASCADE cascades the deletion to dependent objects, so use it carefully in production.
  • Use a migration, not manual psql: a manual delete only affects the current environment; a migration file guarantees multi-environment consistency and leaves a record.
  • Audit by prefix: one switch usually involves a group of same-prefix tables (e.g. ad_*). After cleaning one, sweep the siblings with LIKE 'ad_%' to proactively catch the same class of leftovers.

FAQ​

How do I list all tables in a PostgreSQL database?​

Query information_schema.tables, filtering by table_schema and table_type = 'BASE TABLE' to list all base tables in a schema. It's more scriptable than psql's \dt, and because it's the SQL standard, the same query is portable across databases.

How do I find unused or orphan tables in PostgreSQL?​

List all tables with information_schema.tables, then compare against references in your codebase or query logs. Tables with zero runtime references and no writes are orphan candidates; confirm the row count with SELECT count(*), and once you've verified no data and no foreign-key dependencies, write a DROP migration to clean them up.

What's the difference between information_schema and pg_catalog?​

information_schema is the SQL-standard catalog view — portable across PostgreSQL/MySQL/SQL Server with stable fields, ideal for portable audit scripts. pg_catalog is the PostgreSQL-specific catalog, richer and more detailed (e.g. precise row-count estimates, storage details) but subject to change between versions. For portable schema audits, prefer information_schema.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

PostgreSQL ON CONFLICT: there is no unique constraint? Sync INSERTs after changing the unique key

· 6 min read

Right after tightening a table's unique key — dropping a column that no longer discriminated between rows — every previously working UPSERT immediately failed in bulk with there is no unique or exclusion constraint matching the ON CONFLICT specification.

Encountered this while building AI Analytics — an LLM-powered analytics pipeline that surfaces market trends, user behavior, and sales data for precise operations.

TL;DR​

PostgreSQL's ON CONFLICT (cols) requires cols to exactly match an existing unique constraint or unique index (same columns, same order — otherwise SQL state 42P10). The moment you ALTER the unique key, every INSERT ... ON CONFLICT that references it must be updated; and once the migration lands, the write side must deploy immediately, because the in-between window keeps erroring.

The symptom​

As soon as the unique-key change went live, the scheduled import job failed across the board, with only this line in the write log:

ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
SQL state: 42P10

Zero rows written to the business table, while plain SELECTs against the same table worked fine — the failure was isolated to the ON CONFLICT write path.

Root cause​

The column set you pass to ON CONFLICT (cols) is the arbiter. PostgreSQL requires it to exactly match some UNIQUE constraint or unique index on the table:

  • the set of columns must be the same;
  • the order of columns must be the same;
  • for a partial unique index (one with a WHERE), ON CONFLICT must carry the same WHERE.

When nothing matches, PostgreSQL has no index to decide what "conflict" means, and raises 42P10.

The classic trigger is shrinking a unique key. The original key had 3 columns; you realize one of them (say audience) has 4 distinct values whose metric rows are 100% identical — pure redundancy — so you drop it down to 2 columns. That's the right optimization, but the old INSERT still says ON CONFLICT (c1, c2, c3) while only (c1, c2) remains as a unique constraint. The arbiter has no landing spot, and the statement errors out.

old unique key: UNIQUE (store_id, metric_key, audience)
new unique key: UNIQUE (store_id, metric_key)

old INSERT: ON CONFLICT (store_id, metric_key, audience) ← no match

The fix​

Here is a minimal reproduction — create, trigger, and fix in one go, runnable directly in psql:

-- 1. A table with a 3-column unique key
CREATE TABLE daily_metric (
store_id TEXT NOT NULL,
metric_key TEXT NOT NULL,
audience TEXT NOT NULL,
value NUMERIC,
CONSTRAINT daily_metric_unique UNIQUE (store_id, metric_key, audience)
);

-- 2. Old UPSERT: ON CONFLICT includes audience
INSERT INTO daily_metric (store_id, metric_key, audience, value)
VALUES ('s1', 'revenue', 'visitor', 100)
ON CONFLICT (store_id, metric_key, audience)
DO UPDATE SET value = EXCLUDED.value;

-- 3. Shrink the unique key: drop audience
ALTER TABLE daily_metric
DROP CONSTRAINT daily_metric_unique,
ADD CONSTRAINT daily_metric_unique_new UNIQUE (store_id, metric_key);

-- 4. Re-run the INSERT from step 2 — it now errors ↓
-- ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification

The fix is to shrink the INSERT's ON CONFLICT columns to match the 2-column key. Since audience no longer discriminates, pin it to a literal on the write side so incoming parameters can't synthesize extra rows:

INSERT INTO daily_metric (store_id, metric_key, audience, value)
VALUES ('s1', 'revenue', 'visitor', 100)
ON CONFLICT (store_id, metric_key) -- ← shrunk to match
DO UPDATE SET value = EXCLUDED.value;

The part that actually bites is the deployment order, not the SQL itself:

  1. Ship the migration first (DROP old constraint + ADD new constraint);
  2. Immediately ship the write-side code (the INSERT's ON CONFLICT becomes 2 columns);
  3. Leave no gap between the two — old code against the new schema raises 42P10, and new code against the old schema raises 42P10 just the same (no 2-column unique constraint exists yet).

If you use an ORM like Drizzle, an ON CONFLICT column list baked into a sql template is easy to forget when the schema changes — the cost of schema/write-side drift shows up in another Drizzle + PostgreSQL pitfall too.

Caveats​

Caveats

  • Column order matters: ON CONFLICT (a, b) does not match UNIQUE (b, a) — the order must agree.
  • Partial unique indexes need the WHERE: if the arbiter is UNIQUE ... WHERE active, the INSERT must read ON CONFLICT (cols) WHERE active DO ..., or you get 42P10 all the same.
  • "Just skip on any conflict": use ON CONFLICT DO NOTHING without columns — it specifies no arbiter and matches no specific index, catching every conflict.
  • During rollout: old and new write-side versions may briefly coexist. Make sure both can match the current schema, or ship the migration and the code together with no window in between.

FAQ​

Does PostgreSQL ON CONFLICT require a unique constraint?​

Only when you name columns. ON CONFLICT (cols) must match an existing UNIQUE constraint or unique index exactly, or you get 42P10. If you just want "skip on any conflict" without caring which constraint fired, use ON CONFLICT DO NOTHING without columns — it needs no specific index.

Can PostgreSQL ON CONFLICT target multiple unique constraints?​

No. A single INSERT's ON CONFLICT can name only one arbiter constraint (one column set, or one index name). A table may have multiple unique keys, but a single statement picks exactly one for conflict detection. To handle different unique keys differently, either split into multiple writes or query first in the application layer before choosing INSERT vs UPDATE.

How to fix there is no unique or exclusion constraint matching the ON CONFLICT specification?​

That is error code 42P10: the ON CONFLICT column set has no matching unique index on the table. Check in order: a UNIQUE constraint covers those columns, the columns and their order match exactly, and any INSERT was updated after a recent unique-key change. If the arbiter is a partial unique index with a WHERE, add the same WHERE clause to ON CONFLICT.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me