> For the complete documentation index, see [llms.txt](https://docs.zero.inc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.zero.inc/settings/custom-properties/formulas.md). Agents can also search and read this documentation through its [MCP server](https://docs.zero.inc/~gitbook/mcp).

# Formulas

A formula property calculates its value from other properties instead of storing one. Annual contract value from monthly value, days until renewal, open pipeline per company, a "Large / Medium / Small" band: write the expression once, and every record shows the result. Zero recalculates it on every read, so it never goes stale.

Formulas are a type of [custom property](https://docs.zero.inc/settings/custom-properties.md) on companies, contacts and deals. Once created, they work like other properties in list columns, filters, sorting, grouping and reports. Nobody can edit their values, though: to change a result, change the properties the formula reads.

## Create a formula

1. Create a property the usual way: **Settings → Workspace → Custom properties → New property**, or **Add a property** from a list view's **Properties** menu.
2. Choose **Formula** as the **Property type**.
3. Write the expression. Type `{{` to pick a property to insert. The picker offers only properties a formula can read.
4. Under the editor Zero checks the formula as you type. It shows **Returns a number** (or text, yes/no, date…), or points at the part it does not understand.
5. For number results, pick **Show as**: **Number**, **Currency** or **Percentage**.
6. Check the **Preview on recent** records, then **Save**. You can only save once the formula is valid.

The editor's **Syntax reference** lists every operator and function, and so does this page.

## Referencing properties

Put references in double curly braces:

| Reference              | Means                                                                      |
| ---------------------- | -------------------------------------------------------------------------- |
| `{{value}}`            | A built-in field of the record itself, e.g. a deal's value.                |
| `{{custom.<id>}}`      | A custom property of the record. The `{{` picker inserts these for you.    |
| `{{company.name}}`     | A field of a single related record, such as a deal's or contact's company. |
| `sum({{deals.value}})` | A field across a list of related records, wrapped in an aggregate.         |
| `count({{contacts}})`  | The number of related records.                                             |

Formulas can read custom properties of these types: Plain Text, Number, Currency, Percentage, Rating, Yes/No, Link, Email address, Phone number, Single Select, Date, Time and Formula. They can't read Rich Text, Multi Select, Single User, Multiple Users, Location, or the relation types (Company, Companies, Contact, Contacts, Deal, Deals), not even to count them. A formula that names one of these is rejected.

Built-in fields follow the same rule. Fields with one value, such as a name, a value or a date, can be read. Built-in fields that hold a list of names or words, such as a company profile's investors, categories and founders, a company's domains or a contact's emails, are read with the [list functions](#lists); the `{{` picker marks them "(list)". Lists of ids, such as owners, can't be read, but built-in relations can be counted, e.g. `count({{owners}})` or `count({{contacts}})`.

A company's or contact's built-in **Location** is read one part at a time: `{{location.country}}`, `{{location.countryCode}}`, `{{location.state}}`, `{{location.stateCode}}`, `{{location.county}}`, `{{location.metro}}`, `{{location.city}}` or `{{location.continent}}`. Related records work the same way, e.g. `{{company.location.city}}` on a deal. The whole `{{location}}` can't be read, and a record without a location reads as empty. A Location custom property can't be read at all.

A company's enrichment profile is read by its parts too: the estimated annual revenue range in USD (`{{companyProfile.revenue.min}}` and `.max`), the IPO (`{{companyProfile.ipo.date}}`, `.ticker`, and `.amount`, the share price at the IPO), the acquisition (`{{companyProfile.acquiredBy.name}}`, `.date`, and `.amount`, the price paid) and the investor summary (`{{companyProfile.investorSummary.investments}}`, `.leadInvestments`, `.exits`, `.funds` and `.totalFundsAmount`). The picker offers the revenue range as its low and high end; type the other references yourself. Most profiles have no revenue, IPO or acquisition data, so these read as empty for most companies.

Two kinds of values read differently from how they are shown:

* A **Single Select** property reads as the name of its option, so you compare it with the name: `{{custom.<id>}} = "Enterprise"`.
* A deal's **Stage** (`{{stage}}`) and **Pipeline** (`{{pipelineId}}`) read as ids, not names, so `{{stage}} = "Won"` never matches. To check whether a deal is open, won or lost, pick **Stage → Type** (`{{pipelineStage.type}}`), which reads as `lead`, `in-progress`, `won` or `lost`. For names, write `{{pipelineStage.name}}` or `{{pipeline.name}}`.

A list of related records (a company's deals or contacts, a contact's deals) has many values, so it has to be wrapped in an aggregate such as `sum`, `avg`, `min`, `max` or `count`. A reference can follow at most two relations, and only one of them may be a list.

Formulas can reference other formula properties, up to two levels deep, but not themselves, directly or in a loop.

## Writing expressions

| You write                                           | Meaning                                                                           |
| --------------------------------------------------- | --------------------------------------------------------------------------------- |
| `+ - * / %`                                         | Arithmetic (`%` is the remainder)                                                 |
| `= != < <= > >=`                                    | Comparison (`==` and `<>` also work)                                              |
| `&&` / `and`, `\|\|` / `or`, `!` / `not`            | Combine yes/no conditions                                                         |
| `"text"` or `'text'`, `42`, `true`, `false`, `null` | Literal values                                                                    |
| `if(condition, then, otherwise)`                    | Pick a value by condition                                                         |
| `if (c1) { a } else if (c2) { b } else { c }`       | Several branches. With no final `else`, the result is empty when nothing matches. |
| `{{x}} = any(["a", "b"])`                           | True when the value is one of the listed values (`!=` for "none of")              |

Types must line up: `{{value}} + "text"` is rejected, because you can't add text to a number. Use `concat()` to join values into text. Comparisons can't be chained (`a < b < c`). Write `a < b && b < c` instead.

When an input is empty, the result is usually empty too. Use `coalesce({{x}}, 0)` to fall back to a default.

A formula can be up to 2,000 characters long and use up to 5 aggregates.

## Functions

### Aggregates over related records

| Function                             | Returns                                                               |
| ------------------------------------ | --------------------------------------------------------------------- |
| `sum({{deals.value}})`               | Total of a number across related records                              |
| `avg(...)`, `mean(...)`              | Average                                                               |
| `median(...)`                        | Middle value                                                          |
| `min(...)`, `max(...)`               | Smallest / largest number or date                                     |
| `count({{deals}})`                   | Number of related records (or, with a field, those that have a value) |
| `sumIf({{deals.value}}, condition)`  | Total over the related records matching the condition                 |
| `avgIf`, `minIf`, `maxIf`, `countIf` | The same, filtered by a condition                                     |

The condition of an `…If` function is checked once per related record. It can read fields of those records and of the record itself, e.g. `countIf({{deals}}, {{deals.value}} > 10000)`.

Some relations are summaries that already group related records, such as `analyticsEventsByDate` or `totalDeals`. Formulas reject them. Use the plain relation instead (`{{analyticsEvents}}`, `{{deals}}`).

### Analytics events and sessions

If your workspace sends product analytics to Zero, formulas on companies and contacts can aggregate the record's **Analytics events** (`{{analyticsEvents}}`, with fields such as `type`, `date` and `count`) and **Analytics sessions** (`{{analyticsSessions}}`, e.g. `startTime`, or the UTM tags a session started with: `entryUtm.source`, `.medium`, `.campaign`, `.term` and `.content`). Deals reach their company's events and sessions through `{{company.analyticsEvents}}` and `{{company.analyticsSessions}}`. The `{{` picker lists them in their own groups.

Zero stores events as daily totals per event type. `count()` and `countIf()` over analytics events therefore count events, not days: `count({{analyticsEvents}})` is the total number of events. Over sessions they count sessions. To count some event types in a recent window:

`countIf({{analyticsEvents}}, {{analyticsEvents.type}} = any("signup", "invite_sent") && inLast({{analyticsEvents.date}}, 90, "days"))`

### Numbers

`round(number, decimals?)`, `floor(number)`, `ceil(number)`, `abs(number)`, `power(base, exponent)`, `mod(dividend, divisor)`, `exp(number)`, `log(number)` (natural logarithm), and `min(a, b, …)` / `max(a, b, …)` for the smallest or largest of several values.

### Text

| Function                                   | Returns                                                                                    |
| ------------------------------------------ | ------------------------------------------------------------------------------------------ |
| `concat(a, b, …)`                          | All values joined into one text                                                            |
| `lower(text)`, `upper(text)`, `trim(text)` | Lowercased, uppercased, or without surrounding spaces                                      |
| `length(text)`                             | Number of characters                                                                       |
| `left(text, count)`, `right(text, count)`  | The first / last characters                                                                |
| `replace(text, search, replacement)`       | Text with the first match replaced (case-sensitive)                                        |
| `replaceAll(text, search, replacement)`    | Text with every match replaced (case-sensitive)                                            |
| `splitPart(text, delimiter, index)`        | One part of a split text, counting from 0: `splitPart({{email}}, "@", 1)` gives the domain |
| `contains`, `startsWith`, `endsWith`       | Whether the text contains / starts with / ends with a search text (case-insensitive)       |

### Dates

| Function                          | Returns                                                              |
| --------------------------------- | -------------------------------------------------------------------- |
| `today()`, `now()`                | The current date / date and time                                     |
| `date("2026-01-01")`              | A fixed date, or the day of a date and time                          |
| `daysBetween(from, to)`           | Whole days between two dates (negative when `to` is earlier)         |
| `dateDiff(from, to, "months")`    | Whole units between two dates. Months and years follow the calendar. |
| `dateAdd(date, amount, "days")`   | A date moved forward (or back, with a negative amount)               |
| `inLast(date, amount, "days")`    | Whether the date is within the last amount of units, up to today     |
| `year`, `quarter`, `month`, `day` | Parts of a date as numbers                                           |
| `hour`, `minute`, `second`        | Parts of a date and time (UTC)                                       |
| `endOfMonth(date)`                | Last day of the date's month                                         |
| `formatDate(date, "YYYY-MM-DD")`  | A date as text                                                       |

`inLast()` counts today in the window and never counts a future date. Over a date, the window starts on the day `dateAdd(today(), -amount, unit)` gives, so `inLast({{closeDate}}, 90, "days")` includes the day 90 days ago. Over a date and time, it counts back from now.

Units are `"milliseconds"`, `"seconds"`, `"minutes"`, `"hours"`, `"days"`, `"weeks"`, `"months"` and `"years"`. `formatDate` understands `YYYY`, `YY`, `Q`, `MMMM` (January), `MMM` (Jan), `MM`, `M`, `DD`, `D`, `dddd` (Monday), `ddd` (Mon), `HH`, `hh`, `mm`, `ss` and `A`. Text in `[brackets]` is kept as is.

### Lists

A list field, such as `{{companyProfile.investors}}`, `{{companyProfile.categories}}` or `{{companyProfile.founders}}`, holds several values. A formula reads it only through these functions:

| Function                                       | Returns                                                                   |
| ---------------------------------------------- | ------------------------------------------------------------------------- |
| `contains({{list}}, "Accel")`                  | Whether one of the items is the value                                     |
| `{{list}} = any(["Accel", "Sequoia Capital"])` | Whether any item is one of the listed values (`!=` for "none of them is") |
| `count({{list}})`                              | Number of items (0 for an empty list)                                     |
| `isEmpty({{list}})`, `isNotEmpty({{list}})`    | Whether the list has no items / at least one                              |
| `join({{list}}, ", ")`                         | The items as one text, separated by the given text (`", "` when left out) |

Items match whole and ignore case and surrounding spaces, so `contains({{companyProfile.categories}}, "ai")` matches "AI" but not "Email Marketing". To look for part of an item, search the joined text: `contains(join({{companyProfile.investors}}), "sequoia")`. A missing list reads the same as an empty one, and blank items are skipped. Any other use, such as `{{companyProfile.investors}} = "Accel"`, is rejected. A list on each of several related records, such as the emails of a company's contacts, is read inside a `countIf` condition: `countIf({{contacts}}, contains({{contacts.emails}}, "ana@acme.com"))`.

### Empty values

`coalesce(a, b, …)` gives the first value that isn't missing (`null`). Blank text (`""`) counts as a value, so `coalesce()` keeps it. `isEmpty(value)` and `isNotEmpty(value)` treat both a missing value and blank text as empty. To fall back on either, write `if(isEmpty({{x}}), "Unknown", {{x}})`.

### History

Zero records how some properties change over time, so a formula can look back. These functions work on properties of the record itself whose changes are tracked:

* **Deals:** name, pipeline, stage, value, close date, confidence and custom properties
* **Companies:** name, domain, churned and custom properties
* **Contacts:** name, email, title, phone, LinkedIn and custom properties

Custom properties have history only if formulas can read their type (see [Referencing properties](#referencing-properties)). Formula properties and fields of related records have no history. A deal's stage and pipeline history holds ids, like the fields themselves.

| Function                                    | Returns                                                                                                        |
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `valueAt({{field}}, "-30d")`                | The value at a date (`"2026-01-01"`) or a time ago (`"-30min"`, `"-12h"`, `"-7d"`, `"-2w"`, `"-3mo"`, `"-1y"`) |
| `previousValue({{field}})`                  | The value before the latest change                                                                             |
| `initialValue({{field}})`                   | The value when the record was created                                                                          |
| `timeInValue({{field}}, "days")`            | How long the field has had its current value                                                                   |
| `timeInValue({{field}}, value, "days")`     | How long, in total, the field has had the given value                                                          |
| `timeSinceValue({{field}}, value, "days")`  | Time since the field last had the value (0 while it still has it)                                              |
| `valueSetAt({{field}}, value?, "first")`    | When the field got its current value, or was first (`"first"`) or last (`"last"`) set to the given value       |
| `hasBeenInValue({{field}}, ["a", "b"])`     | Whether the field has, or ever had, any of the values                                                          |
| `hasBeenInAllValues({{field}}, ["a", "b"])` | Whether the field has had every one of the values at some point                                                |

## Examples

| Entity    | Formula                                                                                         | Result                               |
| --------- | ----------------------------------------------------------------------------------------------- | ------------------------------------ |
| Deals     | `{{value}} * 12`                                                                                | Annual value (show as Currency)      |
| Deals     | `if({{value}} > 10000, "Large", if({{value}} > 1000, "Medium", "Small"))`                       | Deal size band                       |
| Deals     | `daysBetween(today(), {{closeDate}})`                                                           | Days until the close date            |
| Deals     | `timeInValue({{stage}}, "days")`                                                                | Days in the current stage            |
| Deals     | `{{value}} - valueAt({{value}}, "-30d")`                                                        | Value change over 30 days            |
| Deals     | `{{pipelineStage.type}} = "won"`                                                                | Whether the deal is won              |
| Deals     | `{{company.location.city}}`                                                                     | The company's city                   |
| Companies | `sumIf({{deals.value}}, {{deals.pipelineStage.type}} != any("won", "lost"))`                    | Open pipeline                        |
| Companies | `sumIf({{deals.value}}, isEmpty({{deals.closeDate}}))`                                          | Pipeline without a close date        |
| Companies | `count({{contacts}})`                                                                           | Number of contacts                   |
| Companies | `if ({{location.country}} = any(["Finland", "Sweden"])) { "Nordics" } else { "Other" }`         | Market by headquarters country       |
| Companies | `countIf({{analyticsEvents}}, inLast({{analyticsEvents.date}}, 30, "days"))`                    | Analytics events in the last 30 days |
| Companies | `if ({{companyProfile.investors}} = any(["Sequoia Capital", "Accel"])) { "Yes" } else { "No" }` | Backed by a top-tier investor        |
| Companies | `count({{companyProfile.founders}})`                                                            | Number of known founders             |
| Contacts  | `splitPart({{email}}, "@", 1)`                                                                  | Email domain                         |
| Contacts  | `concat({{name}}, " (", {{company.name}}, ")")`                                                 | Name with company                    |

## Changing a property to or from a formula

You can turn an existing property into a formula in its edit modal. Zero warns you first: **the values stored in that property are removed from every record**, because the formula's result replaces them. Changing a formula back to another type gives you an empty property, since a formula never stored values.

## Formulas in imports, automations, agents and the API

Formula values can't be written anywhere: imports can't fill them, automations can't set them, and agents treat them as read-only. Agents can still read formula results and see the expression.

In the API a formula is a column with `type: "formula"`, and the expression is in `settings.formula.source`. Read a record's result by naming `custom.<column-id>` in `fields`. The value comes back under that exact key. You can also filter, sort and group by it. `POST /api/columns/formula/validate` checks an expression and previews it without saving. See the [API reference](https://docs.zero.inc/developers/api.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.zero.inc/settings/custom-properties/formulas.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
