typestar

Loops in SQL

FOR counts up or down over a range; EXIT WHEN leaves early.

-- FOR counts up or down; EXIT WHEN leaves any loop early.
DO $$
DECLARE
    bells TEXT := '';
BEGIN
    FOR ring IN 1..6 LOOP
        bells := bells || 'ding ';
        EXIT WHEN ring >= 4;
    END LOOP;
    RAISE NOTICE '%', bells;

    FOR countdown IN REVERSE 3..1 LOOP
        RAISE NOTICE 'T-minus %', countdown;
    END LOOP;
END;
$$;

How it works

  1. FOR ring IN 1..6 LOOP iterates without declaring the counter.
  2. EXIT WHEN ring >= 4 cuts the loop short at four bells.
  3. REVERSE 3..1 counts down for the launch countdown.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
293
Tokens
67
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 4 of 4 in PL/pgSQL blocks, step 8 of 23 in PostgreSQL Stored Procedures.

← Previous Next →

Loops in other languages