> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cube.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Calculated fields

> Create ad-hoc custom dimensions and measures with Semantic SQL in workbooks, with help from AI or the field picker.

Calculated fields are ad-hoc dimensions and measures you add to a workbook
report. You can [promote][ref-promote] a calculated dimension to a workbook field
to use it in other reports of the workbook and on its dashboards. Calculated
fields do not change the shared data model.

As described in [Semantic SQL](https://docs.cube.dev/docs/introduction.md#semantic-sql), Cube routes
analysis through the semantic layer instead of sending arbitrary SQL straight to
the warehouse. The runtime validates every request and applies your security
policies. Semantic SQL builds on Postgres-compatible SQL—including the
`MEASURE()` function—so you can express derived logic on top of existing
semantic definitions with both flexibility and governance.

Calculated fields are expressed as Semantic SQL and pushed down to the Cube
backend for evaluation. The semantic layer compiles them with the rest of the
query—rather than applying them only in the browser—so the same validation,
governance, and warehouse execution path apply as for any other Semantic SQL
analysis.

## Using AI to create calculated fields

You can ask the Cube AI agent to create custom calculations in natural language.
The agent can add or refine calculated fields from different parts of the
product—for example while exploring in **Analytics chat** or working in
**Workbooks**—so you are not limited to a single entry point when you want a new
metric or dimension for the analysis in front of you.

## Creating calculated fields in UI

You can also build and edit calculated fields directly in the workbook. New
fields appear in the **Query fields** section of the field picker sidebar and
belong to the current report. To reuse a dimension in other reports and on
dashboards, [promote it to a workbook field](#promoting-to-a-workbook-field).

### Aggregations from existing dimensions

Right-click a dimension column header and choose an aggregation to create a
calculated field automatically. Available aggregations depend on the column type:

| Column type | Available aggregations |
| - | - |
| Number | Count Distinct, Sum, Average, Min, Max |
| Time | Count Distinct, Min, Max |
| String, Boolean | Count Distinct |

### Calculations from existing measures

Open the menu on a measure column header and use the **Calculations** submenu
for derived calculations:

| Calculation | Description |
| - | - |
| % of total | Ratio of the measure value to the total across all rows |
| % of previous | Ratio of the measure value to the previous row's value |
| % change from previous | Percentage change compared to the previous row |
| Running total | Cumulative sum of the measure across rows |

> [!NOTE]
>
> **% of previous**, **% change from previous**, and **Running total** require at
> least one dimension in the query.

Which calculations are offered depends on the measure’s aggregation type:

| Aggregation type | Available calculations |
| - | - |
| Count, Sum | All calculations |
| Min, Max | Running total |
| Average, Count Distinct | None |

### Filtered measures

When working with query **Results**, pivot so at least one dimension is on
columns, then open the header menu on a **pivoted measure column** and choose
**Create filtered measure**. Cube adds a calculated measure that applies the
column’s slice—for example, from **Count** broken down by **Status**, you get a
measure that only aggregates rows matching that status (such as completed
orders only).

The option appears only for **native** measures on pivoted columns, not for
calculated fields. The same flow works in **Explore** when results are pivoted
the same way.

### Bins and value groups

You can also bucket an existing dimension without writing SQL. Open its menu in
the field picker sidebar and choose **Create bins…** on a number dimension, or
**Group values…** on a string or boolean one (grouping a boolean dimension is
how you rename its `true`/`false` values). Time dimensions have granularities
instead, and an already derived field cannot be bucketed again. To count the
time between two time dimensions, see [durations](#durations-between-dates).

[What's new in bins and value groups in Cube](https://www.youtube-nocookie.com/embed/3hg9GZkSdAI)

[Group values by a rule in Cube](https://www.youtube-nocookie.com/embed/lby5HrW923k)

![The Create bins panel on a number dimension, showing typed boundaries, the label styles, a preview of the five buckets, and the generated Semantic SQL](https://ucarecdn.com/b9890dd7-d82c-4126-a2e5-2f3948eafa72/772aa0f9-light.png)

**Bins** take their boundaries either as a list (**Custom ranges**) or from a
**Range start** and **Range end** (**Equal intervals**), which are prefilled
from the column's own minimum and maximum. For equal intervals, choose whether
the range is split by **Number of bins** or by a fixed **Bin size**. Each
boundary opens a bucket that includes its lower bound and excludes the upper
one, and two open-ended buckets are added at the edges—so `0, 18, 25` yields
`< 0`, `[0, 18)`, `[18, 25)`, `>= 25`, and no row is dropped. **Label style**
renders a bucket as `[10, 20)`, `>= 10 and < 20`, `10 to 19` (offered only while
every boundary is a whole number), or **Custom**, which lets you type your own
label for each bucket. Turn off **Label empty values separately** to fold rows
where the dimension is `NULL` into the last bucket instead of reporting them
under their own label (`Unknown` by default).

**Value groups** collect the dimension's values into named sets. A group is
defined either by the values you pick or by a rule, chosen with the operator in
front of the search box:

* **Search** (the default) narrows the list of values. Pick values, name the
  group, and choose **Add group**. **Select all N matches** picks every value the
  search shows; the list stops at 100 values, so use **Contains** to catch every
  match.
* **Contains**, **Starts with**, and **Ends with** define the group by a rule on
  the text you type. **Is empty** takes no text: its rule matches empty strings
  (`''`), not `NULL`.
  The list shows the values the rule matches, without checkboxes. Name the group
  and choose **Add as rule**.

Rules match case-insensitively, and they are evaluated when the query runs, so
they also catch values that appear in the data later. To add values to an
existing group, type its name; the button then reads **Add to "name"**. Picking
a value that another group holds moves it to the group you add it to. Moving a
value does not change any rule, so a rule in an earlier group can still catch it.

A value can match more than one group, for example two overlapping rules. It
joins the first group that matches it, so the order of the groups is their
precedence. A new group is added after the existing ones, so add the narrower
rule first. By default, whatever matches no group—including `NULL` values—falls
under **Everything else**, which defaults to `Other`; turn off **Group remaining
values** to have those rows return `NULL` instead.

Bucket labels carry their position as a prefix (`1.`, `2.`, zero-padded past nine
buckets) so that sorting the column sorts it by value rather than alphabetically,
which would put `>= 25` before `[0, 18)`. The prefix is visible in results, chart
legends, and axes.

![A workbook result grouped by the bucketed field: one row per bucket, with the created field listed under Query fields in the sidebar](https://ucarecdn.com/23ac9cbb-7503-4326-b74c-134ad54e5e7a/6cffb52c-light.png)

The panel previews the Semantic SQL it generates as you build:

```sql theme={"dark"}
CASE WHEN orders_view.age IS NULL THEN 'Unknown'
  WHEN orders_view.age < 0 THEN '1. < 0'
  WHEN orders_view.age < 18 THEN '2. [0, 18)'
  ELSE '3. >= 18' END
```

Value groups render each group as a branch: picked values as `IN`, text rules as
`ILIKE`, and **Is empty** as `= ''`:

```sql theme={"dark"}
CASE WHEN orders_view.status IN ('new', 'processing') THEN 'Open'
  WHEN orders_view.status ILIKE '%ship%' THEN 'Shipping'
  ELSE 'Other' END
```

> [!NOTE]
>
> **Equal intervals** ranges are resolved into boundaries when the field is created, not
> recomputed from the data. Values arriving later outside the range join the first
> and last buckets instead of extending them.

To change a bucketed field, choose **Edit bins…** or **Edit groups…** from its
menu—either in the sidebar or on its column header in the results. Only fields
this panel generated offer the action; a `CASE` expression written by hand does
not.

A bucketed field can also be **filtered**, the same way as a native dimension —
choose **Filter** from its menu. The value picker offers only the bucket's own
labels (e.g. `Picked` and `Other`), since a bucket can't return a value it
wasn't built to produce, and `is null` / `is not null` are offered only when
the bucket can actually return `NULL`. Editing the bucket afterward keeps the
filter's selection where possible — renaming a label moves the selection with
it — but changing the number of buckets drops a selection that no longer
matches, since the underlying structure changed.

### Top N fields

A Top N field keeps the N members of a string dimension with the highest or
lowest value of a measure, and groups every other member under one label, such
as the 5 biggest customers and an **Other** row. Choose **Top N…** in the
dimension's menu in the field picker sidebar, or in its column header menu in
the results.

The panel has these settings:

* **Show** — **Top** or **Bottom**, and N. N starts at 10.
* **Ranked by** — the measure to rank by. It starts on the first measure the
  report shows.
* **Ranked within** — other dimensions of the report. Leave it on
  **Whole report** to rank across the whole report, or pick dimensions to
  keep N members in each group.
* **Group remaining values as** — the label of the rest, **Other** by default.

The field replaces the dimension in the report and is named like
*Status, top 10*. To change it, choose **Edit Top N…** in its menu. Members are
ranked the same way as by the [Top N filter][ref-top-n-filter]: after the
report's other filters, with ties broken by the member's value.

To hide the rest instead of grouping it, switch **Group remaining values as**
off. The panel then adds a [Top N filter][ref-top-n-filter] to the report
instead of a field.

### Durations between dates

You can count the time between two time dimensions of a semantic view without
writing SQL, for example the days from `created_at` to `shipped_at`. Open the
menu of the start date in the field picker sidebar and choose **Create
duration…**. The action is offered on a time dimension of the data model when
the semantic view has at least one other time dimension.

[Duration between two dates in Cube](https://www.youtube-nocookie.com/embed/CH_2KHnK2Ck)

In the **Create duration** panel, the time dimension you opened the menu on is
the **Start date**. Select the **End date** from the other time dimensions of
the semantic view, and choose a **Unit**: **Days**, **Hours**, **Weeks** or
**Months**. The **Field name** follows your picks, for example
`Created At to Shipped At (days)`, until you type your own. Choose **Create**
to add the field to **Query fields**.

The panel previews the Semantic SQL it generates:

```sql theme={"dark"}
DATEDIFF(day, orders_view.created_at, orders_view.shipped_at)
```

A duration counts the unit boundaries crossed between the two dates, not the
elapsed time: from 23:59 to 00:01 the next day is `1` day, and from 00:01 to
23:59 the same day is `0` days. Both dates are converted to the query time zone
first. When the end date is earlier than the start date, the value is negative,
and when either date is empty, the value is empty.

The generated field is a regular calculated field, with no **Edit duration…**
action: to switch the unit, [edit its SQL expression](#editing-a-calculated-field).
Like any calculated dimension, you can [promote][ref-promote] it to a workbook field.

> [!WARNING]
>
> Durations depend on how the data source translates `DATEDIFF`. They work on
> Postgres, for example, but may fail on other data sources.

### Promoting to a workbook field

A query field belongs to one report. A **workbook field** belongs to the
workbook: it is listed under **Workbook fields** in the field picker sidebar
of every report on the same semantic view, and dashboard
[filters and field switchers](#using-calculated-fields-on-dashboards) can
target it.

To promote a calculated dimension, choose **Promote to workbook field** from its
column header menu in the results or from its menu in the sidebar. In the
**Save calculated field** dialog, enter a **Name** and, optionally, a
**Title**, **Description** and **Format**, then choose **Save**. The field
stays a dimension, and **Value type** is prefilled from its SQL.

Only dimensions can be promoted. Calculated measures stay query fields.

### Promoting to the data model

A workbook field exists only in its workbook. To add it to the data model,
choose **Promote to data model** from its menu in the field picker sidebar.
Cube opens the data model page of the deployment, with a prompt for the
[Semantic Model Agent][ref-model-agent] in the chat input.

The prompt describes the field: its name, title, description, semantic view,
kind, type, format and Semantic SQL expression. If the field is built on other
workbook fields, the prompt also includes their expressions. It asks the agent
to:

1. Find the cubes behind the semantic view members that the expression uses.
2. Stop if the data model already has an equivalent member, and name it.
3. Otherwise, add the member to the cube and include it in the semantic view.
4. Review the change.
5. Commit the change to a new branch and open a pull request. If the
   repository cannot open one, the agent leaves the change on the development
   branch.

The agent does not merge to the main branch and does not change the workbook.
Nothing is sent automatically: read the prompt, edit it if necessary, and send
it.

**Promote to data model** is shown only when all of these are true:

* You have the [Developer role][ref-roles] or a role above it.
* AI features are available for your account, and the deployment has an agent.
* You can [edit the data model][ref-deployment-permissions], on the main
  branch or on development branches.

When the new member is merged and deployed, the workbook field stays in the
workbook, and reports continue to use it. To move a report to the data model
member, replace the field in the report, then delete the workbook field if no
report uses it.

### Editing a calculated field

Select a query field in the sidebar to open the editor. You can change its
**SQL expression**, then choose **Update** to apply.

Select a workbook field in the sidebar to open the **Update calculated field**
dialog. You can change its **Title**, **Description**, **Format** and
**Expression**. Its **Name** does not change, because reports and dashboards
find the field by it, and neither does the **Value type** of a dimension,
because dashboard controls are set up for it.

When you update the expression of a workbook dimension, every report of the
workbook on that semantic view that still uses the previous expression gets
the new one. A report where you changed the expression yourself keeps it.

## Using calculated fields on dashboards

A workbook calculated dimension can be the target of a dashboard
[filter][ref-filter] and an alternative on a dimension
[field switcher][ref-field-switcher]. Both pickers list such fields under
**Workbook fields**. A field whose name the data model also defines is not
listed.

A control on a calculated dimension has some limitations: see the
[filter][ref-filter] and [field switcher][ref-field-switcher] sections. A
published dashboard keeps the field's definition from the moment you publish
it; publish again to show your edits to viewers.

[ref-promote]: #promoting-to-a-workbook-field

[ref-filter]: https://docs.cube.dev/docs/explore-analyze/dashboards/widgets/controls.md#calculated-dimensions

[ref-field-switcher]: https://docs.cube.dev/docs/explore-analyze/dashboards/widgets/controls.md#choosing-what-it-switches

[ref-model-agent]: https://docs.cube.dev/docs/getting-started/develop-in-ide.md#ai-assisted-development

[ref-roles]: https://docs.cube.dev/admin/users-and-permissions/roles-and-permissions.md

[ref-deployment-permissions]: https://docs.cube.dev/admin/users-and-permissions/custom-roles.md#deployment-permissions

[ref-top-n-filter]: https://docs.cube.dev/docs/explore-analyze/workbooks/querying-data.md#top-n-and-bottom-n


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.