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

# How to build a dynamic row policy with a custom setting

> Filter a table per tenant with a single row policy: the policy reads a custom SQL_ setting with getSetting, and each query, session or user supplies the value.

The condition of a [row policy](https://clickhouse.com/docs/reference/statements/create/row-policy.md) can read a [custom setting](https://clickhouse.com/docs/concepts/features/configuration/settings/settings-query-level.md#custom_settings) with the `getSetting` function. A single policy then filters the table by a value that is supplied with each query, set for a session, or fixed for a user, for example a tenant ID.

## Example

As an administrator, create a table, a role that can read it, a user, and the policy:

```sql theme={null}
CREATE TABLE events
(
    tenant_id String,
    value UInt64
)
ENGINE = MergeTree
ORDER BY tenant_id;

INSERT INTO events VALUES ('tenant_a', 1), ('tenant_a', 2), ('tenant_b', 10), ('tenant_c', 100);

CREATE ROLE tenant_reader;
GRANT SELECT ON events TO tenant_reader;

CREATE USER app_user IDENTIFIED WITH sha256_password BY '<password>';
GRANT tenant_reader TO app_user;

CREATE ROW POLICY tenant_filter ON events
FOR SELECT
USING tenant_id = getSetting('SQL_tenant_id')
TO tenant_reader;
```

Connected as `app_user`, pass the setting with the query:

```sql theme={null}
SELECT * FROM events ORDER BY value SETTINGS SQL_tenant_id = 'tenant_a';
```

```text theme={null}
   ┌─tenant_id─┬─value─┐
1. │ tenant_a  │     1 │
2. │ tenant_a  │     2 │
   └───────────┴───────┘
```

Or set it once for the session:

```sql theme={null}
SET SQL_tenant_id = 'tenant_b';

SELECT * FROM events ORDER BY value;
```

```text theme={null}
   ┌─tenant_id─┬─value─┐
1. │ tenant_b  │    10 │
   └───────────┴───────┘
```

Over the HTTP interface, pass the setting as a URL parameter:

```bash theme={null}
curl 'https://<host>:8443/?SQL_tenant_id=tenant_a' \
    --user 'app_user:<password>' \
    --data-binary 'SELECT * FROM events ORDER BY value'
```

## Missing and unexpected values

A value that matches no tenant returns no rows. If the setting is not set at all, the query fails:

```text theme={null}
Code: 115. DB::Exception: Unknown setting 'SQL_tenant_id': In scope tenant_id = getSetting('SQL_tenant_id'). (UNKNOWN_SETTING)
```

To return an empty result instead of an error, use `getSettingOrDefault` in the policy:

```sql theme={null}
ALTER ROW POLICY tenant_filter ON events
FOR SELECT
USING tenant_id = getSettingOrDefault('SQL_tenant_id', '');
```

A custom setting keeps the type of the value you assign. Give it the type of the column it is compared with: with the `String` column of this example, `SETTINGS SQL_tenant_id = 42` fails with a `NO_COMMON_TYPE` error.

## The prefix of custom settings

The name of a custom setting must start with one of the prefixes listed in the [`custom_settings_prefixes`](https://clickhouse.com/docs/reference/settings/server-settings/settings/custom#custom_settings_prefixes) server setting. The `config.xml` file that ships with ClickHouse sets it to `SQL_`, and in ClickHouse Cloud the prefix is always `SQL_`. On a server without this prefix, `SET SQL_tenant_id = 'tenant_a'` fails with `Unknown setting 'SQL_tenant_id'`.

## Who is allowed to set the value

> [!WARNING]
>
> A user who can run their own SQL can set `SQL_tenant_id` to any value and read the rows of any tenant. The policy protects the data only if the end user cannot choose the value.

There are two ways to make sure of that:

* Let a trusted application set the value. The application connects as `app_user`, adds the tenant of the authenticated end user to every request, and never passes SQL or settings from the end user through.
* Fix the value for a database user with a `CONST` [constraint](https://clickhouse.com/docs/concepts/features/configuration/settings/constraints-on-settings.md):

  ```sql theme={null}
  CREATE USER tenant_a_user IDENTIFIED WITH sha256_password BY '<password>'
  SETTINGS SQL_tenant_id = 'tenant_a' CONST;

  GRANT tenant_reader TO tenant_a_user;
  ```

  This user sees the rows of `tenant_a` without passing the setting, and an attempt to change it is refused:

  ```sql theme={null}
  SET SQL_tenant_id = 'tenant_b';
  ```

  ```text theme={null}
  Code: 452. DB::Exception: Setting SQL_tenant_id should not be changed. (SETTING_CONSTRAINT_VIOLATION)
  ```

The policy applies to sessions in which the `tenant_reader` role is enabled. With the default server configuration, a user who has `SELECT` on the table and to whom no policy applies sees all rows. Grant `SELECT` on the table only through the role that the policy names, or add policies for the other users. See the [`TO` clause](https://clickhouse.com/docs/reference/statements/create/row-policy#to-clause) of `CREATE ROW POLICY`.

## Related documentation

* [Custom settings](https://clickhouse.com/docs/concepts/features/configuration/settings/settings-query-level.md#custom_settings)
* [`getSetting`](https://clickhouse.com/docs/reference/functions/regular-functions/other-functions#getSetting) and [`getSettingOrDefault`](https://clickhouse.com/docs/reference/functions/regular-functions/other-functions#getSettingOrDefault)
* [`CREATE ROW POLICY`](https://clickhouse.com/docs/reference/statements/create/row-policy)
* [Does ClickHouse support row-level and column-level security?](https://clickhouse.com/docs/resources/support-center/knowledge-base/security/row-column-policy.md)
