Quick revision
The short answer
A graph database such as Neo4j stores nodes and the relationships between them directly, so following a relationship is a pointer hop rather than a join, and traversals of variable depth stay fast. It fits social graphs, fraud rings, recommendations and network or dependency analysis. Friends of friends of user 42 who are not already friends is MATCH (u:User {id: 42})-[:FRIEND]->()-[:FRIEND]->(fof) WHERE fof <> u AND NOT (u)-[:FRIEND]->(fof) RETURN DISTINCT fof; a relational database can do the same with joins or recursive CTEs, which is often enough for shallow traversals, while graph stores are weaker at large aggregations and bulk analytics.
What to remember
In this answer, we saw that a graph database stores nodes and relationships directly, so traversals follow stored references instead of repeating joins, which pays off for variable-depth questions in social graphs, fraud detection, recommendations and dependency analysis. We wrote the friends of friends query in Cypher, removed user 42, existing friends and duplicates with fof <> u, a NOT pattern and DISTINCT, compared it with plain SQL that is often good enough for two hops, and noted that graph stores are weaker for large aggregations and bulk analytics.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A graph database such as Neo4j stores nodes and the relationships between them directly, so following a relationship is a pointer hop rather than a join, and traversals of variable depth stay fast. It fits social graphs, fraud rings, recommendations and network or dependency analysis. Friends of friends of user 42 who are not already friends is MATCH (u:User {id: 42})-[:FRIEND]->()-[:FRIEND]->(fof) WHERE fof <> u AND NOT (u)-[:FRIEND]->(fof) RETURN DISTINCT fof; a relational database can do the same with joins or recursive CTEs, which is often enough for shallow traversals, while graph stores are weaker at large aggregations and bulk analytics.
Why this question is asked
Almost every system has relationships in its data, and relational databases handle most of them well. Graph databases earn their place when the relationships are the question itself: who is connected to whom, through what, and how far away. Interviewers ask this to check that we can tell those cases apart, and that we can write a basic Cypher query rather than only naming the product. In this answer, we will recap how a graph database stores data, see why traversals are cheap, write the friends of friends query step by step, compare it with SQL, and look at where graph databases are the wrong tool.
1A Quick Recap of the Property Graph Model
Neo4j uses the property graph model. A node is an entity, such as a user, with labels that say what kind of thing it is (User) and properties such as id and name. A relationship connects two nodes, always has a type such as FRIEND and a direction, and can have properties of its own, such as since. Relationships are stored as first-class records, not computed at query time from matching key values.
Cypher, Neo4j's query language and the basis of the ISO GQL standard, describes patterns with ASCII art: (u:User) is a node, -[:FRIEND]-> is a relationship, and a query asks the database to find every place in the graph where that pattern matches.
2Why Traversals Do Not Need Joins
In a relational database, finding a user's friends means looking up rows in a friendship table through an index, and finding friends of friends means doing that again for every friend: each hop is a join, and each join is an index lookup per row. The cost grows with the size of the index and the number of hops. Neo4j stores, for each node, direct references to its relationships, an approach often called index-free adjacency. Moving from a user to their friends follows those references, so the cost depends on how many relationships we actually walk, not on how many users exist in total.
That matters most for traversals of variable depth: 'is there any path of up to five steps between these two accounts', or 'everything that depends on this service, directly or indirectly'. In SQL those need recursive queries whose cost can explode; in a graph database they are a natural pattern.
| Step | Relational | Graph |
|---|---|---|
| Start at user 42 | Index lookup on users | Index lookup on :User(id) |
| Hop 1: friends | Join friendship by index | Follow stored relationships |
| Hop 2: their friends | Join friendship again | Follow stored relationships |
| Cost grows with | Index sizes and hop count | Relationships actually walked |
3Writing the Friends of Friends Query
We want people who are friends of user 42's friends, excluding user 42 and excluding people who are already 42's friends. Let us build it in pieces.
Notice what each line removes. Without fof <> u, the path 42 -> 9 -> 42 returns user 42. Without the NOT pattern, user 9 appears because 7 is friends with 9, even though 42 already knows 9. Without DISTINCT, user 13 appears once for every mutual friend. The last version keeps that count as mutualFriends, which is exactly the ranking a 'people you may know' feature needs. The empty node () in the middle means 'any node', because we do not need to name the friend. If friendships are stored in one direction only, we write -[:FRIEND]- without the arrow to match either direction.
4The Same Query in SQL
Relational databases can answer this too. For exactly two hops, two joins are enough, and for variable depth PostgreSQL and MySQL 8 support recursive common table expressions.
Notice that this is perfectly reasonable SQL, and with an index on friendship(user_id, friend_id) it is fast for a typical user. So for shallow, fixed-depth questions in a system that already runs PostgreSQL, a graph database is often unnecessary. The case for a graph store grows with depth, with variable-length paths, and with queries that combine many relationship types, where SQL becomes long and slow.
5Where a Graph Database Fits and Where It Does Not
Good fits share one trait: the answer depends on the shape of the connections. Social graphs ask who is near whom. Fraud detection looks for rings of accounts that share devices, cards or addresses. Recommendations follow paths like 'users who bought this also bought'. Network and dependency analysis asks what breaks if this router or service fails. In each, the queries walk relationships of varying length.
Graph stores are weaker at the other half of data work. Large aggregations, such as total revenue by month and country across 500 million orders, scan everything and benefit from columnar storage, which a warehouse provides. Bulk analytics over the whole graph, such as PageRank on billions of edges, are better done in dedicated graph processing frameworks or libraries that run in batch. And for ordinary transactional records with simple relationships, a relational database remains simpler to run.
- Do key queries follow relationships of variable depth?YesNext questionNoStay relational
- Are SQL joins or recursive CTEs too slow at real depth?YesGraph database for those queriesNoStay relational, index well
- Keep aggregations in the warehousegraph for traversals only
3 steps in order. Play them, or step through them one at a time.
6Follow-up questions
What does index-free adjacency cost?
It makes writes and storage a little more complex, because each relationship is linked into both of its nodes, and very connected nodes, called super nodes, can have millions of relationships that slow down traversals passing through them. Graph databases mitigate this by grouping relationships by type and direction, but modelling still has to avoid unnecessary super nodes.
How would you limit the query for a user with 5,000 friends?
The second hop could visit millions of paths. We would cap the work, for example by sampling friends, limiting to the top results with LIMIT, or precomputing suggestions in batch and storing them, so the online query only reads the stored list.
Can you use a graph database from Spring?
Yes, Spring Data Neo4j maps nodes and relationships to Java classes with @Node and @Relationship annotations and supports repositories with Cypher queries through @Query.
7Conclusion
In this answer, we saw that a graph database stores nodes and relationships directly, so traversals follow stored references instead of repeating joins, which pays off for variable-depth questions in social graphs, fraud detection, recommendations and dependency analysis. We wrote the friends of friends query in Cypher, removed user 42, existing friends and duplicates with fof <> u, a NOT pattern and DISTINCT, compared it with plain SQL that is often good enough for two hops, and noted that graph stores are weaker for large aggregations and bulk analytics.
Open with
A graph database like Neo4j stores nodes and relationships as first-class records, and each node keeps direct references to its relationships, so a traversal just follows those references instead of joining tables at every hop.
Then, if they want more
That makes queries of variable depth, like any path of up to five steps, fast and natural, which is why it fits social graphs, fraud rings, recommendations and network or dependency analysis. For friends of friends of user 42 I would write MATCH (u:User {id: 42})-[:FRIEND]->()-[:FRIEND]->(fof) WHERE fof <> u AND NOT (u)-[:FRIEND]->(fof) RETURN DISTINCT fof.
The first condition removes 42 itself, reached through a friend; the NOT pattern removes people who are already friends; and DISTINCT removes duplicates when several mutual friends lead to the same person. I could also return count(*) as the number of mutual friends to rank suggestions.
I would add that a relational database can do this with two self-joins or a recursive CTE, which is often enough for shallow, bounded traversals, so I would not add a graph database only for this. And graph stores are weaker for large aggregations and bulk analytics, which belong in a warehouse.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Redis documentation, MongoDB manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "When is a graph database such as Neo4j a better fit than a relational database? Write a...": https://scrivio-interview-library.netlify.app/databases/nosql-fundamentals/74992e75f7/