Can SQL do what DAX does?

TL;DR:

Yes, it can. Measures don’t need a new execution engine, they need a new front end: the parser, the catalog and the planner. The planner turns “this measure, under that filter context” into plain operators that engines already run, and execution doesn’t change.

  • The engine needs to know nothing about measures. Filter context, context transition and relationships all become plain SQL before the engine sees them.
  • The engine does need some SQL done right, above all correlated subqueries and values that keep their own type (VARIANT). Any SQL needs those, measures or not.
  • Fast answers are another story. A compiler outside the engine never sees the data, maybe the compiler should be built built into the planner ?

We showed this with dax-sql, initially written by N.S. Devaraj. It turns DAX into plain SQL, and DuckDB matches Power BI on all 7,358 queries of the suite, with the other engines close behind, although none of them knows anything about filter context.

If that’s all you wanted, you can stop here. The rest is the long and boring version.

Why bother

I’ve always been interested in this question, and I was never happy with the answers.

Most SQL people don’t see the problem. For them, you just write a query, and a cross filter is a WHERE clause with parameters. For Power BI people; A measure is written once and works in any visual, under any filter, and the filters follow the model’s relationships. Hard-coding a SQL query per visual is an abomination, so their answer is that SQL can’t do it. As for the people who really understand how measures are implemented, I think they’re just tired of explaining 🙂

Take a simple measure, “% of all categories”: sales divided by the sales of all categories. In a table by category and year, it must drop the category filter but keep the year. In a chart by region with a slicer on brand, it must keep the region and the brand. One definition has to work in every visual, under any filter, and plain SQL has no way to say that once.

Neither answer helped me much. Database developers are very clever people, and they build far more complex things. If measures were really out of SQL’s reach, someone would have said what exactly was missing. If they were easy, someone would have built them properly. (I mean the real thing, not one wide table with a few joins called a “semantic layer”.)

My theory is that the reason was commercial: ROI. BI tools had already solved the problem, and the money was in the BI tool, so it wasn’t worth doing in SQL. Now there’s a platform shift. Agents are everywhere, and anything that improves their accuracy, and especially their token consumption, is suddenly worth building. An agent that can ask for a measure by name doesn’t have to write, and get right, a long query every time. So measures are finally showing up in SQL. Vendors are adding semantic models to their SQL, and Hyde and Fremlin add a measure column to SQL, with operations that change its evaluation context [9]. Apache Ossie [7], an open standard for semantic models, is standardizing the easy part: tables, relationships and simple measures. The advanced measures are still missing.

So what does an engine need to run them? To answer that, I needed a measure language with real answers to test against. AT has an implementation now (see below), but nothing that says what its right answers are, and Ossie has no measure language beyond simple ones yet. DAX has Power BI. DAX is the test case: what holds for DAX’s filter context holds for any measure with an evaluation context. I use Power BI as the reference because it is the most mature implementation in the market [8], and more precisely a Direct Lake model. Power BI has three storage modes: Import loads the data into its own engine, DirectQuery sends SQL to a database, and Direct Lake reads Delta tables in OneLake directly. They answer some queries differently, so the mode matters. I picked Direct Lake because it is the closest to the SQL engines here: it reads the same Delta tables in OneLake, with no import step of its own.

dax-sql does not fully implement DAX, and I know it is not fully correct. Every time new DAX queries are added, some of them don’t match. The only guarantee is that the queries in the suite match, nothing more.

Why not use what already exists

There are already semantic layers that run on DuckDB. Boring Semantic Layer [15] defines measures in Python on Ibis and compiles them for many engines. Three DuckDB extensions add measures to SQL: yardstick [16] implements Hyde and Fremlin’s AT, and semantic_views [17] and semantic_layer [18] follow Snowflake’s semantic views. They are great projects, and if you need a semantic layer on DuckDB today, try them.

I’m chasing something different, though. I’ve used DAX for years, and I’ll admit I’m attached to it. It is also the one measure language I can check: I send the same query to Power BI and see if the numbers match.

I hope this post and dax-sql are a small contribution to the public discussion: a real answer you can test, with all the results open.

Power BI as a black box

It is an independent open-source project. It is not affiliated with, endorsed by or supported by Microsoft in any way. Power BI, DAX and Fabric are Microsoft trademarks.

dax-sql doesn’t try to copy how Power BI works inside. It is a naive implementation. It reads a semantic model (Ossie YAML, or a Power BI .bim / TMDL), takes a DAX query (or the SQL form shown at the end), and compiles it to one SQL SELECT for DuckDB, Fabric DWH, Polars or DataFusion [6]. It is only a compiler, with no calculation engine of its own. The SQL engine does all the computing.

Each query becomes one plan made of plain operators (scan, filter, join, aggregate, window, CASE), saved as Substrait, an open format for query plans. The SQL for every engine is printed from that same plan, and anything specific to one engine happens only at that printing step. So the four engines below all get the same work.

We know nothing about Power BI’s engines, and we didn’t even look at Power BI’s query plans. They are not useful to a compiler that has no engine to tune. The same data is loaded as Delta tables into OneLake, each model is published there as a Direct Lake model, and every query is sent to it through Fabric’s XMLA endpoint. We send Power BI a DAX query and get numbers back. Whatever it returns, at the moment the query runs, is the truth.

There is no other choice. As far as I know, DAX has no formal specification and no public conformance tests. The documentation explains each function, but not how they all combine, and not the edge cases like the blank row. So Power BI is the reference implementation: whatever it answers is, by definition, what DAX means. That is why the suite has to be built query by query from its answers, and why it is public.

The work was done by AI, and it is basically overfitting the existing DAX queries. Every query in the test suite is checked against Power BI’s answer, and any difference counts as a bug. When an answer doesn’t match, the compiler changes until it does. When a behavior is unclear, we write more probe queries and look at Power BI’s answers, without trying to understand Power BI’s internals.

At the time of writing, the suite has 7,358 DAX queries over 11 models, using about 440 distinct DAX functions. 4,078 are generated: grids that cross many measures with many filters, and random “fuzz” queries. The other 3,280 were written for specific DAX features and patterns, from context transition to calculation groups and row-level security, plus queries over TPC-DS data and Apache Ossie’s own compliance cases. A query count is not a measure of coverage, though. Many generated queries combine features already tested elsewhere, and what matters is the edge cases they hit.

DuckDB matches all 7,358, Fabric DWH 7,332, Polars 7,313 and DataFusion 7,246. Along the way we filed 49 bugs upstream (43 in Polars, 2 in DuckDB, 3 in Ossie, 1 in a T-SQL driver), and 25 of them are already fixed. The live numbers are on the site [6].

Don’t read too much into DuckDB’s 100%. It is not a proof. DuckDB is the first target, and a query that doesn’t match on DuckDB is fixed before anything else, so 100% is how the suite is run, not a result. New queries keep finding new mismatches. What it does show is that every fix so far could be made in the compiler, without touching the engine.

The answers are right, but the generated SQL is still bad. For every TPC-DS query there is also SQL written by hand (by AI too, I know, the irony). At scale factor 1 on DuckDB, dax-sql’s SQL takes about 2.7 times as long overall, and some queries are much worse. The compiler never looks at the data, so a query can be right and still slow. The gap follows the number of subqueries, not outer joins or VARIANT: queries with fewer than five subqueries are about 1.6 times slower than the hand-written SQL, and the worst ones have hundreds.

Everything below comes from making plain SQL return the same numbers as Power BI. Every item is a real workaround in the code or a bug filed upstream.

A language problem, not an engine problem

For me, this is the most important thing I learned. Most of DAX never reaches the engine. The filter context, relationships and expanded tables, bidirectional and many-to-many filters, ALLSELECTED, calculation groups, row-level security and BLANK arithmetic are all handled by the compiler. Relationships become joins and semi-joins (EXISTS), calculation items become a CASE per item, and BLANK + 1 = 1 becomes a COALESCE.

None of this needs anything new from the engine. What is missing is in SQL the language, which has no way to say “this measure, under that filter context”. dax-sql sits on top of four engines that we didn’t change, and almost all of DAX’s logic is in the compiler. This also fits my ROI theory. The engines could do it. Few had a reason to add it to the language.

So the question has two parts. The language part is what Hyde and Fremlin [9] and Ossie [7] are working on. The engine part is much smaller: run the plain SQL that comes out, with the right answers and at a good speed. The list below is what that took with dax-sql’s SQL. It is one implementation’s list, not a definition of what an engine must have. The first four items are about tables, keys and types. R5–R8 are what measures need, and that is where the engines differ most. R9–R14 are DAX’s function library.

The easy part: tables, keys and types

R1. Blank-safe keys. BLANK is a real key value, and Direct Lake adds a blank “ghost” member for facts that have no dimension row. So a IS NOT DISTINCT FROM b must be as cheap as a = b. Polars fixed this. DuckDB and DataFusion already join on it the same way they join on =.

R2. Exact fixed decimals, rounded as DAX rounds. CURRENCY is a decimal with 4 places, and DAX rounds half away from zero. In Polars, CAST truncates and ties round to even. In T-SQL, multiplying two DECIMAL(19,4) values overflows, so one of them has to be narrowed first.

R3. Text compared as Power BI compares it. Matching ignores ASCII case, but é and É are still different. T-SQL ignores trailing spaces, so 'a ' = 'a' is true there and false in Power BI. No engine has this collation, so every dialect builds its own comparison key.

R4. Deep generated SQL. The suite produces dozens of nested CASEs, deeply nested subqueries and long CTE chains. Polars’ parser rejected the CASEs (since fixed). T-SQL runs a CTE again every time it is read, so long chains have to go into temp tables. DataFusion can spend more than 10 seconds just planning them, and that causes most of its timeouts.

None of R1–R4 is exotic, but TPC-H and TPC-DS [10, 11] test none of them, and none of the hard part below either.

The hard part: what measures need

R5. Any correlated subquery, decorrelated. This is the most important item. A correlated subquery reads a column of the outer row, so as written it runs once for each outer row. That is exactly what DAX’s context transition does [8]. Inside an iterator, CALCULATE turns the current row into a filter and evaluates the measure under it.

ADDCOLUMNS ( VALUES ( Product[Category] ), "Sales", CALCULATE ( SUM ( Sales[Amount] ) ) )
SELECT c.category,
(SELECT SUM(s.amount) FROM sales s WHERE s.category = c.category) AS sales
FROM (SELECT DISTINCT category FROM product) c

The SQL follows the DAX very closely. The current row becomes s.category = c.category, and each nested iterator adds one more level of nesting. A measure with VAR, IF or FILTER puts the subquery inside a CASE, an aggregate, an EXISTS or a JOIN’s ON. The compiler doesn’t add the correlation. It is already in the meaning of the DAX.

Run once per row, this would be hopeless at scale. So the engine has to decorrelate it, which means rewriting the loop as joins and GROUP BYs that give the same answer.

Unnesting goes back to Kim [1]. When the inner filter is an equality, as in Figure 2, the rewrite is simple: group once, then left join. DAX is rarely that simple. A running total filters on date <= current date, which is a range. Iterators nest several levels deep, and the outer value can be read through a UNION or a LATERAL. SQL Server’s APPLY operator [3] runs these queries but doesn’t remove the correlation. Neumann and Kemper [2] showed that any correlated subquery can be unnested. The rewrite takes the distinct outer values the subquery reads, joins that small table into the subquery, and joins the result back. Neumann’s later paper [4] does this from the top down, which keeps deep nesting cheap. Always possible doesn’t mean always cheap, though: the table of outer values can be large, and the joined-back plan can be worse than the loop.

DuckDB’s decorrelator implements this work [2, 5], though it still has some open plan issues. Polars still fails on nested and UNION ALL correlation, even after fixing several of these bugs. DataFusion rejects some EXISTS subqueries. Fabric has APPLY, but allows no subquery inside an aggregate, and leaves one inside a CASE correlated (a RANKX took 24 s, against 0.5 s unnested). For Fabric, Polars and DataFusion, dax-sql runs the top-down algorithm itself and sends them SQL without correlation.

Ask: allow a correlated subquery anywhere SQL allows an expression, and unnest all of them, including ranges and nesting.

R6. VARIANT. IF(x, 1, "none") is a valid measure. So is a calculation item that turns numbers into text on some rows. DAX values are dynamically typed, and SQL columns are not. The requirement is a column whose values each keep their own type. A native VARIANT is one way to get it, and a tagged union (a struct with a value per type and a tag) is another. DuckDB has a native VARIANT, so each value keeps its type. Polars has no union type. T-SQL and DataFusion fall back to text, so 1 and "1" look the same, and on T-SQL a float written as text keeps only 15 digits. This causes real mismatches in the suite: Power BI returns the number 100, and the engine returns the text “100”. I didn’t expect this one at all.

R7. Lazy branches and real errors. DAX raises errors, such as a bad argument to PERCENTILE.INC, but only for the rows that reach them. An engine that evaluates every CASE branch on every row raises errors that DAX never would. Polars fails on a failing constant in a branch that no row takes. DataFusion evaluates a THEN on an empty batch, so dax-sql makes the error depend on a column. DuckDB’s error() works the way DAX expects.

R8. Recursion that reads the outer row. XIRR, RATE and YIELD are iterative solvers, and PATH walks a hierarchy. Each one is a WITH RECURSIVE inside a correlated subquery. DuckDB runs it. Fabric has no recursive CTE, so its solvers run a fixed number of Newton steps in CROSS APPLY. Polars’ recursive CTE can’t read the outer row. On DataFusion, dax-sql only writes the financial functions that have a closed form, so XIRR and RATE don’t work yet.

DAX’s function library

R9–R14 are not about measures. They are DAX’s functions, and a new measure language could define them its own way. dax-sql can’t: Power BI’s answer is the answer.

R9. Lists in scalar expressions. XNPV and XIRR take a list of cash flows, and PERCENTILE takes a k that changes by row. That needs arrays with functions like array_reduce and array_position. Polars is missing several of them, and T-SQL falls back to OPENJSON.

R10. Several orderings per SELECT. CONCATENATEX sorts each string on its own key, so one SELECT can have several orderings. T-SQL and DataFusion allow only one per SELECT. T-SQL also requires an ORDER BY in every window.

R11. Series from row values. GENERATESERIES and CALENDAR take bounds computed per row. DataFusion’s generate_series accepts constants only. Polars has since added the per-row form.

R12. IEEE floats done properly. DAX keeps the sign of zero (1 / -0 is −∞), and Polars loses it. T-SQL has no infinity or NaN at all, and most of Fabric’s mismatches are a ±∞ that comes back blank. In DAX, NaN is not equal to itself, but DataFusion and T-SQL say it is. log10(1000) is exactly 3 in DAX, while Polars returns a hair less. A literal with a fraction must be read as a DOUBLE. Read as an exact DECIMAL, it makes sums drift away from Power BI’s.

R13. The Excel library. FORMAT with many decimal places, large factorials, GCD and LCM, log-gamma, a stable hash, LEN counted in UTF-16 units. Each one is small, but one missing function fails the whole query.

R14. Dates are date-times, and now() has a time zone. A DAX date carries a time of day, which a Polars DATE can’t hold, and Polars’ now() has no time zone.

Scorecard

The table reflects one compiler, and not a very clever one. It lists what this compiler asked of the engines, not what every implementation needs. A bug filed upstream means an engine got SQL it accepts wrong, not that DAX can’t be done without that feature. A better compiler, or an engine built for measures, could avoid most of these items. dax-sql itself already does this for R5 on three engines, by unnesting the subqueries before sending the SQL, and a tagged union could stand in for R6. What can’t be avoided is the meaning behind them: someone has to handle the correlation and the dynamic types, in the compiler or in the engine.

Req.DuckDBFabric T-SQLPolarsDataFusion
R1 Blank-safe keys✓✓✓ (fixed)✓
R2 Fixed decimals✓workaroundmissingworkaround
R3 Power BI collationworkaroundworkaroundworkaroundworkaround
R4 Deep SQL✓temp tables✓ (fixed)workaround
R5 Correlated subqueries✓ (open plan issues)unnested by dax-sqlunnested by dax-sqlunnested by dax-sql
R6 VARIANT✓as textas textas text
R7 Lazy branches✓✓missingworkaround
R8 Correlated recursion✓fixed stepsmissingclosed forms only
R9 Lists in scalars✓OPENJSONmissingworkaround
R10 Several orderings✓one per SELECT✓one per SELECT
R11 Per-row series✓✓✓ (fixed)constants only
R12 IEEE floats✓no ±∞, NaNmissingNaN = NaN
R13 Excel library✓✓missingworkaround
R14 Date-times, zones✓✓missing✓
Queries matched (of 7,358)7,3587,3327,3137,246

How to read the table. Every “missing” is a bug filed upstream. A Fabric DWH PM kindly reviewed some of the bug reports. Most of them turned out to be me writing poor T-SQL. The list and its live status are on the Bugs page [12]. Polars and DataFusion move fast, so some cells will get old.

Every DAX query in the suite is deterministic (an ORDER BY and similar tricks force one answer), so a mismatch is never just noise.

What benchmarks miss

Every engine handles the easy part. The hard part is where they differ, and no public benchmark tests it. In TPC-H and TPC-DS, keys are never null, decimals never tie, and every query is written by hand. But a lot of the SQL that engines run today is generated by BI tools, semantic layers and compilers, and agents will generate even more of it. That SQL is deep, correlated and full of mixed types. Before this project, I didn’t know how much correlated subqueries matter, or that any of them can be turned into joins, or that a measure needs values that keep their own type. I suspect many people who choose engines don’t know either, because no benchmark shows it. The suite behind this post is public, with Power BI’s answers, and anyone can use it.

Measures belong in the language

Measures and filter context belong in SQL itself, so that nobody needs a compiler like dax-sql to get there. Ossie is standardizing the model, and this list is a starting point for what engines will need for the advanced measures that come next. There is still a lot to do. I hope it will be real work, built into the engines, and not half-baked workarounds.

The front end from the TL;DR works whatever the measure language: DAX’s CALCULATE, AT in SQL, or what Ossie ends up with. All of them change the evaluation context, and all of them come down to the same correlated subqueries. The primitives in the list above are a separate matter: any SQL with a correlated subquery or mixed types needs them, measures or not, and engines should support them anyway.

This is also why I like the approach of a semantic model as a view in the catalog. The model becomes a database object like any other. You grant access to it with GRANT SELECT, and you get what the database already offers: permissions, lineage, auditing, sharing, and any SQL client or agent can query it. None of this has to be rebuilt in a separate BI server.

Time matters too: dax-sql went from its first commit to matching Power BI on more than 7,000 queries in about two months, with AI writing the code. Soon AI will write a compiler like this in much less time. Then the hard part is no longer the compiler. It is having a large set of correct answers to test it against, and engines that can run the SQL it produces.

I am confident others will show up, in commercial products and, I hope, in open source, and that they will do it better.

Inside or outside the engine

Suppose Ossie gets complex measures and every engine unnests any correlated subquery. BI tools would still have an advantage, because they control everything from the visual down to the storage. A SQL engine sees one query at a time, and knows nothing about who sent it. Power BI sees the whole report page. It knows which visuals are about to send queries, with which filters, and against which model, and it uses that:

  • Fusion. Many measures in one visual, or the same measure under several filters, are computed in one scan instead of many. SQLBI explains the vertical and horizontal versions [13].
  • Caching. Results are cached at several levels. Keeping a cache correct is easier when one product owns the data, the model and the query.
  • Queries that fit the visual. A visual asks only for what it shows: the totals it needs and the top rows it displays.

None of this is about what DAX means, so none of it is in my list. dax-sql compiles one query at a time and does none of it. A SQL engine could learn some of it, like caching results or sharing work across a batch of queries. But only a tool that also draws the dashboard can see the whole page. Measures in SQL fix the language problem, but not this one.

This was another lesson for me. I used to think the way forward was to generate SQL statements and let the engine do the rest. Now I think I was wrong. A compiler outside the engine never sees the data, its statistics or its caches. It writes text and hopes the optimizer copes, and the slow SQL and long planning times above are the cost. A compiler built into the engine can use all of that. For example, dax-sql can’t tell whether a key is ever null, so it writes null-safe joins and blank-row checks just in case. An engine that knows the data would skip them, and it could share one scan across several measures instead of running a subquery for each.

To get the right answer, the engine needs to know nothing about DAX. To get it fast, knowing helps a lot. I think this is one reason Import and Direct Lake work better in Power BI than DirectQuery, which is exactly the “generate SQL and send it” model. Their in-memory columnar storage helps too, of course. It is also one more argument for measures in the language: once a measure is part of SQL, the engine’s own optimizer sees it, and the compiler becomes native.

I saw a small version of this myself. dax-sql is a library, meant to be used by an engine or a tool, not by end users. When I used it inside a DuckDB extension, dax-sql-duckdb [14], the model became a semantic view in DuckDB, queried with AGG() in plain SQL. Sometimes I think that this closer fit between the compiler and the engine is the better approach. I don’t know; this is only what I saw while building it.

So what

So, can SQL do what DAX does? Yes, as far as the right answer goes. The engine doesn’t need DAX. It needs the primitives in this list, or a compiler that works around them. Getting the answer fast is still an open question.

As a Power BI user, this work gave me a new respect for the difference between Direct Lake, Import and DirectQuery. Something as small as the blank member changes the answer from one mode to the next. People don’t realize how much work Power BI does to get every result right.

About Fabric: it already produces Ossie YAML files, so I wonder when Fabric DWH will support them natively. Nothing in this work suggests it couldn’t. The gaps are known SQL features (VARIANT, recursive CTEs, subqueries in aggregates, unnesting inside CASE), not a limit of the architecture.

I think DAX is awesome as a language for measures. But as a query language, I find this much easier:

SELECT dim, AGG(measure) FROM model GROUP BY ALL

After years of using DAX, I still can’t write a simple DAX query by hand. Maybe it’s me, or maybe it’s because I write SQL more often. dax-sql accepts that SQL form too.

The site [6] has the live results, the plans and the bug list.

And a final thought: I can write about this topic without understanding a single line of the code. Just a couple of years ago, that would have been considered crazy. It works because every answer is checked against Power BI, so I don’t have to trust the code, only the results. That is a testament to AI, and to black-box testing. Computer science used to be a bit like mathematics: you reasoned about the code. This felt more like a natural science: you run the experiment, and nature, here Power BI, tells you if you’re wrong.

References

  1. W. Kim. On Optimizing an SQL-like Nested Query. ACM TODS 7(3), 1982.
  2. T. Neumann, A. Kemper. Unnesting Arbitrary Queries. BTW 2015.
  3. C. Galindo-Legaria, M. Joshi. Orthogonal Optimization of Subqueries and Aggregation. SIGMOD 2001.
  4. T. Neumann. Improving Unnesting of Complex Queries. BTW 2025.
  5. DuckDB. Correlated Subqueries in SQL (blog), 2023. https://duckdb.org/2023/05/26/correlated-subqueries-in-sql
  6. dax-sql. https://github.com/djouallah/dax-sql. Live results: https://djouallah.github.io/dax-sql/
  7. Apache Ossie. https://github.com/apache/ossie
  8. M. Russo, A. Ferrari. The Definitive Guide to DAX, 2nd ed. Microsoft Press, 2019.
  9. J. Hyde, J. Fremlin. Measures in SQL. SIGMOD Companion 2024. arXiv:2406.00251
  10. Transaction Processing Performance Council. TPC-H Specification. https://www.tpc.org/tpch/
  11. Transaction Processing Performance Council. TPC-DS Specification. https://www.tpc.org/tpcds/
  12. dax-sql bugs filed upstream, with live status. https://djouallah.github.io/dax-sql/#bugs
  13. SQLBI. Introducing horizontal fusion in DAX. https://www.sqlbi.com/articles/introducing-horizontal-fusion-in-dax/ and Vertical Fusion, DAX Internals. https://docs.sqlbi.com/dax-internals/optimization-notes/vertical-fusion
  14. dax-sql-duckdb, a DuckDB extension built on dax-sql. https://github.com/djouallah/dax-sql-duckdb
  15. Boring Semantic Layer. https://github.com/boringdata/boring-semantic-layer
  16. yardstick, a DuckDB extension implementing Measures in SQL. https://github.com/sidequery/yardstick
  17. semantic_views, a DuckDB extension. https://duckdb.org/community_extensions/extensions/semantic_views
  18. semantic_layer, a DuckDB extension. https://github.com/altertable-ai/duckdb-semantic_layer

One thought on “Can SQL do what DAX does?”

  1. As a Microsoft fan, and long time DAX user since 2010, I assumed this would come. I like the elegance of DAX, but it has always been difficult to write. Of course, AI makes DAX easier to generate. DAX was never going to take over the world, but if a Power BI model can be run as fast in SQL, then why would people use it. BTW, I love GROUP BY ALL. I wish the SQL standards group had worked on real improvements like that over the decades instead of largely useless add ons.

Leave a Reply