Recursive SQL for a BFS: The ultimate interview flex
Why is this Interviews meme funny?
Level 1: Unexpected Tool, Perfect Fit
Imagine you’re in a contest where you have to get through a maze as fast as possible, and you can use anything you want to help you. Most people will just run through the maze or maybe draw a map. But one clever person says, “I’ll use a drone to fly above and find the exit.” Everyone else giggles because it sounds so odd – who uses a drone in a maze race? But then, to everyone’s surprise, the drone idea works brilliantly and that person finds the exit in record time! The story in this meme is just like that, but in a coding interview.
The interviewer told the candidate they could use any programming language to solve a puzzle (finding their way through a “graph” which is like a maze of connected points). Other candidates might pick common languages like Python or Java (just like running normally in the maze). But this candidate picked SQL – a language usually used for talking to databases, not for solving puzzles (SQL in this story is the “drone”). The interviewer almost laughed, thinking “This is silly,” just like everyone laughed at the drone idea. But then the candidate’s SQL solution actually worked, leaving the interviewer amazed.
It’s funny and satisfying because the candidate found a very creative way to solve the problem – an unexpected solution that turned out to be perfectly valid. The humor comes from that element of surprise: someone using a tool in a way that nobody anticipated, and totally succeeding. It’s a feel-good story that makes you smile and think, “Wow, they really did that!”
Level 2: Recursion in a Query
Let’s break down what’s happening here in simpler terms. The meme recounts an Interview scenario where a candidate was asked to implement Breadth-First Search (BFS), which is a fundamental algorithm for graph traversal. Graphs in computer science are just collections of points (called nodes) connected by lines (called edges). Traversal means visiting nodes in some order. BFS specifically starts from one node and explores all directly connected nodes first, then the neighbors of those neighbors, and so on. It’s like ripples spreading out in water: you go outwards level by level. BFS is a classic topic in CS fundamentals and appears often in coding interviews because it tests understanding of data structures (using a queue) and careful logic.
Now, typically, if an interviewer says "use any programming language," candidates choose something like Java, Python, or C++ – general-purpose languages where you can write step-by-step instructions (loops, if-conditions, etc.). SQL, on the other hand, is a database query language. It’s designed to retrieve and manipulate data stored in tables using a declarative style (you specify what you want, not how to compute it step by step). SQL is great for operations like "give me all users from Canada" or "join these two tables," but people don’t usually think of writing algorithms like BFS in SQL. That’s why, when the candidate said "I'll write it in SQL," it was an unexpected language choice – the interviewer even mentions they almost laughed, assuming the candidate might not be serious or wouldn’t manage it.
But SQL does have some advanced features up its sleeve. One of them is the recursive CTE (Common Table Expression). This feature lets you write a query that references itself, effectively creating a loop in a declarative way. Think of it like a function that calls itself, but in SQL’s set-based, mathematical manner. It’s often used for hierarchical data – for example, finding all employees in a company under a certain manager (you start with the manager, then find their direct reports, then reports of those reports, etc.). Sound similar to BFS? Exactly! It’s the same concept of exploring layer by layer.
In the code snippet from the tweet, we see WITH RECURSIVE bfs AS (...). This defines a temporary recursive query named bfs. Inside, there are two parts joined by UNION ALL: the base case and the recursive case.
- The base case selects the starting node’s immediate neighbors from a table called
graph. (That table likely has columns likenode_fromandnode_to, representing edges in the graph. So ifnode_from = 1, it finds allnode_toconnected to node 1 – that’s the first layer of BFS.) They even gave1 AS levelfor those, marking them at distance 1 from the start. - The recursive case then takes each result from the previous step (
bfs) and finds neighbors of those nodes by joining thegraphtable back onto it. TheUNION ALLcombines these new nodes with the ones found before, and because it’s recursive, this keep repeating: newly found nodes feed back into the query again until no new nodes are found. At that point, BFS is complete because you’ve visited everything reachable.
So essentially, the candidate wrote a graph_traversal query. Instead of using an explicit loop in code, the database engine iteratively evaluates the recursive CTE. Each “iteration” adds another level of neighbors. The final result (when you SELECT * FROM bfs at the end) is a list of nodes by increasing level (distance) from the start node. This is exactly what a BFS algorithm would produce!
For clarity, if you’re not familiar with SQL, imagine we have a table graph of connections like this:
| node_from | node_to |
|---|---|
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
| 3 | 5 |
| 5 | 6 |
| (This table means: from node 1 you can go to 2 and 3; from 2 you can go to 4; from 3 to 5; from 5 to 6; and so on.) |
If we run BFS starting at node 1, the base layer finds 2 and 3 (neighbors of 1). The next iteration finds neighbors of 2 and 3 – that would be 4 (neighbor of 2) and 5 (neighbor of 3). The next iteration finds neighbors of 4 and 5 – that gives 6 (neighbor of 5; node 4 might have none). And it would continue until no new nodes are found. The recursive query does exactly that in a set-based way.
For a newcomer or junior developer, the surprising part is that SQL – which you might think of for simple data queries – can do this kind of recursion. It’s not trivial; not all languages have this facility built-in, and many developers don’t encounter recursive CTEs until they hit a specific problem like this. The candidate in the interview basically used a database feature to do an algorithmic task. It’s like solving a problem with a tool from a different toolbox. It requires knowing that tool really well.
This story has quickly spread in programming circles because it’s a perfect blend of InterviewHumor and AlgorithmHumor. On one hand, it’s about an interview situation, something many of us can relate to (nervously solving problems on a whiteboard or shared editor). On the other hand, it’s about bending the usual rules of those problems – using SQL, of all things, to solve a graph problem! It teaches us a lesson too: sometimes, having knowledge outside the standard playbook (like database query tricks) can give you a unique edge. And at the very least, it makes for a memorable story in the world of technical interviews.
Level 3: CTE BFS Power Move
For seasoned developers, this story is both hilarious and impressive. In a high-stakes Facebook coding interview, the interviewer says the usual: "use any language you prefer" – expecting a choice like Python, C++ or Java. Instead, the candidate picks SQL. 😲 It’s such an unexpected_language_choice that the interviewer admits they almost chuckled. In the culture of Technical Interviews, that choice is a curveball. SQL is a query language for databases, not a typical algorithm coding language, especially for something like breadth_first_search which we usually implement with loops and queues.
Why is this funny? Because the candidate not only broke the unwritten rules of the interview game, but did so confidently. This is a real power move: taking an algorithm humor scenario and turning it into database humor at the interviewer’s expense. The tweet sets the scene as if the interviewer was thinking, "Heh, good one – BFS in SQL, really?" But then comes the punchline: the candidate actually does it. The oversized "NEXT ➡️" arrow in the image suggests there’s more code in a thread – implying the candidate proceeded to write a full recursive SQL solution. You can almost hear the stunned silence in that interview room. It swiftly transformed from a potential joke into a jaw-dropping interview storytime on Twitter.
From a senior dev perspective, we see layers of humor here. First, there’s the shared understanding that interviews often test core algorithms like BFS, expecting textbook solutions. And there’s a bit of cynicism: interviewers say "any language," but rarely anticipate something truly outside the box. This candidate took that prompt literally and maxed out the rules. It's reminiscent of tales where someone writes a web server in Excel or implements a 3D game in PowerPoint – delightfully offbeat. Here, the candidate leveraged a recursive_cte to make SQL perform a graph traversal. In practical terms, they used a single (perhaps monstrous) query to do what others do with dozens of lines of code. That’s a flex!
Consider the knowledge required: the candidate had to know that SQL supports recursion (many developers never use that feature unless dealing with hierarchical data). They needed the syntax at their fingertips (WITH RECURSIVE ... UNION ALL ...) and an understanding of how to build a BFS level-by-level using set operations. It's not everyday stuff – this is CSFundamentals meets database wizardry. The interviewer, initially amused, must have quickly shifted to respect. The tweet doesn’t show the ending, but we can imagine the interviewer’s internal dialogue: "Wait, I have to actually read and understand this SQL now..." 😅 It’s likely the candidate wrote something akin to:
-- The candidate's recursive CTE implementation of BFS (simplified example)
WITH RECURSIVE bfs AS (
-- Base case: start from the root node (say node 1 for example)
SELECT
node_to,
1 AS level
FROM graph
WHERE node_from = 1
UNION ALL
-- Recursive step: get neighbors of the nodes found in the previous step
SELECT
g.node_to,
bfs.level + 1
FROM bfs
JOIN graph AS g
ON g.node_from = bfs.node_to
)
SELECT * FROM bfs;
Here, graph is a table of edges with columns like node_from and node_to. The query starts at node_from = 1 (the source node) and finds direct neighbors (level 1). Then the UNION ALL part recursively joins those results back to graph to get the next set of neighbors (level 2), continuing until no more new nodes appear. That’s BFS in pure SQL! The result would list nodes level by level – essentially the BFS tree. The real code in the tweet likely even built a path string (CAST('1,' AS VARCHAR(1000)) in the snippet) to keep track of the traversal path for each node, which is next-level attention to detail.
For seasoned devs, this scenario nails a few things:
- InterviewHumor: The story of a candidate outsmarting the process in a playful way. It’s the kind of tale you retell over lunch to your team: "You won’t believe this interview I heard about…".
- Shared Surprise: Many of us have a mental list of languages to solve interview problems; SQL is not usually on it. It’s funny because we picture ourselves as that interviewer, having to pivot from judging code logic to deciphering a single gnarly SQL query on the fly.
- Respect for the Trick: Under the laughter, there’s genuine respect. Only a strong candidate (perhaps a database guru or someone highly creative) could pull this off. It highlights an important point in tech: there’s often more than one way to solve a problem, and creative solutions stand out.
In the end, the meme resonates because it captures the candidate_surprise_factor perfectly. The interviewer’s almost-chuckle turning into astonishment is something every experienced dev can appreciate – it’s both humorous and a reminder not to underestimate unconventional approaches. Next time someone says "any language," they might actually mean any language – you’ve been warned! 😉
Level 4: Graph Theory, Meet SQL
At the most conceptual level, this meme spotlights an ingenious collision of graph theory with relational database theory. Breadth-First Search (BFS) is a classic graph traversal algorithm from CS Fundamentals: it explores a graph layer by layer, finding all neighbors of a starting node, then neighbors of those neighbors, and so on. Traditionally, BFS is implemented with loops or recursion in a general-purpose language (using a queue data structure). But here the candidate uses SQL, a declarative database query language, to perform the same traversal. How is that even possible? Enter the recursive CTE (Common Table Expression).
Modern SQL (since SQL:1999) supports recursive queries, which essentially allow a query to refer to its own results – achieving a form of iteration or recursion in a single WITH RECURSIVE expression. This is powerful: it lets SQL compute things like transitive closures or graph paths, tasks that early SQL couldn't handle elegantly. In theoretical terms, a recursive CTE repeatedly applies a union of results until no new rows appear, reaching a fixpoint (that is, it stops when BFS has visited all reachable nodes). It’s a set-based simulation of an algorithmic loop. Under the hood, the database executes the recursive query by iteratively evaluating the recursive step, almost as if it were running a loop inside the query planner. The meme’s code snippet (WITH RECURSIVE bfs AS (...) ... UNION ALL ...) shows exactly this: a base query to start from a node, then a recursive part to get the next layer of nodes, repeating until exhaustion.
This is a mind-bending concept if you’re coming from classical algorithm design. It demonstrates that SQL – typically used for data retrieval – is sufficiently expressive to implement graph algorithms in pure set operations. In computational theory, it’s a reminder that given the right extensions (like recursion), a declarative language like SQL can approach the power of a general-purpose language. It’s almost like seeing two worlds meet: relational algebra meets graph traversal. The humor hides in the sheer nerdy elegance of it: solving a procedural problem (graph search) using a declarative query – something you might discuss in a database theory class or a nerdy conference, not usually in a high-pressure coding interview! This candidate basically turned an algorithmic coding question into a database query problem, leveraging the database engine itself to do BFS. It’s a beautiful homage to the depth of SQL: a language often underestimated, suddenly revealing its capability to handle a complex algorithm with just a few clever clauses.
Description
This is the first image in a series, as indicated by a large orange arrow with the word 'NEXT'. The image is a screenshot of a tweet from user Deedy (@deedydas) about a surprising coding interview experience at Facebook. The tweet reads: 'The most bizarre coding interview I've ever done was at Facebook when as usual I asked a candidate to write in any language of their choice.. And they nonchalantly said "I'll write it in SQL", to which I almost let loose a chuckle until...'. Below this text is a dark-themed code editor window displaying the beginning of a SQL query. The code snippet shows a recursive Common Table Expression (CTE) to implement a Breadth-First Search (BFS) algorithm, starting with 'WITH RECURSIVE bfs AS'. The technical context is the impressive and unconventional use of SQL to solve a complex graph traversal problem typically handled by general-purpose programming languages. This resonates with senior engineers who appreciate deep, non-obvious knowledge of tools, showcasing SQL's Turing-completeness in a practical, high-stakes interview setting
Comments
7Comment deleted
Most candidates try to solve the problem. This one solved the interview. The only thing more surprising would be if they calculated Big O notation using only window functions
He wrote BFS as a recursive CTE; anyone who’s willing to let the query planner manage their queue is exactly the sort of optimistic masochist I want untangling our microservice graph
The same developer who implements BFS in SQL probably has a Kubernetes cluster running their personal blog and uses event sourcing for their grocery list
When the candidate said they'd implement BFS in SQL, the interviewer thought they were about to witness a career-ending mistake. Instead, they got a masterclass in why 'any language' should come with an asterisk - because somewhere out there, a senior engineer is absolutely convinced that recursive CTEs are the hill they'll die on, and honestly, after seeing this implementation with VARCHAR(1000) path tracking, they might just be right. It's the database equivalent of showing up to a knife fight with a spoon and somehow winning
Implementing BFS in SQL - because nothing says interview flex like a queue with ACID semantics and an execution plan as your hiring bar
BFS in recursive SQL CTE: Brilliant interview hack, until your graph hits recursion depth and turns into a DFS abyss
Nothing humbles an interviewer faster than watching BFS emerge from a WITH RECURSIVE; you came for Big‑O, you left debating cycle detection, index hints, and whether the optimizer is your queue