NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

PostgreSQL 19: 7 new SQL features you can use today

Get-or-create with ON CONFLICT DO SELECT, JSON from COPY, IGNORE NULLS, faster NOT IN and REPACK, each with SQL and real output from PostgreSQL 19.0.

Updated Nov 23, 202610 min readIntermediatepostgres 19.0

PostgreSQL 19 came out on November 19, 2026. The release announcement covers a lot of ground, much of it for DBAs and replication setups. This guide covers the seven changes that affect the SQL you write every day. Each one has a query you can paste into psql, along with the real output it produced on PostgreSQL 19.0.

You need a PostgreSQL 19 server. Get one from the official downloads page, then check the version:

sql
SELECT version();
text
 PostgreSQL 19.0 on aarch64-apple-darwin24.6.0, compiled by Apple clang version 17.0.0 (clang-1700.6.4.2), 64-bit

1. Get-or-create with ON CONFLICT DO SELECT

"Insert this tag, or give me the existing one" is one of the most common patterns in application code. Until now, Postgres had no clean way to do it in one statement. ON CONFLICT DO NOTHING skips the conflicting row, so RETURNING gives you nothing back, and you need a second query.

PostgreSQL 19 adds DO SELECT, which returns the row that caused the conflict:

get-or-create.sql
CREATE TABLE tags (
  id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text NOT NULL UNIQUE
);
INSERT INTO tags (name) VALUES ('postgres');

-- Before: DO NOTHING returns no row when the tag exists
INSERT INTO tags (name) VALUES ('postgres')
ON CONFLICT (name) DO NOTHING
RETURNING id, name;

-- PostgreSQL 19: DO SELECT returns the existing row
INSERT INTO tags (name) VALUES ('postgres'), ('sql')
ON CONFLICT (name) DO SELECT
RETURNING id, name, old.id IS NULL AS created;
text
 id | name
----+------
(0 rows)

INSERT 0 0
 id |   name   | created
----+----------+---------
  1 | postgres | f
  4 | sql      | t
(2 rows)

INSERT 0 2

You get one row back for every input row, whether it was inserted or already there. old.id IS NULL tells you which case happened. On the DO SELECT path, old holds the existing row. For a fresh insert, old is null. The old and new aliases in RETURNING arrived in Postgres 18.

The common workaround used to be a no-op DO UPDATE. That returns a row, but it really is an update. It writes a new row version, fires update triggers and leaves a dead tuple for vacuum to clean up. The changed xmin (the ID of the transaction that wrote the row) shows it:

sql
SELECT xmin, id FROM tags WHERE name = 'postgres';

-- The old workaround: a no-op update so RETURNING has a row
INSERT INTO tags (name) VALUES ('postgres')
ON CONFLICT (name) DO UPDATE SET name = excluded.name
RETURNING xmin, id;

-- DO SELECT leaves the row alone
INSERT INTO tags (name) VALUES ('postgres')
ON CONFLICT (name) DO SELECT
RETURNING xmin, id;
text
 xmin | id
------+----
  699 |  1

 xmin | id
------+----
  701 |  1

 xmin | id
------+----
  701 |  1

Two details to know. First, RETURNING is required with DO SELECT, and so is a conflict target such as (name). Second, look at the id of sql in the first example: it's 4, not 2. Each attempted insert still takes the next identity value, even when it ends in a conflict. That has always been true for ON CONFLICT, and it matters more now that get-or-create calls are this cheap to make. If you need to lock the existing row, use DO SELECT FOR UPDATE. See the INSERT docs.

2. Export JSON straight from COPY

COPY TO now has a json format. By default it writes one JSON object per line (newline-delimited JSON):

sql
COPY (SELECT id, name FROM tags ORDER BY id) TO STDOUT (FORMAT json);

COPY (SELECT id, name FROM tags ORDER BY id) TO STDOUT (FORMAT json, FORCE_ARRAY);
text
{"id":1,"name":"postgres"}
{"id":4,"name":"sql"}
[
 {"id":1,"name":"postgres"}
,{"id":4,"name":"sql"}
]

FORCE_ARRAY wraps the rows in one array, so JSON.parse can read the whole file. From psql, use \copy to write the file on your machine instead of on the server:

terminal
psql -d mydb -c "\copy (SELECT id, name FROM tags ORDER BY id) TO 'tags.json' (FORMAT json, FORCE_ARRAY)"

This replaces the old json_agg and row_to_json workarounds for exports. It's output only: COPY FROM doesn't accept JSON. Also, SQL NULL and a JSON null value both come out as null, so you can't tell them apart in the file. The COPY docs cover the details.

3. Fill gaps with IGNORE NULLS

Sensor data, prices and status logs often have gaps, and you want the last known value. The lead(), lag(), first_value(), last_value() and nth_value() window functions now accept IGNORE NULLS:

sql
CREATE TABLE readings (
  ts   timestamp PRIMARY KEY,
  temp numeric
);
INSERT INTO readings VALUES
  ('2026-11-23 09:00', 21.5),
  ('2026-11-23 09:05', NULL),
  ('2026-11-23 09:10', NULL),
  ('2026-11-23 09:15', 22.1),
  ('2026-11-23 09:20', NULL);

SELECT ts::time AS at,
       temp,
       last_value(temp) IGNORE NULLS OVER (ORDER BY ts) AS last_known,
       lag(temp) IGNORE NULLS OVER (ORDER BY ts)        AS previous
FROM readings
ORDER BY ts;
text
    at    | temp | last_known | previous
----------+------+------------+----------
 09:00:00 | 21.5 |       21.5 |
 09:05:00 |      |       21.5 |     21.5
 09:10:00 |      |       21.5 |     21.5
 09:15:00 | 22.1 |       22.1 |     21.5
 09:20:00 |      |       22.1 |     22.1

Before this, a forward fill needed a running count() to build groups, then a second window over those groups.

4. Clean JSON strings inside jsonpath

The SQL/JSON path language gained string methods: lower(), upper(), initcap(), btrim(), ltrim(), rtrim(), replace() and split_part(). You can normalise a value without pulling it out of the document first:

sql
SELECT jsonb_path_query(doc, '$.email.btrim().lower()')              AS email,
       jsonb_path_query(doc, '$.email.btrim().split_part("@", 2)')   AS domain,
       jsonb_path_query(doc, '$.name.initcap()')                     AS name
FROM (VALUES ('{"email": "  [email protected] ", "name": "ada lovelace"}'::jsonb)) AS t(doc);

SELECT jsonb_path_query_array(
  '{"tags": ["Postgres", "SQL", "postgres-19"]}',
  '$.tags[*] ? (@.lower() starts with "postgres")'
) AS matches;
text
       email       |    domain     |      name
-------------------+---------------+----------------
 "[email protected]" | "Example.COM" | "Ada Lovelace"

           matches
-----------------------------
 ["Postgres", "postgres-19"]

The second query is where this helps most: a case-insensitive filter inside the path, which used to need jsonb_array_elements_text and a subquery. The methods are immutable, so you can use them in expression indexes. See the jsonpath operators.

5. Random dates for seed data

random(min, max) now accepts dates and timestamps, which helps when you generate test fixtures:

sql
SELECT random(date '2026-01-01', date '2026-12-31')    AS signup_day,
       random(timestamp '2026-11-01 00:00',
              timestamp '2026-11-30 23:59')            AS last_seen
FROM generate_series(1, 3);
text
 signup_day |         last_seen
------------+----------------------------
 2026-02-13 | 2026-11-14 19:44:33.846486
 2026-04-01 | 2026-11-12 18:18:07.847322
 2026-06-08 | 2026-11-17 21:32:12.564499

Your values will differ. Call setseed() first if you need the same values on every run. This replaces the old date '2026-01-01' + (random() * 364)::int arithmetic.

6. NOT IN gets an anti-join, if the column is NOT NULL

NOT IN (subquery) has long been a performance trap in Postgres. The usual advice was to rewrite it as NOT EXISTS. PostgreSQL 19 can now plan NOT IN as an anti-join, but only when it can prove that neither side contains NULL:

sql
CREATE TABLE customers (id bigint PRIMARY KEY);
CREATE TABLE orders (
  id          bigint PRIMARY KEY,
  customer_id bigint NOT NULL
);
INSERT INTO customers SELECT generate_series(1, 100000);
INSERT INTO orders SELECT g, g % 50000 + 1 FROM generate_series(1, 200000) g;
ANALYZE customers, orders;

EXPLAIN (COSTS OFF)
SELECT id FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
text
                    QUERY PLAN
--------------------------------------------------
 Hash Right Anti Join
   Hash Cond: (orders.customer_id = customers.id)
   ->  Seq Scan on orders
   ->  Hash
         ->  Seq Scan on customers

Drop the NOT NULL from orders.customer_id and run the same EXPLAIN. Now the plan checks the subquery for each customer, as every earlier version did, even PostgreSQL 14 with the NOT NULL in place:

text
 Gather
   Workers Planned: 2
   ->  Parallel Index Only Scan using customers_pkey on customers
         Filter: (NOT (ANY (id = (SubPlan any_1).col1)))
         SubPlan any_1
           ->  Materialize
                 ->  Seq Scan on orders

The difference is large. On the same data:

sql
\timing on
SELECT count(*) FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);

ALTER TABLE orders ALTER COLUMN customer_id DROP NOT NULL;
SET statement_timeout = '30s';

SELECT count(*) FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
text
 count
-------
 50000
(1 row)

Time: 34.188 ms
ALTER TABLE
SET
ERROR:  canceling statement due to statement timeout
Time: 30077.603 ms (00:30.078)

That's 34 ms with the constraint. Without it, the query still hadn't finished after 30 seconds. The fix is free if your data allows it: declare foreign key columns NOT NULL. NOT EXISTS is still the safer habit, because it gets an anti-join whether the column is nullable or not.

7. REPACK replaces VACUUM FULL and CLUSTER

Tables with many deletes and updates keep their dead space after VACUUM. VACUUM FULL returned that space to the operating system, but it locked the table for the whole rewrite. PostgreSQL 19 adds REPACK, and its CONCURRENTLY option lets reads and writes continue while it runs:

sql
CREATE TABLE events (
  id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  payload text
);
INSERT INTO events (payload)
SELECT repeat('x', 200) FROM generate_series(1, 200000);
DELETE FROM events WHERE id % 10 <> 0;  -- keep 10% of the rows
VACUUM events;

SELECT pg_size_pretty(pg_table_size('events')) AS before;
REPACK (VERBOSE, CONCURRENTLY) events;
SELECT pg_size_pretty(pg_table_size('events')) AS after;
text
 before
--------
 47 MB

INFO:  repacking "public.events" in physical order
INFO:  "public.events": found 0 removable, 20000 nonremovable row versions in 6061 pages
REPACK
  after
---------
 5152 kB

REPACK events USING INDEX events_pkey also sorts the rows by that index, which is what CLUSTER did. Both old commands still work.

The full list of limits is in the REPACK docs.

Before you upgrade

Some changes in 19 can break or slow down existing setups. These matter most to application developers:

  • JIT is now off by default. If you run large analytical queries, test them and set jit = on if they get slower.
  • max_locks_per_transaction now defaults to 128, up from 64, because lock memory is sized differently. If you raised it before, double your old value to keep the same capacity.
  • json_array() over a query with no rows now returns [], not NULL. Check any code that tests the result for null.
  • standard_conforming_strings is always on. Dumps made with an older pg_dump using standard_conforming_strings = off won't load. Create new dumps with the PostgreSQL 19 pg_dump.
  • MD5 password logins now raise a warning after each successful login. You can turn it off with md5_password_warnings, but the better fix is to move to SCRAM before MD5 support is removed.
  • io_workers is gone. New settings replace it, including io_min_workers and io_max_workers, and the I/O worker pool now grows and shrinks between them.

On a fresh 19.0 server:

sql
SHOW jit;
SHOW max_locks_per_transaction;
SELECT json_array(SELECT 1 WHERE false) AS empty;
text
 jit
-----
 off

 max_locks_per_transaction
---------------------------
 128

 empty
-------
 []

The complete list is in the incompatibilities section of the release notes.

Also new, beyond the scope of this guide

These features need a replica or a production workload to show properly:

  • WAIT FOR LSN makes a standby wait until it has replayed a given point in the WAL. You get read-your-writes consistency when reads go to replicas.
  • pg_plan_advice and pg_stash_advice pin query plans, so you can fix a plan that got slower without changing the application.
  • Logical replication no longer needs a restart to change wal_level. Creating the first logical slot raises it automatically. Sequences can now be replicated too.

Next steps

Related tutorials