Text-to-SQL over a raw warehouse schema fails less because the model writes bad SQL and more because the schema does not say what "revenue" or "active customer" means, or which joins are safe. A semantic layer (dbt's MetricFlow, Cube, Snowflake semantic views, Databricks metric views) turns those decisions into a governed contract. The model picks metrics and dimensions; a deterministic compiler writes the SQL. In dbt Labs' published 2026 benchmark, that change took accuracy from 84–90% to 98–100% on in-scope questions. More important, questions outside the model's coverage were refused rather than answered wrongly.
The rest of this post covers why raw-schema text-to-SQL gets numbers wrong, what a semantic layer actually guarantees, the architecture we would build, how to measure correctness properly, and the governance that keeps it correct after launch. There is a reusable evaluation harness in the middle. Steal it.
01Why does text-to-SQL give wrong answers on real schemas?
Public benchmarks flatter text-to-SQL. On the original Spider benchmark, schemas are small and questions are unambiguous. Spider 2.0 (ICLR 2025) moved to enterprise-shaped databases on BigQuery, Snowflake and SQLite. Its abstract reports that an o1-preview-based agent solved 21.3% of tasks, against 91.2% on Spider 1.0 and 73.0% on BIRD. Leaderboard scores have climbed since, but the gap between toy schemas and real ones has not closed.
Benchmarks are still the easy case, because every question in them has one agreed answer. Your warehouse does not. The failures we see fall into four groups, and only the first is about SQL skill.
1. Syntax and dialect errors (the problem everyone talks about)
Wrong date functions, QUALIFY on an engine that lacks it, a misquoted identifier. These are loud. The query fails, the agent retries, and frontier models now fix most of them on their own. This is the least dangerous failure, because nobody sees a wrong number.
2. Ambiguous metrics (the problem that matters)
"What was revenue last quarter?" Your warehouse probably has orders., orders., invoices., payments. and a fct_revenue model someone built in 2023 that finance doesn't trust. Each one is defensible. They give different numbers. The schema cannot tell the model that finance means recognised revenue, net of refunds, in GBP at the month-end rate, excluding internal test accounts.
The same applies to every business noun: "active user", "churned", "customer", "last quarter" (calendar or fiscal?). The model resolves the ambiguity silently and confidently. The SQL runs. The number is plausible. Nobody knows it is wrong until it reaches a board deck.
3. Join path errors and fan-out
This one is mechanical, and it produces numbers that are too big rather than random. Consider an illustrative schema:
orders (order_id PK, customer_id, amount, ordered_at)
order_items (order_item_id PK, order_id FK, sku, quantity)
refunds (refund_id PK, order_id FK, refund_amount)Ask "revenue and units sold by month" and a model will happily write:
-- Looks right. Is wrong.
select
date_trunc('month', o.ordered_at) as month,
sum(o.amount) as revenue,
sum(i.quantity) as units
from orders o
join order_items i on i.order_id = o.order_id
group by 1;Every order is repeated once per line item, so sum(o. is multiplied by the number of line items on each order. Worked example: an order of £100 with three line items contributes £300. If the average order has 2.4 line items, reported revenue is inflated by 140% (2.4× the true figure). Add left join refunds and you get a chasm trap: two independent one-to-many relationships multiplying each other. The model has done nothing syntactically wrong. The schema just doesn't encode cardinality in a way the model is forced to respect.
4. Context that lives nowhere in the schema
Soft-deleted rows. Test tenants. A currency column that has to be applied. A status enum where 'complete' and 'completed' both exist because of a 2022 migration. Fiscal years starting in April. Each one is tribal knowledge. You can stuff it into a prompt, but prompts are not versioned contracts, and they do not scale past a few dozen tables. dbt Labs' own benchmark notes that, to make text-to-SQL competitive, they "loaded the entire schema as context, which isn't practical for larger datasets" (source).
The common thread: categories 2–4 are not model failures. They are missing specification. Better models will make category 1 disappear. They will not make the rest disappear, because the information is not in the input.
02What a semantic layer actually guarantees
A semantic layer is a declarative model of your business on top of the warehouse. It holds entities (customer, order), the keys that relate them, dimensions you can slice by, and metrics with exact aggregation logic. A query engine compiles requests like "metric X by dimension Y, filtered by Z" into SQL for your warehouse.
For AI analytics, the value is a change in what the model is asked to do:
| Raw-schema text-to-SQL | Semantic-layer-grounded | |
|---|---|---|
| Model's job | Write arbitrary SQL against hundreds of tables | Pick from a named list of metrics, dimensions and filters |
| Who decides join paths | The model, per query | The compiler, from declared entity relationships |
| Fan-out protection | None unless the model notices | Enforced (MetricFlow refuses fan-out joins; Cube dedupes using primary keys) |
| Metric definition | Re-derived every time | Defined once, reviewed, versioned |
| Out-of-scope question | Returns a plausible wrong number | Fails to compile, or the agent says it can't answer |
| Auditability | A SQL string per answer | A metric request plus deterministic compiled SQL |
| Context needed | Whole schema plus tribal knowledge | Metric catalogue (names, descriptions, valid dimensions) |
The last-but-two row matters most. dbt Labs put it plainly in their April 2026 benchmark write-up: questions the semantic layer couldn't answer "still can't be answered today, without additional modeling … the Semantic Layer tells you it can't answer. It never returns invalid data. Text-to-SQL will cheerfully give you a wrong number."
What the published numbers say (and don't)
That benchmark reran data.world's ACME Insurance dataset (Sequeda et al.), 11 questions, each run 20 times. On modelled data:
| Model | Text-to-SQL | Semantic layer |
|---|---|---|
| Claude Sonnet 4.6 | 90.0% | 98.2% |
| GPT-5.3-Codex | 84.1% | 100.0% |
Read it carefully. It is a vendor benchmark, with 11 questions on a small schema, and the text-to-SQL arm got the full schema in context. Three findings carry over regardless. Modelling quality improved both approaches. Reasoning effort "barely matters" for semantic-layer queries, because the task is narrow. And coverage, not accuracy, was the binding constraint: several questions needed new dbt models before the semantic layer could answer them at all. The code is open (dbt-labs/dbt-llm-sl-bench), so run it against your own models before quoting it to anyone.
03dbt Semantic Layer (MetricFlow) vs Cube vs warehouse-native: which one?
The market has settled into three shapes. All of them do the core job. The differences are where definitions live and who can query them.
| dbt Semantic Layer / MetricFlow | Cube | Snowflake semantic views / Databricks metric views | |
|---|---|---|---|
| Where definitions live | YAML beside your dbt models | YAML/JS data model in a Cube project | Database objects in the warehouse catalogue |
| Engine licence | MetricFlow is Apache 2.0 (announcement); hosted APIs are a dbt platform feature | Cube Core is open source; Cube Cloud adds hosted APIs and AI features | Bundled with the warehouse |
| Fan-out handling | Disallows fan-out and chasm joins; up to two hops (join logic) | Dedupes measures using primary keys (joins) | Declared relationships; check each vendor's semantics |
| Access control | Inherits warehouse grants via the credentials used | access_ with row- and member-level rules in the model (docs) |
Native warehouse RBAC and row access policies |
| Caching | Limited; relies on the warehouse | Pre-aggregations, a strong point | Warehouse result caching |
| Agent interface | dbt MCP server (list_, get_, query_, get_) |
REST, GraphQL, SQL API; MCP | Cortex Analyst / Genie and SQL |
| Best fit | You already run dbt and want metrics reviewed in the same PRs as models | Multi-warehouse, embedded analytics, or you need caching and per-tenant security in one place | Single-warehouse shops that want the fewest moving parts |
Our default: if you already run dbt, use the dbt Semantic Layer. Metric changes go through the same pull requests, CI and owners as the models beneath them, and that is most of the governance battle. Choose Cube when you serve analytics to customers (multi-tenant row-level security plus pre-aggregations is hard to rebuild elsewhere) or span several warehouses. Choose warehouse-native when you are all-in on one warehouse and your AI interface is that vendor's own.
Portability is improving. The Open Semantic Interchange specification shipped its first version in January 2026 under Apache 2.0, with dbt Labs, Cube, Snowflake, Databricks, Salesforce and others signed up. It has since entered the Apache Incubator, on 22 June 2026, as Apache Ossie (update). We wouldn't choose a vendor on OSI support yet. We would avoid one that refuses to commit to it.
04Defining metrics that can't fan out: a MetricFlow example
This uses the latest dbt semantic layer YAML spec, supported in dbt Fusion, the dbt platform's Latest track and dbt Core v1.12. Semantic definitions now sit beside the model's columns, and measures have been replaced by type: simple metrics.
# models/marts/orders.yml
version: 2
models:
- name: orders
description: "One row per order. Excludes test tenants and soft-deleted orders."
semantic_model:
enabled: true
agg_time_dimension: ordered_at
columns:
- name: order_id
entity: { type: primary, name: order }
- name: customer_id
entity: { type: foreign, name: customer }
- name: ordered_at
granularity: day
dimension: { type: time }
- name: channel
dimension: { type: categorical }
- name: amount_net_gbp
data_type: numeric
metrics:
- name: revenue
description: >
Recognised order revenue, net of refunds, in GBP at month-end rate.
This is the finance definition. Owner: finance-data.
type: simple
agg: sum
expr: amount_net_gbp
- name: orders_count
type: simple
agg: count
expr: 1
- name: order_items
semantic_model:
enabled: true
agg_time_dimension: ordered_at
columns:
- name: order_item_id
entity: { type: primary, name: order_item }
- name: order_id
entity: { type: foreign, name: order }
- name: ordered_at
granularity: day
dimension: { type: time }
- name: quantity
data_type: numeric
metrics:
- name: units_sold
type: simple
agg: sum
expr: quantity
metrics:
- name: units_per_order
description: "Average basket size."
type: ratio
numerator: units_sold
denominator: orders_countNow "revenue and units sold by month" becomes a metric request:
dbt sl query --metrics revenue,units_sold --group-by metric_time__month --compileMetricFlow aggregates each metric at its own grain and then joins the aggregates on metric_time. It does not join orders to order_items row by row, so the fan-out query from earlier cannot be produced. If someone asks for revenue grouped by order_, that needs a primary-to-foreign join, which MetricFlow rejects as fan-out (join logic). That is the behaviour you want. The answer to "revenue by SKU" depends on an allocation rule (by line value? by quantity?), and someone has to define it as a metric on the item grain.
Run dbt sl validate in CI. It catches broken references and invalid metric definitions before an agent ever sees them.
The Cube equivalent
cubes:
- name: orders
sql_table: analytics.orders
joins:
- name: customers
relationship: many_to_one
sql: "{CUBE}.customer_id = {customers}.customer_id"
dimensions:
- name: order_id
sql: order_id
type: number
primary_key: true # required to avoid over-counting across joins
- name: ordered_at
sql: ordered_at
type: time
- name: channel
sql: channel
type: string
measures:
- name: revenue
description: "Recognised revenue, net of refunds, GBP. Owner: finance-data."
sql: amount_net_gbp
type: sum
access_policy:
- group: regional_analyst
member_level:
includes: "*"
row_level:
filters:
- member: customers.country
operator: equals
values: ["{ userAttributes.country }"]
views:
- name: sales
description: "The only surface exposed to the AI agent."
cubes:
- join_path: orders
includes: [revenue, ordered_at, channel]
- join_path: orders.customers
prefix: true
includes: [country, segment]Two Cube habits pay off. Expose views, not cubes, to agents, because a view is a curated surface with fixed join paths. And put primary_ on every cube that takes part in a join; Cube's docs say it "uses primary keys to avoid fanouts" (joins). In Cube Core, the policy reads security instead of user.
05The architecture we'd build for AI analytics
┌──────────────────────────────────────────────┐
│ Agent (LLM) │
user question → │ 1. list_metrics / get_dimensions (catalogue) │
+ identity │ 2. map question → {metrics, group_by, where} │
│ 3. if no fit → say so; log to backlog │
└──────────────────────────────────────────────┘
│ structured metric request (not SQL)
▼
┌──────────────────────────────────────────────┐
│ Semantic layer (MetricFlow / Cube) │
│ - validates names, dims, filters │
│ - deterministic SQL compilation │
│ - access policy evaluated for *this user* │
└──────────────────────────────────────────────┘
│ compiled SQL, user-scoped credentials
▼
┌──────────────────────────────────────────────┐
│ Warehouse (row access policies, read-only) │
└──────────────────────────────────────────────┘
▼
answer + metric names + compiled SQL + definitions shown to user
every request logged: question, request, SQL, row count, latencyThe decisions that matter:
- The model emits a metric request, never SQL, on the main path. With the dbt MCP server that means
query_, a good example of MCP tool design agents can actually use: few, high-level tools. With Cube, a REST or semantic-SQL query against a view. If you let the agent fall back to raw SQL "when the semantic layer can't answer", you have rebuilt the original problem with extra steps.metrics - Raw SQL, if you allow it at all, is a separate, labelled mode. Call it "exploratory". Run it in a read-only role with a row limit and a cost cap. Show a banner saying the number is not governed. Analysts will find it useful. Executives should not see it by default.
- Refusal is a feature. When a question doesn't map, the agent says which metric or dimension is missing and logs it. That log is your modelling backlog, ranked by demand. It is the most useful artefact the system produces.
- Show the working. Every answer names the metric, its definition and the filters applied, with the compiled SQL one click away. People forgive "I can't answer that". They do not forgive a wrong number they can't trace.
- Identity flows through. The agent queries as the user, not as a shared service account. More on that below.
06Reference: a golden-question harness for measuring text-to-SQL accuracy
This is the asset. Most teams "evaluate" AI analytics by having someone try ten questions in a demo. That tells you nothing about the 11th question, or about next month after someone renames a column. You need a regression suite, built the way you would build LLM evals for any use case: a golden set, a grader and a CI gate. Here is the shape we use.
Step 1: write golden questions as data
# evals/golden/revenue.yml
- id: rev-001
question: "What was revenue last quarter?"
paraphrases:
- "How much did we make in Q1?"
- "Total revenue for the previous quarter"
expected:
kind: metric_request # what a correct agent should ask for
metrics: [revenue]
group_by: []
where: ["{{ TimeDimension('metric_time', 'quarter') }} = '2026-01-01'"]
reference_sql: | # hand-written by the metric owner
select sum(amount_net_gbp) from analytics.orders
where ordered_at >= '2026-01-01' and ordered_at < '2026-04-01'
compare: { order_sensitive: false, abs_tol: 0.01 }
as_of: "2026-06-04" # freeze relative dates
owner: finance-data
tier: board # board | operational | exploratory
- id: rev-014
question: "Revenue by SKU last month"
expected:
kind: refusal # no SKU-grain revenue metric exists
reason_contains: ["sku", "revenue"]
owner: finance-data
tier: operationalThree things here are unusual and important. Paraphrases: the same question phrased differently must give the same answer, which catches brittleness that a single phrasing hides. Expected refusals: a correct "I can't answer that" is a pass, and a confident number is a fail. Pinned as_of: "last quarter" means nothing in a test unless you fix the date.
Step 2: compare results, not SQL strings
Two correct queries rarely look alike, so string or AST comparison produces false failures. Compare result sets. This comparator is dependency-free and handles column order, row order, numeric tolerance and NULLs:
# evals/compare.py
import math
from collections import Counter
from decimal import Decimal
def _norm(v, ndigits):
if v is None:
return ("null",)
if isinstance(v, (int, float, Decimal)):
f = float(v)
return ("num", round(f, ndigits)) if math.isfinite(f) else ("num", str(f))
return ("str", str(v).strip().lower())
def _canon_row(row, ndigits):
# Sort values within a row so column order and aliasing don't matter.
return tuple(sorted((_norm(v, ndigits) for v in row), key=repr))
def results_match(got, want, *, order_sensitive=False, abs_tol=0.01):
"""got/want: lists of tuples from a DB-API cursor."""
if len(got) != len(want):
return False, f"row count {len(got)} != {len(want)}"
ndigits = max(0, -int(math.floor(math.log10(abs_tol)))) if abs_tol else 6
g = [_canon_row(r, ndigits) for r in got]
w = [_canon_row(r, ndigits) for r in want]
if order_sensitive:
ok = g == w
else:
ok = Counter(g) == Counter(w)
return ok, "" if ok else "values differ"Rounding to a tolerance is crude, since values either side of a rounding boundary can fail. It is good enough for currency at 0.01. Sorting values within a row is a deliberate trade-off: it forgives column reordering, at the cost of missing a swapped pair of identically typed columns. For board-tier questions, also compare the metric request itself (metrics and group_by sets equal), which catches the right number for the wrong reason.
Step 3: score what matters
Run each question and each paraphrase n times (we use 5; dbt's benchmark used 20) at production temperature. Then report:
| Score | Definition | Why it matters |
|---|---|---|
| Correct | Result matches reference, or expected refusal given | Headline accuracy |
| Wrong-confident | Returned a number that doesn't match | The only number executives should care about. Target: 0 for board tier |
| False refusal | Refused a question in coverage | Usability; drives people back to Slack |
| Consistency | Share of question groups where every run and paraphrase agrees | Catches flakiness that averages hide |
| Coverage | Share of real user questions (from logs) that map to an existing metric | Tells you where to model next |
Hold wrong-confident and false refusal as separate numbers. A system that refuses everything has zero wrong answers and no users. A system that never refuses has a great demo and a credibility problem.
Step 4: wire it into CI
Run the board and operational tiers on every pull request that touches models/ or metric YAML, after dbt sl validate. Block merge on any wrong-confident result in the board tier. Run the full suite nightly against production data with a pinned model version, and re-baseline deliberately when you change models. Source new golden questions from the refusal log and from any answer a user flags as wrong. Every incident becomes a test.
Readiness checklist before you put this in front of executives
- Every board-tier metric has a named owner and a description that says what it excludes.
- The agent's main path cannot emit raw SQL.
- At least 50 golden questions, each with two or more paraphrases, including at least 10 expected refusals. (These are our working thresholds, not a published standard.)
- Wrong-confident rate is 0 on the board tier across three consecutive nightly runs.
- Queries run with the asking user's identity; a test proves user A cannot see user B's rows.
- Every answer shows metric names, definitions and filters; compiled SQL is one click away.
- The refusal log is reviewed weekly and feeds the modelling backlog.
- Metric changes need owner approval in code review (CODEOWNERS on metric YAML).
- Relative-date handling ("last quarter", "YTD") is defined once, including fiscal calendar.
- A rollback path exists for metric definitions, the same as for code.
07Governance: keeping AI analytics correct after launch
Accuracy on launch day is the easy part. Drift is the long-term risk: a model gets refactored, a column changes meaning, finance changes the revenue recognition rule, and the agent keeps answering with the old confidence.
Metrics are code. They live in Git, change through pull requests and have owners. Put CODEOWNERS on metric YAML so a change to revenue needs finance-data's approval. When a definition changes in substance, create revenue_v2, run both side by side, then deprecate: the same expand/contract idea as a zero-downtime Postgres migration. Don't silently redefine a number people have already put in decks.
Descriptions are prompts. The agent picks metrics largely from names and descriptions. "Revenue" with no description invites the model to pick it for "bookings", "GMV" or "sales". Write descriptions that say what the metric is not ("Excludes VAT and marketplace GMV; for GMV use gmv"). Treat a vague description as a bug.
Expose less. An agent with 400 metrics is worse than one with 40 well-described ones, for the same reasons a human analyst would be. Start with a curated set (a Cube view, or a tagged subset of dbt metrics) and grow it from the refusal log.
Log everything, keep it. For each request, store the question, the user, the metric request, the compiled SQL, the row count and whether the user flagged it. If the agent is already traced, the OpenTelemetry GenAI conventions for LLM observability give you a natural place to record it. That log is your audit trail, your eval source and your answer when someone asks "where did this number come from?"
Identity and row-level security belong below the agent. Never rely on the prompt to restrict data ("only show the user their own region"). Prompts are not access control. Enforce access in the semantic layer (Cube access_) or the warehouse (row access policies), and propagate the end user's identity so the agent can't see more than the person asking. See our post on securing AI agents against prompt injection for why an instruction-following model must never be your security boundary.
Where this crosses into other layers
This is a Data layer problem that leaks into most of the others. The access model is Security: identity propagation from your IdP through the agent to the warehouse is the same work as any zero-trust rollout, such as replacing the VPN with zero trust access. The agent itself, with its tools, retries, model pinning and evals, is AI & Automation, and that agent harness matters as much as the model. The UI that shows definitions and compiled SQL alongside the answer is Design (the same problem as showing sources and uncertainty in AI UX), and it decides whether people trust the system. And deciding who owns "revenue" is Strategy, because no tool resolves a disagreement between finance and sales about what a customer is. Most failed AI analytics projects we hear about failed at that last step, not in the SQL.
08When you don't need a semantic layer
Be honest about scope.
- One team, one analyst, a dozen tables. A well-documented dbt project and a careful prompt may be enough. Add the semantic layer when a second team starts asking the same questions differently.
- Exploratory data science. People who read SQL and want a fast first draft are well served by plain text-to-SQL in a notebook. They check the output anyway.
- Operational lookups. "Show me order 12345" is retrieval, not analytics. No aggregation, no fan-out risk. A parameterised query or an API is simpler than either approach.
- You have no agreed metrics yet. A semantic layer encodes decisions; it can't make them. If finance and sales disagree on revenue, settle that first, or you will just encode the argument in YAML.
Where you do need one: any answer that reaches an executive, a customer or a regulator, or any number someone will act on without checking the SQL.
09FAQ
Do better LLMs make the semantic layer unnecessary?
No. Better models fix syntax and dialect errors and get better at join reasoning. They cannot recover a business definition that isn't in the input. dbt Labs' 2026 benchmark found text-to-SQL improved substantially since 2023, yet the semantic-layer arm still won on in-scope questions and never returned invalid data on out-of-scope ones (source).
How do I measure text-to-SQL accuracy properly?
Compare query results against reference answers written by metric owners, not SQL strings. Include paraphrases and expected refusals, pin relative dates, run each case several times, and report wrong-confident answers separately from refusals. The harness above is a working starting point.
Can I use the dbt Semantic Layer without the dbt platform?
MetricFlow is open source under Apache 2.0, and self-hosted users can run mf query and mf validate-configs locally (commands). The hosted Semantic Layer APIs and their integrations are dbt platform features, available on the Starter, Enterprise and Enterprise+ plans but not the free Developer plan (availability). At the time of writing, Starter includes 5,000 queried metrics a month and the Enterprise tiers 20,000 (pricing). If you need an always-on query service for agents without the platform, budget for running and securing that yourself.
What about questions the semantic layer can't answer?
The agent should say so, name what's missing and log it. Review the log weekly and model the most-requested gaps. If you must allow ad hoc SQL, keep it in a clearly labelled exploratory mode with a read-only role and limits, never as a silent fallback.
Does a semantic layer slow queries down?
Compilation overhead is small next to warehouse execution. Compiled SQL can be less tuned than hand-written SQL for unusual queries, and fan-out-safe plans aggregate before joining, which sometimes means more subqueries. If latency matters, Cube's pre-aggregations or materialised dbt models help. Measure on your workload before you optimise.
Is OSI (Apache Ossie) worth adopting now?
It's worth tracking, not betting on. The spec exists and the major vendors have signed up, but converters and tool coverage are still maturing. Write your definitions in whichever layer you choose, and prefer vendors that have committed to the standard so migration stays possible.