This New Postgres Feature Is Incredibly Powerful
Postgres 19 gets graph queries, atomic ON CONFLICT DO SELECT, and built-in REPACK. We break down what's changing and how to use the new features.
Postgres 19 will include built-in support for graph queries. The release also includes several features that simplify working with data and table maintenance. The key changes are reviewed below.
ON CONFLICT DO SELECT
Often you need to insert a row only if it doesn't already exist, and in either case get that row as the result. Before Postgres 19, this required two queries: INSERT and SELECT.
The ON CONFLICT ... DO NOTHING RETURNING * construct does not return a row if it already exists. Therefore, an additional SELECT is required. Such a pair of queries is not atomic.
In Postgres 19, the same task is solved with a single query:
INSERT INTO users (email, name) ...with theON CONFLICT (email) DO SELECT RETURNING *construct returns the existing row if a conflict occurred, or the inserted row.- If the row needs to be modified in the same query,
ON CONFLICT (email) DO SELECT ... FOR UPDATE RETURNING id, nameis used.
Since the operation is performed by a single statement, it is atomic. The row is either inserted or selected.
Graph Queries
Graph queries make it possible to describe relationships between tables without long chains of JOINs. To do this, you first create a graph.
Creating a Graph
The CREATE PROPERTY GRAPH command sets the graph's name, for example my_shop, and describes its structure:
- Vertex tables are tables that store data:
customers,orders,products. - Edge tables are tables that define relationships between vertices:
customer_ordersandorder_items.
For each edge, a source and a destination are specified. For customer_orders, the source is customers and the destination is orders. For order_items, the source is orders and the destination is products.
A graph does not create new tables. It works on top of existing tables, like a view. The current schema remains unchanged, and graph queries are added as an additional layer.
Example
Suppose you need to find all products ordered by the customer Alice. In SQL, this requires a query with four JOIN operators across five tables. The result of such a query is a mechanical keyboard and an ergonomic mouse.
In graph syntax, the same result is obtained by following a chain of transitions:
The query follows the chain: from customers to their orders, from orders to order items, and from order items to products. The results match those of the SQL query. If you need to output several columns, they are specified separately at the end of the query.
Neo4j Comparison
Graph queries in Postgres do not replace specialized graph databases such as Neo4j when graph-native storage and high-performance graph traversal are required. In that case, the choice still belongs to a specialized DBMS.
Built-in graph queries are useful when the main problem is complex joins across several tables. For such tasks, the syntax becomes noticeably more compact and easier to understand.
REPACK
Postgres не обновляет строку на месте. Он записывает новую версию строки, а старую оставляет. Команда VACUUM помечает место от старых версий как пригодное для повторного использования, но не возвращает его операционной системе. Поэтому размер файлов таблицы не уменьшается.
Команда REPACK перезаписывает всю таблицу в новый файл без свободного места. Это освобождает место на диске.
Ранее для этого использовали VACUUM FULL, но он блокирует таблицу на время перезаписи. Для больших таблиц это делало операцию практически неприменимой. Поэтому многие пользователи применяли расширение pg_repack. В Postgres 19 аналогичная функциональность встроена в ядро.
Ключевое слово CONCURRENTLY сохраняет возможность чтения и записи в таблицу во время выполнения REPACK.
Для операции требуется свободное место на диске, достаточное для второй копии таблицы и всех её индексов.
Для обычных таблиц REPACK заменяет pg_repack без установки расширения. Полной замены pg_repack для всех сценариев он не является.
Other Changes
- Planner hints (PG plan advice). Postgres chooses the query execution plan, and this choice can change over time. A query that ran fast for a year may slow down without any changes to the code. The new PG plan advice module lets you fix the plan while the query still runs fast and keep it.
- JIT disabled by default. JIT compilation translates heavy queries into machine code. The decision to apply it was based on the planner's cost estimate. According to the release notes, that estimate was unreliable, and JIT was enabled for queries that did not need it.
- Parallel index vacuuming. The
VACUUMcommand can clean indexes using several parallel processes. To enable this, the parameter must be set manually. This reduces the cleanup time for large tables. - Grouping by columns. If a column that is functionally dependent on the primary key is added to
SELECT, it does not need to be added toGROUP BY. Postgres performs this check automatically. - Export to JSON. The
COPYcommand can export data directly to JSON format. Converting from CSV is no longer required.
Release Status
The beta version of Postgres 19 (Beta 2) was released in July. The final release is expected in September or October. Users of older versions are advised to download the beta and test their applications on it in advance.
ON CONFLICT DO SELECT
PostgreSQL 19 introduces the `ON CONFLICT DO SELECT` construct, which allows inserting a row or retrieving an already existing one with a single atomic query.
- Previously two queries were required: an INSERT with
ON CONFLICT ... DO NOTHING RETURNING *and then a SELECT, and this was not atomic - In PG 19 one query is enough:
INSERT INTO users (email, name) VALUES ... ON CONFLICT (email) DO SELECT RETURNING * - To modify a row, you can use
ON CONFLICT (email) DO SELECT FOR UPDATE RETURNING id, name - The query executes atomically: the row is either inserted or selected
Graph Queries (Property Graph)
The graph syntax of PG 19 simplifies complex multi-table joins: a chain of JOINs is replaced by an intuitive path through the graph. The graph does not create new tables; it is overlaid on the existing schema, much like a view.
- Example: find all products ordered by the user Alice; the regular query contains four JOINs, while the graph query replaces them with a single path
- Graph path: customers → customer_orders → orders → order_items → products
- The results match: Alice ordered a mechanical keyboard and an ergonomic mouse
- Multiple columns can be selected by specifying COLUMNS at the end of the graph query
- The graph is created with the command
CREATE PROPERTY GRAPH my_shop, in which the vertices (VERTEX TABLES) are customers, orders, and products, and the edges (EDGE TABLES) are customer_orders and order_items - For customer_orders the source is customers and the destination is orders; for order_items the source is orders and the destination is products
- The schema remains unchanged; the graph only describes the relationships between already existing tables
Graphs vs. Neo4j
The graph capabilities of PG 19 are convenient for queries with many JOINs, but they do not replace specialized graph databases like Neo4j when graph storage and high traversal performance are needed.
- A specialized graph database remains the best choice if graph storage and traversal performance are required
- PG's graph syntax is useful when writing many joins in SQL becomes cumbersome
REPACK
The `REPACK` command rebuilds a table into a new file without wasted space, returning disk space to the operating system. The `CONCURRENTLY` keyword allows working with the table during the rebuild.
- Postgres does not update rows in place: a new version is created, and the old one remains as "dead" space
- VACUUM marks dead space as reusable, but does not return it to the OS
VACUUM FULLalso returns space, but locks the table for the duration of the rewrite- The pg_repack extension used to solve this problem; now the functionality is built into Postgres
- The
CONCURRENTLYkeyword keeps the table available for reading and writing during operation - Free space is required for a second copy of the table and all of its indexes
Other PostgreSQL 19 Features
Brief overview of other PG 19 innovations: planner hints, JIT disabled by default, parallel index cleanup, automatic grouping, and COPY export to JSON.
- The new PG plan advice module allows locking in a query execution plan while it is still fast
- JIT is disabled by default: the planner's cost estimates proved unreliable and triggered unnecessary compilation
- VACUUM can clean up indexes using multiple parallel workers; it must be enabled manually
- Postgres automatically adds columns listed in SELECT to the GROUP BY clause
- The COPY command can export data directly to JSON
Release and Testing
Beta 2 was released in July, and the final release is expected in September or October. It is recommended to test the beta now if you are using an older version.
- Beta 2 was released in July
- The final release is expected around September or October
- It is recommended to download the beta and test current applications on it
- An article about PG durable is mentioned, which places durable workflows inside Postgres
