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

# DO

The `DO` [statement](/docs/stable/sql-statements.md) defines a code block that executes [PL/pgSQL](/docs/stable/plpgsql.md) syntax.

## Required privileges

* To define a `DO` block with a [user-defined type](/docs/stable/create-type.md), a user must have `USAGE` privilege on the user-defined type.

## Synopsis

![do syntax diagram](https://mintcdn.com/cockroachlabs/UZNSFbmU2EwEm6G5/images/sql-diagrams/common/do.svg?fit=max\&auto=format\&n=UZNSFbmU2EwEm6G5\&q=85\&s=64f72b10a354431a7feb894a96b1bfa5)

## Parameters

| Parameter | Description |
| - | - |
| `routine_body_str` | The body of the code block. |

## Examples

### Declare a variable in a `DO` block

The following example uses the [PL/pgSQL `DECLARE` syntax](/docs/stable/plpgsql#declare-a-variable) to declare variables to use in the code block.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
DO $$
DECLARE
    x INT := 10;
    y INT := 5;
    result INT;
BEGIN
    result := x + y;
    RAISE NOTICE 'The sum of % and % is %', x, y, result;
END $$;
```

```
NOTICE: The sum of 10 and 5 is 15
DO
```

### Use a loop in a `DO` block

The following example uses the [PL/pgSQL `WHILE` syntax](/docs/stable/plpgsql#write-loops) to loop through several statements.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
DO $$
DECLARE
   counter INT := 1;
BEGIN
   WHILE counter <= 5 LOOP
       RAISE NOTICE 'Counter: %', counter;
       counter := counter + 1;
   END LOOP;
END $$;
```

```
NOTICE: Counter: 1
NOTICE: Counter: 2
NOTICE: Counter: 3
NOTICE: Counter: 4
NOTICE: Counter: 5
DO
```

### Use a common table expression in a `DO` block

The following example uses a [common table expression](/docs/stable/common-table-expressions.md) in the body of the code block.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
DO $$
DECLARE
    sum_result INT;
BEGIN
    WITH numbers AS (
        SELECT generate_series(1, 5) AS num
    )
    SELECT sum(num) INTO sum_result
    FROM numbers;

    RAISE NOTICE 'Sum of numbers 1-5: %', sum_result;
END $$;
```

```
NOTICE: Sum of numbers 1-5: 15
DO
```

## See also

* [PL/pgSQL](/docs/stable/plpgsql.md)
* [Stored Procedures](/docs/stable/stored-procedures.md)
* [User-Defined Functions](/docs/stable/user-defined-functions.md)
