Enterprise Java

Graph Queries with PostgreSQL

Relational databases are traditionally designed to store structured data in tables with relationships established through primary keys and foreign keys. While this approach works well for many applications, some use cases require navigating complex relationships between entities. Consider applications such as social networks, recommendation engines, fraud detection systems, organizational hierarchies, and dependency management, where queries often involve finding friends of a particular user, identifying employees reporting to a manager, discovering products connected through recommendations, exploring dependencies between software components, or finding all nodes reachable from a particular node. These are graph-related problems.

A graph represents information using vertices (nodes) and edges (relationships). Although PostgreSQL is primarily a relational database, it provides powerful SQL capabilities for modeling and querying graph structures. PostgreSQL supports recursive Common Table Expressions (CTEs), which make it possible to traverse relationships across multiple levels without requiring a dedicated graph database. This article explores how to model graph data in PostgreSQL and execute graph queries using practical SQL examples.

1. Understanding Graph Data

A graph consists of two fundamental components: vertices (nodes), which represent entities such as users, employees, products, or locations, and edges (relationships), which represent connections between two vertices, such as friendships, reporting relationships, or dependencies.

For example, consider a social network where users can follow other users. The graph can be represented as follows:

Alice --> Bob
Alice --> Charlie
Bob   --> David
Charlie --> David
David --> Emma

Here, each user represents a node, while each follow relationship represents a directed edge. Graphs can be classified into different types based on how their relationships are represented. A directed graph has relationships with a specific direction, such as one user following another, whereas an undirected graph represents relationships that work in both directions, such as mutual friendships. A weighted graph assigns additional values to edges, such as distance, cost, or relationship strength, while an unweighted graph treats all edges equally. Understanding these concepts helps determine how graph data should be modeled and queried in PostgreSQL.

1.1 When Should You Use PostgreSQL for Graph Queries?

PostgreSQL can be a good choice for graph-related workloads when graph traversal is only one part of a larger application. Some suitable use cases include:

  • Organizational Hierarchies: Finding reporting structures and employee relationships.
  • Product Recommendations: Discovering related products through multiple relationships.
  • Dependency Management: Traversing dependencies between software packages or services.
  • Social Networks: Finding followers, connections, and relationship paths.
  • Access Control: Evaluating inherited permissions and hierarchical ownership.

However, PostgreSQL is not necessarily the best solution for every graph workload. If an application requires frequent complex graph traversals, advanced path algorithms, or large-scale graph analytics, a dedicated graph database such as Neo4j may provide a more suitable architecture. The choice depends on graph size, traversal complexity, query frequency, operational requirements, and existing infrastructure.

2. Modeling Graph Data in PostgreSQL

A common approach is to represent nodes and edges using separate relational tables.

2.1 Create the Nodes Table

The following table stores users in a social network.

CREATE TABLE users (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name VARCHAR(100) NOT NULL
);

INSERT INTO users (name)
VALUES
  ('Alice'),
  ('Bob'),
  ('Charlie'),
  ('David'),
  ('Emma');

Each user has a unique identifier that can be referenced by relationships in the graph.

2.2 Create the Edges Table

The edges table stores relationships between users.

CREATE TABLE follows (
  source_id BIGINT NOT NULL REFERENCES users(id),
  target_id BIGINT NOT NULL REFERENCES users(id),
  PRIMARY KEY (source_id, target_id)
);

INSERT INTO follows (source_id, target_id)
VALUES
  (1, 2),
  (1, 3),
  (2, 4),
  (3, 4),
  (4, 5);

Here, the source_id column represents the starting node, while the target_id column represents the destination node. For example, the relationship (1, 2) indicates that Alice follows Bob. An index on the destination column can improve queries that traverse relationships in reverse.

CREATE INDEX idx_follows_target ON follows(target_id);

3. Querying Direct Relationships

Before exploring recursive queries, let’s start with a simple graph query.

3.1 Find Direct Connections

To find all users directly followed by Alice, we can join the users and follows tables.

SELECT
  source.name AS follower,
  target.name AS following
FROM
  follows f
  JOIN users source ON source.id = f.source_id
  JOIN users target ON target.id = f.target_id
WHERE
  source.name = 'Alice';

The query returns:

follower | following
----------+-----------
Alice    | Bob
Alice    | Charlie

This query only retrieves direct relationships. It does not traverse connections beyond the first level. For multi-level traversal, PostgreSQL provides recursive CTEs.

4. Graph Traversal Using Recursive CTEs

Recursive Common Table Expressions are one of the most useful PostgreSQL features for querying graph structures. A recursive CTE consists of two parts:

  • Anchor Query: Defines the initial set of nodes from which traversal begins.
  • Recursive Query: Repeatedly finds connected nodes using the results from the previous iteration.

The general syntax is:

WITH RECURSIVE cte_name AS (
  -- Anchor query
  SELECT
    ...
  UNION ALL
  -- Recursive query
  SELECT
    ...
  FROM ...
  JOIN cte_name
  ON ...
)
SELECT
  *
FROM cte_name;

PostgreSQL continues evaluating the recursive part until no additional rows are produced. You can learn more about the execution model in the PostgreSQL documentation on WITH queries.

4.1 Find All Reachable Nodes

Suppose we want to find every user reachable from Alice, including users connected through multiple intermediate relationships. We can use the following recursive query:

WITH RECURSIVE graph AS (
  SELECT
    id,
    name,
    0 AS depth
  FROM users
  WHERE name = 'Alice'

  UNION ALL

  SELECT
    u.id,
    u.name,
    g.depth + 1
  FROM graph g
  JOIN follows f
    ON f.source_id = g.id
  JOIN users u
    ON u.id = f.target_id
)
SELECT
  *
FROM graph
ORDER BY depth;

The result is:

id | name    | depth
---+---------+------
1  | Alice   | 0
2  | Bob     | 1
3  | Charlie | 1
4  | David   | 2
4  | David   | 2
5  | Emma    | 3
5  | Emma    | 3

The depth column indicates the number of edges traversed from the starting node. Notice that David is reachable through both Bob and Charlie. Consequently, the query can return David more than once, representing different paths through the graph. Emma is also returned twice because there are two distinct paths leading to her. This behavior is important when working with graphs that contain multiple paths between nodes.

4.2 Limit Graph Traversal Depth

Sometimes, applications only need to explore relationships up to a specific depth.

For example, a social network might want to retrieve users within two connection levels.

We can introduce a depth condition into the recursive query.

WITH RECURSIVE graph AS (
  SELECT
    id,
    name,
    0 AS depth
  FROM users
  WHERE name = 'Alice'

  UNION ALL

  SELECT
    u.id,
    u.name,
    g.depth + 1
  FROM graph g
  JOIN follows f
    ON f.source_id = g.id
  JOIN users u
    ON u.id = f.target_id
  WHERE g.depth < 2
)
SELECT
  *
FROM graph
ORDER BY depth;

The condition g.depth < 2 ensures that recursion stops after exploring two levels of relationships. The query retrieves Alice’s direct connections and users reachable within two edges.

Limiting traversal depth is useful for controlling query execution time and avoiding unnecessary exploration of large graphs.

5. Conclusion

PostgreSQL provides several capabilities for working with graph-shaped data without requiring a separate graph database. By modeling vertices and edges using relational tables, developers can use recursive Common Table Expressions to perform multi-level traversal, discover connected nodes, track paths, and detect cycles.

For more specialized graph workloads, extensions such as Apache AGE introduce graph-oriented querying through the openCypher language.

The important consideration is choosing the right approach based on the complexity and scale of the application. Recursive CTEs work well for many hierarchical and moderately complex graph queries, while dedicated graph extensions or databases may be more appropriate for advanced graph analytics and large-scale traversal workloads.

Understanding these options allows developers to take advantage of PostgreSQL’s relational capabilities while solving graph-related problems efficiently.

Yatin B.

An experienced full-stack engineer and solution architect with expertise in Core Java, Spring/Spring Boot, MVC, Security, AOP, Angular, React, cloud technologies (AWS and GCP), CI/CD (Jenkins), Docker, and Kubernetes. Skilled in designing scalable architectures and building agentic AI solutions, including AI agents, LLM integrations, agent orchestration, and enterprise AI systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button