---
title: BEGIN END compound statement
description: Group a sequence of statements, variable declarations, and exception handlers into a block with the BEGIN END compound statement in Databricks SQL and Databricks Runtime 16.3 and above.
canonical_url: https://docs.databricks.com/aws/en/sql/language-manual/control-flow/compound-stmt
---

# BEGIN END compound statement

**Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks SQL ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime 16.3 and above

Implements a SQL Script block that can contain a sequence of SQL statements, control-of-flow statements, local variable declarations, and exception handlers. When marked as `ATOMIC`, the block runs as a transactional unit where all statements succeed together or fail together.

> [!NOTE]
>
> When invoking a compound statement from a notebook it must be the only statement in the cell.

## Syntax

```
[ label : ]
      BEGIN [ ATOMIC ]
      [ { declare_variable | declare_condition } ; [...] ]
      [ declare_cursor ; [...] ]
      [ declare_handler ; [...] ]
      [ SQL_statement ; [...] ]
      END [ label ]

declare_variable
  DECLARE variable_name [, ...] datatype [ DEFAULT default_expr ]

declare_condition
  DECLARE condition_name CONDITION [ FOR SQLSTATE [ VALUE ] sqlstate ]

declare_cursor
  DECLARE cursor_name [ ASENSITIVE | INSENSITIVE ] CURSOR FOR query [ FOR READ ONLY ]

declare_handler
  DECLARE handler_type HANDLER FOR condition_values handler_action

handler_type
  EXIT | CONTINUE

condition_values
 { { SQLSTATE [ VALUE ] sqlstate | condition_name } [, ...] |
   { SQLEXCEPTION | NOT FOUND } [, ...] }
```

Prior to Databricks Runtime 17.2 you can only declare one variable at a time.

## Parameters

* **[label](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-names.md#label-name)**

  An optional identifier is used to qualify variables defined within the compound and to leave the compound.
  Both label occurrences must match, and the `END` label can only be specified if `label:` is specified.

  [label](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-names.md#label-name) must not be specified for a top level compound statement or for an `ATOMIC` compound statement.

* **`ATOMIC`**

  **Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks SQL ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime 17.0 and above

  > [!NOTE]
  > **Preview**
  >
  > ATOMIC compound statements are in [Public Preview](https://docs.databricks.com/aws/en/release-notes/release-types.md).

  Marks the compound statement as an atomic transaction block. All statements within the block run as a single transactional unit: either all statements succeed together, or all changes are rolled back if any statement fails. Databricks automatically commits changes when the block completes successfully, or rolls back all changes if any statement fails.

  Atomic blocks provide the same isolation, visibility, error handling, and limit semantics as explicit [interactive transactions](https://docs.databricks.com/aws/en/transactions/transaction-modes.md#interactive). However, atomic blocks offer simpler syntax with automatic commit and rollback behavior.

  Entering a `BEGIN ATOMIC ... END` block implicitly begins a transaction. Successful completion implicitly commits the transaction. Errors cause the transaction to abort and roll back automatically.

  > [!NOTE]
  >
  > Multi-table transactions require Databricks Runtime 18.0 and above and [catalog commits](https://docs.databricks.com/aws/en/tables/features/catalog-commits.md) enabled on all tables. Single-table atomic transactions work in Databricks Runtime 17.0 and above without additional requirements.

  The following restrictions apply to atomic compound statements:

  * Nested `BEGIN ATOMIC ... END` blocks are not allowed.
  * An atomic block can contain a non-atomic `BEGIN ... END` block. The inner block is not a nested transaction; its statements run as part of the outer atomic transaction.
  * Atomic blocks cannot be nested within non-atomic `BEGIN ... END` blocks.
  * You can `CALL` an atomic stored procedure from an atomic block. The procedure body is flattened into the outer transaction. All statements run as part of a single larger transaction. This is not a nested transaction.
  * Exception handlers (`DECLARE ... HANDLER`) are not allowed within atomic blocks.
  * Atomic blocks cannot be defined within exception handlers.
  * Only DML operations (`INSERT`, `UPDATE`, `DELETE`, `MERGE`), `SELECT` statements, variable declarations and assignments, control-flow statements (`IF`, `SIGNAL`, and similar), and calls to atomic stored procedures are allowed within atomic blocks. DDL statements and other operations are not supported.
  * Setting of local or session variables is non-transactional. That is, variable assignments are not subject to being rolled back on transaction failure.

  See [Non-interactive transactions](https://docs.databricks.com/aws/en/transactions/transaction-modes.md#non-interactive).

* **`NOT ATOMIC`**

  Specifies that, if an SQL statement within the compound fails, previous SQL statements will not be rolled back.
  This is the default behavior when `ATOMIC` is not specified.

* **`declare_variable`**

  A local variable declaration for one or more variables

  * **[variable\_name](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-names.md#variable-name)**

    A name for the variable.
    The name must not be qualified, and be unique within the compound statement.

  * **`data_type`**

    Any supported data type. If data\_type is omitted, you must specify DEFAULT, and the type is derived from the default\_expression.

  * **`{ DEFAULT | = } default_expression`**

    Defines the variable's initial value after declaration. default\_expression must be castable to data\_type. If no default is specified, the variable is initialized with NULL.

* **`Declare_condition`**

  A local condition declaration

  * **[condition\_name](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-names.md#condition-name)**

    The unqualified name of the condition is scoped to the compound statement.

  * **`sqlstate`**

    A `STRING` literal of 5 alphanumeric characters (case insensitive) consisting of A-Z and 0..9. The SQLSTATE must not start with '00', '01', or 'XX'. Any SQLSTATE starting with '02' will be caught by the predefined NOT FOUND exception as well. If not specified, the SQLSTATE is '45000'.

* <a id="declare_cursor" />**`declare_cursor`**

  **Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime 18.1 and above

  A local cursor declaration for iterating through query results.

  > [!NOTE]
  >
  > For `DECLARE CURSOR`, only syntax errors are detected and raised. The query is not executed until the cursor is opened with [OPEN](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/open-stmt.md).

  * **[cursor\_name](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-names.md#cursor-name)**: An unqualified name for the cursor, unique among cursors in this compound statement. When referencing the cursor in [OPEN](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/open-stmt.md), [FETCH](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/fetch-stmt.md), or [CLOSE](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/close-stmt.md), you can qualify the cursor name with the compound statement label (e.g., `label.my_cursor`) to disambiguate in nested scopes.
  * **`ASENSITIVE` | `INSENSITIVE`**: Optional. Once the cursor is opened, the result set is not affected by DML changes. This is the default and only supported behavior.
  * **query**: The [query](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-query.md) that defines the cursor; it is executed when the cursor is opened with [OPEN](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/open-stmt.md).

* **`declare_handler`**

  A declaration for an error handler.

  * **`handler_type`**
    * **`EXIT`**

      Classifies the handler to exit the compound statement after the condition is handled. All cursors opened within the compound statement and nested compound statements are implicitly closed.

    * **`CONTINUE`**

      **Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime 18.1 and above

      Classifies the handler to continue execution after the handler completes. Execution resumes with the statement following the one that raised the condition.

  * **`condition_values`**

    Specifies to which sqlstates or conditions the handler applies.
    Condition values must be unique within all handlers within the compound statement.
    Specific condition values take precedence over `SQLEXCEPTION`.

  * **`sqlstate`**

    A `STRING` literal of 5 characters `'A'-'Z'` and `'0'-'9'` (case insensitive).

  * **[condition\_name](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-names.md#condition-name)**

    A condition defined within this compound, an outer compound statement, or a system-defined error class.

  * **`SQLEXCEPTION`**

    Applies to any user-facing error condition.

  * **`NOT FOUND`**

    Applies to any error condition with a SQLSTATE '02' class, including the [CURSOR\_NO\_MORE\_ROWS](https://docs.databricks.com/aws/en/error-messages/error-classes.md#cursor_no_more_rows) condition (SQLSTATE `'02000'`) raised when fetching beyond the end of a cursor result set.

  * **`handler_action`**

    A SQL statement to execute when any of the condition values occur.
    To add multiple statements, use a nested compound statement.

* **`SQL_statement`**

  A SQL statement such as a DDL, DML, control statement, or compound statement.
  Any `SELECT` or `VALUES` statement produces a result set that the invoker can consume.

## Examples

### Non-atomic compound statement with exception handler

```sql
-- A compound statement with local variables, exit handler, and nested compound
> BEGIN
    DECLARE a INT DEFAULT 1;
    DECLARE b INT DEFAULT 5;
    DECLARE EXIT HANDLER FOR DIVIDE_BY_ZERO
      div0: BEGIN
        VALUES (15);
      END div0;
    SET a = 10;
    SET a = b / 0;
    VALUES (a);
END;
15
```

### Atomic compound statement

```sql
-- An atomic compound statement that ensures all changes commit together
> BEGIN ATOMIC
    INSERT INTO accounts VALUES (1, 'Alice', 1000);
    INSERT INTO accounts VALUES (2, 'Bob', 2000);
    UPDATE accounts SET balance = balance + 100 WHERE id = 1;
END;
```

### Atomic compound statement with automatic rollback

```sql
-- If any statement fails, all changes are rolled back automatically
> BEGIN ATOMIC
    INSERT INTO orders VALUES (101, 'Product A', 50.00);
    UPDATE inventory SET quantity = quantity - 1 WHERE product = 'Product A';
    -- If this statement fails, both the INSERT and UPDATE are rolled back
    INSERT INTO audit_log VALUES (101, current_timestamp(), 1/0);
END;
-- Error: Division by zero
-- All changes rolled back automatically
```

### Atomic compound statement with variables

```sql
-- Variables can be used within atomic blocks
> BEGIN ATOMIC
    DECLARE total_amount DECIMAL(10, 2);

    INSERT INTO sales VALUES (301, 150.00, current_date());

    SET total_amount = (SELECT SUM(amount) FROM sales WHERE sale_date = current_date());

    UPDATE daily_summary SET total = total_amount WHERE summary_date = current_date();
END;
```

## Related articles

* [SQL Scripting](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-scripting.md)
* [Transactions](https://docs.databricks.com/aws/en/transactions/index.md)
* [Transaction modes](https://docs.databricks.com/aws/en/transactions/transaction-modes.md)
* [BEGIN TRANSACTION](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-txn-begin.md)
* [COMMIT](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-txn-commit.md)
* [ROLLBACK](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-txn-rollback.md)
* [CASE Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/case-stmt.md)
* [IF Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/if-stmt.md)
* [LOOP Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/loop-stmt.md)
* [WHILE Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/while-stmt.md)
* [REPEAT Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/repeat-stmt.md)
* [FOR Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/for-stmt.md)
* [ITERATE Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/iterate-stmt.md)
* [LEAVE Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/leave-stmt.md)
* [SIGNAl Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/signal-stmt.md)
* [RESIGNAL Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/resignal-stmt.md)
* [GET DIAGNOSTICS Statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/get-diagnostics-stmt.md)
* [OPEN statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/open-stmt.md)
* [FETCH statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/fetch-stmt.md)
* [CLOSE statement](https://docs.databricks.com/aws/en/sql/language-manual/control-flow/close-stmt.md)
