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

# CANCEL QUERY

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

The `CANCEL QUERY` <InternalLink path="sql-statements">statement</InternalLink> cancels a running SQL query.

## Considerations

* Schema changes are treated differently than other SQL queries. You can use <InternalLink path="show-jobs">`SHOW JOBS`</InternalLink> to monitor the progress of schema changes and <InternalLink path="cancel-job">`CANCEL JOB`</InternalLink> to cancel schema changes that are taking longer than expected.
* In rare cases where a query is close to completion when a cancellation request is issued, the query may run to completion.
* In addition to the `CANCEL QUERY` statement, CockroachDB also supports query cancellation by <InternalLink path="install-client-drivers">client drivers and ORMs</InternalLink> using the PostgreSQL wire protocol (pgwire). This allows CockroachDB to stop executing queries that your application is no longer waiting for, thereby reducing load on the cluster. pgwire query cancellation differs from the `CANCEL QUERY` statement in the following ways:
  * It is how most client drivers and ORMS implement query cancellation. For example, it is [used by PGJDBC](https://github.com/pgjdbc/pgjdbc/blob/3a54d28e0b416a84353d85e73a23180a6719435e/pgjdbc/src/main/java/org/postgresql/core/QueryExecutorBase.java#L171) to implement the [`setQueryTimeout` method](https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/jdbc/PgStatement#setQueryTimeout-int-).
  * The cancellation request is sent over a different network connection than is used by SQL connections.
  * If there are too many unsuccessful cancellation attempts, CockroachDB will start rejecting pgwire cancellations.

## Required privileges

Members of the `admin` role (including `root`, which belongs to `admin` by default) can cancel any currently active queries. User that are not members of the `admin` role can cancel only their own currently active queries. To view and cancel another non-admin user's query, the user must be a member of the `admin` role or must have the `VIEWACTIVITY` <InternalLink path="security-reference/authorization#supported-privileges">system privilege</InternalLink> (or the legacy <InternalLink path="create-user#create-a-user-that-can-see-and-cancel-non-admin-queries-and-sessions">`VIEWACTIVITY`</InternalLink> <InternalLink path="security-reference/authorization">role option</InternalLink>) and the `CANCELQUERY` <InternalLink path="security-reference/authorization#supported-privileges">system privilege</InternalLink> (or the legacy <InternalLink path="create-user#create-a-user-that-can-see-and-cancel-non-admin-queries-and-sessions">`CANCELQUERY`</InternalLink> <InternalLink path="security-reference/authorization">role option</InternalLink>) defined.

## Synopsis

<img src="https://mintcdn.com/cockroachlabs/WFQ6LFOxKnUpgIkd/images/sql-diagrams/v24.1/cancel_query.svg?fit=max&auto=format&n=WFQ6LFOxKnUpgIkd&q=85&s=5dffbc241ddab3e300617a4bceb117ad" alt="cancel_query syntax diagram" style={{maxWidth: "100%", overflowX: "auto"}} width="573" height="145" data-path="images/sql-diagrams/v24.1/cancel_query.svg" />

## Parameters

<Note>
  | Parameter      | Description                                                                                                                                                                                                                                                                                                  |
  | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
  | `query\_id`    | A <InternalLink path="scalar-expressions">scalar expression</InternalLink> that produces the ID of the query to cancel.  `CANCEL QUERY` accepts a single query ID. If a subquery is used and returns multiple IDs, the `CANCEL QUERY` statement will fail. To cancel multiple queries, use `CANCEL QUERIES`. |
  | `select\_stmt` | A <InternalLink path="selection-queries">selection query</InternalLink> whose result you want to cancel.                                                                                                                                                                                                     |
</Note>

## Response

When a query is successfully cancelled, CockroachDB sends a `query execution canceled` error to the client that issued the query.

* If the canceled query was a single, stand-alone statement, no further action is required by the client.
* If the canceled query was part of a larger, multi-statement <InternalLink path="transactions">transaction</InternalLink>, the client should then issue a <InternalLink path="rollback-transaction">`ROLLBACK`</InternalLink> statement.

## Examples

### Cancel a query via the query ID

In this example, we use the <InternalLink path="show-statements">`SHOW STATEMENTS`</InternalLink> statement to get the ID of a query and then pass the ID into the `CANCEL QUERY` statement:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SHOW STATEMENTS;
```

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
              query_id             | node_id |            session_id            | user_name |                start                |                query                 | client_address  | application_name | distributed |   phase
-----------------------------------+---------+----------------------------------+-----------+-------------------------------------+--------------------------------------+-----------------+------------------+-------------+------------
  1673f58fca5301900000000000000001 |       1 | 1673f583067d51280000000000000001 | demo      | 2021-04-08 18:31:29.079614+00:00:00 | SELECT * FROM rides ORDER BY revenue | 127.0.0.1:55212 | $ cockroach demo |    true     | executing
  1673f590433eaa000000000000000001 |       1 | 1673f58a4ba3c8e80000000000000001 | demo      | 2021-04-08 18:31:31.108372+00:00:00 | SHOW CLUSTER STATEMENTS              | 127.0.0.1:55215 | $ cockroach sql  |    false    | executing
(2 rows)
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CANCEL QUERY '1673f590433eaa000000000000000001';
```

### Cancel a query via a subquery

In this example, we nest a <InternalLink path="select-clause">`SELECT` clause</InternalLink> that retrieves the ID of a query inside the `CANCEL QUERY` statement:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CANCEL QUERY (WITH x AS (SHOW CLUSTER STATEMENTS) SELECT query_id FROM x
      WHERE client_address = '127.0.0.1:55212'
          AND user_name = 'demo'
          AND query = 'SELECT * FROM rides ORDER BY revenue');
```

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CANCEL QUERIES 1
```

`CANCEL QUERY` accepts a single query ID. If a subquery is used and returns multiple IDs, the `CANCEL QUERY` statement will fail. To cancel multiple queries, use `CANCEL QUERIES`.

## See also

* <InternalLink path="manage-long-running-queries">Manage Long-Running Queries</InternalLink>
* <InternalLink path="show-statements">`SHOW STATEMENTS`</InternalLink>
* <InternalLink path="cancel-session">`CANCEL SESSION`</InternalLink>
* <InternalLink path="sql-statements">SQL Statements</InternalLink>
