EXIT / CONTINUE

Exits a loop or skips to the next iteration.

Category: control-flow

Syntax

EXIT [<label>] [WHEN <condition>];
CONTINUE [<label>] [WHEN <condition>];

Description

## Overview EXIT terminates a loop, and CONTINUE skips to the next iteration of a loop. Both support an optional label to target a specific enclosing loop and an optional WHEN clause for conditional execution. ## Behavior - EXIT without a label breaks out of the innermost enclosing loop. With a label, it breaks the loop whose label matches. - CONTINUE without a label skips to the next iteration of the innermost loop. With a label, it skips to the next iteration of the labeled loop. - When the WHEN clause is present, the condition is evaluated first. If false (or NULL), the statement has no effect and execution continues normally. - Label matching is case-insensitive and uses the executor's label stack. If the label does not match the current loop, the control-flow signal propagates outward through enclosing loops. - EXIT can also be used to leave a named BEGIN...END block (not just loops), consistent with PostgreSQL behavior. ## Differences from PostgreSQL - Behavior is consistent with PostgreSQL PL/pgSQL. No known deviations.

Parameters

NameTypeDescription
labelSpecify the target loop label to exit or continue. Omit to target the innermost enclosing loop.
conditionProvide a boolean expression. The EXIT or CONTINUE fires only when this evaluates to true.

Examples

DO $$
DECLARE
  counter INT := 0;
BEGIN
  LOOP
    counter := counter + 1;
    EXIT WHEN counter >= 10;
  END LOOP;
  PRINT 'Final:', counter;
END;
$$;
DO $$
DECLARE
  i INT;
BEGIN
  FOR i IN 1..20 LOOP
    CONTINUE WHEN i % 2 = 0;
    PRINT 'Odd:', i;
  END LOOP;
END;
$$;
DO $$
DECLARE
  i INT;
  j INT;
BEGIN
  <<outer>>
  FOR i IN 1..5 LOOP
    FOR j IN 1..5 LOOP
      EXIT outer WHEN i * j > 12;
      PRINT i, '*', j, '=', i * j;
    END LOOP;
  END LOOP;
  PRINT 'Exited at', i, j;
END;
$$;
DO $$
DECLARE
  rec RECORD;
BEGIN
  FOR rec IN SELECT id, name FROM customers ORDER BY id LOOP
    CONTINUE WHEN rec.name IS NULL;
    PRINT rec.id, rec.name;
    EXIT WHEN rec.id > 100;
  END LOOP;
END;
$$;

Pitfalls

See Also

Open in interactive docs →   DeltaForge home →