People often assume SQL parsing means “turn the string into a tree” and then execution can start. The step in between — bind — is the most underrated: it decides which table and column every name refers to, in which scope.
This is the first post in the plan implementation series: what bind does, and why the order matters.
1. Four components
| Component | Role |
|---|---|
Builder | The driver for semantic analysis, one per select; also holds partial results |
BindContext | A scope: which relations are visible here; scopes nest |
Binding | The definition of a relation (table or subquery) and its columns |
Expr | Everything except relations becomes an expression |
The key design is nested BindContexts: a subquery isn’t “a new parser”, it’s a new scope on top of the parent. Name lookup walks up until it finds something or errors.
2. The order is not arbitrary
plan binds in this order:
CTE → from → expand * → preprocess select list
→ where → group by → having → select list → order by → limit
It looks like copying the SQL grammar, but each step expands the set of visible names:
- before
from, only CTEs are visible; - after
from, table and join columns enter scope; - after
group by, aggregate expressions exist; havingsees groups and aggregates, not select aliases.
Get the order wrong and semantics break — e.g. binding select list before where lets where see aliases it shouldn’t.
3. from is recursive divide-and-conquer
A from clause can be a table, a join, a subquery, a values list, or any nesting of those.
plan splits N tables into “the first N-1” and “the last”, recursively, then merges scopes:
if len(tables) == 1 {
buildTable(tables[0], ctx, depth)
} else {
leftCtx := NewBindContext(ctx)
left, _ := buildTables(tables[:n-1], leftCtx, depth)
right, _ := buildTable(tables[n-1], ctx, depth)
// merge left/right into ctx
}
The benefit: the left side of every join is a complete scope, the right side is a single table, and there is exactly one merge rule — no special case for three-way joins.
4. CTEs: record, then expand on demand
Two steps:
- On
WITH, register the definition in the BindContext; don’t bind it yet; - When
fromsees a name that is a CTE, expand it then.
This avoids binding unused CTEs and leaves room for recursive CTEs.
5. A detail people miss: expanding *
select * isn’t resolved at runtime. Bind must expand it into concrete columns because:
- column pruning and reference counting rely on a fixed column set;
- output column order must be deterministic.
Hence “expand *” sits after from and before select-list preprocessing: you must know the relations first.
6. What bind produces
Builder (results), BindContext (scopes and relations), Binding (relation definitions), Expr (expressions).
These are not a plan, but every plan node takes information from them. The next post covers how they become a plan tree.
Series: Database kernel · Project page
Get the next post
New posts on database kernels and engineering.