Files
posthog.com/contents/docs/data-warehouse/sql/variables.mdx
Ian Vanagas d6485a8ed3 Docs: Fix dashboard filters SQL variables (#13462)
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2025-10-31 08:47:28 +00:00

61 lines
2.7 KiB
Plaintext

---
title: SQL variables
sidebar: Docs
showTitle: true
availability:
free: full
selfServe: full
enterprise: full
---
SQL variables enable you to dynamically set values in your queries.
## Creating SQL variables
To create a variable, go to the [SQL editor](https://app.posthog.com/sql), click the **Variables** tab, click **Add variable**, and choose your variable type (string, number, date, list, or boolean). Enter the variable name and value(s) and click **Save** and you'll be able to use it in any of your project's queries.
For example, you can create a list type variable with the key `event_names` and add events like `$pageview` and `$autocapture` as values.
<ProductScreenshot
imageLight="https://res.cloudinary.com/dmukukwp6/image/upload/q_auto,f_auto/Clean_Shot_2025_10_02_at_17_04_16_2x_aac766c379.png"
imageDark="https://res.cloudinary.com/dmukukwp6/image/upload/q_auto,f_auto/Clean_Shot_2025_10_02_at_17_04_41_2x_aaefee30c4.png"
alt="Creating a variable"
classes="rounded"
/>
## Using variables in SQL queries
Once created, variables can be used in queries with the `{variables.<variable-name>}` syntax like this:
```sql
select *
from events
where event = {variables.event_names}
```
You can set the value for the variable in the same **Variables** tab, on the insight, or on the dashboard once you've created and added an SQL insight to it. For example, below we set the "event names" variable to `$autocapture` on the dashboard. This means every instance of `{variables.event_names}` in the queries on the dashboard is replaced with `$autocapture`.
<ProductScreenshot
imageLight="https://res.cloudinary.com/dmukukwp6/image/upload/w_1600,c_limit,q_auto,f_auto/Clean_Shot_2025_10_02_at_17_12_45_2x_0e6a9a873a.png"
imageDark="https://res.cloudinary.com/dmukukwp6/image/upload/w_1600,c_limit,q_auto,f_auto/Clean_Shot_2025_10_02_at_17_12_27_2x_b5f9fcff28.png"
alt="Using a variable in a SQL query"
classes="rounded"
/>
## Dashboard date range filter variables
Beyond the SQL variables you set up, you can access the dashboard's date range filters through the `filters.dateRange.from` and `filters.dateRange.to` variables like this:
```sql
select *
from events
where event = {variables.event_names}
and timestamp >= {filters.dateRange.from} and timestamp < {filters.dateRange.to}
```
<ProductScreenshot
imageLight="https://res.cloudinary.com/dmukukwp6/image/upload/w_1600,c_limit,q_auto,f_auto/Clean_Shot_2025_10_02_at_17_16_57_2x_161c9b6f38.png"
imageDark="https://res.cloudinary.com/dmukukwp6/image/upload/w_1600,c_limit,q_auto,f_auto/Clean_Shot_2025_10_02_at_17_17_11_2x_a670c7930a.png"
alt="Using dashboard filter variables in a SQL query"
classes="rounded"
/>