Interview Question: "How would you find the shortest path between two nodes in SQL? Explain the MATCH clause and path functions. Compare recursive CTEs vs MATCH for graph traversal." â Asked at LinkedIn, Twitter, Meta for Graph Database roles
âšī¸
Difficulty: Advanced | Companies: LinkedIn, Twitter, Meta, Pinterest, Amazon Neptune | Time: 60-75 minutes
Graphs without a graph database
A graph in SQL is two tables: nodes with identities and edges with direction. Everything else â paths, shortest routes, communities, reachability â is recursion over that pair, and the quality of the answer depends on how faithfully the recursion respects cycles, weights, and depth limits. Relational engines handle shallow traversals well and deep ones badly, so the design question is not whether SQL can express the algorithm, because it plainly can, but where the traversal stops being predictable. This lesson builds the model, walks the recursive forms for path search and shortest path, compares them with a bidirectional search, computes centrality and structural patterns, and closes with the boundary past which the workload should move to a graph engine.
Graph Data Model in SQL
-- Create graph tables (node and edge tables)
CREATE TABLE graph_nodes (
node_id INT PRIMARY KEY,
node_type VARCHAR(50),
label VARCHAR(100),
properties JSONB
);
CREATE TABLE graph_edges (
edge_id SERIAL PRIMARY KEY,
source_node INT REFERENCES graph_nodes(node_id),
target_node INT REFERENCES graph_nodes(node_id),
edge_type VARCHAR(50),
weight DECIMAL(10,2),
properties JSONB
);
-- Insert social network data
INSERT INTO graph_nodes VALUES
(1, 'person', 'Alice', '{"age": 30, "city": "SF"}'),
(2, 'person', 'Bob', '{"age": 25, "city": "NYC"}'),
(3, 'person', 'Charlie', '{"age": 35, "city": "SF"}'),
(4, 'person', 'Diana', '{"age": 28, "city": "LA"}'),
(5, 'person', 'Eve', '{"age": 32, "city": "NYC"}'),
(6, 'company', 'TechCorp', '{"industry": "tech"}'),
(7, 'company', 'FinanceInc', '{"industry": "finance"}'),
(8, 'skill', 'SQL', '{"level": "advanced"}'),
(9, 'skill', 'Python', '{"level": "intermediate"}'),
(10, 'skill', 'Java', '{"level": "beginner"}');
INSERT INTO graph_edges (source_node, target_node, edge_type, weight, properties) VALUES
(1, 2, 'knows', 0.8, '{"since": "2020"}'),
(1, 3, 'knows', 0.9, '{"since": "2019"}'),
(2, 4, 'knows', 0.7, '{"since": "2021"}'),
(3, 5, 'knows', 0.85, '{"since": "2020"}'),
(4, 5, 'knows', 0.6, '{"since": "2022"}'),
(1, 6, 'works_at', NULL, '{"role": "engineer"}'),
(2, 7, 'works_at', NULL, '{"role": "analyst"}'),
(3, 6, 'works_at', NULL, '{"role": "manager"}'),
(1, 8, 'has_skill', 0.9, NULL),
(1, 9, 'has_skill', 0.7, NULL),
(2, 8, 'has_skill', 0.8, NULL),
(3, 9, 'has_skill', 0.85, NULL),
(4, 10, 'has_skill', 0.6, NULL),
(5, 8, 'has_skill', 0.75, NULL),
(5, 9, 'has_skill', 0.8, NULL);
Two modelling decisions do most of the later work. First, whether edges are typed: keeping knows, works_at, and has_skill in one table with a type column keeps the schema small, but every traversal must filter that column, and forgetting the filter returns paths that mix employment with friendship. Second, what a null weight means â the sample stores null where distance is undefined, so coalescing it to one during a shortest-path walk silently invents cost on relationships that had none. Adding a composite index on source plus edge type, and another on target, turns each recursive step into an index probe instead of a scan; with ten thousand edges the difference is milliseconds, with a hundred million it separates a working feature from a timeout.
Recursive CTE Graph Traversal
-- Find all paths from Alice to Eve
WITH RECURSIVE graph_paths AS (
-- Anchor: Start from Alice
SELECT
node_id,
label,
1 AS depth,
ARRAY[node_id] AS path,
label::TEXT AS path_text,
0.0 AS total_weight
FROM graph_nodes
WHERE label = 'Alice'
UNION ALL
-- Recursive: Traverse edges
SELECT
n.node_id,
n.label,
p.depth + 1,
p.path || n.node_id,
p.path_text || ' â ' || n.label,
p.total_weight + COALESCE(e.weight, 0)
FROM graph_paths p
INNER JOIN graph_edges e ON p.node_id = e.source_node
INNER JOIN graph_nodes n ON e.target_node = n.node_id
WHERE n.node_id != ALL(p.path) -- No cycles
AND p.depth < 10 -- Max depth
)
SELECT
path_text,
depth,
total_weight,
path
FROM graph_paths
WHERE label = 'Eve'
ORDER BY depth, total_weight;
Output:
| path_text | depth | total_weight | path |
|---|---|---|---|
| Alice â Bob â Diana â Eve | 4 | 2.10 | {1,2,4,5} |
| Alice â Charlie â Eve | 3 | 1.75 | {1,3,5} |
| Alice â Bob â Diana â Eve | 4 | 2.10 | {1,2,4,5} |
The recursive form has three parts: an anchor that seeds the starting node with depth one and an empty path, a recursive term that joins the current frontier to the edge table, and a predicate that stops expansion. The cycle guard is the piece worth arguing about in review â rejecting any node already in the path array guarantees termination, but it also discards alternative routes that legitimately pass through a node, so a query hunting for several distinct paths needs a depth cap instead of a visited set. Path arrays grow with depth and membership tests scan them linearly, which is fine at ten elements and noticeable at a thousand. Order results by depth and total weight together, because the fewest hops is rarely the cheapest route.
Shortest Path with Dijkstra
-- Dijkstra's algorithm using recursive CTE
WITH RECURSIVE dijkstra AS (
-- Initialize: source node has distance 0
SELECT
node_id,
label,
0 AS distance,
ARRAY[node_id] AS path,
label::TEXT AS path_text
FROM graph_nodes
WHERE label = 'Alice'
UNION ALL
-- Relax edges
SELECT
n.node_id,
n.label,
d.distance + COALESCE(e.weight, 1),
d.path || n.node_id,
d.path_text || ' â ' || n.label
FROM dijkstra d
INNER JOIN graph_edges e ON d.node_id = e.source_node
INNER JOIN graph_nodes n ON e.target_node = n.node_id
WHERE n.node_id != ALL(d.path)
AND d.distance + COALESCE(e.weight, 1) < (
SELECT MIN(distance) FROM dijkstra WHERE node_id = n.node_id
)
)
SELECT DISTINCT ON (node_id)
node_id,
label,
distance,
path_text
FROM dijkstra
WHERE label = 'Eve'
ORDER BY node_id, distance;
A recursive CTE is a poor stand-in for Dijkstra, and it is worth knowing why. The real algorithm settles each node once using a priority queue; the recursive form relaxes edges in breadth-first order and relies on a correlated minimum to prune, so it can revisit the same node many times before pruning takes hold. On the ten-node sample that is irrelevant, and on a graph full of cycles it is the difference between milliseconds and minutes. The distinct clause at the end hides the duplication rather than preventing it. When weights drive the answer, either accept the approximation for shallow graphs, carry cumulative distances in a visited set inside the recursive term, or call a shortest-path routine from an extension â most distributions ship one backed by a heap.
Bidirectional Search
-- Bidirectional BFS from both source and target
WITH RECURSIVE
forward_search AS (
SELECT
node_id,
1 AS depth,
ARRAY[node_id] AS path
FROM graph_nodes WHERE label = 'Alice'
UNION ALL
SELECT
n.node_id,
f.depth + 1,
f.path || n.node_id
FROM forward_search f
JOIN graph_edges e ON f.node_id = e.source_node
JOIN graph_nodes n ON e.target_node = n.node_id
WHERE n.node_id != ALL(f.path) AND f.depth < 5
),
backward_search AS (
SELECT
node_id,
1 AS depth,
ARRAY[node_id] AS path
FROM graph_nodes WHERE label = 'Eve'
UNION ALL
SELECT
n.node_id,
b.depth + 1,
b.path || n.node_id
FROM backward_search b
JOIN graph_edges e ON b.node_id = e.target_node
JOIN graph_nodes n ON e.source_node = n.node_id
WHERE n.node_id != ALL(b.path) AND b.depth < 5
)
SELECT
f.path || b.path[2:] AS full_path,
f.depth + b.depth - 1 AS total_depth
FROM forward_search f
JOIN backward_search b ON f.node_id = b.node_id
WHERE f.node_id NOT IN (SELECT node_id FROM graph_nodes WHERE label IN ('Alice', 'Eve'))
ORDER BY total_depth
LIMIT 5;
Searching from both ends turns an exponential frontier into two much smaller ones: instead of exploring every node within radius d, each side explores roughly half the distance, and the product of the two frontiers collapses. The complexity table further down shows the win, because the search space falls from a branching factor raised to the full distance to twice that factor raised to half of it. The correctness condition is the meeting point: forward and backward frontiers must join on a node both sides reached, and the combined path counts that node exactly once. Two traps follow â the depth caps must match or one side stops early, and any filter on node type or edge type must be applied in both directions or the join is comparing incompatible sets.
Graph Centrality Measures
-- Degree centrality
SELECT
n.node_id,
n.label,
COUNT(DISTINCT e1.edge_id) AS out_degree,
COUNT(DISTINCT e2.edge_id) AS in_degree,
COUNT(DISTINCT e1.edge_id) + COUNT(DISTINCT e2.edge_id) AS total_degree
FROM graph_nodes n
LEFT JOIN graph_edges e1 ON n.node_id = e1.source_node
LEFT JOIN graph_edges e2 ON n.node_id = e2.target_node
GROUP BY n.node_id, n.label
ORDER BY total_degree DESC;
-- Betweenness centrality (simplified)
WITH all_shortest_paths AS (
SELECT
source_node,
target_node,
path,
path_text
FROM graph_paths
WHERE source_node != target_node
)
SELECT
n.node_id,
n.label,
COUNT(*) FILTER (WHERE n.node_id = ANY(
SELECT unnest(path[2:array_length(path, 1)-1])
)) AS betweenness_count
FROM graph_nodes n
CROSS JOIN all_shortest_paths p
GROUP BY n.node_id, n.label
ORDER BY betweenness_count DESC;
Centrality turns structure into a ranking, and each variant answers a different question. Degree centrality counts direct connections, which is cheap and good for spotting hubs. Betweenness counts how often a node sits on the shortest path between other pairs, which identifies brokers and bridges â and is expensive, because it needs all-pairs shortest paths, so the simplified version above reuses a precomputed path table instead of recomputing. Note that filtering an unnested path array counts a node once for every path containing it, so a node on a thousand paths scores a thousand. Report these figures relative to the maximum rather than as raw counts, because totals from graphs of different sizes are not comparable and a score of four hundred means nothing on its own.
MATCH Clause (ISO SQL/PGQ)
-- PostgreSQL 14+ graph query syntax (experimental)
-- CREATE PROPERTY GRAPH for graph queries
-- Simulated MATCH with recursive CTE
WITH RECURSIVE match_query AS (
-- Pattern: (a:person)-[:knows]->(b:person)
SELECT
a.node_id AS a_id,
a.label AS a_name,
b.node_id AS b_id,
b.label AS b_name,
e.weight
FROM graph_nodes a
JOIN graph_edges e ON a.node_id = e.source_node
JOIN graph_nodes b ON e.target_node = b.node_id
WHERE a.node_type = 'person'
AND b.node_type = 'person'
AND e.edge_type = 'knows'
)
SELECT * FROM match_query;
The SQL/PGQ standard writes patterns declaratively: nodes in parentheses, edges in brackets with an arrow for direction, and the engine decides how to traverse. Practical support is still thin â PostgreSQL reaches it through extensions, SQL Server and Oracle ship it directly, and most deployments today express the same shapes with recursive CTEs like the one above. Writing the recursive version first is useful discipline because it forces the decisions the standard hides: which edge types may be traversed, how deep the match may go, and whether the pattern wants distinct paths or permits repeats. When you later move to a platform with native pattern matching, those decisions carry over as the plan you should expect to see.
Graph Pattern Matching
-- Find triangles (3-clique)
SELECT
a.label AS person_a,
b.label AS person_b,
c.label AS person_c
FROM graph_nodes a
JOIN graph_edges e1 ON a.node_id = e1.source_node
JOIN graph_nodes b ON e1.target_node = b.node_id
JOIN graph_edges e2 ON b.node_id = e2.source_node
JOIN graph_nodes c ON e2.target_node = c.node_id
JOIN graph_edges e3 ON c.node_id = e3.source_node
WHERE e3.target_node = a.node_id
AND a.node_id < b.node_id
AND b.node_id < c.node_id;
-- Find 2-hop neighbors
WITH RECURSIVE two_hop AS (
SELECT
n1.node_id AS source,
n2.node_id AS neighbor,
1 AS hops
FROM graph_nodes n1
JOIN graph_edges e ON n1.node_id = e.source_node
JOIN graph_nodes n2 ON e.target_node = n2.node_id
UNION
SELECT
t.source,
n3.node_id,
2
FROM two_hop t
JOIN graph_edges e ON t.neighbor = e.source_node
JOIN graph_nodes n3 ON e.target_node = n3.node_id
WHERE n3.node_id != t.source
)
SELECT DISTINCT
s.label AS source,
n.label AS two_hop_neighbor
FROM two_hop t
JOIN graph_nodes s ON t.source = s.node_id
JOIN graph_nodes n ON t.neighbor = n.node_id
WHERE t.hops = 2
ORDER BY s.label, n.label;
Triangle finding is a chain of three self-joins with a symmetry guard: the monotonic ordering constraint on node ids ensures each triangle is returned once instead of six times. Drop that guard and the query returns every permutation, so any count built on it is inflated sixfold â a mistake that survives casual testing because the rows still look like triangles. The two-hop query uses deduplicating union rather than plain union for the same reason: it collapses the frontier at each level, trading a sort per iteration for protection against paths that fan out. Both queries are quadratic in the worst case, so run them against a sampled subgraph first and read the plan before scaling to the full edge set.
Graph Aggregation
-- Community detection (label propagation simplified)
WITH RECURSIVE communities AS (
SELECT
node_id,
node_id AS community_id,
1 AS iteration
FROM graph_nodes
UNION ALL
SELECT
c.node_id,
mode() WITHIN GROUP (ORDER BY c2.community_id),
c.iteration + 1
FROM communities c
JOIN graph_edges e ON c.node_id = e.source_node
JOIN communities c2 ON e.target_node = c2.node_id
WHERE c.iteration < 10
GROUP BY c.node_id, c.iteration
HAVING mode() WITHIN GROUP (ORDER BY c2.community_id) != c.community_id
)
SELECT DISTINCT
n.label,
c.community_id
FROM communities c
JOIN graph_nodes n ON c.node_id = n.node_id
WHERE c.iteration = (SELECT MAX(iteration) FROM communities)
ORDER BY c.community_id, n.label;
Label propagation is community detection by voting: each node adopts the most common label among its neighbours and repeats until the labels stop moving. Two properties decide whether it converges to anything useful. Ties must break deterministically, or two runs on identical data produce different communities and the dashboard drifts for no reason; and the iteration cap bounds work but also bounds quality, because a graph with long chains needs many passes before a label travels from one end to the other. The having clause inside the recursive term stops a node once its own label is unchanged, which is the correct early exit. In production this shape is a placeholder â real community detection uses modularity optimisation or topic similarity, neither of which this query computes.
Mathematical Graph Theory
Graph where:
- nodes
- edges
Adjacency matrix :
Degree centrality:
Betweenness centrality:
âšī¸
Graph Algorithms: For production graph workloads, consider dedicated graph databases like Neo4j, Amazon Neptune, or Apache AGE extension for PostgreSQL.
Performance Considerations
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| BFS | ||
| DFS | ||
| Dijkstra | ||
| Betweenness |
â ī¸
SQL Limitations: SQL graph queries are less efficient than native graph databases for deep traversals. Use recursive CTEs for shallow graphs (< 10 levels).
Knowing when to leave SQL
The boundary is measurable rather than a matter of taste. Count the joins in the recursive step, the depth you expect, and how many nodes the frontier reaches at that depth; once a single level emits a few tens of thousands of rows, planning and array comparison dominate and the answer arrives late or not at all. The signals are specific: a depth cap raised more than once just to let a query finish, path arrays growing past a few hundred elements, or a pattern that wants variable-length edge sequences instead of a fixed hop count. At that point the graph belongs in a graph engine â Neo4j, Amazon Neptune, or Apache AGE â and SQL keeps the reporting copy that feeds dashboards and nightly exports.
Common Mistakes
Traversing edges without filtering the edge type
Fix: Filter type at every recursive step so friendship and employment paths cannot mix
Removing cycles by rejecting any node already in the path
Fix: Use a depth cap when alternative routes matter, and reserve the visited set for simple reachability
Counting triangles without an ordering constraint on the node ids
Fix: Enforce a monotonic id order so each triangle appears exactly once
Best Practices
- Index source and target columns separately so every recursive step is an index probe
- Define the meaning of a null weight before writing any shortest-path query
- Apply identical filters to both directions in a bidirectional search
- Report centrality as a ratio to the maximum so graphs of different sizes stay comparable
- Benchmark a traversal on a sampled subgraph before committing to the full edge set
Interview Questions
Q1: Recursive CTE or MATCH clause for graph traversal?
MATCH states intent and lets the engine plan it, but support varies; a recursive CTE works everywhere and exposes the cycle and depth decisions explicitly
Q2: Why can a recursive CTE shortest path be slow?
It relaxes in breadth-first order with no priority queue, so nodes are revisited repeatedly until a correlated minimum prunes them
Q3: How do you stop a traversal from looping forever?
Either reject nodes already present in the path array or cap the depth, chosen from whether alternative routes must survive
Q4: When should this workload move to a graph database?
When frontier sizes per level, path array growth, or variable-length pattern requirements exceed what indexed recursive joins deliver predictably
Key Takeaways
- A graph in SQL is node and edge tables plus recursion that respects cycles, weights, and depth
- Index both edge directions and decide what a null weight means before writing traversal queries
- Bidirectional search wins because the frontier product collapses when both halves meet
- Centrality and triangle counts need deduplication guards or the results are inflated
- The exit condition to a graph engine is measurable: frontier size, path length, and pattern variability