DO

On this page Carat arrow pointing down

The DO statement defines a code block that executes PL/pgSQL syntax.

Required privileges

  • To define a DO block with a user-defined type, a user must have USAGE privilege on the user-defined type.

Synopsis

DO LANGUAGE PLPGSQL routine_body_str

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 to declare variables to use in the code block.

icon/buttons/copy
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 to loop through several statements.

icon/buttons/copy
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 in the body of the code block.

icon/buttons/copy
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


Yes No
On this page

Yes No