Fluent SQL SELECT Query Builder in Python

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement a fluent Python SQL SELECT builder consisting of two factory functions, table(name) and cond(column, operator, value), alongside the Query and Condition classes. Callers construct queries either directly or via a namespace object o exposing o.table and o.cond, chain builder methods in arbitrary order, and call render() to produce an exact SQL SELECT string.

Builder API

  • table(name: str) -> Query: Creates a Query targeting name.
  • cond(column: str, operator: str, value: Value) -> Condition: Creates a single predicate comparing column against value using operator.
  • Query.select(*columns: str) -> Query: Appends one or more column names to this query's projection list and returns self.
  • Query.where(*conditions: Condition) -> Query: Appends one or more Condition instances to this query's filter list and returns self.
  • Query.alias(name: str) -> Query: Assigns (or updates) this table's SQL alias (FROM <table> AS <alias>) and returns self.
  • Query.join(other: Query, using: str) -> Query: Appends an inner join against another distinct single-table Query on a shared column (JOIN <other> USING (<using>)) and returns self.
  • Query.render() -> str: Formats and returns the complete SQL statement without mutating stored builder state.

Note that select, where, alias, and join mutate the Query in place and return self (so both chained calls q.select(...).where(...) and standalone statements left.join(right, using=...) take effect on left).

SQL Rendering & Validation Rules

  1. Clause order & formatting: Emit clauses in standard SQL order: SELECT <cols> FROM <table> [JOIN <other> USING (<col>) ...] [WHERE <preds>]. Use uppercase SQL keywords (SELECT, FROM, AS, JOIN, USING, WHERE, AND, IS NULL, IS NOT NULL, TRUE, FALSE), single spaces between clauses and operators, ", " between projected columns, " AND " between predicates, and no trailing semicolon.
  2. Column qualification:
    • If a Query has .alias(a), qualify all of its projected columns and WHERE predicates with a. (even when not joined).
    • Inside a joined query, any participating Query without an alias qualifies its projected columns and WHERE predicates with <table_name>..
    • On an unaliased single-table query without joins, leave columns unqualified.
  3. Projection & filter ordering: Concatenate projected columns in table order (left Query first, then each joined Query in .join() order), preserving .select() call order within each table; if zero columns are selected across all tables, emit SELECT *. Combine all WHERE conditions across participating tables in the same table order using AND.
  4. Literals & operators:
    • Supported operators: "=", "!=", "<>", "<", "<=", ">", ">=". Any other operator raises ValueError.
    • bool: True -> TRUE, False -> FALSE.
    • int and finite float: unquoted numeric text (25, -3, 2.5); NaN or +/-inf raises ValueError.
    • str: wrapped in single quotes with internal single quotes doubled ("DHL's Express" -> 'DHL''s Express').
    • None: permitted only with "=" (<col> IS NULL) or "!=" / "<>" (<col> IS NOT NULL); pairing None with <, <=, >, or >= raises ValueError.
    • Unsupported value types (or passing non-Condition / non-Query objects to where / join) raise TypeError.

Examples

Example 1

o.table("customers").select("customer_id", "tier").render()

Output:

"SELECT customer_id, tier FROM customers"

Walk-through: A single unaliased table without joins renders unqualified column names separated by ", " in .select() order.

Example 2

o.table("shipments").select("shipment_id", "carrier", "weight_kg").where(
    o.cond("weight_kg", ">=", 25),
    o.cond("carrier", "=", "DHL's Express"),
    o.cond("delivered_at", "=", None),
).render()

Output:

"SELECT shipment_id, carrier, weight_kg FROM shipments WHERE weight_kg >= 25 AND carrier = 'DHL''s Express' AND delivered_at IS NULL"

Walk-through: Integers render bare (25), strings are single-quoted with embedded apostrophes doubled ('DHL''s Express'), = None renders as IS NULL, and multiple predicates join with AND.

Example 3

(
    o.table("invoices")
    .where(o.cond("total_cents", ">", 5000))
    .alias("inv")
    .select("invoice_id", "total_cents")
    .render()
)

Output:

"SELECT inv.invoice_id, inv.total_cents FROM invoices AS inv WHERE inv.total_cents > 5000"

Walk-through: Even though .where() ran before .alias("inv") and .select(), rendering happens lazily at the end so AS inv is emitted and inv. prefixes both selected columns and filter columns.

Example 4

customers = o.table("customers").select("customer_id", "tier").alias("c")
orders = o.table("orders").select("order_id").alias("ord").where(o.cond("paid", "=", True))
customers.join(orders, using="customer_id")
customers.render()

Output:

"SELECT c.customer_id, c.tier, ord.order_id FROM customers AS c JOIN orders AS ord USING (customer_id) WHERE ord.paid = TRUE"

Walk-through: customers.join(orders, using="customer_id") mutates customers in place, concatenates c's selected columns ahead of ord's, emits JOIN orders AS ord USING (customer_id), and qualifies ord's boolean filter as ord.paid = TRUE.

Constraints

  • Every table name, column name, alias, and using column must be a valid plain ASCII identifier matching [A-Za-z_][A-Za-z0-9_]*; any other string or non-string raises ValueError.
  • join(other, using) only accepts a distinct single-table Query (other is not self and other has no joins of its own, both when join() is called and when render() runs); violations raise ValueError.
  • Across a joined query, all active table qualifiers (each table's alias if set, otherwise its table name) must be unique case-insensitively (customers vs. Customers, or aliases C vs. c, must raise ValueError).

Step-by-step walkthrough

  1. Pin down the exact SQL contract

    Callers drive the query builder through a fluent API (a design pattern where configuration methods return self so calls read left-to-right in a chain). Because render() must produce exact SQL text, review the formatting and scoping rules first:

    • Keywords and spacing: uppercase SQL keywords (SELECT, FROM, AS, JOIN, USING, WHERE, AND), single spaces between tokens, ", " between columns, and no trailing semicolon.
    • Aliases and column prefixes: .alias("inv") emits FROM invoices AS inv and prefixes that table's selected columns and filter conditions (inv.total_cents) even on a single-table query.
    • Joins: .join(other, using="customer_id") emits JOIN orders AS ord USING (customer_id). Inside a join, any table without an alias falls back to its own table name (customers.customer_id) so column references are never ambiguous.
    • Selected columns: left query's columns first, then each joined query's columns in .join() order, preserving .select() order within each table. When zero columns are selected anywhere, emit SELECT *.
    • Conditions: multiple predicates in one .where(...), repeated .where(...) calls, and predicates across joined tables all combine with AND, left query first.
    • In-place mutation: In Example 4, customers.join(orders, using="customer_id") is called as a standalone statement before customers.render(). Thus builder methods must mutate the receiver in place while also returning self.

    Trace how the four examples map onto those rules:

    1. o.table("customers").select("customer_id", "tier")
       -> SELECT customer_id, tier FROM customers
    
    2. o.table("shipments").select("shipment_id", "carrier", "weight_kg").where(
           o.cond("weight_kg", ">=", 25),
           o.cond("carrier", "=", "DHL's Express"),
           o.cond("delivered_at", "=", None))
       -> SELECT shipment_id, carrier, weight_kg FROM shipments WHERE weight_kg >= 25 AND carrier = 'DHL''s Express' AND delivered_at IS NULL
    
    3. o.table("invoices").where(o.cond("total_cents", ">", 5000)).alias("inv").select("invoice_id", "total_cents")
       -> SELECT inv.invoice_id, inv.total_cents FROM invoices AS inv WHERE inv.total_cents > 5000
    
    4. customers.join(orders, using="customer_id")
       -> SELECT c.customer_id, c.tier, ord.order_id FROM customers AS c JOIN orders AS ord USING (customer_id) WHERE ord.paid = TRUE
    
  2. Record first, render last

    Concatenating SQL strings eagerly inside .select() or .where() breaks immediately on Example 3, where .where(...) is called before .alias("inv") and .select(...):

    Eager string concatenation (broken):
      o.table("invoices")                        -> "FROM invoices"
       .where(o.cond("total_cents", ">", 5000))  -> "FROM invoices WHERE total_cents > 5000"  (missing 'inv.'!)
       .alias("inv")                             -> too late: WHERE text was already frozen
    
    Record first, render last (clean):
      o.table("invoices")                        -> table_name="invoices"
       .where(o.cond("total_cents", ">", 5000))  -> conditions=[Condition("total_cents", ">", 5000)]
       .alias("inv")                             -> alias_name="inv"
       .select("invoice_id", "total_cents")      -> columns=["invoice_id", "total_cents"]
       .render()                                 -> prefixes everything with "inv." at render time!
    

    So Query stores five structured fields (table_name, columns, conditions, alias_name, joins), validates inputs eagerly, and leaves string construction entirely to render():

    class Query:
        """A SELECT on one table, optionally joined with other single-table queries.
    
        Builder methods mutate this Query in place and return self so calls can be chained.
        """
    
        def __init__(self, table_name: str):
            self.table_name: str = check_identifier(table_name)
            # columns: plain column names in call order, e.g. ["id", "email"]
            self.columns: List[str] = []
            # conditions: Condition objects in call order, combined later with AND
            self.conditions: List[Condition] = []
            # alias_name: optional SQL table alias, e.g. "u" for `FROM users AS u`
            self.alias_name: Optional[str] = None
            # joins: list of (other_query, shared_using_column) pairs, e.g. [(apps, "user_id")]
            self.joins: List[Tuple["Query", str]] = []
    
        def select(self, *columns: str) -> "Query":
            for column in columns:
                self.columns.append(check_identifier(column))
            return self
    
        def where(self, *conditions: Condition) -> "Query":
            for condition in conditions:
                if not isinstance(condition, Condition):
                    raise TypeError("where() takes conditions made by cond()")
                self.conditions.append(condition)
            return self
    
        def alias(self, name: str) -> "Query":
            self.alias_name = check_identifier(name)
            return self
    
        def join(self, other: "Query", using: str) -> "Query":
            if not isinstance(other, Query):
                raise TypeError("join() takes another query")
            # Only flat joins of distinct single-table queries are representable without subqueries
            if other is self or other.joins:
                raise ValueError("join() takes a different, single-table query")
            shared_col = check_identifier(using)
            self.joins.append((other, shared_col))
            return self
    
  3. Validate identifiers and format SQL literals

    Each Python scalar in cond(column, operator, value) maps to a specific SQL literal syntax:

    • None becomes NULL.
    • bool becomes TRUE or FALSE. Check isinstance(value, bool) before isinstance(value, int) because bool subclasses int in Python (isinstance(True, int) evaluates to True!).
    • int and finite float render unquoted (25, -12, 4.75). Reject NaN and +/-inf via math.isfinite(value) because standard SQL has no numeric literal for them.
    • str wraps in single quotes with any embedded single quote doubled ("DHL's Express" -> 'DHL''s Express').

    Because table, column, and alias identifiers cannot be quoted as string values, check_identifier enforces [A-Za-z_][A-Za-z0-9_]*, rejecting SQL-injection attempts like "customers; DROP TABLE customers" immediately:

    IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
    OPERATORS = ("=", "!=", "<>", "<", "<=", ">", ">=")
    
    
    def check_identifier(name: str) -> str:
        """Return name if it is a plain SQL identifier, else raise ValueError."""
        # Table, column, and alias names cannot be bound as value literals, so validate strictly
        if not isinstance(name, str) or not IDENTIFIER.fullmatch(name):
            raise ValueError(f"not a plain identifier: {name!r}")
        return name
    
    
    def sql_literal(value: Value) -> str:
        """Convert one Python scalar value into its exact SQL literal text."""
        if value is None:
            return "NULL"
        # Check bool BEFORE int because bool is a subclass of int in Python (isinstance(True, int) is True)
        if isinstance(value, bool):
            return "TRUE" if value else "FALSE"
        if isinstance(value, int):
            return str(value)
        if isinstance(value, float):
            # NaN and +/-inf have no standard SQL numeric literal
            if not math.isfinite(value):
                raise ValueError(f"SQL has no literal for {value!r}")
            return repr(value)
        if isinstance(value, str):
            # Standard SQL escapes a single quote inside a string literal by doubling it ('O''Brien')
            escaped = value.replace("'", "''")
            return "'" + escaped + "'"
        raise TypeError(f"unsupported value type: {type(value).__name__}")
    
  4. Build table-independent Condition objects

    When caller code creates o.cond("total_cents", ">", 5000), that Condition is not yet attached to any Query and cannot know whether its qualifier will be None, "inv", or "invoices". So Condition stores (column, operator, value) and receives qualifier later inside Condition.render(qualifier).

    None requires special handling because SQL uses three-valued logic (TRUE, FALSE, and UNKNOWN). Writing delivered_at = NULL evaluates to UNKNOWN on every row and matches nothing! Instead, = None must emit IS NULL, != None and <> None must emit IS NOT NULL, and ordering operators like > None must raise ValueError:

    def qualify(qualifier: Optional[str], column: str) -> str:
        """Prefix column with 'qualifier.' when a table or alias prefix is active."""
        if qualifier is None:
            return column
        return qualifier + "." + column
    
    
    class Condition:
        """One comparison `column operator value`, made by cond()."""
    
        def __init__(self, column: str, operator: str, value: Value):
            # Store raw pieces now; the table/alias prefix is unknown until Query.render() runs
            self.column = check_identifier(column)
            if operator not in OPERATORS:
                raise ValueError(f"unsupported operator: {operator!r}")
            if value is None and operator not in ("=", "!=", "<>"):
                raise ValueError("None can only be compared with =, != or <>")
            # Validate value conversion eagerly so bad types/NaNs fail at cond(...) call time
            sql_literal(value)
            self.operator = operator
            self.value = value
    
        def render(self, qualifier: Optional[str]) -> str:
            qualified_col = qualify(qualifier, self.column)
            if self.value is None:
                # In SQL three-valued logic, `col = NULL` is UNKNOWN (never true), so use IS [NOT] NULL
                if self.operator == "=":
                    return qualified_col + " IS NULL"
                return qualified_col + " IS NOT NULL"
            return qualified_col + " " + self.operator + " " + sql_literal(self.value)
    
  5. Choose qualifiers and assemble SQL clauses

    Three rules determine a table's column prefix:

    +-----------------------------------+--------------------+-------------------------+
    | Query context                     | Active qualifier   | Rendered column example |
    +-----------------------------------+--------------------+-------------------------+
    | Query has .alias("inv")           | alias ("inv")      | inv.total_cents         |
    | Unaliased, participating in JOIN  | table name         | customers.customer_id   |
    | Unaliased, single-table query     | None (unqualified) | customer_id             |
    +-----------------------------------+--------------------+-------------------------+
    

    In any joined query, participating qualifiers must be distinct case-insensitively (customers vs. Customers, or aliases C vs. c) because unquoted SQL identifiers ignore case. Tracking prefix.lower() in seen_lower catches collisions cleanly before emitting SELECT, FROM, JOIN ... USING (...), and WHERE:

        def qualifier(self, is_joined: bool) -> Optional[str]:
            """Prefix for this table's columns: alias if set, table name in a join, else None."""
            if self.alias_name is not None:
                return self.alias_name
            if is_joined:
                return self.table_name
            return None
    
        def table_sql(self) -> str:
            """Render the FROM / JOIN target, e.g. 'users' or 'users AS u'."""
            if self.alias_name is None:
                return self.table_name
            return self.table_name + " AS " + self.alias_name
    
        def render(self) -> str:
            # Phase 1: gather the left query followed by each joined query, checking for nested joins
            parts: List["Query"] = [self]
            for other, _ in self.joins:
                if other.joins:
                    raise ValueError("a joined query cannot have joins of its own")
                parts.append(other)
            is_joined = len(parts) > 1
    
            # Phase 2: compute each table's column qualifier and reject case-insensitive collisions
            qualifiers: List[Optional[str]] = []
            seen_lower = set()
            for part in parts:
                prefix = part.qualifier(is_joined)
                if prefix is not None:
                    # Unquoted SQL identifiers are case-insensitive ('U' and 'u' collide)
                    lower_key = prefix.lower()
                    if lower_key in seen_lower:
                        raise ValueError(f"two tables are both called {prefix!r}; give one an alias")
                    seen_lower.add(lower_key)
                qualifiers.append(prefix)
    
            # Phase 3: qualify SELECT columns and render WHERE conditions in table order
            select_items: List[str] = []
            where_items: List[str] = []
            for part, prefix in zip(parts, qualifiers):
                for column in part.columns:
                    select_items.append(qualify(prefix, column))
                for condition in part.conditions:
                    where_items.append(condition.render(prefix))
    
            # Phase 4: assemble SQL clauses in fixed grammar order (SELECT, FROM, JOIN, WHERE)
            if select_items:
                clauses = ["SELECT " + ", ".join(select_items)]
            else:
                clauses = ["SELECT *"]
            clauses.append("FROM " + self.table_sql())
            for other, using_col in self.joins:
                clauses.append("JOIN " + other.table_sql() + " USING (" + using_col + ")")
            if where_items:
                clauses.append("WHERE " + " AND ".join(where_items))
            return " ".join(clauses)
    

    Notice why if other.joins: is checked both inside join() and again inside render(): because Query objects are mutable, a caller could attach middle to left first and subsequently call middle.join(refunds, ...) before calling left.render().

  6. Trace Example 4 from start to finish

    Walk through Example 4 step by step:

    1. customers = o.table("customers").select("customer_id", "tier").alias("c")
         customers.table_name = "customers"
         customers.columns    = ["customer_id", "tier"]
         customers.alias_name = "c"
    
    2. orders = o.table("orders").select("order_id").alias("ord").where(o.cond("paid", "=", True))
         orders.table_name    = "orders"
         orders.columns       = ["order_id"]
         orders.alias_name    = "ord"
         orders.conditions    = [Condition("paid", "=", True)]
    
    3. customers.join(orders, using="customer_id")
         customers.joins      = [(orders, "customer_id")]   (mutated in place)
    
    4. customers.render():
         parts        = [customers, orders],  is_joined = True
         qualifiers   = ["c", "ord"],         seen_lower = {"c", "ord"}
         select_items = ["c.customer_id", "c.tier", "ord.order_id"]
         where_items  = ["ord.paid = TRUE"]
         clauses      = [
           "SELECT c.customer_id, c.tier, ord.order_id",
           "FROM customers AS c",
           "JOIN orders AS ord USING (customer_id)",
           "WHERE ord.paid = TRUE"
         ]
         result -> "SELECT c.customer_id, c.tier, ord.order_id FROM customers AS c JOIN orders AS ord USING (customer_id) WHERE ord.paid = TRUE"
    
  7. Complete solution

    from typing import List, Optional, Tuple, Union
    import math
    import re
    
    Value = Union[None, bool, int, float, str]
    
    # Plain SQL identifier: starts with a letter or underscore, followed by letters, digits, or underscores
    IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
    OPERATORS = ("=", "!=", "<>", "<", "<=", ">", ">=")
    
    
    def check_identifier(name: str) -> str:
        """Return name if it is a plain SQL identifier, else raise ValueError."""
        # Table, column, and alias names cannot be bound as value literals, so validate strictly
        if not isinstance(name, str) or not IDENTIFIER.fullmatch(name):
            raise ValueError(f"not a plain identifier: {name!r}")
        return name
    
    
    def sql_literal(value: Value) -> str:
        """Convert one Python scalar value into its exact SQL literal text."""
        if value is None:
            return "NULL"
        # Check bool BEFORE int because bool is a subclass of int in Python (isinstance(True, int) is True)
        if isinstance(value, bool):
            return "TRUE" if value else "FALSE"
        if isinstance(value, int):
            return str(value)
        if isinstance(value, float):
            # NaN and +/-inf have no standard SQL numeric literal
            if not math.isfinite(value):
                raise ValueError(f"SQL has no literal for {value!r}")
            return repr(value)
        if isinstance(value, str):
            # Standard SQL escapes a single quote inside a string literal by doubling it ('O''Brien')
            escaped = value.replace("'", "''")
            return "'" + escaped + "'"
        raise TypeError(f"unsupported value type: {type(value).__name__}")
    
    
    def qualify(qualifier: Optional[str], column: str) -> str:
        """Prefix column with 'qualifier.' when a table or alias prefix is active."""
        if qualifier is None:
            return column
        return qualifier + "." + column
    
    
    class Condition:
        """One comparison `column operator value`, made by cond()."""
    
        def __init__(self, column: str, operator: str, value: Value):
            # Store raw pieces now; the table/alias prefix is unknown until Query.render() runs
            self.column = check_identifier(column)
            if operator not in OPERATORS:
                raise ValueError(f"unsupported operator: {operator!r}")
            if value is None and operator not in ("=", "!=", "<>"):
                raise ValueError("None can only be compared with =, != or <>")
            # Validate value conversion eagerly so bad types/NaNs fail at cond(...) call time
            sql_literal(value)
            self.operator = operator
            self.value = value
    
        def render(self, qualifier: Optional[str]) -> str:
            qualified_col = qualify(qualifier, self.column)
            if self.value is None:
                # In SQL three-valued logic, `col = NULL` is UNKNOWN (never true), so use IS [NOT] NULL
                if self.operator == "=":
                    return qualified_col + " IS NULL"
                return qualified_col + " IS NOT NULL"
            return qualified_col + " " + self.operator + " " + sql_literal(self.value)
    
    
    class Query:
        """A SELECT on one table, optionally joined with other single-table queries.
    
        Builder methods mutate this Query in place and return self so calls can be chained.
        """
    
        def __init__(self, table_name: str):
            self.table_name: str = check_identifier(table_name)
            # columns: plain column names in call order, e.g. ["id", "email"]
            self.columns: List[str] = []
            # conditions: Condition objects in call order, combined later with AND
            self.conditions: List[Condition] = []
            # alias_name: optional SQL table alias, e.g. "u" for `FROM users AS u`
            self.alias_name: Optional[str] = None
            # joins: list of (other_query, shared_using_column) pairs, e.g. [(apps, "user_id")]
            self.joins: List[Tuple["Query", str]] = []
    
        def select(self, *columns: str) -> "Query":
            for column in columns:
                self.columns.append(check_identifier(column))
            return self
    
        def where(self, *conditions: Condition) -> "Query":
            for condition in conditions:
                if not isinstance(condition, Condition):
                    raise TypeError("where() takes conditions made by cond()")
                self.conditions.append(condition)
            return self
    
        def alias(self, name: str) -> "Query":
            self.alias_name = check_identifier(name)
            return self
    
        def join(self, other: "Query", using: str) -> "Query":
            if not isinstance(other, Query):
                raise TypeError("join() takes another query")
            # Only flat joins of distinct single-table queries are representable without subqueries
            if other is self or other.joins:
                raise ValueError("join() takes a different, single-table query")
            shared_col = check_identifier(using)
            self.joins.append((other, shared_col))
            return self
    
        def qualifier(self, is_joined: bool) -> Optional[str]:
            """Prefix for this table's columns: alias if set, table name in a join, else None."""
            if self.alias_name is not None:
                return self.alias_name
            if is_joined:
                return self.table_name
            return None
    
        def table_sql(self) -> str:
            """Render the FROM / JOIN target, e.g. 'users' or 'users AS u'."""
            if self.alias_name is None:
                return self.table_name
            return self.table_name + " AS " + self.alias_name
    
        def render(self) -> str:
            # Phase 1: gather the left query followed by each joined query, checking for nested joins
            parts: List["Query"] = [self]
            for other, _ in self.joins:
                if other.joins:
                    raise ValueError("a joined query cannot have joins of its own")
                parts.append(other)
            is_joined = len(parts) > 1
    
            # Phase 2: compute each table's column qualifier and reject case-insensitive collisions
            qualifiers: List[Optional[str]] = []
            seen_lower = set()
            for part in parts:
                prefix = part.qualifier(is_joined)
                if prefix is not None:
                    # Unquoted SQL identifiers are case-insensitive ('U' and 'u' collide)
                    lower_key = prefix.lower()
                    if lower_key in seen_lower:
                        raise ValueError(f"two tables are both called {prefix!r}; give one an alias")
                    seen_lower.add(lower_key)
                qualifiers.append(prefix)
    
            # Phase 3: qualify SELECT columns and render WHERE conditions in table order
            select_items: List[str] = []
            where_items: List[str] = []
            for part, prefix in zip(parts, qualifiers):
                for column in part.columns:
                    select_items.append(qualify(prefix, column))
                for condition in part.conditions:
                    where_items.append(condition.render(prefix))
    
            # Phase 4: assemble SQL clauses in fixed grammar order (SELECT, FROM, JOIN, WHERE)
            if select_items:
                clauses = ["SELECT " + ", ".join(select_items)]
            else:
                clauses = ["SELECT *"]
            clauses.append("FROM " + self.table_sql())
            for other, using_col in self.joins:
                clauses.append("JOIN " + other.table_sql() + " USING (" + using_col + ")")
            if where_items:
                clauses.append("WHERE " + " AND ".join(where_items))
            return " ".join(clauses)
    
    
    def table(name: str) -> Query:
        """o.table(name): start a query on one table."""
        return Query(name)
    
    
    def cond(column: str, operator: str, value: Value) -> Condition:
        """o.cond(column, operator, value): one condition for where()."""
        return Condition(column, operator, value)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a SQL query builder like jotting down customer requests on a cafe notepad before printing the kitchen ticket. A guest might give instructions in any sequence ("only orders over $50", "label this table inv", "show invoice_id and total_cents"), whereas SQL grammar insists on one rigid order (SELECT ... FROM ... JOIN ... WHERE ...). Applying the builder pattern (an object that records configuration pieces incrementally and assembles the finished product in one step at the end) cleanly decouples collecting caller intent from formatting SQL text.

Eagerly concatenating SQL substrings inside .where() or .select() fails immediately whenever methods run out of SQL clause order. For example, if .where(o.cond("total_cents", ">", 5000)) baked "WHERE total_cents > 5000" into a string right away, calling .alias("inv") on the next step would leave WHERE missing its inv. prefix, and a second .select() call would have nowhere clean to splice extra columns. Likewise, o.cond(...) is instantiated before being passed to any Query, so it cannot know its table qualifier at construction time.

Instead, every builder method appends validated items onto plain lists on Query, and render() formats everything in one final pass. Tracing Example 3: 1. o.table("invoices") initializes table_name = "invoices". 2. .where(o.cond("total_cents", ">", 5000)) appends Condition("total_cents", ">", 5000) to conditions. 3. .alias("inv") sets alias_name = "inv", and .select("invoice_id", "total_cents") appends both column names to columns. 4. .render() observes alias_name = "inv", prefixes every selected column and condition with "inv.", and emits "SELECT inv.invoice_id, inv.total_cents FROM invoices AS inv WHERE inv.total_cents > 5000".

Complexity

  • Builder methods (table, cond, select, where, alias, join): O(k) time for a call passing k arguments (treating identifier lengths as bounded by a small constant, or linear in total identifier character length), since each identifier is validated once via IDENTIFIER.fullmatch and appended to a Python list in O(1) amortized time.
  • render() time: O(S), where S is the character length of the rendered SQL string. Each participating table is visited once (using an O(1) hash-set lookup on prefix.lower() to detect collisions), each column and condition is formatted once, and all pieces are joined in linear time via ", ".join(...), " AND ".join(...), and " ".join(...).
  • Space: O(C + W) on Query to store C projected column names and W Condition instances, plus O(S) temporary memory inside render() for the formatted clause list and output string.

Edge cases

  • No select() called anywhere: Emits SELECT *. In a multi-table join where one table selects columns and a bridge table selects none, only the selected columns appear.
  • Apostrophes inside string literals: "DHL's Express" becomes 'DHL''s Express' by doubling embedded single quotes; "" becomes ''.
  • None comparisons (NULL): Under SQL three-valued logic (expressions evaluate to TRUE, FALSE, or UNKNOWN), col = NULL is always UNKNOWN and matches zero rows. Thus = None renders IS NULL, != None and <> None render IS NOT NULL, and ordering operators like > None raise ValueError.
  • Booleans vs. integers: Because bool subclasses int in Python (isinstance(True, int) is True), sql_literal checks bool before int so True/False render as TRUE/FALSE instead of 1/0.
  • Non-finite floats: float("nan") and float("inf") lack standard SQL numeric literals and raise ValueError eagerly in cond(...).
  • Arbitrary chaining order and repeated calls: Calling .where() before .alias() or invoking .select() and .where() multiple times yields identical SQL because qualification and clause assembly happen lazily in render().
  • Self-joins and case-insensitive collisions: Unaliased customers JOIN customers (or customers JOIN Customers, or aliases C and c) is rejected via prefix.lower(), whereas employees AS mgr JOIN employees AS rep succeeds cleanly.
  • Post-join mutations: Because join() stores a live reference to other, adding .where() onto orders after customers.join(orders, ...) still appears in customers.render(); if orders later adds its own .join(), customers.render() catches other.joins and raises ValueError.
  • Identifier injection attempts: Strings like "customers; DROP TABLE customers", "customer_id, tier", or "9col" fail IDENTIFIER.fullmatch and raise ValueError.

Common mistakes

  • Building SQL substrings eagerly inside .where() or .select(). Breaks whenever .alias() or .join() is called afterward and requires retroactively prefixing columns.
  • Formatting literals with str(value) or repr(value) indiscriminately. str("west") omits quotes entirely, while repr("DHL's Express") wraps the string in double quotes ("DHL's Express"), which standard SQL interprets as a column identifier rather than a text literal.
  • Escaping quotes with backslashes (\'). Standard SQLite and PostgreSQL (standard_conforming_strings = on) treat \ literally, turning 'Macy\'s' into a syntax error or a SQL injection vector (untrusted input altering query structure).
  • Emitting col = NULL for None. Executes without error while silently matching zero rows.
  • Returning new copies without mutating self. Standalone calls such as customers.join(orders, using="customer_id") discard the return value and fail if customers was not mutated in place.
  • Qualifying SELECT columns while forgetting WHERE columns. SELECT c.tier FROM customers AS c WHERE tier = 'gold' fails with an ambiguous-column error as soon as a joined table also has a tier column.

Alternative approaches

  • Immutable copy-on-write builder: Each method (select, where, alias, join) clones Query and its internal lists rather than mutating self, letting callers safely branch multiple queries off one shared base template at the cost of requiring reassignment (customers = customers.join(...)).
  • Explicit AST + dialect compiler: Model queries and expressions as an abstract syntax tree (AST) (nodes like SelectStmt, BinaryPredicate, ColumnRef, Literal) paired with per-dialect visitors for SQLite, PostgreSQL, and MySQL.

Follow-up questions

  • How would you redesign render() to output SQL placeholders alongside a bound-parameter list, and what security and database benefits does that provide? Have render() (or render_params()) emit a placeholder such as ? (SQLite) or %s (PostgreSQL psycopg) for each non-None condition value while collecting raw Python values in a params list — returning, for instance, ("SELECT shipment_id FROM shipments WHERE weight_kg >= ? AND carrier = ? AND delivered_at IS NULL", [25, "DHL's Express"]). A parameterized query transmits the SQL structure and data values separately so the database parses and compiles the query plan before reading any parameter bytes, eliminating value-based SQL injection, preserving exact driver types, and enabling database plan caching. Note that None still emits IS [NOT] NULL with zero bound parameters, and identifiers still require check_identifier because SQL placeholders cannot parameterize table or column names.
  • How would you extend .join() to support custom ON predicates as well as LEFT OUTER JOIN semantics? Store join entries as (join_keyword, other_query, using_col, on_expr) where join_keyword is "JOIN" or "LEFT JOIN" (a left outer join, keeping every left-hand row and filling unmatched right-hand columns with NULL), accepting either using= or on= (never both). Introduce a column-reference type (such as o.col("ord", "customer_id")) so on= compares two columns without quoting the right-hand side as a string literal. Crucially, for a LEFT JOIN, predicates belonging solely to the right-hand query (like ord.paid = TRUE) must move into that join's ON clause rather than the outer WHERE clause — otherwise NULL-padded unmatched rows fail WHERE and silently degrade the outer join into an inner join.
  • How can the API express OR logic and arbitrarily nested boolean condition groups while keeping caller code clean? Add a composite ConditionGroup(glue, children) created via o.any_of(*children) (OR) and o.all_of(*children) (AND), implementing the same .render(qualifier) interface as Condition. Because SQL binds AND tighter than OR (a OR b AND c parses as a OR (b AND c)), ConditionGroup.render joins rendered children with " OR " or " AND " and wraps OR groups in parentheses — e.g., WHERE (tier = 'gold' OR tier = 'platinum') AND active = TRUE. Explicit any_of / all_of helpers avoid the operator-precedence traps of overloading Python's bitwise | and &.
  • How would you store and render .order_by() and .limit() clauses, especially when multiple queries are joined together? Add self.order_by_items: List[Tuple[str, str]] (column identifier plus direction validated against ("ASC", "DESC")) and self.limit_value: Optional[int] (a non-negative int, rejecting bool) on Query, emitting ORDER BY ... after WHERE and LIMIT ... last. Across joins, qualify each participating query's order_by_items with its active prefix (c.tier ASC, ord.order_id DESC) in table order just like SELECT. By contrast, SQL LIMIT caps the entire joined result set, so only the root query may carry a top-level LIMIT; if a joined right-hand query specifies its own .limit(5), either raise ValueError or compile that right-hand Query into a parenthesized derived table subquery (JOIN (SELECT ... LIMIT 5) AS ord USING (customer_id)).

Follow-up questions

Similar questions

More Pylon Lending interview questions

All 1 Pylon Lending questions →