What Changes for SQL in PostgreSQL 19
Postgres 19.0 was released on November 19. Two articles covered the beta here in September, Getting Ready for PostgreSQL 19 and Plan Advice in PostgreSQL 19. Before updating The Art of PostgreSQL for 19, we ran the queries it teaches on 19.0 and on 18.6, and read the final release notes against them. This article is what we found, limited to what Postgres 19 changes: 7 headline features withdrawn before the release, 11 changes that reach SQL you already wrote, about 20 new features, and an 8-step checklist for the upgrade.
The release-day posts mostly lead with REPACK, plan advice and ON CONFLICT DO SELECT. For SQL that already exists, the change with the most
consequences is quieter: the planner now reads your NOT NULL constraints
and rewrites queries with them.
What made it into 19.0
Seven headline features were withdrawn between the first beta and the
release, along with smaller changes such as fast defaults for domains with
constraints and more object types inside CREATE SCHEMA.
| Feature | Withdrawn |
|---|---|
Non-text output formats for pg_dumpall | June 18 |
GROUP BY ALL | July 17 |
ALTER TABLE … MERGE/SPLIT PARTITION(S) | August 27 |
| SQL/PGQ property graphs | September 7 |
pg_get_role_ddl() and its siblings | September 13 |
UPDATE/DELETE … FOR PORTION OF | September 15 |
| Online enabling and disabling of data checksums | September 16 |
The September article covered four of them, with the reasons for each
one. A course of The Art of PostgreSQL had also previewed FOR PORTION OF,
written against a beta.
In 19.0 a temporal update is still a delete and re-insert of the pieces
left over, and the new range_minus_multi() computes those pieces:
select range_minus_multi(
daterange('2014-01-01', '2021-01-01'),
daterange('2017-01-01', '2020-01-01')
);
range_minus_multi
-------------------------
[2014-01-01,2017-01-01)
[2020-01-01,2021-01-01)
It’s a function rather than an operator because an operator returns one
value. Range subtraction with - must return a single range, so it fails
as soon as the result would be two pieces:
select daterange('2014-01-01', '2021-01-01')
- daterange('2017-01-01', '2020-01-01');
ERROR: result of range difference would not be contiguous
range_minus_multi() returns a set instead: no row when nothing is left,
one row, or two when the second range splits the first. It was added for
FOR PORTION OF, to compute the leftover history to re-insert, and it
stayed in 19 after the revert.
Multiranges, available since 14, hold several pieces in one value, so -
on them never fails, and unnest() turns the result into rows. On 18, this
gives the same two rows as range_minus_multi() on 19:
select unnest(datemultirange(daterange('2014-01-01', '2021-01-01'))
- datemultirange(daterange('2017-01-01', '2020-01-01')));
unnest
-------------------------
[2014-01-01,2017-01-01)
[2020-01-01,2021-01-01)
If you tried 19 during the beta, or read about it then, the September
article here included, check each feature against the 19.0 release notes
before relying on it. A script written on a beta with GROUP BY ALL,
FOR PORTION OF or MERGE PARTITIONS fails on 19.0 with a syntax
error.
What changes in SQL you already wrote
NOT IN becomes an anti join
The usual advice, The Art of PostgreSQL included, warns against NOT IN
with a subquery.
The first reason holds in 19: if the subquery returns a single NULL, x NOT IN (…) is never true, and the query quietly returns nothing. The second
reason was about plans: prefer NOT EXISTS, because that’s the form the
planner can run as a hash anti join.
That second reason changed in 19. When the planner can prove that neither
side contains a NULL, it now converts NOT IN into an anti join too.
Here’s the same query on both versions. Both driverid columns are declared
NOT NULL:
explain (costs off)
select surname
from f1db.drivers d
where driverid not in (select driverid
from f1db.results r
where r.position = 1);
On 18.6:
QUERY PLAN
------------------------------------------------------------
Seq Scan on drivers d
Filter: (NOT (ANY (driverid = (hashed SubPlan 1).col1)))
SubPlan 1
-> Seq Scan on results r
Filter: ("position" = 1)
On 19.0:
QUERY PLAN
----------------------------------------
Hash Right Anti Join
Hash Cond: (r.driverid = d.driverid)
-> Seq Scan on results r
Filter: ("position" = 1)
-> Hash
-> Seq Scan on drivers d
Right means the hash is built on the side whose rows the join returns:
the planner hashes the 864 drivers, scans the 1,119 race winners against
that hash, and returns the drivers left without a match. That’s the
cheaper way round here, and Postgres has had this join type since 16.
The proof comes from the schema. drivers.number is nullable, and a NOT IN
over it keeps the hashed SubPlan on 19:
explain (costs off)
select surname
from f1db.drivers d
where number not in (select number from f1db.results);
QUERY PLAN
--------------------------------------------------------------
Seq Scan on drivers d
Filter: (NOT (ANY (number = (hashed SubPlan any_1).col1)))
SubPlan any_1
-> Seq Scan on results
It has to be a real NOT NULL constraint. We tried with two otherwise
identical tables: on the one whose column has check (id is not null), the
NOT IN stays a hashed SubPlan. On the one whose column is declared not null, it becomes a Hash Anti Join.
The same reasoning now applies to an outer join used as an anti join. When
the IS NULL test is on the join key, 18 already plans an anti join. In 19,
the test can be on any column the schema declares NOT NULL:
explain (costs off)
select d.surname
from f1db.drivers d
left join f1db.results r
on r.driverid = d.driverid
and r.position = 1
where r.resultid is null;
18.6 joins every row and filters afterwards:
QUERY PLAN
----------------------------------------
Hash Right Join
Hash Cond: (r.driverid = d.driverid)
Filter: (r.resultid IS NULL)
-> Seq Scan on results r
Filter: ("position" = 1)
-> Hash
-> Seq Scan on drivers d
19.0 knows that resultid can only be NULL when no row matched, and
gives the same plan as the NOT IN query, since both now ask the same
question:
QUERY PLAN
----------------------------------------
Hash Right Anti Join
Hash Cond: (r.driverid = d.driverid)
-> Seq Scan on results r
Filter: ("position" = 1)
-> Hash
-> Seq Scan on drivers d
The advice stays, with a new reason next to it. Prefer NOT EXISTS because
it means the same thing with or without NULLs, and declare NOT NULL
wherever it’s true, because the planner now uses it. Those two conversions
are part of a series of changes in 19 that all read nullability:
IS DISTINCT FROMbecomes plain=on non-nullable inputs.x IS NOT DISTINCT FROM NULLbecomesx IS NULL.COALESCE()stops at its first non-nullable argument.IS TRUEandIS FALSEon a non-nullable input become plain boolean tests.
So the way a column becomes NOT NULL now matters. A common recipe for a
large table adds CHECK (col IS NOT NULL) NOT VALID and then runs
VALIDATE CONSTRAINT, which avoids a long lock. The result is a validated
CHECK, while the catalog still records the column as nullable, and the
catalog is what these rewrites read. Since 18, ALTER TABLE … ADD CONSTRAINT … NOT NULL col NOT VALID, followed by a VALIDATE in its own transaction,
gives the same short lock and a real NOT NULL constraint.
Eager aggregation
The classic advice for reports is “aggregate, then join”: when you sum
points per constructor, sum them per constructorid first and join the
names afterwards. In 19 the planner can do that by itself, and
enable_eager_aggregate is on by default:
explain (costs off)
select c.name, sum(r.points)
from f1db.results r
join f1db.constructors c using (constructorid)
group by c.name;
On 18.6, all 26,576 results go through the join before the aggregate:
QUERY PLAN
--------------------------------------------------------
HashAggregate
Group Key: c.name
-> Hash Join
Hash Cond: (r.constructorid = c.constructorid)
-> Seq Scan on results r
-> Hash
-> Seq Scan on constructors c
On 19.0, a Partial HashAggregate reduces them to one row per constructor
below the join, and a Finalize step merges the groups that share a name:
QUERY PLAN
--------------------------------------------------------------
Finalize GroupAggregate
Group Key: c.name
-> Sort
Sort Key: c.name
-> Hash Join
Hash Cond: (r.constructorid = c.constructorid)
-> Partial HashAggregate
Group Key: r.constructorid
-> Seq Scan on results r
-> Hash
-> Seq Scan on constructors c
Partial and Finalize nodes used to come with parallel query. They now show up in a plan with no parallel workers. Aggregating before the join by hand still matters: when a join multiplies rows and would count some of them twice, aggregating first changes the result, and the planner keeps the result of your query as written.
Built-in functions can shadow yours
19 adds random(timestamptz, timestamptz), along with versions for date
and timestamp. A function with that name is a classic test-data helper,
and the book defines one in public. Built-in functions live in
pg_catalog, which is searched first unless the search_path says
otherwise, so after the upgrade the same call runs a different function.
On 18.6, the call is inlined from the book’s SQL helper:
explain (verbose, costs off)
select random(timestamptz '2017-01-01', timestamptz '2017-12-31');
Result
Output: ('2017-01-01 00:00:00+00'::timestamp with time zone + ((random(0, 31449600))::double precision * '00:00:01'::interval))
On 19.0, with the same helper installed:
Result
Output: random('2017-01-01 00:00:00+00'::timestamp with time zone, '2017-12-31 00:00:00+00'::timestamp with time zone)
Nothing errors, and the helper’s body stops running. The same happened in
17 with random(int, int). This query lists your functions that a built-in
with the same name and argument types now takes over:
select p.oid::regprocedure as shadowed
from pg_proc p
where p.pronamespace not in ('pg_catalog'::regnamespace,
'information_schema'::regnamespace)
and exists (select 1
from pg_proc c
where c.pronamespace = 'pg_catalog'::regnamespace
and c.proname = p.proname
and c.proargtypes = p.proargtypes)
order by 1;
shadowed
------------------------------------------------------------------
public.random(timestamp with time zone,timestamp with time zone)
public.random(integer,integer)
Run it on a 19 server where your schema is already loaded, such as a restored copy or a test upgrade.
Full-text search and pg_trgm after an upgrade
Two changes in 19 affect indexes and stored values built on an earlier version:
- Character classification follows the database’s collation provider.
The databases concerned use ICU or builtin, with a locale that classifies
characters differently from the database’s
LC_CTYPE, aLC_CTYPEofCin particular. Afterpg_upgrade, the release notes recommend reindexing the full-text andpg_trgmindexes and recomputing any storedtsvector. The builtinC.UTF-8provider, often recommended for a stable sort order, is one of the configurations this is about. - The Snowball stemmers were updated. Dutch moved to a different
algorithm (the previous one is kept as
dutch_porter). English, French, German, Spanish and others now produce different stems for some words. Atsvectorstored before the upgrade keeps the old stems, whileto_tsquery()produces the new ones, so searches for those words can miss rows. The same goes for an index on ato_tsvector()expression. This follows from how storedtsvectorvalues work, and the release notes leave it implicit.
This continues a change from 18, where full-text search started reading its
configuration files and dictionaries with the cluster’s collation provider.
The July round-up
described that 18 step as a pg_trgm lower-casing change; the 18 release
notes limit it to ICU and builtin clusters.
Smaller changes
json_array()over an empty query returns[]. It used to returnNULL. No driver in the Lab’s data is from Mars:select json_array(select code from f1db.drivers where nationality = 'Martian' order by code) as codes;On 18.6:
codes -------On 19.0:
codes ------- []To get the 19 behaviour on 18 already, and keep it through the upgrade, wrap the call in
coalesce():select coalesce(json_array(select code from f1db.drivers where nationality = 'Martian' order by code), json '[]') as codes;This returns
[]on both 18.6 and 19.0, and the same array asjson_array()when the query finds rows. Once every server runs 19, the plainjson_array()call does the same.JIT is off by default. The planner used to switch it on from cost estimates, and on queries that run fast anyway, compiling could take longer than the query itself. A few more rows in a table were enough to cross
jit_above_costand make a query suddenly slower. Servers that kept the default lose that performance cliff. Reporting workloads that gained from JIT now turn it on where they run, for the reporting role in the database it queries, next to the other settings that role usually gets:alter role reporting in database f1db set jit = on; alter role reporting in database f1db set work_mem = '256MB'; alter role reporting in database f1db set max_parallel_workers_per_gather = 4; alter role reporting in database f1db set statement_timeout = '1h'; alter role reporting in database f1db set lock_timeout = '5s';That’s more memory for sorts and hashes, more parallel workers, room for hour-long queries, and a quick exit when a lock is in the way.
work_memapplies to each sort or hash node in each parallel worker, so size it with the number of concurrent reporting sessions in mind. The same role keeps the server defaults in other databases, new sessions pick the settings up, and psql’s\drdslists them.Subplans have new names. SubPlans and InitPlans are now named after what they compute. On the same query, with a scalar subquery, a
NOT IN, anEXISTSand anInitPlan, 18 printsSubPlan 1,SubPlan 2,SubPlan 4andInitPlan 5, and 19 printsSubPlan expr_1,SubPlan any_1,SubPlan exists_to_any_1andInitPlan expr_2. Scripts and tools that readEXPLAINtext should expect the new names. sqlfmt, which I maintain, handles them: its parser takes any name afterSubPlan,InitPlanorCTE, andsqlfmt explain diffbetween the 18 and 19 plans of that query reports the structure unchanged.standard_conforming_stringsis locked toon. The default has beenonsince 9.1, fifteen years ago, and 19 retires the legacy syntax where a backslash escapes characters inside a plain'…'literal. The parameter stays, because client libraries read it and dump scripts set it, butset standard_conforming_strings = offnow fails withERROR: non-standard string literals are not supported. Backslash escapes keep working inE'…'strings, andescape_string_warningis gone. A dump taken with a pre-19pg_dumpfrom a server running with the settingoffwon’t load into 19; 19’spg_dumpsets itonin its own session and produces a dump that loads.log_lock_waitsis on by default, so lock waits longer thandeadlock_timeoutreach the server log.
What 19 adds
Window functions that skip NULLs
lag(), lead(), first_value(), last_value() and nth_value() accept
IGNORE NULLS. Carrying the last known value forward, a step in many
gaps-and-islands queries, now fits in a single window call. Here is the
query from Kimi Räikkönen’s 2017 season, where he did not finish the
Spanish Grand Prix, leaving a NULL finishing position for that round:
select races.round,
races.name,
results.position as finish,
lag(results.position) over(order by races.round) as prev_plain,
lag(results.position) ignore nulls over(
order by races.round
) as prev_ignore_nulls
from f1db.results
join f1db.races using(raceid)
join f1db.drivers using(driverid)
where drivers.surname = 'Räikkönen'
and extract(year from races.date) = 2017
order by races.round
limit 8;
Read Getting Ready for PostgreSQL 19 for the result and how the two columns differ after that round.
Get-or-create in one statement
INSERT … ON CONFLICT DO SELECT … RETURNING returns the row that already
exists, optionally locked FOR UPDATE or FOR SHARE. Until 19,
get-or-create took either DO NOTHING and a second SELECT, or a no-op DO UPDATE that writes a new row version. The new pg_stat_lock view
completes the picture with per-lock-type statistics.
A whole model in one CREATE SCHEMA
CREATE SCHEMA can create its tables in the same statement, and since 19 a
foreign key can reference a table that appears later in that statement:
create schema demo_fk
create table race
(
raceid bigint primary key,
circuitid bigint references circuit
)
create table circuit
(
circuitid bigint primary key,
name text
);
18.6 stops at the first table with ERROR: relation "circuit" does not exist, and 19.0 creates both. A model written as a single script can list
its tables in any order with respect to their foreign keys. Only foreign
keys get this treatment: a view or an index still has to come after the
table it uses, as the CREATE SCHEMA documentation says.
COPY
COPY gains three things in 19. on_error set_null loads the row and puts
a NULL in each field that doesn’t parse, where on_error ignore (since
17) skips the whole row:
create temp table t_import (id int, points numeric, label text);
copy t_import from stdin (format csv, on_error set_null);
1,10.5,ok
2,DNF,bad points
three,3,bad id
\.
table t_import;
NOTICE: in 2 rows, columns were set to null due to data type incompatibility
id | points | label
----+--------+------------
1 | 10.5 | ok
2 | | bad points
| 3 | bad id
HEADER now takes a number, to skip several header lines. And COPY TO
writes JSON, one object per line, or one array with force_array:
copy (select driverid, code, surname
from f1db.drivers
order by driverid
limit 3)
to stdout (format json, force_array);
[
{"driverid":1,"code":"HAM","surname":"Hamilton"}
,{"driverid":2,"code":"HEI","surname":"Heidfeld"}
,{"driverid":3,"code":"ROS","surname":"Rosberg"}
]
Case-insensitive JSON lookups with an index
19 adds string methods to jsonpath: lower(), upper(), initcap(),
ltrim(), rtrim(), btrim(), replace() and split_part(). They are
immutable, like the SQL functions they call, so a jsonpath expression that
uses them can go in an index. The Lab’s magic.cards table holds Magic: The
Gathering cards as jsonb, with arrays such as subtypes. Here’s a
case-insensitive index over them:
create index cards_subtypes_lower
on magic.cards
using gin ((jsonb_path_query_array(data, '$.subtypes[*].lower()')));
18.6 rejects the path before it gets to the index:
ERROR: syntax error at or near "(" of jsonpath input
On 19.0 the index builds, and a query that repeats the expression uses it:
explain (costs off)
select data->>'name' as name
from magic.cards
where jsonb_path_query_array(data, '$.subtypes[*].lower()') @> '["cleric"]';
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on cards
Recheck Cond: (jsonb_path_query_array(data, '$."subtypes"[*].lower()'::jsonpath, '{}'::jsonb, false) @> '["cleric"]'::jsonb)
-> Bitmap Index Scan on cards_subtypes_lower
Index Cond: (jsonb_path_query_array(data, '$."subtypes"[*].lower()'::jsonpath, '{}'::jsonb, false) @> '["cleric"]'::jsonb)
The query finds 534 of the 34,207 cards. On 18, lowercasing every element of a JSON array inside an index takes a helper function of your own, declared immutable.
Keeping a good plan
The plan advice article
covers pg_plan_advice and pg_stash_advice. Other 19 changes answer
neighbouring questions:
- pg_stat_statements counts generic and custom plans separately, in
generic_plan_callsandcustom_plan_calls. When one prepared statement has two plans and only one of them is slow, these counts are the first clue. - Extended statistics can travel with a dump.
pg_dump --statisticsnow includes them, reading them from servers as old as 10. A plainpg_dumpleaves statistics out:--no-statisticsis the default.pg_upgradeis the other way round: it runspg_dump --statisticsunless told--no-statistics, so an upgrade to 19 carries extended statistics along with the per-column ones.pg_restore_extended_stats()andpg_clear_extended_stats()manage them directly. CREATE STATISTICSaccepts virtual generated columns. A computed column that is never stored can now carry extended statistics, like any other column.EXPLAIN (ANALYZE, IO)reports asynchronous I/O and prefetching on sequential, bitmap heap and TID range scans. A Memoize node now prints the planner’s estimates, cache capacity and expected hit ratio included, so you can compare them with the actual hits.
And the rest, briefly
REPACKunifiesVACUUM FULLandCLUSTER, which stay available for compatibility.REPACK (CONCURRENTLY)comes with its restrictions:- it needs a primary key or a replica identity;
- it isn’t MVCC-safe;
- it takes a short exclusive lock at the end.
- Constraints:
ALTER CONSTRAINT … [NOT] ENFORCEDnow works onCHECKconstraints. - SQL/JSON:
IS JSONnow works on domains. - Replication:
WAIT FOR LSNgives read-your-writes on a standby. In 19.0 it can hang when the target LSN falls on a WAL page boundary. The fix is in the 19 branch for 19.1, and until then aTIMEOUTis a good idea.- With
wal_level = replica, logical replication can start without a server restart. - Subscriptions can synchronize sequence values from the publisher.
- psql:
\pset display_trueand\pset display_falsechange how booleans print, and%Sputs thesearch_pathin the prompt.
What we find most interesting
The schema as planner input. Postgres has read constraints for a long
time. Since 9.0 it removes a LEFT JOIN to a unique key that the query
never reads. Since 9.1 a GROUP BY on a primary key lets the select list
use the table’s other columns, and The Art of PostgreSQL has its readers
fix the Chinook primary key first, “as PostgreSQL implements group by
inference”. Since 9.6 foreign keys inform join size estimates. The 2019
talk Data Modeling, Normalization and
Denormalization
has a slide titled “Constraints are Guarantees”, and quotes Fred Brooks:
“Show me your tables, and I won’t usually need your flowcharts.” Postgres
19 adds nullability to the list. Most of the planner work in this release
reads it, and a column declared NOT NULL now changes plans, while a
CHECK that says the same thing leaves them as they were. When someone
asks whether a constraint is worth the trouble, there is now one more plan
to show them.
Plan stability as a set of tools. Plan advice gets the attention, but 19 also counts generic and custom plans, can carry extended statistics through a dump, and allows statistics on virtual columns. Together they answer “why did this query change plan, and how do I keep the good one” better than any single feature has before.
A release that shipped late on purpose. Seven features came out after
the first beta, and the release landed in November rather than the usual
September or October. The reverts covered in September came from design problems
found during the beta, and the project held those features back rather than
ship them with a documented limitation. MERGE PARTITIONS has now been
pulled late in two cycles, 17 and 19. Engineers decide what goes into a
Postgres release, so pulling a feature a month before it ships stays an
option, one that is much harder to take with a date promised to a market.
A personal note. 19 also adds event triggers written in PL/Python. I wrote event triggers in the first place, for 9.3, and in September 2013 I proposed the patches to support them in PL/Tcl, PL/Perl and PL/Python. PL/Tcl and PL/Perl made it into 9.4. The PL/Python patch failed its regression tests and was never finished. In July 2025, Euler Taveira picked it up from that thread, and the commit lists me as co-author, twelve years later.
Before you upgrade
Everything above that can change what an existing application sees, as a checklist:
- Constraints: list the columns whose
NOT NULLlives in aCHECK, and turn the ones the planner should know about intoNOT NULLconstraints. - Functions: run the shadowing query on a restored copy. Drop each function it lists to use the built-in, or rename it to keep calling yours.
- Text search: recompute stored
tsvectorvalues and rebuild full-text indexes to pick up the new stems. On the ICU and builtin databases described above, rebuild thepg_trgmindexes too. - Plans: compare the plans of your important queries, for anti joins
and eager aggregation, and set
jit = onfor the databases or roles that run large analytical queries. - Output: check code that reads
json_array()over a query that can return no rows, and tools that parseEXPLAINsubplan names. - Strings: find the applications and scripts that set
standard_conforming_stringsorescape_string_warning, take dumps with 19’spg_dump, and move backslash escapes toE'…'strings. - Statistics: after
pg_upgrade, the planner statistics are in place, extended ones included. The activity counters that trigger autovacuum start over, and thepg_upgradedocumentation recommendsvacuumdb --all --analyze-onlyto refresh them. After a dump and restore, use 19’spg_dump --statistics, or runANALYZE. - Replicas: give
WAIT FOR LSNaTIMEOUTuntil 19.1.
Second Edition, Updated (2026)
PostgreSQL 10 through 18, a new pgvector chapter, 56 new figures, and a free practice lab.
See what's new →