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

# SQL expressions

> Calculate a value from event properties before Lago applies the billable metric's aggregation.

A SQL expression calculates a value from the data in each usage event. Use one when the measurement you need combines several properties or transforms a reported value.

For example, an event might report storage size, the number of replicas and a start and end time. An expression can combine these properties to calculate GB-hours.

Lago evaluates the expression for each event, then applies the metric's aggregation. With `Sum`, Lago adds the calculated values together.

## Create a custom expression

Set `expression` to the calculation you want Lago to run for each event. Choose an aggregation type based on how you want to combine or select the results. Custom expressions work with every aggregation type except `Count`.

> [tab] Dashboard
>
> 1. Define the `name` and `code` of the billable metric.
> 2. Choose an aggregation type.
> 3. Select **Custom expression** as the aggregation option instead of **Unique field**.
> 4. Enter your custom expression in the side panel.
> 5. Test the custom expression.
> 6. Save the billable metric.
>
> ![Side panel of the Lago dashboard where a custom expression is entered for a billable metric](https://mintcdn.com/lago-docs/L57i4PY_iDpAEuWL/guide/billable-metrics/images/custom-expression-creation.png?fit=max\&auto=format\&n=L57i4PY_iDpAEuWL\&q=85\&s=e2f0bb331d9fb36c03508d22e89f469a)
>
> Create a custom expression for a billable metric

> [tab] API
>
> * **Storage:** Calculate GB-hours from storage size, replicas and duration.
> * **Seats:** Combine `user_id` and `app_id` into an identifier for `Count unique`.
>
> ```bash Storage {13,14} theme={"dark"}
> LAGO_URL="https://api.getlago.com"
> API_KEY="__YOUR_API_KEY__"
>
> curl --location --request POST "$LAGO_URL/api/v2/billable_metrics" \
>   --header "Authorization: Bearer $API_KEY" \
>   --header 'Content-Type: application/json' \
>   --data-raw '{
>     "billable_metric": {
>       "name": "Storage",
>       "code": "storage",
>       "description": "GB hours consumed",
>       "aggregation_type": "sum_agg",
>       "expression": "event.properties.gb * event.properties.replicas * (event.properties.ended_at - event.properties.started_at) / 3600",
>       "field_name": "consumed_gb_hours",
>       "recurring": false
>     }
>   }'
> ```
>
> ```bash Seats {13} theme={"dark"}
> LAGO_URL="https://api.getlago.com"
> API_KEY="__YOUR_API_KEY__"
>
> curl --location --request POST "$LAGO_URL/api/v2/billable_metrics" \
>   --header "Authorization: Bearer $API_KEY" \
>   --header 'Content-Type: application/json' \
>   --data-raw '{
>     "billable_metric": {
>       "name": "Seats",
>       "code": "seats",
>       "description": "Number of seats used",
>       "aggregation_type": "unique_count_agg",
>       "expression": "CONCAT(event.properties.user_id, '\''-'\'' , event.properties.app_id)",
>       "field_name": "seat_id",
>       "recurring": true
>     }
>   }'
> ```

## Worked example

The `storage` metric above receives one event for `contract_example`:

```json theme={"dark"}
{
  "transaction_id": "storage_20270116_customer_example_001",
  "external_contract_id": "contract_example",
  "code": "storage",
  "timestamp": 1800057600,
  "properties": {
    "gb": 10,
    "replicas": 3,
    "started_at": 1800057600,
    "ended_at": 1800064800
  }
}
```

This event reports 10 GB of storage across three replicas for two hours.

The expression calculates:

**10 GB × 3 replicas × 2 hours = 60 GB-hours**

The `Sum` aggregation adds these 60 GB-hours to the values calculated from other matching events in the billing cycle.

## Test a custom expression

Test your expression with a sample event before saving the metric. Use values you can calculate manually, then compare your expected result with Lago's result.

For the storage example above, the expected result is 60.

The Dashboard testing tool runs the expression against a sample event whose fields you can edit. If the expression is invalid, Lago returns an error. Fix the expression before saving the metric.

* Use the supported attributes: `event.code`, `event.timestamp` and properties under `event.properties`.
* Use precise paths: `event.timestamp` for the event timestamp, `event.properties.your_field` for a property.

![Lago dashboard testing a custom expression against a sample event and showing the result](https://mintcdn.com/lago-docs/L57i4PY_iDpAEuWL/guide/billable-metrics/images/test-custom-expression.png?fit=max\&auto=format\&n=L57i4PY_iDpAEuWL\&q=85\&s=b78b53417f8d4b209949406a3ec7f67d)

Test your custom expression

## Supported expressions

Use an expression that matches the value you want to calculate:

| Purpose | Example |
| - | - |
| Combine two identifiers | `CONCAT(event.properties.user_id, '-', event.properties.app_id)` |
| Calculate storage across replicas | `event.properties.gb * event.properties.replicas` |
| Round a reported duration | `ROUND(event.properties.duration_msec)` |
| Select the smaller reported value | `LEAST(event.properties.disk1_usage_mb, event.properties.disk2_usage_mb)` |

The following sections describe the supported attributes, literal values, operators and functions:

* [Event attributes](#event-attributes)
* [Literal values](#literal-values)
* [Operators](#operators)
* [Functions](#functions)
  * [`CONCAT`](#concat)
  * [`ROUND`](#round)
  * [`FLOOR`](#floor)
  * [`CEIL`](#ceil)
  * [`LEAST`](#least)
  * [`GREATEST`](#greatest)

If you need an expression Lago does not support yet, contact the Lago team or contribute it to the open-source project.

### Event attributes

Lago expressions may include the following event attributes:

* `event.code` (event code)
* `event.timestamp` (event timestamp)
* `event.properties.[property_name]` (event property)

For example, `event.properties.my_property` is a valid event attribute.

### Literal values

You can include values directly in an expression:

* `123` (integer)
* `123.45` (decimal)
* `'Hello, world!'` (string)

### Operators

Lago expressions may include basic operators:

* `+` (addition)
* `-` (subtraction)
* `*` (multiplication)
* `/` (division)
* unary minus (`-12`)

### Functions

#### `CONCAT`

`CONCAT` joins two or more strings.

```SQL theme={"dark"}
CONCAT(str1, str2[,strs,...])
```

**Parameters:**

* `str1`: The first string to concatenate
* `str2`: The second string to concatenate
* `strs`: (Optional) Additional strings to concatenate.

**Returns:** A string containing the joined values.

**Examples:**

* `CONCAT(event.properties.user_id, '-', event.properties.app_id)`

#### `ROUND`

`ROUND` rounds a number to the specified precision.

```SQL theme={"dark"}
ROUND(value, precision)
```

**Parameters:**

* `value`: The number to round
* `precision`: (Optional) Number of decimal places. Defaults to `0`.

**Returns:** A number rounded to the specified precision.

**Examples:**

* `ROUND(14.2355)` returns `14`
* `ROUND(14.2355, 0)` returns `14`
* `ROUND(14.2355, 2)` returns `14.24`
* `ROUND(14.2355, -1)` returns `10`

#### `FLOOR`

`FLOOR` rounds a number down to the specified precision. With the default precision of `0`, it rounds down to an integer.

```SQL theme={"dark"}
FLOOR(value, precision)
```

**Parameters:**

* `value`: The number to round
* `precision`: (Optional) Number of decimal places. Defaults to `0`.

**Returns:** A number rounded down to the specified precision.

**Examples:**

* `FLOOR(16.2365)` returns `16`
* `FLOOR(16.2365, 0)` returns `16`
* `FLOOR(16.2365, 2)` returns `16.23`
* `FLOOR(16.2365, -1)` returns `10`

#### `CEIL`

`CEIL` rounds a number up to the specified precision. With the default precision of `0`, it rounds up to an integer.

```SQL theme={"dark"}
CEIL(value, precision)
```

**Parameters:**

* `value`: The number to round
* `precision`: (Optional) Number of decimal places. Defaults to `0`.

**Returns:** A number rounded up to the specified precision.

**Examples:**

* `CEIL(14.2345)` returns `15`
* `CEIL(14.2345, 0)` returns `15`
* `CEIL(14.2345, 2)` returns `14.24`
* `CEIL(14.2345, -1)` returns `20`

#### `LEAST`

`LEAST` returns the smallest of two or more numbers.

```SQL theme={"dark"}
LEAST(num1, num2[,nums,...])
```

**Parameters:**

* `num1`: The first number to compare
* `num2`: The second number to compare
* `nums`: (Optional) Additional numbers to compare.

**Returns:** The minimum of the given numbers.

**Examples:**

* `LEAST(event.properties.disk1_usage_mb, event.properties.disk2_usage_mb, 10.0)`

#### `GREATEST`

`GREATEST` returns the largest of two or more numbers.

```SQL theme={"dark"}
GREATEST(num1, num2[,nums,...])
```

**Parameters:**

* `num1`: The first number to compare
* `num2`: The second number to compare
* `nums`: (Optional) Additional numbers to compare.

**Returns:** The maximum of the given numbers.

**Examples:**

* `GREATEST(event.properties.memory_mb, 10.0)`

> [card] [Aggregation types](https://getlago.com/docs/v2/guide/billable-metrics/aggregation-types/overview.md)
>
> What happens to the computed values.

> [card] [Ingest usage](https://getlago.com/docs/v2/guide/events/ingesting-usage.md)
>
> Send the properties your expression reads.

> [card] [Create a billable metric (API)](https://getlago.com/docs/v2/api-reference/billable-metrics/create.md)
>
> `POST /billable_metrics`

> [card] [Billable metric object (API)](https://getlago.com/docs/v2/api-reference/billable-metrics/object.md)
>
> The `expression` field.


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