0
0
PostgreSQLquery~10 mins

LOOP, WHILE, FOR iterations in PostgreSQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - LOOP, WHILE, FOR iterations
Start Loop
Check Condition?
NoExit Loop
Yes
Execute Loop Body
Update Variables
Back to Check Condition
The loop starts, checks a condition, runs the body if true, updates variables, then repeats until the condition is false.
Execution Sample
PostgreSQL
DO $$
DECLARE
  counter INT := 1;
BEGIN
  WHILE counter <= 3 LOOP
    RAISE NOTICE 'Counter: %', counter;
    counter := counter + 1;
  END LOOP;
END $$;
This code runs a WHILE loop that prints the counter value from 1 to 3.
Execution Table
StepcounterCondition (counter <= 3)ActionOutput
11TruePrint 'Counter: 1', counter = 2Counter: 1
22TruePrint 'Counter: 2', counter = 3Counter: 2
33TruePrint 'Counter: 3', counter = 4Counter: 3
44FalseExit loop
💡 counter becomes 4, condition 4 <= 3 is False, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
counter12344
Key Moments - 2 Insights
Why does the loop stop when counter is 4 even though the loop body changes counter inside?
Because the condition is checked before each loop iteration (see execution_table step 4). When counter is 4, the condition counter <= 3 is false, so the loop exits before running the body again.
What happens if we forget to update the counter inside the loop?
The condition will always be true (if initially true), causing an infinite loop. Unlike the execution_table, it shows counter increasing each step to eventually stop the loop.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of counter at step 3?
A2
B3
C4
D1
💡 Hint
Check the 'counter' column in execution_table row with Step 3.
At which step does the loop condition become false?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look at the 'Condition (counter <= 3)' column in execution_table to find when it is False.
If we change the initial counter to 4, what happens to the loop execution?
ALoop runs once
BLoop runs three times
CLoop does not run at all
DLoop runs infinitely
💡 Hint
Refer to variable_tracker start value and condition check in execution_table step 1.
Concept Snapshot
LOOP, WHILE, FOR iterations in PostgreSQL:
- Use WHILE condition LOOP ... END LOOP to repeat while condition is true.
- Condition is checked before each iteration.
- Update variables inside loop to avoid infinite loops.
- Loop exits when condition becomes false.
Full Transcript
This example shows a WHILE loop in PostgreSQL that starts with counter = 1. Each loop iteration checks if counter is less than or equal to 3. If true, it prints the counter and increases it by 1. When counter reaches 4, the condition fails and the loop stops. The variable tracker shows how counter changes from 1 to 4. Key points include the condition check before the loop body and the importance of updating the counter to avoid infinite loops.