The Table Thief

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L4
Asked in
DoorDash

Problem

You're building a data-lineage tool that needs to know which tables each query reads. Given a SQL query string sql, pull the table names that follow its FROM and JOIN keywords, where a name may be trailed by an alias that isn't part of it.

Somewhere in that query, tables are hiding.

Example 1

Input:

sql = "SELECT a.id, b.name\nFROM orders a\nJOIN customers b ON a.customer_id = b.id"

Output:

["customers","orders"]

Example 2

Input:

sql = "SELECT a.id\nFROM users a\nJOIN users b ON a.manager_id = b.id"

Output:

["users"]

Worked solution and explanation

Nothing about the word orders marks it as a table: it looks like any column or alias. What identifies it is position, the first word after FROM or JOIN. That makes this keyword-anchored extraction: find the anchor, capture the single token after it, and stop before the alias. Each of the 3 sample queries leans on a different part of that: an alias to skip, a self-join that repeats a table, and keywords typed in mixed case.

From anchor to captured name

Step 1: Match the keyword without keeping it

(?:FROM|JOIN) is a non-capturing group. findall returns whatever the capture groups hold, so a plain (FROM|JOIN) would hand back pairs like ('FROM', 'orders') that you then have to unpack. With only the name captured, you get a flat list of strings.

Step 2: Treat a line break as a space

\s+ matches any whitespace character, newlines included. Formatted SQL puts the table on the next line as often as on the same one, and a literal space in the pattern would miss those.

Step 3: End the capture where the alias begins

(\w+) takes word characters and stops at the first whitespace. In FROM orders a the capture is orders and the alias a is never examined, so there is no alias-parsing code to write.

Step 4: Ignore the case of the keywords

re.IGNORECASE lets from and Left Join match. Only the Join part is matched, which is why a LEFT join needs no alternative of its own, and neither does INNER or CROSS. The captured name comes back exactly as the query spelled it.

Step 5: Collapse repeats and fix the order

findall yields one entry per occurrence, in the order written, so the self-join gives ['users', 'users']. The lineage question is which tables a query reads, so set removes the repeat and sorted makes the answer independent of join order.

Keyword-anchored extraction
import re

def extract_table_names(sql):
    pattern = re.compile(r'(?:FROM|JOIN)\s+(\w+)', re.IGNORECASE)
    names = pattern.findall(sql)
    return sorted(set(names))

One compiled pattern, one pass, then normalize into a sorted unique set.

Splitting on whitespace instead

The version most people write first has no regex: split the query on whitespace and take the token after each keyword.

Token after the keyword
def extract_table_names(sql):
    tokens = sql.split()
    names = []
    for i, tok in enumerate(tokens[:-1]):
        if tok in ('FROM', 'JOIN'):
            names.append(tokens[i + 1])
    return names

Exact uppercase comparison, no dedup, no sort.

Run on the 3 sample queries, it returns ['orders', 'customers'] for the first: the right tables in query order, which fails against ['customers', 'orders']. The self-join returns ['users', 'users']. The third query returns []. It spells its keywords from and Left Join, and no token equals an uppercase keyword.

Matches as found
Returning names directly keeps duplicates and query order. A query that joins orders to customers and one that joins customers to orders read the same tables but produce different lists.
Sorted unique names
sorted(set(names)) returns one entry per table in alphabetical order. Any 2 queries that read the same tables give the same list, which is what lets you diff or dedupe lineage rows.

Where the pattern stops understanding SQL

Common follow-up questions