---
title: Query tags
description: Apply custom key-value query tags to SQL workloads for grouping, filtering, and cost attribution on Databricks SQL warehouses, Lakehouse//RT compute, and serverless compute for notebooks and jobs.
canonical_url: https://docs.databricks.com/aws/en/sql/user/queries/query-tags
---

# Query tags

Query tags are custom key-value pairs you apply to SQL workloads so you can group, filter, and track costs on Databricks SQL warehouses, [Lakehouse Real-Time](https://docs.databricks.com/aws/en/compute/sql-warehouse/real-time.md) (Lakehouse//RT) compute, and serverless compute for [notebooks](https://docs.databricks.com/aws/en/compute/serverless/notebooks.md) and [jobs](https://docs.databricks.com/aws/en/jobs/run-serverless-jobs.md).

Use them to group queries by business context, track compute costs, and identify sources of long-running queries.

Tags appear in the `system.query.history` table and on the **Query History** page of the Databricks UI. The [ListQueries API](https://docs.databricks.com/api/workspace/queryhistory/list) also returns tags when they are present. For example, you might tag queries with `team:marketing` to track marketing workload costs, or filter on the automatically applied `@@dbt_model_name` tag to identify queries generated by a specific dbt model.

> [!WARNING]
>
> Tag data is stored as plain text and might be replicated globally. Do not include passwords, personally identifiable information, or other sensitive data in tag keys or values.

## <a id="requirements" />Requirements

To use query tags, you must have the following:

* You must have access to the `query_tags` column in the `system.query.history` table. If you don't have access, contact your account admin. See [Query history system table reference](https://docs.databricks.com/aws/en/admin/system-tables/query-history.md).

* Your connector or driver must meet a minimum version requirement. See the specific tool or connector section in [Set query tags from tools and connectors](https://docs.databricks.com/aws/en/sql/user/queries/query-tags.md#tools) for version details.

* **Databricks SDK for Python**: Minimum version 0.86.0 for query tag support.

## <a id="how-tags-work" />How query tags work

Query tags are scoped to [Databricks SQL sessions](https://docs.databricks.com/aws/en/sql/user/queries/sessions.md). You can set them at session level or statement level:

* **Session-level tags** apply to all subsequent statements in the session. Set them when creating a session using a configuration parameter, or within a session using the `SET QUERY_TAGS` SQL statement.
* **Statement-level tags** apply to a single statement only. Subsequent statements revert to the session-level tags. Statement-level tags are available in the Python Connector (v4.2.6 or above), Node.js Connector (v1.12.0 or above), Go Connector (v1.9.0 or above), and the Statement Execution API.

### <a id="session-config" />Session configuration parameter syntax

Several tools and connectors accept query tags as a session configuration parameter called `query_tags` (or `ssp_query_tags` for Simba-based drivers). The value is a serialized string of key-value pairs, with a colon (`:`) separating keys and values and a comma (`,`) separating pairs.

If a key or value contains a colon (`:`), comma (`,`), or backslash (`\`), escape it with a leading backslash.

The following example specifies tags `team:eng`, `cost_center:701`, a key-only tag `exp`, and a `metadata` tag with a JSON value.

Unescaped intent:

```text
team:eng, cost_center:701, exp, metadata:{"foo":"bar","baz":1}
```

Escaped configuration string:

```text
query_tags = team:eng,cost_center:701,exp,metadata:{"foo"\\:"bar"\\,"baz"\\:1}
```

### <a id="sql-statements" />SQL statements

Use the `SET QUERY_TAGS` statement to set, read, or remove query tags for the current session. You can use this statement anywhere you can submit SQL to a warehouse, including the SQL editor, notebooks, and dashboards. You can also use it in notebooks and jobs that run on serverless compute. See [Serverless notebooks and jobs](https://docs.databricks.com/aws/en/sql/user/queries/query-tags.md#serverless).

For syntax, parameters, and examples, see [SET QUERY\_TAGS](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-aux-conf-mgmt-set-query-tags.md).

## <a id="tools" />Set query tags from tools and connectors

The following sections describe how to set query tags from each supported tool, connector, and driver.

> [!NOTE]
>
> The connectors and drivers in this section describe setup for Databricks SQL warehouses. For the connection methods supported on [Lakehouse Real-Time](https://docs.databricks.com/aws/en/compute/sql-warehouse/real-time.md) (Lakehouse//RT), see [Connectivity](https://docs.databricks.com/aws/en/compute/sql-warehouse/real-time.md#connectivity).

### <a id="serverless" />Serverless notebooks and jobs

To tag queries that run on serverless compute for [notebooks](https://docs.databricks.com/aws/en/compute/serverless/notebooks.md) and [jobs](https://docs.databricks.com/aws/en/jobs/run-serverless-jobs.md), run the `SET QUERY_TAGS` statement before the queries you want to tag. Tags apply to all subsequent statements in the session until you change or unset them.

```sql
SET QUERY_TAGS['team'] = 'marketing', QUERY_TAGS['cost_center'] = '701';

SELECT * FROM samples.nyctaxi.trips LIMIT 10;
```

In the `system.query.history` table, these queries have a `compute.type` value of `SERVERLESS_COMPUTE`. See [Query history system table reference](https://docs.databricks.com/aws/en/admin/system-tables/query-history.md).

### <a id="sea" />Databricks SQL Statement Execution API (SEA)

Include the `query_tags` field in the request body of [POST /api/2.0/sql/statements](https://docs.databricks.com/api/workspace/statementexecution/executestatement) to apply statement-level tags. Tags set this way apply only to that statement execution.

```bash
curl -X POST "https://${DATABRICKS_HOST}/api/2.0/sql/statements" \
  -H "Authorization: Bearer ${DATABRICKS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "warehouse_id": "abc123",
    "statement": "SELECT * FROM samples.nyctaxi.trips LIMIT 10",
    "query_tags": [
        { "key": "team", "value": "engineering" },
        { "key": "env", "value": "prod" }
      ]
  }'
```

### <a id="dbt" />dbt

Minimum version: dbt-databricks 1.11.0

The following reserved query tag keys are set automatically for all dbt runs and can't be overridden:

```json
{
  "@@dbt_model_name": "my_model",
  "@@dbt_core_version": "1.10.7",
  "@@dbt_databricks_version": "1.11.0",
  "@@dbt_materialized": "incremental"
}
```

> [!NOTE]
>
> Default tags are subject to syntax limitations. Model names that include unescaped colons or commas result in `tag_invalid: true` in the system table.

You can add custom query tags at both project and model levels. Model configuration takes priority over connection configuration.

#### Project-level tag

File: `~/.dbt/profiles.yml`

```yaml
your_profile_name:
  target: dev
  outputs:
    dev:
      query_tags: '{"team": "marketing", "cost_center": "3000"}'
```

#### Model-level tag

File: `~/.dbt/dbt_project.yml`

```yaml
name: 'your_project'
version: '1.0.0'
config-version: 2
models:
  your_model:
    +query_tags: '{"team": "content-marketing"}'
```

#### Result with both configurations

When both project-level and model-level tags are set, the tags are merged. Model-level values override project-level values for the same key.

```json
  "team": "content-marketing",
  "cost_center": "3000",
  "@@dbt_model_name": "model.dev.your_model",
  "@@dbt_core_version": "1.10.7",
  "@@dbt_databricks_version": "1.11.0",
  "@@dbt_materialized": "incremental"
}
```

### <a id="power-bi" />Power BI

Minimum version: October 2025 release

1. Configure the connection to the warehouse.
2. Go to the Databricks settings dialog.
   ![Databricks settings dialog in Power BI.](https://docs.databricks.com/aws/en/images/sql/query-tag-powerBI.png)
3. In the **Query tags** text box, enter query tags using the [session configuration parameter syntax](https://docs.databricks.com/aws/en/sql/user/queries/query-tags.md#session-config).
4. Click **OK**.

> [!NOTE]
>
> Changing query tags and clicking **OK** starts a new session. Previously set tags are discarded.

#### <a id="auto-query-tags" />Auto query tags

Auto query tags automatically attach Power BI context metadata to queries sent to Databricks warehouses. As of the July 2026 Power BI service release, auto query tags are enabled automatically—no configuration is required to turn them on. Auto query tags are only available when using the [Arrow Database Connectivity (ADBC)](https://docs.databricks.com/aws/en/partners/bi/power-bi/adbc.md) driver. They are not supported with the ODBC driver, and they are not available when Power BI connects through the on-premises data gateway (the Power BI gateway).

Power BI automatically attaches the following reserved tags (prefixed with `@@`) to queries. The tags available depend on the Power BI connection mode:

| Tag key                        | DirectQuery | Import |
| ------------------------------ | ----------- | ------ |
| `@@powerbi_activity_id`        | Yes         | Yes    |
| `@@powerbi_customer_tenant_id` | Yes         | Yes    |
| `@@powerbi_workspace_id`       | Yes         | Yes    |
| `@@powerbi_dataset_id`         | Yes         | No     |
| `@@powerbi_report_id`          | Yes         | No     |
| `@@powerbi_visual_id`          | Yes         | No     |

> [!NOTE]
>
> Auto query tags are not attached to metadata queries (such as catalog or schema discovery queries) in any mode.

#### <a id="disable-auto-query-tags" />Turn off auto query tags

Auto query tags are on by default. To turn them off, modify the M query in the Power Query Editor to include `EnableAutoQueryTags="false"` in the connector call options.

```powerquery
let
    Source = DatabricksMultiCloud.Catalogs(
        "myworkspace.cloud.databricks.com",
        "/sql/1.0/warehouses/abc123",
        # highlight-next-line
        [Catalog=null, Database=null, EnableAutoQueryTags="false",
         EnableAutomaticProxyDiscovery=null, Implementation="2.0"]),
    samples_Database = Source{[Name="samples",Kind="Database"]}[Data],
    nyctaxi_Schema = samples_Database{[Name="nyctaxi",Kind="Schema"]}[Data],
    trips_Table = nyctaxi_Schema{[Name="trips",Kind="Table"]}[Data]
in
    trips_Table
```

### <a id="tableau" />Tableau

Set query tags in Tableau using the Initial SQL feature.

1. Configure the connection to the warehouse.
2. Navigate to the **Initial SQL** tab.
3. Enter query tags using the [SET QUERY\_TAGS](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-aux-conf-mgmt-set-query-tags.md). You can include Tableau parameters in the key or value.
4. Click **Sign In** to save and authenticate.

> [!NOTE]
>
> Changing the Initial SQL and clicking **Sign In** starts a new session. Previously set tags are discarded.

### <a id="python" />Python Connector

Minimum version: v4.1.3 (session-level), v4.2.6 (statement-level)

#### Session-level tags

Pass the `query_tags` parameter when creating a connection. All statements in the session inherit these tags.

```python
from databricks import sql
import os

with sql.connect(
    server_hostname = os.getenv("DATABRICKS_SERVER_HOSTNAME"),
    http_path       = os.getenv("DATABRICKS_HTTP_PATH"),
    access_token    = os.getenv("DATABRICKS_TOKEN"),
    query_tags = {"team": "engineering", "dashboard": "abc123"}
) as connection:
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM samples.nyctaxi.trips LIMIT 10")
        result = cursor.fetchall()
```

#### Statement-level tags

Pass `query_tags` to `cursor.execute()` to tag a single statement. Subsequent statements revert to the session-level tags.

```python
from databricks import sql
import os

with sql.connect(
    server_hostname = os.getenv("DATABRICKS_SERVER_HOSTNAME"),
    http_path       = os.getenv("DATABRICKS_HTTP_PATH"),
    access_token    = os.getenv("DATABRICKS_TOKEN"),
) as connection:
    with connection.cursor() as cursor:
        cursor.execute(
            "SELECT * FROM samples.nyctaxi.trips LIMIT 10",
            query_tags={"team": "engineering", "dashboard": "abc123"}
        )
        result = cursor.fetchall()
```

### <a id="nodejs" />Node.js Connector

Minimum version: v1.12.0

#### Session-level tags

Pass `queryTags` when opening a session. All statements in the session inherit these tags.

```javascript
const { DBSQLClient } = require('@databricks/sql');
const client = new DBSQLClient();

client
  .connect({
    host: process.env.DATABRICKS_SERVER_HOSTNAME,
    path: process.env.DATABRICKS_HTTP_PATH,
    token: process.env.DATABRICKS_TOKEN,
  })
  .then(async (client) => {
    const session = await client.openSession({
      queryTags: {
        team: 'engineering',
        env: 'prod',
      },
    });

    const queryOperation = await session.executeStatement('SELECT * FROM samples.nyctaxi.trips LIMIT 10');
    const result = await queryOperation.fetchAll();

    await queryOperation.close();
    await session.close();
    await client.close();
  })
  .catch((error) => {
    console.error(error);
  });
```

#### Statement-level tags

Pass `queryTags` to `executeStatement()` to tag a single statement. Subsequent statements revert to the session-level tags.

```javascript
const { DBSQLClient } = require('@databricks/sql');
const client = new DBSQLClient();

client
  .connect({
    host: process.env.DATABRICKS_SERVER_HOSTNAME,
    path: process.env.DATABRICKS_HTTP_PATH,
    token: process.env.DATABRICKS_TOKEN,
  })
  .then(async (client) => {
    const session = await client.openSession();

    const queryOperation = await session.executeStatement('SELECT * FROM samples.nyctaxi.trips LIMIT 10', {
      queryTags: {
        team: 'engineering',
        request_id: 'abc-123',
      },
    });
    const result = await queryOperation.fetchAll();

    await queryOperation.close();
    await session.close();
    await client.close();
  })
  .catch((error) => {
    console.error(error);
  });
```

### <a id="go" />Go Connector

Minimum version: v1.9.0

#### DSN connection string

Include `query_tags` as a query parameter in the DSN string.

```go
package main
    "database/sql"
    "fmt"
    _ "github.com/databricks/databricks-sql-go"
)

func main() {
    dsn := "token:dapi1234@myworkspace.cloud.databricks.com:443/sql/1.0/endpoints/abc123?query_tags=team:engineering,env:prod"

    db, err := sql.Open("databricks", dsn)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    rows, err := db.Query("SELECT * FROM samples.nyctaxi.trips LIMIT 10")
    if err != nil {
        panic(err)
    }
    defer rows.Close()
}
```

#### NewConnector with WithQueryTags

Use `WithQueryTags` to set session-level tags from a map. The connector handles serialization automatically.

```go
package main

import (
    "database/sql"
    "os"
    dbsql "github.com/databricks/databricks-sql-go"
)

func main() {
    connector, err := dbsql.NewConnector(
        dbsql.WithAccessToken(os.Getenv("DATABRICKS_ACCESS_TOKEN")),
        dbsql.WithServerHostname(os.Getenv("DATABRICKS_HOST")),
        dbsql.WithPort(443),
        dbsql.WithHTTPPath(os.Getenv("DATABRICKS_HTTP_PATH")),
        dbsql.WithQueryTags(map[string]string{
            "team": "engineering",
            "env":  "prod",
        }),
    )
    if err != nil {
        panic(err)
    }

    db := sql.OpenDB(connector)
    defer db.Close()

    rows, err := db.Query("SELECT * FROM samples.nyctaxi.trips LIMIT 10")
    if err != nil {
        panic(err)
    }
    defer rows.Close()
}
```

#### Statement-level tags

Use `driverctx.NewContextWithQueryTags` to attach tags to a single statement. Pass the resulting context to `QueryContext` or `ExecContext`.

```go
package main

import (
    "context"
    "database/sql"
    "os"
    dbsql "github.com/databricks/databricks-sql-go"
    "github.com/databricks/databricks-sql-go/driverctx"
)

func main() {
    connector, err := dbsql.NewConnector(
        dbsql.WithAccessToken(os.Getenv("DATABRICKS_ACCESS_TOKEN")),
        dbsql.WithServerHostname(os.Getenv("DATABRICKS_HOST")),
        dbsql.WithPort(443),
        dbsql.WithHTTPPath(os.Getenv("DATABRICKS_HTTP_PATH")),
    )
    if err != nil {
        panic(err)
    }

    db := sql.OpenDB(connector)
    defer db.Close()

    ctx := driverctx.NewContextWithQueryTags(context.Background(), map[string]string{
        "team":        "data-eng",
        "application": "etl-pipeline",
    })

    rows, err := db.QueryContext(ctx, "SELECT * FROM samples.nyctaxi.trips LIMIT 10")
    if err != nil {
        panic(err)
    }
    defer rows.Close()
}
```

### <a id="jdbc-oss" />JDBC driver (OSS)

Minimum version: v3.0.3

#### Connection URL

Include `query_tags` directly in the JDBC connection URL string.

```java
String url = "jdbc:databricks://myworkspace.cloud.databricks.com:443/default;" +
             "httpPath=/sql/1.0/endpoints/abc123;" +
             "query_tags=team:engineering,env:prod;" +
             "AuthMech=3;UID=token;PWD=dapi1234";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM samples.nyctaxi.trips LIMIT 10");
```

#### Properties object

You can also set `query_tags` using a `Properties` object.

```java
String url = "jdbc:databricks://myworkspace.cloud.databricks.com:443/default";
Properties properties = new Properties();
properties.put("httpPath", "/sql/1.0/endpoints/abc123");
properties.put("query_tags", "team:engineering,env:prod");
properties.put("UID", "token");
properties.put("PWD", "dapi1234");

Connection conn = DriverManager.getConnection(url, properties);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM samples.nyctaxi.trips LIMIT 10");
```

### <a id="jdbc-simba" />JDBC driver (Simba)

The Simba driver uses the parameter name `ssp_query_tags` instead of `query_tags`.

#### Connection URL

Include `ssp_query_tags` in the JDBC connection URL string.

```java
String url = "jdbc:databricks://myworkspace.cloud.databricks.com:443;" +
             "httpPath=/sql/1.0/endpoints/abc123;" +
             "ssp_query_tags=team:engineering,env:prod;" +
             "AuthMech=3;UID=token;PWD=dapi1234";

Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM samples.nyctaxi.trips LIMIT 10");
```

#### Properties object

You can also set `ssp_query_tags` using a `Properties` object.

```java
String url = "jdbc:databricks://myworkspace.cloud.databricks.com:443";
Properties properties = new Properties();
properties.put("httpPath", "/sql/1.0/endpoints/abc123");
properties.put("ssp_query_tags", "team:engineering,env:prod");
properties.put("AuthMech", "3");
properties.put("UID", "token");
properties.put("PWD", "dapi1234");

Connection conn = DriverManager.getConnection(url, properties);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM samples.nyctaxi.trips LIMIT 10");
```

### <a id="odbc" />ODBC driver

Include the `ssp_query_tags` parameter in your ODBC connection configuration. You must also set `ApplySSPWithQueries=0` in the connection configuration.

## <a id="view" />View query tags

Query the `system.query.history` table to view query tags. You can group and filter by key or key-value pair.

```sql
SELECT statement_id, query_tags, executed_by, start_time
FROM system.query.history
WHERE MAP_CONTAINS_KEY(query_tags, 'team')
  AND query_tags['team'] = 'engineering'
ORDER BY start_time DESC
LIMIT 100;
```

Key-only tags appear with a `null` value. To filter for a key-only tag:

```sql
WHERE MAP_CONTAINS_KEY(query_tags, 'key') AND query_tags['key'] IS NULL
```

For more information, see [Query history system table reference](https://docs.databricks.com/aws/en/admin/system-tables/query-history.md).

## <a id="limitations" />Limitations

The following limits apply to query tags.

### General limits

The following limits apply to all query tags regardless of how they are set.

* Query tags are supported on Databricks SQL warehouses, [Lakehouse Real-Time](https://docs.databricks.com/aws/en/compute/sql-warehouse/real-time.md) (Lakehouse//RT) compute, and serverless compute for [notebooks](https://docs.databricks.com/aws/en/compute/serverless/notebooks.md) and [jobs](https://docs.databricks.com/aws/en/jobs/run-serverless-jobs.md). The `query_tags` column is not populated for other compute types.
* Query tags are limited to 10 KB per session. If the total size exceeds this limit, incoming tags are dropped and a `tags_dropped: true` sentinel tag is added.
* Each query supports a maximum of 20 user-specified tags.
* Tag keys and values must not exceed 128 characters.
* Tag keys must not contain the characters `,`, `:`, `-`, `/`, `=`, or `.`.
* Keys starting with `@@` are reserved for internal use.

### Session configuration parameter behavior

When you set tags using session configuration parameters (not SQL), the following additional behavior applies:

* Tags that exceed the 20-tag maximum are discarded and a `tag_truncated: true` sentinel tag is added.
* Tags with keys or values that exceed 128 characters, or keys that contain invalid characters, are discarded and a `tag_invalid: true` sentinel tag is added.

When you set tags using SQL statements, invalid tag keys cause the statement to fail with an error at execution time.
