Malloy Semantic Layer: What It Is & How To Use It In 2026
Malloy is the semantic layer we recommend for AI analytics: an open-source (MIT) language for semantic modeling and querying that compiles to SQL. It was started at Google Cloud by Lloyd Tabb, the Looker co-founder who designed LookML, and as of October 2026 it runs on BigQuery, Snowflake, PostgreSQL, DuckDB, MotherDuck, MySQL, Trino, Presto and Databricks. As a semantic layer for AI agents it does four things unusually well: an agent asks for a measure by name instead of re-deriving its formula, aggregates stay correct across joins, every query is checked against the model before any SQL runs, and a restricted mode keeps LLM-written queries inside the model. The costs are real too: Malloy is still labelled experimental, its ecosystem is small, and language models know SQL far better than they know Malloy.
The Malloy code below compiles and runs as written (@malloydata/malloy 0.0.436 on DuckDB, October 2026), and the SQL shown is the compiler's actual output.
What Malloy is
The project describes Malloy as “a semantic modeling and query language built on top of SQL.” You define a source once (a table plus its joins, dimensions, measures and saved views) and write short queries against it; the compiler turns each into SQL that runs where your data lives. The first GitHub commit came in August 2021, after Google bought Looker (BigDATAwire). It keeps LookML’s central idea (put joins and measures in a model so nobody re-derives them) and adds a query language of its own.
- Maturity: the malloydata/malloy README no longer says “experimental”, but the malloydata GitHub organization still describes Malloy as “an experimental language for describing data relationships and transformations”. Packages are versioned 0.0.x and ship every few weeks (v0.0.436 on October 26, 2026), and the 4.0 revision in October 2023 turned code written in the older syntax from warnings into errors.
- Commercial backing: Publisher, the open-source model server, is “created and maintained by Credible”, a startup building a governed context engine for AI on top of Malloy, which announced a $10 million seed round in July 2026.
- Learning material: the official documentation and the malloy-samples repo (e-commerce, flights, IMDb, GA4 and more).
Core concepts in one model
Here is a small, complete .malloy file: three tables, two joins, a few dimensions and measures, and one saved view.
// index.malloy: a small e-commerce model
source: users is duckdb.table('users') extend {
primary_key: id
}
source: products is duckdb.table('products') extend {
primary_key: id
}
source: order_items is duckdb.table('order_items') extend {
primary_key: id
join_one: users with user_id
join_one: products with product_id
dimension:
order_month is created_at.month
#" An item that was neither cancelled nor returned
is_valid is status != 'Cancelled' & 'Returned'
measure:
#" Net revenue: sale price of valid items
revenue is sale_price.sum() { where: is_valid }
#" Distinct orders with at least one valid item
order_count is count(order_id) { where: is_valid }
#" Revenue per order
average_order_value is revenue / order_count
#" Distinct customers with a valid order
customer_count is count(user_id) { where: is_valid }
#" Cost of goods sold: product cost once per item sold
cogs is source.sum(products.cost) { where: is_valid }
gross_margin is revenue - cogs
view: revenue_by_month is {
group_by: order_month
aggregate: revenue, order_count
order_by: order_month
}
}
Sources and joins
A source is a table (or a query) extended with modeling. primary_key says what makes a row unique, and join_one: users with user_id joins on that key: each order item has one user. join_many declares the other direction and join_cross a cross product. Joins are left outer by default, and Malloy keeps them as a graph rather than one wide table; the join documentation says aggregates navigate that graph “so they are always computed correctly regardless of join pattern, avoiding the fan and chasm traps.”
Dimensions and measures
A dimension is a per-row value you group or filter by; a measure is an aggregate. Measures build on each other (average_order_value is revenue / order_count) and can carry their own filters ({ where: is_valid }). Two details trip up people coming from SQL: count(order_id) is a distinct count, and status != 'Cancelled' & 'Returned' means “neither cancelled nor returned”. The #" lines are description annotations, which an agent reads to tell two similar measures apart, so write them.
Views and refinements
A view is a saved query on a source. Run it as it is, or refine it with + to add a filter or a grouping without copying it:
run: order_items -> revenue_by_month
run: order_items -> revenue_by_month + { where: users.country = 'Germany' }
The first query compiles to this DuckDB SQL. The revenue and order_count definitions, including the cancelled and returned rule, arrive in the SQL without the query mentioning them:
SELECT
DATE_TRUNC('month', base."created_at") as "order_month",
COALESCE(SUM(CASE WHEN ((COALESCE(base."status"!='Cancelled',true)) and (COALESCE(base."status"!='Returned',true))) THEN base."sale_price" END),0) as "revenue",
count(distinct CASE WHEN ((COALESCE(base."status"!='Cancelled',true)) and (COALESCE(base."status"!='Returned',true))) THEN base."order_id" END) as "order_count"
FROM order_items as base
GROUP BY 1
ORDER BY 1 ASC NULLS LAST
Views can also be chained into multi-stage pipelines with ->, each stage becoming a CTE, and can use calculate: for window functions such as rank() (views documentation).
Nested queries
Nesting returns a summary row per group with a subtable inside each row, which has no single-clause SQL equivalent. This query returns each country’s 2026 revenue and customers plus its two best sellers:
run: order_items -> {
where: created_at ? @2026
group_by: users.country
aggregate: revenue, customer_count
nest: top_products is {
group_by: products.name
aggregate: revenue
limit: 2
}
}
The SQL Malloy generated on DuckDB:
WITH __stage0 AS (
SELECT
group_set,
users_0."country" as "country__0",
CASE WHEN group_set=0 THEN
COALESCE(SUM(CASE WHEN ((COALESCE(base."status"!='Cancelled',true)) and (COALESCE(base."status"!='Returned',true))) THEN base."sale_price" END),0)
END as "revenue__0",
CASE WHEN group_set=0 THEN
count(distinct CASE WHEN ((COALESCE(base."status"!='Cancelled',true)) and (COALESCE(base."status"!='Returned',true))) THEN base."user_id" END)
END as "customer_count__0",
CASE WHEN group_set=1 THEN
products_0."name"
END as "name__1",
CASE WHEN group_set=1 THEN
COALESCE(SUM(CASE WHEN ((COALESCE(base."status"!='Cancelled',true)) and (COALESCE(base."status"!='Returned',true))) THEN base."sale_price" END),0)
END as "revenue__1"
FROM order_items as base
LEFT JOIN users AS users_0
ON users_0."id"=base."user_id"
LEFT JOIN products AS products_0
ON products_0."id"=base."product_id"
CROSS JOIN (SELECT UNNEST(GENERATE_SERIES(0,1,1)) as group_set ) as group_set
WHERE (base."created_at">=TIMESTAMP '2026-01-01 00:00:00') and (base."created_at"<TIMESTAMP '2027-01-01 00:00:00')
GROUP BY 1,2,5
)
, __stage1 AS (
SELECT
*,
CASE WHEN GROUP_SET=1 THEN
ROW_NUMBER() OVER (PARTITION BY CAST("country__0" as VARCHAR), group_set ORDER BY "revenue__1" desc) END as __row_number__1
FROM __stage0
)
, __stage2 AS (
SELECT * FROM __stage1
WHERE NOT ((GROUP_SET = 1 AND __row_number__1 > 2))
)
SELECT
"country__0" as "country",
MAX(CASE WHEN group_set=0 THEN "revenue__0" END) as "revenue",
MAX(CASE WHEN group_set=0 THEN "customer_count__0" END) as "customer_count",
COALESCE(LIST({
"name": "name__1",
"revenue": "revenue__1"} ORDER BY "revenue__1" DESC NULLS LAST) FILTER (WHERE group_set=1),[]) as "top_products"
FROM __stage2
GROUP BY 1
ORDER BY 2 desc NULLS LAST
That is a cross join against a group-set series, a window function and a list aggregate. Asking a model to hand-write that for every “top N within each group” question invites subtle bugs; in Malloy it is one nest:, and nests can go several levels deep (nesting documentation).
How Malloy compiles to SQL across dialects
Each connection.table() names a connection, and the compiler emits SQL in its dialect: moving the model from DuckDB to BigQuery means changing duckdb.table('order_items') to something like bigquery.table('my-project.shop.order_items'), with measures, views and queries unchanged. SQL Server, Oracle and ClickHouse are not among the engines the README lists. DuckDB is the easiest start (a model over Parquet runs on a laptop); on BigQuery, see our BigQuery MCP guide.
Why we recommend Malloy for AI agents
An agent answering data questions re-derives a metric slightly differently each time, double-counts across a join, references a column that does not exist, or wanders into tables nobody vetted. Malloy has a specific answer to each, below. With what the sections above showed (one MIT project for model and queries, nine SQL engines, a nest for “top N in each group”), that is why we recommend it.
Measures are names, not formulas
With raw SQL, every question about revenue makes the model rewrite revenue: which statuses to exclude, which column, which grain. With Malloy the agent writes aggregate: revenue and the compiler inlines the one definition, as the SQL above shows. The definition can still be wrong, but it is wrong in one place, a plain-text file in Git where a fix is a reviewable diff that corrects every later answer.
Aggregates stay correct across joins
Fan-out is the classic silent error in model-written SQL. Malloy makes the grain of every aggregate explicit. In the model above, cogs is source.sum(products.cost) adds a product’s cost once per item sold; products.cost.sum() adds each product’s cost once, full stop:
run: order_items -> {
aggregate:
cogs
distinct_product_cost is products.cost.sum() { where: is_valid }
}
On a nine-row test dataset built for this post, where several items share a product, cogs returns 194 and distinct_product_cost returns 119. Both are legitimate questions; if an agent writes the ambiguous sum(products.cost), the compiler warns:
Join path is required for this calculation; use `products.cost.sum()` or `source.sum(products.cost)` to get a result weighted with respect to `source`
An agent can apply that fix on its next turn. Per the aggregate locality rules, sum and avg need an explicit locality when they reach through a join; count, min and max do not.
The compiler catches mistakes before the warehouse does
Every Malloy query is compiled against the model first. Ask for a field that does not exist:
run: order_items -> {
group_by: users.region
aggregate: revenue
}
and you get 'region' is not defined (error code field-not-found) before a single byte is scanned. For an agent that is a cheap, exact feedback loop: compile, read the error, fix, compile again.
A restricted mode for LLM-written queries
Malloy’s runtime (as of 0.0.436) has a loadRestrictedQuery method whose doc comment says it is for a query “whose text comes from an untrusted source”, naming “an MCP client, an LLM-authored query” among the examples. In restricted mode the compiler rejects import statements, raw connection.table() and connection.sql() sources and raw SQL functions (error restricted-construct-forbidden), while every source, measure and view in the model stays available. That turns “only use the semantic layer” from a prompt instruction into a compiler rule.
Where Malloy falls short
Models know SQL much better than Malloy. MotherDuck tested this directly. In its agentic-malloy experiment on Adyen’s DABstep benchmark, an agent (Sonnet authoring, Opus as fixer) built a Malloy model from a 26-question training set and then answered about 419 held-out questions through it. Malloy scored 382 of 419 (91.2%); the Markdown plus SQL baseline scored 418 of 419 (99.8%), and Malloy used about 2.5 times the prompt tokens. The write-up calls the hypothesis “not supported”, says the layer was “mostly bypassed”, and found the model-written Malloy itself accurate (MotherDuck’s discussion).
That matches our own result: we took Dot from 10% to 90% on a DABstep slice without a semantic layer. DABstep is multi-step analysis over one payments dataset, which in my read rewards flexible SQL more than shared definitions, so many people asking about the same few dozen metrics is a different workload. Still, Malloy does not make an agent more accurate on its own.
A young project. 0.0.x versions and an “experimental” label mean you pin versions, keep queries under test and expect the occasional breaking change.
A small ecosystem. Malloy’s own tools cover modeling (VS Code extension), queries (CLI, npm), simple dashboards (Composer) and serving (Publisher, Malloyyo); for business users you build or buy the front end.
The model has to tell the truth about keys. Malloy’s join math depends on primary keys and on join_one really being one-to-one; its troubleshooting guide warns that when it is not, results inflate silently. The compiler checks names and types, not your data.
It solves computation, not orientation. It makes “compute net revenue” deterministic but doesn’t decide which of your revenue numbers someone meant; see the semantic layer solves the wrong half and what a semantic layer is.
Malloy and MCP: Publisher and Malloyyo
Two open-source, MIT-licensed projects put a Malloy model in front of Claude, Cursor or an agent you build.
Publisher
Publisher, created and maintained by Credible, loads Malloy packages and serves them through a web UI, a REST API and MCP. It starts with three bundled DuckDB example packages and no credentials, and Claude Code can register its MCP endpoint with one command:
npx @malloy-publisher/server@latest --port 4000
# in a second terminal: register the MCP endpoint with Claude Code
claude mcp add --transport http malloy http://127.0.0.1:4040/mcp -s user
Cursor, VS Code, Codex and Claude Desktop use the same endpoint. Its tools include get_context (discover sources, views and fields), execute_query, search_database_schema, compile_model and reload_package. Access control is written into the model: givens for runtime parameters, #(access_filter) for row-level access and #(authorize) to gate a whole source.
The README says the server, MCP and REST alike, is “stateless and unauthenticated” and can read any data your models connect to. It recommends binding to loopback (--host 127.0.0.1) for local use and an authenticating gateway before exposing it more widely: the access annotations decide what a caller may see, but something else has to establish who the caller is.
Malloyyo
Malloyyo, in the malloydata organization, describes itself as a way to “serve any AI a Malloy semantic model over MCP”: set up a repo, have Claude build the model, publish it to a Malloyyo server, then ask questions or build dashboards in Claude or on the web. “The AI can only query what the model exposes,” and datasets are granted to roles. DuckDB is built in; BigQuery, Snowflake, MotherDuck, Databricks and Postgres are listed too.
npm install -g @malloydata/malloyyo
cd my-model-repo
malloyyo init # sets the repo up for Claude
claude # "connect to my warehouse and build a Malloy model from these dbt sources"
malloyyo publish # push it to your Malloyyo server
It calls itself “a small tool”, so treat it as early software.
Malloy vs LookML
Same designer, same core idea, different scope.
Malloy | LookML | |
|---|---|---|
What it is | A modeling language and a query language that compile to SQL | Looker’s modeling language; Google describes it as “a dependency language like make” |
How you query | Malloy queries: views, refinements, nests, pipelines | Through Explores in Looker, which writes the SQL; an Explore is “the FROM clause of a query” |
Where it runs | Wherever the compiler runs: VS Code, CLI, npm, Publisher, your own app | Inside Looker |
License | MIT, open source | Part of Looker, a commercial Google Cloud product |
Around it | A small set of open-source tools | A full BI platform |
AI access | Publisher and Malloyyo over MCP; a restricted compile mode for untrusted queries | Looker’s own AI features (see our Looker AI guide) |
Should a Looker team move to Malloy for AI? For new models, yes. A large LookML estate is valuable because it is already maintained, and a big-bang migration resets that, so move it gradually: let your AI query through LookML meanwhile (Dot does, with row access from Looker user attributes) and port explores as you touch them. Publisher’s bundled Malloy skills include a LookML review skill for that move.
Malloy vs dbt MetricFlow
MetricFlow is the engine behind the dbt Semantic Layer: semantic models in YAML inside your dbt project (dbt docs), metrics built on them, and queries that ask for metrics grouped by dimensions. dbt Labs open-sourced MetricFlow under Apache 2.0 in October 2025; the hosted APIs that BI tools and agents call come with a paid dbt plan (details in our dbt Semantic Layer guide).
- Query shape. MetricFlow answers metric requests (these metrics, by these dimensions, with these filters); Malloy is a general query language with nesting, pipelines and window calculations. For an agent, MetricFlow is the narrower interface; Malloy is more expressive, and its restricted mode keeps that inside the model.
- Where it lives. MetricFlow sits in your dbt project next to its models; Malloy models any table, including the ones dbt builds, from its own files.
- Format. YAML configuration versus a language with a compiler and its own error messages.
We recommend Malloy unless you are committed to dbt’s platform and want metrics defined beside the models, where MetricFlow is the shorter path. Our semantic layer tools comparison covers the wider field, and Malloy vs LookML vs dbt vs Cube vs Power BI asks which one an AI should read in your stack.
How GetDot uses a Malloy model
Dot treats Malloy as a semantic layer connection (Malloy integration), added in July 2026 “so metric definitions in code answer with full fidelity.” There are two ways in.
Connect the Malloy project you already have
Point Dot at the repo on GitHub, GitLab or Bitbucket, including a project in a subfolder of a larger repo (August 2026). Dot compiles the model with the Malloy engine inside Dot, so there is no Malloy server to host, and every query it writes compiles in Malloy’s restricted mode. The warehouse comes from malloy-config.json (BigQuery, Snowflake, Postgres, MySQL, Databricks, Trino or Presto); its secrets stay out of your repo, and row-level security per group applies to Malloy sources (added in July 2026).
Or have the Context Agent write one
If you have no model, the Context Agent can write an optional Malloy model over BigQuery, Snowflake, DuckDB or Dot’s managed warehouse, checked against your existing dashboards. Changes go through environments, isolated copies of the data model where you test a redefined metric and review the diff before merging (optionally as a Git pull request). Given the MotherDuck result, that review matters, and Dot’s Train tests Dot against questions with answers you trust and reports accuracy before and after.
Where the answers show up
Publisher and Malloyyo suit engineers who will run the server and its authentication. When the askers are a sales team in Slack or a CFO on email, need different row-level permissions, or need context the model does not hold (what we call a context layer), a governed analyst fits better (we build one, so weigh that accordingly). People ask Dot in Slack, Teams, email, the web app or an MCP client such as Claude (Dot’s MCP connection), with their own Dot permissions.
If you already keep a Malloy model, start free and connect it; the Free plan includes 300 one-time credits with full Pro features.
FAQ
Yes, the one we recommend for AI analytics, and a query language too: one language covers both the definitions (sources, joins, dimensions, measures, views) and the questions, which compile to SQL for your warehouse.
It is actively maintained but young: still called experimental, versioned 0.0.x, and the 4.0 syntax change in 2023 broke older code. Pin versions, keep important queries under test and budget for upgrades.
As of October 2026: BigQuery, Snowflake, DuckDB, MotherDuck, PostgreSQL, MySQL, Trino, Presto and Databricks, with only the connection.table() references changing between them.
Two, both MIT: Publisher (maintained by Credible) and Malloyyo (in the malloydata organization). Publisher is unauthenticated by default, so put an authenticating gateway in front of it before anyone else can reach it.
For new models, yes. Move a large LookML estate gradually, with agents querying through LookML meanwhile, as Dot does.
Not strictly: in MotherDuck’s DABstep experiment, Markdown plus SQL beat a Malloy layer on accuracy and tokens. A layer pays off when many people ask about the same metrics and the numbers must match everywhere.
Rick Radewagen
Rick is a co-founder of Dot, on a mission to make data accessible to everyone. When he's not building AI-powered analytics, you'll find him obsessing over well-arranged pixels and surprising himself by learning new languages.