DEV Community

Cover image for PostgreSQL 19 Dropped SQL/PGQ: GraphRAG on Postgres Today
Bhavik Mehta
Bhavik Mehta

Posted on Originally published at bhavikmehta.dev on

PostgreSQL 19 Dropped SQL/PGQ: GraphRAG on Postgres Today

In July I wrote that PostgreSQL 19 was becoming a graph database. On September 7, 2026, the feature that post was about was reverted, and PostgreSQL 19 shipped on November 19 without it. If you prototyped against the beta's CREATE PROPERTY GRAPH syntax, that code does not run on the release you are upgrading to.

This is the follow-up: what actually happened, why the reasons matter for anyone storing graphs in Postgres, and how I would build GraphRAG on PostgreSQL today with the tools that did ship.

Timeline of SQL/PGQ in PostgreSQL 19: committed March 16, reverted September 7, released without it November 19

Does PostgreSQL 19 Support Graph Queries?

No. PostgreSQL 19 was released on November 19, 2026 without SQL/PGQ. CREATE PROPERTY GRAPH and GRAPH_TABLE were committed in March 2026 and shipped in the betas, then reverted on September 7 after the release team found unresolved design issues. Graph-style queries on PostgreSQL 19 still use recursive CTEs or the Apache AGE extension.

Here is the timeline, because most write-ups you will find online still describe the beta:

Date (2026) Event
March 16 SQL/PGQ committed for PostgreSQL 19
June to August Feature available in the PostgreSQL 19 betas
September 2 Release management team proposes reverting it from 19
September 7 Revert commit 2b9e1aff4d lands, unwinding 47 commits
November 19 PostgreSQL 19 released; release notes contain no SQL/PGQ

The revert commit removed about 15,800 lines across 125 files. That is not a feature flag being turned off; it is the whole implementation coming out of the release branch.

Why SQL/PGQ Was Reverted: The New Findings

The revert commit itself gives no reason, only the list of reverted commits and a link to the discussion. The reasons are in the release management team's message on pgsql-hackers, written by Melanie Plageman on September 2. Three problems are named, and every one of them is a lesson for anyone who stores a graph in relational tables, with or without SQL/PGQ.

Orphaned metadata. Dropping things a property graph depended on could leave label and property definitions behind. The message describes these as showing up as phantom entries in information_schema views. The graph's description of itself drifted away from the tables it described.

Silent breakage. Because of how properties were scoped across labels, a graph query could become silently unqueryable after a property was dropped. Silent is the important word. A loud error at ALTER TABLE time is fine; a query that stops working later is not.

Dependency ordering. A materialized view that queried a GRAPH_TABLE produced a pg_dump dependency loop that was not resolved. A feature that can break your backups cannot ship in a database whose main promise is your data.

The team acknowledged that the ideal fix was out of scope for 19 and that reverting would make it easier to fix properly in 20. Andres Freund went further in the same thread: he agreed it was not ready for 19, reported locking problems in the query rewriter, and wrote that it might not be ready to stay in 20 either.

So do not plan around SQL/PGQ arriving in PostgreSQL 20. The project's roadmap lists PostgreSQL 20 for September 2027, but nobody has committed to the feature being in it.

Note: The common thread in all three problems is that the graph definition's invariants were checked when the graph was created, not maintained as the underlying tables changed. Keep that in mind; it is exactly the failure mode you will rebuild by hand if you are not careful in the design below.

The Mental Model: GraphRAG Is Seed, Expand, Prune

GraphRAG adds relationships to retrieval. Plain vector RAG answers "which chunks look like this question?" It fails on questions whose answer is spread across documents that do not look like the question: "which suppliers of the parts in the delayed order also supply our largest competitor?" No single chunk contains that; the answer is a path.

A GraphRAG retrieval step has three stages:

  1. Seed. Find entry points with hybrid search: pgvector similarity for meaning, Postgres full-text search for exact names, IDs and part numbers.
  2. Expand. From the entities in those seed chunks, walk the knowledge graph one or two hops to pull in related entities and the chunks where those relationships were stated.
  3. Prune. Rank and cut the expanded set down to a context budget the model can use.

Here is the non-obvious part, and the reason losing SQL/PGQ hurts less than it sounds. The expansion in GraphRAG is shallow. You walk one or two hops out from your seeds, because every extra hop multiplies the candidate set and dilutes relevance. Deep, unbounded traversals (shortest paths across millions of nodes, community detection, PageRank) belong to graph analytics, not to retrieval.

Shallow, bounded expansion is what a recursive CTE with a depth cap does well. SQL/PGQ would have made these queries nicer to write: MATCH (a)-[r]->(b) reads better than a self-join. But for this workload it was mostly ergonomics, not capability. Notably, the beta implementation did not support variable-length paths either, so the hop count was going to be fixed and explicit in either syntax.

The Implementation: GraphRAG on PostgreSQL 19

The schema is four tables. I am deliberately modeling them the way CREATE PROPERTY GRAPH would have expected: vertex tables with primary keys, edge tables with foreign keys to both ends. If SQL/PGQ returns, the port is one DDL statement plus query rewrites, not a migration.

CREATE EXTENSION IF NOT EXISTS vector;

-- Source text, split into chunks. The unit of retrieval.
CREATE TABLE chunks (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id  bigint NOT NULL,
  doc_id     bigint NOT NULL,
  content    text   NOT NULL,
  embedding  vector(1536) NOT NULL,
  tsv        tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
);

-- Vertices: resolved entities (people, companies, parts, services).
CREATE TABLE entities (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id  bigint NOT NULL,
  name       text   NOT NULL,
  kind       text   NOT NULL,
  UNIQUE (tenant_id, kind, name)
);

-- Which chunk mentions which entity. Links text to the graph.
CREATE TABLE mentions (
  chunk_id   bigint NOT NULL REFERENCES chunks   ON DELETE CASCADE,
  entity_id  bigint NOT NULL REFERENCES entities ON DELETE CASCADE,
  PRIMARY KEY (chunk_id, entity_id)
);

-- Edges: extracted relationships, each traceable to the chunk that stated it.
CREATE TABLE relations (
  src_id     bigint NOT NULL REFERENCES entities ON DELETE CASCADE,
  dst_id     bigint NOT NULL REFERENCES entities ON DELETE CASCADE,
  rel        text   NOT NULL,
  weight     real   NOT NULL DEFAULT 1.0,
  chunk_id   bigint NOT NULL REFERENCES chunks   ON DELETE CASCADE,
  PRIMARY KEY (src_id, rel, dst_id, chunk_id)
);

CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON chunks USING gin (tsv);
CREATE INDEX ON relations (dst_id);
CREATE INDEX ON mentions (entity_id);
Enter fullscreen mode Exit fullscreen mode

Two design decisions carry most of the weight here.

Every edge has a chunk_id. A relationship without provenance is a claim you cannot cite, and GraphRAG answers you cannot cite are worse than plain RAG answers. Provenance also gives you deletion for free: delete a document and its chunks, and ON DELETE CASCADE removes every relationship that document asserted.

That cascade is the direct answer to the SQL/PGQ revert. The reverted feature checked its invariants at creation time; these foreign keys enforce them on every write. There is no way to end up with an edge pointing at a deleted entity, which is the relational version of the phantom metadata the release team found.

Step 1: Hybrid Seed With Reciprocal Rank Fusion

Vector search alone misses exact identifiers ("part 7841-B"); full-text search alone misses paraphrases. Run both and fuse the rankings with reciprocal rank fusion (RRF), which only needs ranks, so you never have to normalize a cosine distance against a ts_rank score.

BEGIN;
-- Filtered HNSW scans can return fewer rows than LIMIT without this (pgvector 0.8+).
SET LOCAL hnsw.iterative_scan = relaxed_order;

WITH vec AS (
  SELECT id, row_number() OVER () AS r       -- rank = order the index returned
  FROM (
    SELECT id FROM chunks
    WHERE tenant_id = $3
    ORDER BY embedding <=> $1                -- plain ORDER BY + LIMIT keeps the HNSW scan
    LIMIT 40
  ) v
),
fts AS (
  SELECT id, row_number() OVER (ORDER BY rank DESC) AS r
  FROM (
    SELECT id, ts_rank_cd(tsv, q) AS rank
    FROM chunks, websearch_to_tsquery('english', $2) AS q
    WHERE tenant_id = $3 AND tsv @@ q
    ORDER BY rank DESC
    LIMIT 40
  ) f
)
SELECT id, sum(1.0 / (60 + r)) AS rrf
FROM (SELECT * FROM vec UNION ALL SELECT * FROM fts) ranked
GROUP BY id
ORDER BY rrf DESC
LIMIT 8;

COMMIT;
Enter fullscreen mode Exit fullscreen mode

$1 is the question embedding, $2 the raw question text, $3 the tenant. The vector branch ranks rows after the inner ORDER BY ... LIMIT, because wrapping the distance in a window function directly can stop the planner from using the HNSW index at all. The constant 60 is the conventional RRF damping term; it keeps the first rank from dominating. A chunk that ranks well in both lists rises above one that ranks first in only one.

The SET LOCAL line matters more than it looks. The tenant_id filter is applied after the HNSW index produces candidates, so a selective filter can leave you with 3 rows when you asked for 40. Iterative index scans, added in pgvector 0.8.0, keep scanning the index until enough rows pass the filter. They are off by default in the current 0.8.x releases. The changelog for the upcoming pgvector 1.0 says it turns them on by default for HNSW.

Step 2: Bounded Graph Expansion With a Recursive CTE

Take the entities mentioned in the seed chunks and walk outward. Three constraints make this safe: a hard depth cap, cycle detection, and a per-node fan-out limit.

WITH RECURSIVE seeds AS (
  SELECT DISTINCT m.entity_id
  FROM mentions m
  WHERE m.chunk_id = ANY($1::bigint[])        -- seed chunk ids from step 1
),
walk AS (
  SELECT s.entity_id, 0 AS depth, 1.0::real AS score, NULL::bigint AS via_chunk
  FROM seeds s

  UNION ALL

  SELECT nb.dst_id, w.depth + 1, w.score * nb.weight * 0.5, nb.chunk_id
  FROM walk w
  CROSS JOIN LATERAL (
    SELECT r.dst_id, r.weight, r.chunk_id
    FROM relations r
    WHERE r.src_id = w.entity_id
    ORDER BY r.weight DESC
    LIMIT 8                                     -- fan-out cap per node
  ) nb
  WHERE w.depth < 2                             -- hop cap
) CYCLE entity_id SET is_cycle USING path
SELECT entity_id, max(score) AS score, array_agg(DISTINCT via_chunk) AS evidence
FROM walk
WHERE NOT is_cycle
GROUP BY entity_id
ORDER BY score DESC
LIMIT 30;
Enter fullscreen mode Exit fullscreen mode

Line by line, the parts that are not obvious:

  • CROSS JOIN LATERAL ... LIMIT 8 is the fan-out cap. A plain join in the recursive term expands every neighbor of every node; one well-connected entity turns two hops into tens of thousands of rows. The lateral subquery keeps only the strongest edges per node.
  • w.score * nb.weight * 0.5 decays relevance with distance. A hop-two neighbor reached through weak edges scores well below a direct neighbor of a seed.
  • CYCLE entity_id SET is_cycle USING path is standard SQL cycle detection (PostgreSQL 14 and later). Without it, A relates to B relates to A loops until the depth cap stops it, wasting the whole budget on two nodes.
  • array_agg(DISTINCT via_chunk) returns the chunks that asserted each relationship, which become citations in the final answer.

This query walks outgoing edges only. If your relationships are symmetric (partners_with), either store both directions at write time or add a second lateral branch over relations.dst_id, which is why that column has its own index.

Step 3: Prune and Assemble

The final context is the seed chunks plus the evidence chunks from the walk, deduplicated, ordered by score, and cut at a token budget. Keep this step in application code rather than SQL, because the budget depends on the model and the prompt template, and it is the step you will tune most often.

For comparison, this is roughly what the hop-two expansion looked like in the beta SQL/PGQ syntax. It is here only to show the port path; it does not run on the released PostgreSQL 19:

-- Beta-only syntax, reverted before the PostgreSQL 19 release.
SELECT *
FROM GRAPH_TABLE (kg
  MATCH (a IS entity WHERE a.id = 42)-[r1 IS relates]->(b IS entity)
        -[r2 IS relates]->(c IS entity)
  COLUMNS (b.name AS hop1, c.name AS hop2, r2.chunk_id AS evidence)
);
Enter fullscreen mode Exit fullscreen mode

Notice what it does not express: the fan-out cap, the score decay, the cycle handling. Those are retrieval policy, and they live in SQL around the pattern match either way.

If you are wiring this into an agent rather than a fixed pipeline, the same queries can be exposed as parameterized tools; I covered that setup in Google's MCP Toolbox for Databases.

The Failure Modes

Hub entities. Every knowledge graph extracted from real documents has a few entities connected to everything: your company name, "United States", "customer". Expansion through a hub returns noise. The fan-out cap limits the damage, but the better fix is to down-weight edges by the degree of the node they pass through, or exclude a short list of hub entities from expansion entirely.

Fragmented entities. "Postgres", "PostgreSQL" and "postgresql 19" become three vertices unless you resolve them at extraction time. A fragmented graph silently loses paths: the walk reaches "Postgres" and never sees the edges attached to "PostgreSQL". Entity resolution quality caps GraphRAG quality, and no query fixes it later.

Filtered vector search returning too few rows. Covered above, but it deserves a place on this list because it fails silently. Without iterative scans, a tenant with a small share of the rows gets fewer seeds than everyone else, and retrieval quality drops for exactly the customers least likely to report it.

Context dilution. More graph context is not better context. Every hop adds candidates faster than it adds relevance. If answers get worse after you add GraphRAG, check the expansion size before blaming the model. A walk that returns 25 entities when 6 would answer the question is a retrieval bug, not a model problem.

Building on beta features. The meta failure mode, and the one the revert just demonstrated. Syntax that exists in a beta is a proposal, not a contract. I wrote the July post knowing the feature was in beta and said so; the revert is still a reminder to never put beta-only syntax on a production path.

The Tradeoffs: When Not to Do This

Choose Apache AGE if your team thinks in Cypher and you want variable-length path queries inside Postgres. The catch is version support: AGE's README lists support up to PostgreSQL 18, and its latest release is built for PostgreSQL 18. Choosing AGE today means not upgrading to PostgreSQL 19 until AGE catches up.

Choose Neo4j when graph analytics are the product: global community summaries in the style of Microsoft's GraphRAG, multi-hop path finding over large graphs, or graph algorithms you would otherwise reimplement. That is real capability Postgres does not have, and it comes with a second system, a sync pipeline and two query languages.

Choose plain vector RAG if your questions are answered by single passages. Measure first: sample your real questions and count how many need facts from two or more documents. If that share is small, the graph is complexity without payoff. My comparison of LangChain and LlamaIndex covers where plain retrieval pipelines are enough.

The Postgres approach in this post trades traversal depth and graph algorithms for one database, one backup, one permission model, and transactional consistency between your documents and the relationships extracted from them. For retrieval, where walks are one or two hops, that is usually the right trade. The same consolidation logic is what drove Instacart to move search from Elasticsearch to Postgres.

Operational Reality

Evaluate retrieval, not just answers. Keep a fixed set of questions with the documents that should be retrieved for each, and run it on every change to extraction, chunking or the expansion query. Graph changes are notoriously easy to make worse without noticing.

Log the walk. For every query, record seed count, expanded entity count, and the evidence chunks used. The first production issue will be a question that expanded into a hub, and you want to see that in a log line, not reconstruct it.

Watch table bloat. Re-extracting documents rewrites relations and mentions heavily. PostgreSQL 19's new REPACK (CONCURRENTLY) reclaims that space without blocking reads and writes, and its parallel autovacuum of table indexes helps with tables that carry several large indexes. Those two features are reasons to upgrade for this workload, SQL/PGQ or not.

Check extension support before upgrading. pgvector's changelog does not yet mention PostgreSQL 19 explicitly, and AGE stops at 18. Upgrade a staging copy first, and run your retrieval eval set against it before touching production.

Keep the port path open. Vertex tables with primary keys, edge tables with foreign keys, no graph logic hidden in triggers. If SQL/PGQ lands in a later release, you will add one CREATE PROPERTY GRAPH statement over these tables and rewrite the pattern match, while the retrieval policy around it stays the same.

The open question I am watching is not whether SQL/PGQ comes back, but whether it comes back with its invariants enforced continuously, the way foreign keys are. If it does, Postgres becomes a genuinely safe place to keep a knowledge graph next to the data it describes. Until then, the boring version above works, and it is what I would ship in my own projects.

This post is a follow-up to PostgreSQL 19 Graph Queries (SQL/PGQ) Explained, my July walkthrough of the beta syntax. Read it for how CREATE PROPERTY GRAPH and GRAPH_TABLE were designed to work; read this one for what actually shipped.

References


Disclaimer: This blog post was researched, written, and published with the assistance of AI. The content reflects general information on the topic and does not represent the personal opinions, beliefs, professional advice, or endorsements of Bhavik Mehta. Nothing in this post should be construed as legal, financial, technical, or professional advice. Readers should independently verify any information before acting on it.


Originally published at bhavikmehta.dev.

Top comments (0)