# Filter rows per tenant with session context


> Pass a tenant or end-user value with each connection or short-lived token, and filter secure views by it with session_context().

Session context is a small set of key/value pairs, such as `tenant=acme`, that travels with a connection to MotherDuck. A [secure view](./secure-views.md) reads it with `session_context('<key>')`, so one Share can return each tenant or end user only their own rows, even when every one of them connects as the same service account.

```sql
SELECT id, tenant_id, amount
FROM orders
WHERE tenant_id = session_context('tenant')
```

Use this when you need to:

- Run SQL from your application on behalf of its end users, through one MotherDuck token, and filter by the end user.
- Embed Dives for many customers from one service account, with each customer seeing only their rows.
- Hand each end user a token that only ever sees that user's rows, without a service account per user.

Without session context, a secure view can only tell consumers apart by their MotherDuck user or role, so per-tenant isolation needs a service account per tenant. You'll know it worked when two connections that use the same token, with different contexts, get different rows from the same query.

You can set a session context and read it with `session_context()` on every plan. Its main use is in secure views, which are available on **Business** and **Enterprise** plans, including free trials.

## How session context works

A connection's session context comes from two sources:

| Source | Who sets it | How | When it changes |
| --- | --- | --- | --- |
| Connection context | The client that opens the connection | `SET motherduck_session_context`, the connection string, `PRAGMA MD_CONNECT`, or Postgres startup options | Never. It's fixed once the client connects |
| Token context | Whoever mints a short-lived token | A Dive embed session, or the [token API](#step-3-mint-a-token-with-a-context) | Never. It's fixed when the token is minted. To change it, mint a new token |

`session_context('<key>')` reads one map that merges both sources:

- **The token wins.** When the token and the connection set the same key, `session_context()` returns the token's value. A key only the connection sets returns the connection's value.
- **The token can lock a key.** A token that sets a key to `''` (an empty string) keeps the connection from setting it: `session_context()` returns `''`. See [Protect keys the token doesn't set](#protect-keys-the-token-doesnt-set).

- **A missing key is `NULL`.** A filter such as `tenant_id = session_context('tenant')` then matches no rows, so a connection without a context sees nothing rather than everything.
- **The context is the consumer's.** A secure view is evaluated for each query with the context of the connection that runs it, never the Share owner's.
- **Keys ignore case.** `session_context('Tenant')` and `session_context('tenant')` read the same key.

## Before you start

- You can create secure views. See [Before you start](./secure-views.md#before-you-start) on the secure views page.
- The table you share has a column to filter by, such as `tenant_id`.
- Each client that sets a connection context runs DuckDB 1.5.6 or later with an up-to-date MotherDuck extension. Older clients send no context, so `session_context()` returns `NULL` for every key and the secure view returns no rows.

## Step 1: Filter a secure view by session context

Create a Share whose secure view compares a column with `session_context()`, then grant it to the account your application connects as:

```sql
CREATE SHARE orders_share FROM acme_saas (ACCESS RESTRICTED)
WITH SECURE VIEW REPLACES orders AS (
    SELECT id, tenant_id, region, amount, order_date
    FROM orders
    WHERE tenant_id = session_context('tenant')
);

GRANT READ ON SHARE orders_share TO app_service_account;
```

`session_context()` returns a `VARCHAR`. To compare it with a column of another type, cast it, for example `customer_id = session_context('customer_id')::INTEGER`.

You can also enter the same filter in the UI editor's **Only rows matching** box. The editor's preview has no session context, so `session_context()` returns `NULL` there and the preview shows no rows.

## Step 2: Set the connection context

Set the context before the client connects to MotherDuck. Once connected, the context can't be changed or cleared, and detaching and re-attaching keeps it.

### SQL

`SET` takes one JSON object whose values are strings. On a new DuckDB instance, load the MotherDuck extension first, because DuckDB loads it automatically for `ATTACH 'md:'` but not for `SET`:

```sql
LOAD motherduck;
SET motherduck_session_context = '{"tenant": "acme", "region": "eu"}';
ATTACH 'md:';
```

To set the context and connect in one statement, pass `session_context.<key>=<value>` pairs to `PRAGMA MD_CONNECT`. It needs the extension loaded first too:

```sql
LOAD motherduck;
PRAGMA MD_CONNECT('session_context.tenant=acme&session_context.region=eu');
```

### Connection string

Add one `session_context.<key>=<value>` pair per key to the `md:` connection string you open DuckDB with:

```bash
duckdb 'md:?session_context.tenant=acme&session_context.region=eu'
```

To pass the whole object at once, use `session_context=<json>` instead. One connection string can't carry both forms.

`ATTACH 'md:?...'` doesn't read connection string parameters, so pass the pairs when you open DuckDB or with `PRAGMA MD_CONNECT`.

### Python

```python
import duckdb

con = duckdb.connect("md:?session_context.tenant=acme&session_context.region=eu")
print(con.execute("SELECT session_context('tenant')").fetchone())  # ('acme',)
```

For values a connection string can't carry, use `SET` on a new in-memory instance, as in [Run SQL for your end users from an application](#run-sql-for-your-end-users-from-an-application).

### Postgres endpoint

Through the [Postgres endpoint](/key-tasks/authenticating-and-connecting-to-motherduck/postgres-endpoint/), pass the pairs as startup options:

```bash
PGOPTIONS="-c session_context.tenant=acme -c session_context.region=eu" \
  psql "postgresql://postgres:$MOTHERDUCK_TOKEN@pg.us-east-1-aws.motherduck.com:5432/<database_name>"
```

`options='-c session_context={"tenant":"acme"}'` passes the whole object instead.

In a connection string, values are taken literally and can't contain `&` or `#`. To pass any other value, use `SET` with a JSON object.

Each DuckDB instance has one connection context. To give different end users different contexts, open a separate DuckDB instance for each of them; see [Run SQL for your end users from an application](#run-sql-for-your-end-users-from-an-application).

### Name the session

The key `name` is the connection's [session name](/key-tasks/authenticating-and-connecting-to-motherduck/connecting-to-motherduck/#session-names), so a context can name the session next to the values your policies read:

```sql
SET motherduck_session_context = '{"tenant": "acme", "name": "acme"}';
```

- **It routes read scaling connections.** Connections with the same `name` reach the same read scaling Duckling, as with [`session_name`](/key-tasks/authenticating-and-connecting-to-motherduck/read-scaling/#session-affinity-with-session-name).
- **It's the `SESSION_NAME` in [query history](/sql-reference/motherduck-sql-reference/md_information_schema/query_history/)** for the connection's queries.
- **A policy can read it** with `session_context('name')`.

The value is 1 to 64 characters of letters, digits, `.`, `_`, and `-`, and starts with a letter or digit.

When more than one source names the session, the stronger one wins:

| Strength | Where it's set | Who sets it |
| --- | --- | --- |
| 1 (weakest) | `session_name` on the connection or the embed session | The client or your backend |
| 2 | `name` in the connection context | The client |
| 3 (strongest) | `name` in the [token context](#name-the-tokens-session) | Whoever minted the token |

Without any of them, the client generates a session name. `session_context('name')` returns the token's `name`, or else the connection's, and never `session_name`: it's `NULL` when neither context sets `name`.

## Step 3: Mint a token with a context

A token context comes with every connection that uses the token, so the token's holder doesn't need to set anything, and can't change the keys it sets. Only short-lived, read scaling tokens carry a context. Mint one in either of two ways.

**For an embedded Dive:** pass `context` when your backend creates the embed session. See [Pass a session context](/key-tasks/dives/embedding-dives/#pass-a-session-context).

**For any other client:** call [`POST /v1/tokens/short-lived`](/sql-reference/rest-api/tokens-create-short-lived/) with a token of the account the end user should connect as, such as a service account:

```bash
curl -X POST https://api.motherduck.com/v1/tokens/short-lived \
  -H "Authorization: Bearer <service_account_token>" \
  -H "Content-Type: application/json" \
  -d '{"token_type": "read_scaling", "context": {"tenant": "acme"}}'
```

The response contains the new token and when it expires:

```json
{"token": "<short_lived_token>", "expire_at": "<timestamp>"}
```

- **`token_type` is required,** and `read_scaling` is the only value it accepts.
- **The token works like an access token.** Use it as `motherduck_token` or as the Postgres endpoint password. A client that exchanges it for its own short-lived token keeps the context.
- **It lasts 24 hours.** When the token you call the API with is an access token, the new token expires no later than that access token, and revoking the access token revokes it too.
- **It mints for the caller only,** so it takes no username. A read scaling token can't call it, so a minted token can't mint another one.

### Name the token's session

A token context can set `name` too. The token's name wins over a [name in the connection context](#name-the-session) and over `session_name`, so whoever mints the token decides which read scaling Duckling serves it:

```json
{"tenant": "acme", "name": "acme"}
```

The same rule applies to the value. On an embed session, the name also replaces the embed session's `session_name`.

A token without a `name` leaves the key to the connection, and a token can't lock `name` with `''`. If a policy reads `session_context('name')`, set a `name` on every token.

## Verify the context

Read the context back from the connection that set it:

```sql
SELECT session_context('tenant'), session_context('region'), session_context('missing');
```

| session_context('tenant') | session_context('region') | session_context('missing') |
| --- | --- | --- |
| acme | eu | NULL |

`current_setting('motherduck_session_context')` shows the connection context as the client sends it, with lowercased keys, such as `{"region":"eu","tenant":"acme"}`. It doesn't include the token context.

A client in [SaaS mode](/key-tasks/authenticating-and-connecting-to-motherduck/authenticating-to-motherduck/#authentication-using-saas-mode) can't call `session_context()` directly: the query fails with a permission error. Secure views still read the context, so check it through the secure view.

Then attach the Share and query the secure view. A connection with `tenant=acme` gets only Acme's rows, and a connection without a context gets none:

```sql
ATTACH 'md:_share/orders_share/<share_token>' AS orders_check;

SELECT tenant_id, count(*) FROM orders_check.orders GROUP BY tenant_id;
```

| tenant_id | count_star() |
| --- | --- |
| acme | 2 |

## Examples

### Embed Dives for many tenants from one service account

Your backend creates every embed session for the same target service account and passes the viewer's tenant as the embed session's context. The Dive's SQL is the same for every tenant, and the secure view does the filtering.

1. Grant the Share from [Step 1](#step-1-filter-a-secure-view-by-session-context) to the target service account, here `embed_sa`, and have the Dive read the Share's `orders` table.
2. When a viewer opens the page, look up their tenant in your application and create the embed session with it:

   ```javascript
   const response = await fetch(
     `https://api.motherduck.com/v1/dives/${DIVE_ID}/embed-session`,
     {
       method: "POST",
       headers: {
         Authorization: `Bearer ${MOTHERDUCK_TOKEN}`,
         "Content-Type": "application/json",
       },
       body: JSON.stringify({
         username: "embed_sa",
         // From your own authentication, never from the browser.
         context: { tenant: viewer.tenantId },
       }),
     }
   );
   ```

Each viewer sees only their tenant's orders, from one Dive and one service account. The context is stored on the embed session's token, so a viewer can't change it from the browser.

### Give each end user a token for their own rows

An application that lets end users query MotherDuck directly, without a Dive, mints a token for each of them with [`POST /v1/tokens/short-lived`](#step-3-mint-a-token-with-a-context), calling it with the service account's token. Each token carries that user's tenant, and the end user's client connects with it like any read scaling token. The end user never sees the service account's token, and can't change the tenant their token carries.

### Run SQL for your end users from an application

A trusted application holds the token, opens one DuckDB instance for each end user, sets that user's identity as the connection context, and only then runs the user's SQL. The end user never sees the token or the DuckDB configuration.

```sql
CREATE SHARE reports_share FROM acme_crm (ACCESS RESTRICTED)
WITH SECURE VIEW REPLACES accounts AS (
    SELECT id, name, account_owner, arr
    FROM accounts
    WHERE account_owner = session_context('user')
);

GRANT READ ON SHARE reports_share TO app_service_account;
```

```python
import json
import duckdb

def connect_for(end_user_email: str) -> duckdb.DuckDBPyConnection:
    # A new in-memory DuckDB instance per end user. The token comes from the
    # motherduck_token environment variable, which only the application can read.
    con = duckdb.connect()
    con.execute("LOAD motherduck")
    context = json.dumps({"user": end_user_email}).replace("'", "''")
    con.execute(f"SET motherduck_session_context = '{context}'")
    con.execute("ATTACH 'md:'")
    return con

con = connect_for("maria@example.com")
rows = con.execute("SELECT * FROM reports_share.accounts").fetchall()
```

Each connection sees only the accounts its end user owns. Because the context is fixed once connected, an end user who runs `SET motherduck_session_context` gets an error instead of someone else's rows.

### Combine an application's context with a tenant's token

Both sources merge into one map, so a policy can read keys from each. Here each tenant's token carries `{"tenant": "acme"}`, and the application adds the end user's region to each connection:

```sql
ALTER SHARE orders_share
    ADD OR REPLACE SECURE VIEW REPLACES orders AS (
        SELECT id, tenant_id, region, amount, order_date
        FROM orders
        WHERE tenant_id = session_context('tenant')   -- from the token
          AND region = session_context('region')      -- from the connection
    );
```

If the connection also sets `tenant`, the token's `acme` still wins.

### Protect keys the token doesn't set

A key the token doesn't set falls back to the connection, and whoever holds the token can set the connection context. So a policy is only as safe as the keys every token used with it sets.

For example, the secure view in [Step 1](#step-1-filter-a-secure-view-by-session-context) filters on `tenant`. A token minted without a `tenant` key lets its holder connect with `session_context.tenant=globex` and read that tenant's orders.

To prevent this, set every key your policies read on every token you mint. For a key the token shouldn't grant, set it to `''`:

```json
{"tenant": "", "region": "eu"}
```

The token's `''` wins over any connection value, so `session_context('tenant')` returns `''`, `tenant_id = ''` matches no rows, and the holder can't name a tenant. To treat a locked key exactly like a missing one, read it with `nullif(session_context('tenant'), '')`.

### Match one of several values

Values are strings, so pass a list as a string and cast it to `VARCHAR[]`. DuckDB casts both `'[eu, us]'` and `'["eu", "us"]'`:

```sql
SET motherduck_session_context = '{"regions": "[eu, us]"}';
```

```sql
ALTER SHARE orders_share
    ADD OR REPLACE SECURE VIEW REPLACES orders AS (
        SELECT id, tenant_id, region, amount, order_date
        FROM orders
        WHERE list_contains(session_context('regions')::VARCHAR[], region)
    );
```

### Hide whole tables by context

Session context filters rows, not tables: every connection sees the same tables in the catalog. To make a table return nothing to some connections, check the table's own name against a list in the context, in that table's secure view:

```sql
ALTER SHARE orders_share
    ADD OR REPLACE SECURE VIEW REPLACES customers AS (
        SELECT id, name, tenant_id
        FROM customers
        WHERE list_contains(session_context('allowed_tables')::VARCHAR[], 'customers')
          AND tenant_id = session_context('tenant')
    );
```

The table stays visible to every connection, and a secure view without the check isn't protected by it.

## Trust model

A secure view trusts whoever sets the context it reads. Choose the source by who holds the token:

- **Connection context trusts whoever holds the token and can open a connection.** Anyone with the token can connect with any connection context they like. It's safe only when a trusted application holds the token, and end users never see the token or the DuckDB configuration. If end users can run their own DuckDB, Postgres client, or BI tool with the token, treat the connection context as their input.
- **Token context trusts whoever minted the token.** The holder can't change the keys it sets, which makes it the source to use when you hand a token to an end user or an embedded Dive's viewers. [Protect](#protect-keys-the-token-doesnt-set) every other key your policies read.

## Keys, values, and limits

- Keys contain only lowercase letters, digits, `_`, and `.`. MotherDuck lowercases keys when you set them and when you read them, and refuses two keys that differ only in case.
- `name` is the session name. See [Name the session](#name-the-session).
- Values are strings. They must be valid UTF-8 and can't contain a NUL character.
- Each source holds at most 64 keys and 4 KiB of keys and values together. The merged map is therefore bounded at 128 keys and 8 KiB.
- `session_context()` returns the same value for every row of a query, so a filter such as `tenant_id = session_context('tenant')` is pushed down into the table scan like a filter on a constant.

## Limitations

- **A token with a context is a read scaling token.** The [read scaling restrictions](/key-tasks/authenticating-and-connecting-to-motherduck/read-scaling/#permissions) apply: it reads data, and it can't write or run administrative operations.
- **A token's context is fixed.** To change it, mint a new token. An embed session's context can't be revoked: a client that renews the session's token gets a new token with the same context.
- **The context is fixed per connection.** To change it, open a new DuckDB instance.
- **Query plans don't use per-tenant row counts.** All connections to a Duckling share table statistics, so MotherDuck estimates the size of a secure view that reads `session_context()` the same way for every connection. Results are correct for each tenant, but a plan may suit some tenants better than others.

## Troubleshooting

| Error or symptom | Cause and fix |
| --- | --- |
| The secure view returns no rows | `session_context()` returns `NULL` for the key. Check it with `SELECT session_context('<key>')` on the same connection. If it's `NULL`, set the context before connecting, check the key's spelling, and confirm the client runs DuckDB 1.5.6 or later with an up-to-date MotherDuck extension |
| `... can only be set during initialization` | The client set `motherduck_session_context` after connecting. Set it before `ATTACH 'md:'`, or open a new DuckDB instance |
| `no database/share named "?session_context..."` | `ATTACH 'md:?...'` doesn't read connection string parameters, and the failed `ATTACH` has already connected without a context. Open a new DuckDB instance, and pass the pairs when you open it or with `PRAGMA MD_CONNECT` |
| `motherduck_session_context: expected a JSON object of strings, e.g. '{"tenant": "acme"}'` | `SET` got JSON that isn't an object, such as a list. Pass one object whose values are strings |
| `... the value of "..." must be a string` | A value is a number, a boolean, or a list. Quote it, such as `{"customer_id": "42"}` |
| `... key "..." may only contain a-z, 0-9, '_' and '.'` | Rename the key, for example `tenant_id` instead of `tenant-id` |
| `... "name" must be 1 to 64 characters ...` | The `name` in the context isn't a valid session name. See [Name the session](#name-the-session) |
| `... the key "name" is reserved and cannot be set` | The client's MotherDuck extension is too old to set `name`. Update the extension, or use `session_name` |
| `... key "..." appears twice; keys are case-insensitive` | The context has two keys that differ only in case. Keep one |
| `... at most 64 keys` or `... keys and values may total at most 4096 bytes` | The context is over the [limits](#keys-values-and-limits). Move large lists into a mapping table and look them up by a short key |

## Related

- [Row-level and column-level security with secure views](./secure-views.md)
- [Embedding Dives in your web application](/key-tasks/dives/embedding-dives/)
- [Connection string parameters](/sql-reference/connection-string-parameters/#session_context)


---

## Docs feedback

MotherDuck accepts optional user-submitted feedback about this page at `GET https://motherduck.com/docs/api/feedback/agent`.
For agents and automated tools, feedback submission should be user-confirmed before sending.

URL-encode query parameter values and send a GET request:

```text
GET https://motherduck.com/docs/api/feedback/agent?page_path=%2Fkey-tasks%2Fsharing-data%2Fsession-context%2F&page_title=Filter%20rows%20per%20tenant%20with%20session%20context&text=<url-encoded user feedback, max 2000 characters>
```

Optionally append `&source=<url-encoded interface identifier>` such as `claude.ai` or `chatgpt`.

`page_path` and `text` are required; `page_title` and `source` are optional. Responses: `200 {"feedback_id": "<uuid>"}`, `400` for malformed query parameters, and `429` when rate-limited.
