How NL2SQL resolves joins without guessing
How a breadth first search over the foreign key graph finds the join path in an NL2SQL system, so the model never writes a join condition. It covers the three tiers, ambiguous paths, read only access and when to ask the user.
- Written by
- Baraqix Engineering
- Published
- Read
- 8 min
- Filed under
- data, build notes
Contents8 sections
An NL2SQL system resolves joins without guessing by taking the join conditions away from the language model. The foreign keys in the schema become a graph, one step picks the tables a question needs, and a breadth first search over that graph returns the shortest join path between them. The join conditions come from the schema, not from the model.
That is how SYS/NL2SQL-02 works, the three tier NL2SQL system with breadth first join resolution listed under systems we have built. The team it was built for needed answers from a relational database with dozens of tables, and every question went through one analyst. This note covers the join step in detail, because it decides whether the SQL can be right before any of it is generated.
Why a model should not write join conditions
A language model writing SQL against a schema it has only partly seen will usually produce something that parses. The failure is quieter than a syntax error. It joins orders to customers on a column that looks plausible, picks the wrong one of two foreign keys between the same tables, or skips a link table and joins two tables that have no direct relationship at all. The query runs, rows come back, and the numbers are wrong in a way nobody notices until someone checks them by hand.
Join conditions are also the part of a query that needs the least intelligence. They are already written down. Every foreign key states exactly which column points at which, and the database enforces it. Asking a model to reconstruct that from column names means guessing at a fact the system can look up. So the model is kept to the parts of the problem that need language: understanding the question, choosing the tables and columns it is about, and writing the filters, grouping and ordering.
The three tier shape
On the home page, SYS/NL2SQL-02 is described as a three tier pipeline. The stack is Python, PostgreSQL and the OpenAI API.
- Tier one maps the question to the relevant tables.
- Tier two finds the join path by running a breadth first search over the foreign key graph, so the model never guesses a join.
- Tier three generates the SQL, validates it against the schema and runs it read only. The rows come back with the query shown.
The diagram at the top of this note draws the same pipeline at a finer grain. Intent detection and schema linking is tier one. The group of three boxes after it zooms in on how tier three writes the SQL, cheapest first: a template match when the question fits a known shape, guided generation when no template matches, and full generation as the last fallback. The diagram labels those three as tiers of generation, and all of them sit inside tier three of the pipeline above. Whichever of them writes the query, the join conditions come from the resolver, and every query passes the same validation and read only guard before it reaches Postgres.
Turning foreign keys into a graph
In PostgreSQL the foreign keys are in the pg_constraint catalog and in the information_schema views. Read them when the system starts, and again whenever a migration changes the schema, and each one becomes an edge between two tables labelled with its exact join condition.
Edges go in both directions. A foreign key from orders to customers is declared on orders, but a question that starts from customers needs to walk it the other way. The search treats the graph as undirected, while each edge keeps its direction for what the join means.
The inset on the diagram shows a small version of this: customers, orders, order_items, products, payments and categories. A question about which products a customer has bought names customers and products. The resolver connects them through orders and order_items, and every condition on that path is one the schema already declares.
Breadth first search finds the shortest path
Breadth first search explores the graph one hop at a time, so the first time it reaches the target table it has found a path with the fewest joins. That is the right default: the shorter path is usually the relationship the question means, and every extra join is another chance to multiply rows or drop them.
type ForeignKey = { table: string; column: string; refTable: string; refColumn: string };
type Edge = { from: string; to: string; on: string };
// One edge per foreign key, stored in both directions so the search can walk either way.
function buildGraph(fks: ForeignKey[]): Map<string, Edge[]> {
const graph = new Map<string, Edge[]>();
const add = (e: Edge) => graph.set(e.from, [...(graph.get(e.from) ?? []), e]);
for (const fk of fks) {
const on = `${fk.table}.${fk.column} = ${fk.refTable}.${fk.refColumn}`;
add({ from: fk.table, to: fk.refTable, on });
add({ from: fk.refTable, to: fk.table, on });
}
return graph;
}
// Breadth first: the first time we reach the goal, the path has the fewest joins.
function joinPath(graph: Map<string, Edge[]>, start: string, goal: string): Edge[] | null {
const via = new Map<string, Edge | null>([[start, null]]);
const queue = [start];
while (queue.length > 0) {
const table = queue.shift()!;
if (table === goal) {
const path: Edge[] = [];
for (let e = via.get(goal); e; e = via.get(e.from)) path.unshift(e);
return path;
}
for (const edge of graph.get(table) ?? []) {
if (!via.has(edge.to)) {
via.set(edge.to, edge);
queue.push(edge.to);
}
}
}
return null; // no chain of foreign keys connects them, so do not invent one
}
const graph = buildGraph([
{ table: "orders", column: "customer_id", refTable: "customers", refColumn: "id" },
{ table: "order_items", column: "order_id", refTable: "orders", refColumn: "id" },
{ table: "order_items", column: "product_id", refTable: "products", refColumn: "id" },
{ table: "payments", column: "order_id", refTable: "orders", refColumn: "id" },
{ table: "products", column: "category_id", refTable: "categories", refColumn: "id" },
]);
console.log(joinPath(graph, "customers", "products"));Run against the six tables in the diagram, the search from customers to products returns three edges: customers to orders, orders to order_items and order_items to products, each carrying its condition. Those conditions go into the SQL exactly as written. The model is never asked to produce them.
A question that touches more than two tables runs the search from one of them to each of the others and merges the paths, keeping each edge once. Strictly, the smallest set of joins that connects several tables is a Steiner tree problem, which is hard in general. For the handful of tables a typical business question touches, merged shortest paths usually give the same answer.
When the graph has more than one answer
The shortest path is not always unique, and some schema shapes are ambiguous by design.
Two paths of equal length
Two tables can be connected by two different paths with the same number of hops. A shipments table might reach customers through orders and also through an addresses table. Plain breadth first search returns whichever it reaches first, which depends on the order the edges were loaded, and load order should never decide what a query means. The fix is to let the search collect every path of the shortest length and treat more than one result as ambiguity.
A related case is two foreign keys between the same pair of tables, such as orders.billing_address_id and orders.shipping_address_id. The graph then has two edges between orders and addresses, both one hop long. Keep them as separate edges labelled with their column names so the tie is visible. A question about where orders were shipped settles it. When nothing in the question decides, the system should ask.
Self references
An employees table with a manager_id column that points back at employees is a foreign key from a table to itself. In the graph it is a loop. Breadth first search ignores it when looking for a path between two different tables, because the table is already visited, and that is correct. A question about who reports to a given manager does need that edge, joined to a second alias of the same table. The resolver has to recognise that edge and offer it as a join between two aliases when the question is about the hierarchy. A question about the whole chain of command, at any depth, needs a recursive query with WITH RECURSIVE, which suits a template better than free generation.
Many to many link tables
In the diagram, order_items is the link between orders and products. The two sit two hops apart in the graph, which is correct, because the link table is the relationship. The risk is in table selection. The model may name orders and products and leave order_items out, since the question never mentions it. The resolver adds it back, because the shortest path runs through it. Link tables also carry their own columns, such as a quantity, and a question that filters on one keeps the link table in the query.
| Case | What the graph shows | What the resolver does |
|---|---|---|
| One shortest path | A single path with the fewest edges | Uses it as is |
| Equal length paths | Two or more paths with the same number of hops | Lets the question choose, otherwise asks |
| Two keys between the same tables | Parallel edges with different column labels | Matches the role in the question, otherwise asks |
| Self reference | A loop on one table | Joins the table to an alias of itself when the question is about the hierarchy |
| Link table | Two hops through a table the question never names | Adds the link table automatically |
| No path | Tables in parts of the schema with no foreign key between them | Stops and says so, and never invents a join |
Asking when the question is ambiguous
When the graph offers two equally short answers and the question does not choose between them, the honest move is to ask. The resolver already knows the options, so the clarifying question can be concrete: did you mean customers by billing address or by shipping address? That costs a few seconds. A confident answer on the wrong key costs a decision made on wrong numbers.
The same rule applies when there is no path at all. If the selected tables sit in parts of the schema that no chain of foreign keys connects, the system should say that it cannot relate them and show which tables it found. Joining them on columns that happen to share a name is exactly the guess this design exists to prevent.
Validation and read only access
Correct joins do not make a query safe on their own. Tier three validates the SQL against the schema before it runs, so every table and column the query names has to exist. A validator can go one step further and compare the joins in the generated query with the edges the resolver returned, and reject any join it did not produce.
Read only is the last line, and it belongs in the database. Run the query as a role that has only SELECT on the tables it may see, inside a read only transaction, with a statement timeout and a row limit. A check in application code that parses the statement and accepts only a single SELECT is a useful fast rejection. Matching the text against the word SELECT is weaker than it looks. It rejects a recursive query, which starts with WITH, and it passes a SELECT that calls a function which writes. The permission itself belongs in the database role, because no prompt can change a role.
Then the answer comes back with the query shown, so anyone who reads SQL can check the joins, and a wrong answer can be traced to the step that caused it.
How we approach this for a client
For a client, this work starts with a Discovery Sprint. It takes two weeks, at a fixed price agreed before we start. On a data project the Sprint runs the join resolver over your real schema and measures how often it is right. At the end you have two things: an architecture document with the system design, the risks in order and a build plan with a price for the next stage, and a working spike in a repository you own. You keep both whether or not we continue.
Baraqix Engineering. Written by the engineers who did the work.
NOTE/05. First published .


