FOREACH for array iteration in PostgreSQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using FOREACH to loop over an array in PostgreSQL, it's important to understand how the time taken grows as the array gets bigger.
We want to know how the number of steps changes when the array length increases.
Analyze the time complexity of the following code snippet.
DECLARE
my_array integer[] := ARRAY[1,2,3,4,5];
element integer;
BEGIN
FOREACH element IN ARRAY my_array LOOP
RAISE NOTICE 'Element: %', element;
END LOOP;
END;
This code loops through each element in an integer array and prints it.
- Primary operation: Looping through each element of the array once.
- How many times: Exactly once for each element in the array.
As the array gets longer, the number of steps grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The steps increase in a straight line as the array size grows.
Time Complexity: O(n)
This means the time to complete the loop grows directly with the number of elements in the array.
[X] Wrong: "FOREACH loops run in constant time no matter the array size."
[OK] Correct: Each element must be visited once, so the time grows with the array length, not fixed.
Understanding how looping over arrays scales helps you explain performance clearly in interviews and shows you grasp how data size affects query speed.
"What if we nested a FOREACH loop inside another FOREACH loop over the same array? How would the time complexity change?"
Practice
FOREACH statement in PostgreSQL when working with arrays?Solution
Step 1: Understand FOREACH usage context
FOREACH is used inside PL/pgSQL to iterate over array elements one by one.Step 2: Identify the main purpose
It simplifies looping through arrays without manual index handling.Final Answer:
To loop through each element of an array easily inside PL/pgSQL. -> Option BQuick Check:
FOREACH loops over array elements [OK]
- Confusing FOREACH with array creation or sorting
- Thinking FOREACH works outside PL/pgSQL
- Assuming FOREACH converts arrays to strings
arr using FOREACH in PL/pgSQL?Solution
Step 1: Recall FOREACH syntax
The correct syntax uses 'IN ARRAY' to specify the array to loop over.Step 2: Match syntax options
Only FOREACH element IN ARRAY arr LOOP ... END LOOP; uses 'IN ARRAY' correctly; others use invalid keywords.Final Answer:
FOREACH element IN ARRAY arr LOOP ... END LOOP; -> Option AQuick Check:
FOREACH ... IN ARRAY ... is correct syntax [OK]
- Using FROM, ON, or OVER instead of IN ARRAY
- Omitting LOOP or END LOOP keywords
- Trying to use FOREACH outside PL/pgSQL
DECLARE
arr integer[] := ARRAY[2, 4, 6];
sum integer := 0;
BEGIN
FOREACH val IN ARRAY arr LOOP
sum := sum + val;
END LOOP;
RAISE NOTICE '%', sum;
END;What will be the output when this block runs?
Solution
Step 1: Understand the loop iteration
The FOREACH loops over arr elements: 2, 4, and 6.Step 2: Calculate the sum
sum starts at 0, then adds 2 + 4 + 6 = 12.Final Answer:
12 -> Option CQuick Check:
2 + 4 + 6 = 12 [OK]
- Assuming FOREACH does not add elements
- Confusing sum initialization
- Expecting syntax error due to RAISE NOTICE
DECLARE
arr text[] := ARRAY['a', 'b', 'c'];
ch text;
BEGIN
FOREACH ch IN arr LOOP
RAISE NOTICE '%', ch;
END LOOP;
END;Solution
Step 1: Check FOREACH syntax
FOREACH requires 'IN ARRAY' before the array variable to iterate properly.Step 2: Identify the error
The code uses 'IN arr' instead of 'IN ARRAY arr', causing syntax error.Final Answer:
FOREACH must use 'IN ARRAY' before the array variable. -> Option DQuick Check:
FOREACH ... IN ARRAY ... is correct syntax [OK]
- Omitting 'ARRAY' keyword in FOREACH
- Wrong variable type for array elements
- Misunderstanding RAISE NOTICE usage
FOREACH. Which of the following code snippets correctly implements this?Solution
Step 1: Check FOREACH syntax correctness
CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOREACH val IN ARRAY arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql; uses 'FOREACH val IN ARRAY arr LOOP', which is the correct syntax.Step 2: Verify logic for counting even numbers
Inside the loop, it checks if val is even and increments count correctly.Final Answer:
FOREACH val IN ARRAY arr LOOP with IF val % 2 = 0 logic -> Option AQuick Check:
FOREACH ... IN ARRAY ... and correct IF condition [OK]
- Using 'FROM' or 'ON ARRAY' instead of 'IN ARRAY'
- Confusing FOREACH with FOR loops
- Missing RETURN statement or wrong logic
