Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

2.2 KB
Raw Blame
# MBQL shape rules

These are prescriptive because the shape of common questions is often counter-intuitive.

## Scalar questions produce a single row

Questions of the form *"what is the average/percentage/share/portion/total/median …"* should produce a single aggregated value. Do not add a breakout, even when:

- A dimension word appears in the user's question ("percentage of **department** expenses")
- A dimension word appears in the metric's name (e.g., metric named "Department expense approval rate")

In those cases, the dimension word is describing *scope* — it's not an instruction to group. Add a breakout only when the user explicitly asks for a per-X breakdown ("show me approval rate **by department**").

## Superlative questions sort and limit

Questions of the form *"which / who / what has the most / highest / slowest / largest / fastest …"* ask for a single winner (or small top-N). In one stage, set four keys: `aggregation` on the measure, `breakout` on the entity being ranked, `order-by` descending on that aggregation, and `limit`:

```json
{"lib/type": "mbql.stage/mbql",
 "source-table": ["Sample Database", null, "ORDERS"],
 "aggregation": [["sum", {}, ["field", {}, ["Sample Database", null, "ORDERS", "TOTAL"]]]],
 "breakout": [["field", {}, ["Sample Database", null, "ORDERS", "PRODUCT_ID"]]],
 "order-by": [["desc", {}, ["aggregation", {}, 0]]],
 "limit": 1}
```

`aggregation`, `breakout`, `order-by`, and `limit` are stage *keys*, never clause heads — don't write `["aggregate", …]`, `["order-by", …]`, or `["limit", …]` as clauses. Refer to an aggregation in the same stage by its 0-based index: `["aggregation", {}, 0]`. Direction clauses carry the mandatory options map like every other clause: `["desc", {}, <ref>]`.

Grouping without sort+limit answers a different question — it returns every entity, which obscures the winner.

## Percentage-of-whole questions

*"What percentage of X is Y?"* is a distribution question. Group by the dimension, aggregate the measure (often a count or sum), and let the visualization present the breakdown. A pie chart handles this well but isn't mandatory. Don't try to compute the percentage in a calculated column unless the user needs the number as a column value.