Design a Fluent Query Builder with Chaining and Join Support
Data Structure DesignModel answerLast updated
Build a Python query builder that chains table, select, where, alias, and join methods, rendering to SQL strings that match an exact expected format.
Design and implement a query builder in Python that supports a fluent, chainable API. Your implementation will be tested against an existing suite that calls methods and compares the output of render() against expected SQL strings.
The entry point provides two factory methods:
o.table(name)— starts a query for the given tableo.cond(column, operator, value)— creates a condition object
The query object returned by table() supports these methods:
select(*columns)— specifies which columns to retrievewhere(*conditions)— filters rows using condition objectsalias(name)— assigns a table aliasjoin(other_query, using=column)— joins with another query on a shared columnrender()— returns the final SQL string
Example Usage
# Simple query
o.table("users").select("id", "email").render()
# Query with conditions
o.table("products").select("id", "upc", "volume").where(
o.cond("volume", ">", 300),
o.cond("upc", "=", "1337")
).render()
# Query with alias
o.table("products").select("product_id", "price").alias("p").render()
# Joined queries
users = o.table("users").select("user_id", "email").alias("u")
apps = o.table("applications").select("loan_id").alias("app")
users.join(apps, using="user_id").render()
Requirements
- Each method call returns a query object, enabling method chaining
- The
render()method produces a SQLSELECTstatement matching the exact format expected by the tests - Conditions created with
condsupport at least=and>operators - Multiple conditions passed to
whereare combined appropriately - When queries are joined, the shared column specified in
usingdetermines the join relationship - The exact formatting details (keyword case, spacing, use of
AS, semicolons, etc.) are determined by the test expectations
Questions to Clarify
Before implementing, confirm with the interviewer:
- What exact SQL format do the tests expect? (Keyword case, spacing, whether
ASappears before aliases, semicolon at end) - When a table has an alias, should selected columns be qualified with it (e.g.,
p.price)? - How are multiple conditions combined? With
AND? Canwherebe called multiple times? - Which operators must be supported beyond
=and>? - How should string values with embedded quotes be escaped?
- Should methods return new query objects (immutable) or modify the existing one (mutable)?
- In a joined query, which columns appear in the final
SELECTclause and in what order? - How should
Nonevalues render in conditions?
Hints
Hint 1
Store the query components (table, columns, conditions, alias, joins) as internal state and assemble them only when render() is called
Hint 2
Decide early whether your builder is mutable or immutable—the join example suggests mutation since the result isn't reassigned
Hint 3
When qualifying column names in joins, check whether a table has an alias and use it; otherwise use the table name
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to design a clean, chainable API while managing internal state and producing exact string output. The core challenge is translating method calls into a structured representation that can be rendered to SQL in a single pass.
Architecture
The builder maintains internal state for:
- Table name and optional alias
- Selected columns (list)
- Conditions (list of condition objects)
- Joined query (reference to another builder) and join column
Each fluent method modifies this state and returns self, enabling chaining. The render() method traverses the state once to construct the final SQL string.
Key Design Decisions
Mutable vs Immutable: The join example (users.join(apps, using="user_id")) doesn't reassign the result, suggesting the builder mutates in place. An immutable design would require users = users.join(...), which is more functional but less convenient for complex queries.
Condition Objects: Rather than accepting raw tuples, the cond() factory returns a condition object encapsulating column, operator, and value. This allows validation at creation time and cleaner rendering logic.
Column Qualification: In joins, columns must be qualified with their table alias (or table name if no alias). Without a join, qualification is typically omitted unless the test suite requires it.
Literal Rendering:
- Numbers render bare:
300 - Strings are single-quoted with embedded quotes escaped:
'1337'or'O''Reilly' Nonetypically renders asNULL- Booleans as
TRUE/FALSE(database-dependent)
Implementation
class Condition:
def __init__(self, column, operator, value):
self.column = column
self.operator = operator
self.value = value
def render(self, qualifier=None):
col = f"{qualifier}.{self.column}" if qualifier else self.column
val = self._render_value(self.value)
return f"{col} {self.operator} {val}"
def _render_value(self, value):
if value is None:
return "NULL"
elif isinstance(value, str):
# Escape single quotes by doubling them
escaped = value.replace("'", "''")
return f"'{escaped}'"
elif isinstance(value, bool):
return "TRUE" if value else "FALSE"
else:
return str(value)
class QueryBuilder:
def __init__(self, table_name):
self._table = table_name
self._columns = []
self._conditions = []
self._alias = None
self._joined = None
self._join_column = None
def select(self, *columns):
self._columns.extend(columns)
return self
def where(self, *conditions):
self._conditions.extend(conditions)
return self
def alias(self, name):
self._alias = name
return self
def join(self, other, using):
self._joined = other
self._join_column = using
return self
def render(self):
parts = ["SELECT"]
# Build column list
if self._joined:
# Qualify columns with their table aliases
left_qual = self._alias or self._table
cols = [f"{left_qual}.{c}" for c in self._columns]
right_qual = self._joined._alias or self._joined._table
cols.extend([f"{right_qual}.{c}" for c in self._joined._columns])
parts.append(" " + ", ".join(cols))
else:
parts.append(" " + ", ".join(self._columns))
# FROM clause
parts.append(" FROM " + self._table)
if self._alias and not self._joined:
parts.append(" AS " + self._alias)
elif self._alias:
parts.append(" " + self._alias)
# JOIN clause
if self._joined:
other_table = self._joined._table
other_alias = self._joined._alias
if other_alias:
parts.append(f" JOIN {other_table} {other_alias}")
else:
parts.append(f" JOIN {other_table}")
parts.append(f" USING ({self._join_column})")
# WHERE clause
if self._conditions:
qualifier = self._alias if self._alias else None
cond_strs = [c.render(qualifier) for c in self._conditions]
parts.append(" WHERE " + " AND ".join(cond_strs))
return "".join(parts) + ";"
class QueryFactory:
def table(self, name):
return QueryBuilder(name)
def cond(self, column, operator, value):
return Condition(column, operator, value)
# Entry point
o = QueryFactory()
Complexity
- Time: O(n) where n is the total number of columns and conditions; each is visited once during rendering
- Space: O(n) to store columns, conditions, and the generated string
Common Mistakes
-
Call-order dependency: Building SQL incrementally as methods are called makes clause ordering fragile. Always defer to
render(). -
Forgetting to escape quotes: A value like
O'Reillywill break the query if not escaped toO''Reilly. -
Over-qualifying columns: Adding table prefixes when there's no join clutters the output and may fail tests.
-
Immutability confusion: If you return new objects from each method, the join example breaks. Match the expected pattern.
-
Hardcoding format: Tests might expect
JOIN ... USINGwhile you emitJOIN ... ON. Read the test expectations carefully or confirm with the interviewer.
Extensions
Once the core works, typical follow-ups include:
ORDER BYandLIMITclausesORsupport in conditions- Subqueries in
FROMorWHERE - Parameter binding instead of inline literals (for real SQL libraries)