LOOP is a procedural control-flow construct available in PostgreSQL's PL/pgSQL (and Oracle's PL/SQL) that runs a block of code repeatedly. Unlike FOR or WHILE, LOOP itself has no built-in termination condition; the block continues indefinitely until an EXIT, EXIT WHEN, or RAISE EXCEPTION halts execution. Because LOOP runs inside functions, procedures, or DO blocks, it executes on the server, avoiding client round-trips. Use it when you need flexible, conditionally controlled iteration that cannot be expressed as a set-based SQL operation. Overuse of LOOP can hurt performance, so prefer set operations when possible.
label
(optional) - text - An identifier that lets you reference the loop for EXIT or CONTINUE control.WHILE, FOR, EXIT, CONTINUE, CURSOR, DO block, PL/pgSQL functions
PostgreSQL 7.0 (PL/pgSQL initial release)
LOOP is a PL/pgSQL control structure that repeats a block of code until an explicit EXIT or EXIT WHEN condition stops it.
Place EXIT or EXIT WHEN inside the loop body. When the condition evaluates to true, PostgreSQL exits that loop level.
No. LOOP runs only inside PL/pgSQL contexts such as functions, procedures, or DO blocks. Running it in a plain psql script outside those contexts raises a syntax error.
Use LOOP when the termination condition is complex or evaluated mid-loop, or when you need multiple exit points. If you have a simple counter or cursor iteration, WHILE or FOR is more concise.