Explain, Measured

· postgresql

Upserts, partitions, triggers and string matching on PostgreSQL 18

Twenty-one small measurements this week, mostly about writing rows and matching text. Two of them went the other way from what I expected.

Setup

PostgreSQL 18.6, built from source, default settings (work_mem 4MB, shared_buffers 128MB). The database collation is C. MacBook Air M5, 24 GB RAM. Same machine as my previous posts.

Query times are EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) execution time, run several times in one session, first run thrown away, median of the rest (3 unless I say otherwise). Inserts, upserts and MERGE ran inside a transaction that I rolled back, so each run starts from the same table. Where I give seconds, that is wall clock from psql, and it includes connecting, which took 0.005 s for SELECT 1. Buffers are from the top plan node. Sizes are decimal MB. Parallel workers were off unless I say otherwise.

Upserts

A 1,000,000-row table with an int primary key. 100,000 incoming rows, of which 50,000 already exist.

StatementTime
INSERT ... ON CONFLICT DO NOTHING71.3 ms
INSERT ... WHERE NOT EXISTS (...)82.6 ms
INSERT ... ON CONFLICT DO UPDATE153.8 ms
MERGE (update matched, insert the rest)165.45 ms

The NOT EXISTS form is not the same thing under concurrent inserts: two sessions can both see "not there" and one of them fails on the key. I only ran one session.

An upsert that changes nothing

Next I sent 50,000 rows that all exist and carry the same value already. These runs were committed, with a CHECKPOINT before each.

StatementWALTime
ON CONFLICT DO UPDATE SET v = EXCLUDED.v16.2 MB0.107 s
same, plus WHERE x_up.v IS DISTINCT FROM EXCLUDED.v4.6 MB0.040 s

Without the WHERE, every row gets a new version even though nothing changed. With it, nothing is updated, yet it still wrote 4.6 MB. I didn't check what those WAL records were.

One DELETE or batches

2,000,000 rows, delete the first 1,000,000. Either one statement, or 100 statements of 10,000 rows, each committing on its own. Three runs, each on a freshly loaded table.

MethodWall clockWAL
one DELETE0.441 / 0.446 / 0.406 s132.7 / 140.0 / 144.5 MB
100 batches0.208 / 0.208 / 0.212 s140.0 / 139.9 / 140.1 MB

I expected the batches to cost more in total. They were about twice as fast, every time, and wrote the same WAL. I didn't test why.

Monthly partitions

6,000,000 rows spread over 2026 with an index on the timestamp, once as a plain table and once as 12 monthly partitions.

QueryPlain tablePartitioned
one day0.777 ms, 203 buffers0.890 ms, 203 buffers
one month (509,589 rows)24.7 ms, index scan, 6,159 buffers23.0 ms, seq scan of one partition, 4,763 buffers
whole table184.7 ms276.9 ms

Pruning did its job, but it didn't make the one-day query faster. Reading every partition took 276.9 ms against 184.7 ms for one table.

Removing January (509,590 rows) is where the partitions paid off. DROP TABLE on the partition took 0.007 s and 0.1 MB of WAL. The same DELETE on the plain table took 0.221 s and 67.8 MB of WAL, and the table was still 594.3 MB right after. I didn't vacuum it.

Planning time and partition count

Empty-ish tables with 10, 100 and 1,000 range partitions, 100,000 rows in total. Median of 5.

PartitionsWHERE k = 5, planningcount(*), planningcount(*), execution
100.007 ms0.018 ms3.491 ms
1000.005 ms0.084 ms3.604 ms
1,0000.007 ms13.166 ms16.387 ms

When the planner can prune at plan time, the count didn't matter here. A query that touches all 1,000 partitions spent more time planning than the 100-partition one spent running.

Row triggers and CHECK constraints

1,000,000 rows inserted with INSERT ... SELECT.

TableTime
no trigger750.1 ms
BEFORE INSERT row trigger, PL/pgSQL, RETURN NEW953.4 ms
AFTER INSERT row trigger, same function1,398.1 ms

The trigger does nothing, and the AFTER version still took 1,398.1 ms against 750.1 ms. One of its three runs was 1,044.3 ms.

CHECK constraints made no difference I could see: 829.9 ms with none, 795.1 ms with one, 840.1 ms with five. The plain table took 750.1 ms in the trigger test and 829.9 ms here, so I read these differences as noise.

I also tried stored generated columns. A GENERATED ... STORED md5 column took the table from 76.6 MB to 109.3 MB. The insert times came out in an order I don't trust (the plain table was the slowest), so I left them out.

The latest row per group

10,000 customers, 2,000,000 orders, an index on (customer_id, created_at DESC). All three return the same 10,000 rows.

QueryTimeBuffers
DISTINCT ON (customer_id)519.7 ms2,007,520
row_number() ... WHERE rn = 1522.1 ms2,007,520
LATERAL (... ORDER BY created_at DESC LIMIT 1)17.3 ms40,054

The first two walk the whole index. LATERAL jumps into it once per customer.

Using an aggregate twice

Customers whose order total is above 1.1 times the average total. Wall clock, median of 3.

FormTime
subquery written twice0.260 s
CTE referenced twice0.137 s
temp table, ANALYZE, then the query0.137 s

A CTE used twice was materialized (the plan shows CTE Scan), so the grouping ran once, same as the temp table.

Running total

RowsWindow functionCorrelated subquery
5,0000.789 ms529.7 ms
10,0001.558 ms2,145.5 ms

The correlated subquery is the median of 2. Doubling the rows made it about four times slower.

Hash or sort for GROUP BY

2,000,000 rows.

GroupsPlanner's choice (hash)Hash turned off (sort)
1,00097.4 ms176.9 ms
1,000,000298.6 ms209.2 ms
1,000,000, work_mem 64MB262.5 ms216.0 ms

With a million groups the planner still picked hashing, and it was the slower plan.

LIKE, regex and ILIKE

1,000,000 strings made of two md5 hashes with a word between them, 109.3 MB. 10,000 contain Needle. All forms returned 10,000.

ConditionTime
LIKE '%Needle%'56.6 ms
~ 'Needle'176.0 ms
~ '^[0-9a-f]{32} Needle'1,171.9 ms
lower(s) LIKE '%needle%'117.8 ms
ILIKE '%needle%'134.0 ms
~* 'needle'177.0 ms

Sorting under a linguistic collation

1,000,000 strings sorted in memory (work_mem 256MB, quicksort). COLLATE "C": 162.3 ms. COLLATE "en_US.UTF-8" (the macOS libc locale): 3,411.8 ms. This build has no ICU collations, so I didn't test ICU.

Smaller ones

Arrays. 200,000 items with about 5 tags each out of 1,000. An int[] column with GIN (24.8 MB table plus 2.7 MB index) against a join table with a primary key (67.9 MB). For one tag (992 items): GIN 0.155 ms, join with EXISTS 0.411 ms, no index 9.406 ms. For items with two given tags: GIN 0.032 ms, join with GROUP BY ... HAVING 0.228 ms.

string_agg 52.3 ms, array_agg of the text 53.1 ms, array_agg of an int 53.2 ms, for 1,000,000 rows into 10,000 groups. No difference.

A million integers: generate_series 62.5 ms, a recursive CTE 128.8 ms.

An IN list against a 1,000,000-row primary key. With 10,000 values, planning took 0.813 ms and execution 4.831 ms. = ANY('{...}'::int[]) with the same values: 0.564 ms and 4.652 ms. At 1,000 values both executed in under half a millisecond.

Files