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.
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.
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 namesExact 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
namesdirectly keeps duplicates and query order. A query that joinsorderstocustomersand one that joinscustomerstoordersread 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
- What does this return for an empty string, or a query with no
FROMat all?findallreturns an empty list, so the result is[]with no special case needed. Lineage jobs see plenty of statements likeSELECT 1, and they should pass through without raising. - A query selects a column called
valid_from. What comes back?For
SELECT valid_from AS start FROM plansyou get['AS', 'plans'], because the keyword group matches the tail of the column name. Putting\bin front of the group fixes it, and effective-date columns named like this are common enough in warehouse tables that it's the first hardening to make. - How would you handle schema-qualified names such as
analytics.orders?As written,
\w+stops at the dot and returns only the schema, which is wrong; widening the capture to[\w.]+keeps the full name. Most production warehouses qualify tables, so ask whether the lineage graph keys on the bare table or the full path. - Should
Ordersandorderscount as the same table?Right now they stay as 2 entries, because the set compares names exactly as captured. Whether to lowercase before deduping depends on the warehouse's identifier rules, so it's a question to put to the interviewer instead of guessing.
- What about CTEs, subqueries, comments and string literals?
A CTE name after
FROMis reported as if it were a table, and aFROMinside a comment or a quoted string is matched like any other.FROM (SELECT ...)is safe by luck, since(is not a word character and the innerFROMstill matches. Past this point the right tool is a SQL parser that knows what a token is.