Difficulty: Intermediate
When would you use a graph database like Neo4j instead of a relational database?
Use a graph database when the relationships between records are the main thing you query, especially multi-hop traversals of unknown depth such as "friends of friends", "accounts linked to this fraud ring", or "shortest path between two stations". Graph databases store edges as first-class data, so following a relationship is a direct pointer hop instead of a join that gets more expensive at each level.
User, Account, Device, Merchant.(:User)-[:PAID {amount_paise: 50000}]->(:Merchant).This is the labeled property graph model used by Neo4j, Memgraph and Amazon Neptune (which also supports RDF). Queries use Cypher or openCypher, Gremlin, or the newer ISO standard GQL published in 2024.
In a relational database, "friends of friends of friends" is three self-joins on a friendships table, and each join probes an index, so cost grows with the size of the intermediate result sets. Neo4j uses index-free adjacency: each node record points directly to its relationships, so a traversal cost depends on how many edges you actually walk, not on the total size of the table. Variable-length patterns like -[:KNOWS*1..4]-> are natural to write.
| Situation | Better fit |
|---|---|
| Aggregations, reports, sums over many rows | Relational or columnar |
| Fixed shape, shallow relationships (orders and items) | Relational |
| Strong multi-table transactions and mature tooling | Relational |
| Deep or variable-depth relationship queries | Graph |
| Path finding, centrality, community detection | Graph |
PostgreSQL can handle moderate graph needs with recursive CTEs (WITH RECURSIVE), and the Apache AGE extension adds openCypher. The SQL:2023 standard also added property graph queries (SQL/PGQ). Many teams keep the system of record in PostgreSQL and project relationship data into a graph store for the specific traversal workloads.
// Neo4j Cypher (run in cypher-shell or Neo4j Browser)
MATCH (flagged:Account {id: 'ACC-1001'})-[:USED_DEVICE]->(d:Device)
<-[:USED_DEVICE]-(other:Account)
WHERE other <> flagged
RETURN other.id AS suspect, count(DISTINCT d) AS shared_devices
ORDER BY shared_devices DESC
LIMIT 20;
// Friends of friends up to 3 hops
MATCH (me:User {id: 42})-[:FOLLOWS*1..3]->(u:User)
RETURN DISTINCT u.name LIMIT 50;
Patterns describe the shape of the connection; variable-length hops replace a stack of self-joins.
WITH RECURSIVE reach AS (
SELECT followee_id AS user_id, 1 AS depth
FROM follows WHERE follower_id = 42
UNION
SELECT f.followee_id, r.depth + 1
FROM follows f
JOIN reach r ON f.follower_id = r.user_id
WHERE r.depth < 3
)
SELECT DISTINCT user_id FROM reach;
Works fine for small graphs, but intermediate result sets grow quickly with depth and fan-out.
Graph Database, Neo4j, Cypher, Index-Free Adjacency, Traversal