LOOP, WHILE, FOR iterations in PostgreSQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use loops like LOOP, WHILE, or FOR in PostgreSQL, the time it takes to run depends on how many times the loop runs.
We want to understand how the total work grows as the number of loop cycles increases.
Analyze the time complexity of the following code snippet.
DO $$
DECLARE
counter INTEGER := 1;
BEGIN
WHILE counter <= 1000 LOOP
-- some simple operation
counter := counter + 1;
END LOOP;
END $$;
This code runs a WHILE loop that repeats a simple operation 1000 times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop body runs once each time the counter increases.
- How many times: The loop runs exactly 1000 times in this example.
As the number of loop cycles grows, the total work grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: If you double the number of loop cycles, the total work doubles too.
Time Complexity: O(n)
This means the time to finish grows directly in proportion to how many times the loop runs.
[X] Wrong: "The loop always takes the same time no matter how many times it runs."
[OK] Correct: Each loop cycle adds more work, so more cycles mean more total time.
Understanding how loops affect time helps you explain how your code scales and shows you can think about efficiency clearly.
"What if we added a nested loop inside the existing loop? How would the time complexity change?"
Practice
LOOP statement do in PostgreSQL procedural code?Solution
Step 1: Understand the LOOP statement
ALOOPin PostgreSQL repeats the code inside it indefinitely until anEXITcommand is used to stop it.Step 2: Compare with other loops
UnlikeWHILEorFOR,LOOPdoes not check a condition automatically; it relies onEXITto stop.Final Answer:
Repeats the code inside it until anEXITcommand is reached. -> Option DQuick Check:
LOOP repeats until EXIT [OK]
- Thinking LOOP stops automatically without EXIT
- Confusing LOOP with WHILE or FOR
- Assuming LOOP checks conditions itself
FOR loop iterating over rows from a query in PostgreSQL?Solution
Step 1: Recall FOR loop syntax for query iteration
The correct syntax usesFOR record IN SELECT ... LOOPto iterate over query rows.Step 2: Check each option
FOR record IN SELECT * FROM users LOOP matches the correct syntax. Options B, C, and D are invalid or incomplete.Final Answer:
FOR record IN SELECT * FROM users LOOP -> Option CQuick Check:
FOR ... IN SELECT ... LOOP is correct syntax [OK]
- Omitting IN keyword
- Using parentheses incorrectly
- Mixing WHILE syntax with FOR
DECLARE
counter INT := 1;
total INT := 0;
BEGIN
WHILE counter <= 3 LOOP
total := total + counter;
counter := counter + 1;
END LOOP;
RAISE NOTICE 'Total: %', total;
END;Solution
Step 1: Trace the WHILE loop iterations
The loop runs while counter is 1, 2, and 3. Each time, total adds counter's value.Step 2: Calculate total after loop
Total = 0 + 1 + 2 + 3 = 6 after the loop ends.Final Answer:
Total: 6 -> Option BQuick Check:
Sum 1+2+3 = 6 [OK]
- Stopping loop too early
- Adding counter after increment
- Confusing total initialization
DECLARE
i INT := 1;
BEGIN
WHILE i < 5 LOOP
RAISE NOTICE '%', i;
END LOOP;
END;Solution
Step 1: Check loop control variable usage
The variableiis never increased inside the loop, so the conditioni < 5never becomes false.Step 2: Understand loop behavior
Without increment, the loop runs forever causing an infinite loop error.Final Answer:
Missing increment of variableiinside the loop. -> Option AQuick Check:
Loop needs variable increment to stop [OK]
- Forgetting to increment loop variable
- Assuming loop stops automatically
- Misreading WHILE condition
price column from a products table using a FOR loop in PL/pgSQL. Which code snippet correctly does this?Solution
Step 1: Identify correct FOR loop syntax for query rows
DECLARE total NUMERIC := 0; BEGIN FOR rec IN SELECT price FROM products LOOP total := total + rec.price; END LOOP; RAISE NOTICE '%', total; END; usesFOR rec IN SELECT price FROM products LOOP, which is correct syntax to iterate query results.Step 2: Verify accumulation and output
Inside the loop, it addsrec.pricetototaland then outputs total withRAISE NOTICE.Final Answer:
DECLARE total NUMERIC := 0; BEGIN FOR rec IN SELECT price FROM products LOOP total := total + rec.price; END LOOP; RAISE NOTICE '%', total; END; -> Option AQuick Check:
FOR ... IN SELECT ... LOOP sums prices [OK]
- Omitting IN keyword in FOR loop
- Using WHILE instead of FOR for query rows
- Incorrect loop variable or query syntax
