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
FOR ring IN 1..6 LOOPiterates without declaring the counter.EXIT WHEN ring >= 4cuts the loop short at four bells.REVERSE 3..1counts down for the launch countdown.
Keywords and builtins used here
BEGINDECLAREDOENDFORINTEXTWHEN
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.
Step 4 of 4 in PL/pgSQL blocks, step 8 of 23 in PostgreSQL Stored Procedures.