When a graph database helps

NoSQL and choosing a database Mid-level Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Predict the output

Walk the reporting chain under the CEO. What's printed?

SQL · PostgreSQL 17
CREATE TABLE staff (id int, boss int, name text);
INSERT INTO staff VALUES
  (1, NULL, 'ceo'), (2, 1, 'cto'), (3, 2, 'dev'), (4, 1, 'cfo');
WITH RECURSIVE tree AS (
  SELECT id, name, 0 AS depth FROM staff WHERE boss IS NULL
  UNION ALL
  SELECT s.id, s.name, t.depth + 1
  FROM staff s JOIN tree t ON s.boss = t.id
)
SELECT max(depth) FROM tree;

Options
Hint 1 of 1

Count the hops from the CEO to the dev.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 2

Correct. ceo (0) → cto (1) → dev (2).

WITH RECURSIVE starts at the CEO with depth 0 and adds one level per join. The deepest chain is ceo, cto, dev, so the maximum depth is 2.

Why not the others?
  • B 3. Depth starts at 0 for the CEO.
  • C 1. dev is two levels below the CEO.
  • D 4. That's the number of rows.
Result on PostgreSQL 17 (psql)
max
2

(1 row)

30-second answer

When the questions are about paths and relationships of unknown depth: friends of friends, shortest routes, fraud rings, dependency trees. A graph database stores relationships as direct links, so traversing many hops costs per hop rather than per join over whole tables. For fixed-depth or occasional traversals, PostgreSQL's recursive CTEs handle trees and small graphs fine.

Practise saying it · 30 s. No recording, just a timer

When use a graph database?

Say your answer out loud, then check which of these points you covered:

  • Variable-depth relationships
  • Traversal cost per hop
  • Recursive CTEs for trees
  • Supernodes

Deep dive

Recursive CTEs: WITH RECURSIVE walks hierarchies like org charts or categories.

Graph queries (Cypher, Gremlin) express patterns rather than joins.

Graph databases are rarely the system of record for everything; feed them from your main store.

Watch supernodes (one node with millions of edges).

Common mistakes

  • Adopting a graph database for a simple parent-child tree.
  • Recursive queries without a depth limit or cycle check.
  • Ignoring supernodes.

Senior take & follow-ups

Variable-depth relationship queries favour graphs; recursive CTEs cover trees.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you stop a recursive CTE on a cycle?

    Show hint

    Track the path or use the CYCLE clause (PostgreSQL 14+).

  2. What's a supernode?

    Show hint

    A vertex with a huge number of edges that makes traversals explode.

Suggest a fix if something here is wrong or out of date.