Bird
Raised Fist0
PostgreSQLquery~5 mins

FOREACH for array iteration in PostgreSQL - Time & Space Complexity

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Time Complexity: FOREACH for array iteration
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping through each element of the array once.
  • How many times: Exactly once for each element in the array.
How Execution Grows With Input

As the array gets longer, the number of steps grows directly with the number of elements.

Input Size (n)Approx. Operations
1010 steps
100100 steps
10001000 steps

Pattern observation: The steps increase in a straight line as the array size grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the loop grows directly with the number of elements in the array.

Common Mistake

[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.

Interview Connect

Understanding how looping over arrays scales helps you explain performance clearly in interviews and shows you grasp how data size affects query speed.

Self-Check

"What if we nested a FOREACH loop inside another FOREACH loop over the same array? How would the time complexity change?"

Practice

(1/5)
1. What is the main purpose of the FOREACH statement in PostgreSQL when working with arrays?
easy
A. To convert an array into a string.
B. To loop through each element of an array easily inside PL/pgSQL.
C. To sort the elements of an array in ascending order.
D. To create a new array from existing tables.

Solution

  1. Step 1: Understand FOREACH usage context

    FOREACH is used inside PL/pgSQL to iterate over array elements one by one.
  2. Step 2: Identify the main purpose

    It simplifies looping through arrays without manual index handling.
  3. Final Answer:

    To loop through each element of an array easily inside PL/pgSQL. -> Option B
  4. Quick Check:

    FOREACH loops over array elements [OK]
Hint: FOREACH loops over array elements inside PL/pgSQL [OK]
Common Mistakes:
  • Confusing FOREACH with array creation or sorting
  • Thinking FOREACH works outside PL/pgSQL
  • Assuming FOREACH converts arrays to strings
2. Which of the following is the correct syntax to iterate over an integer array arr using FOREACH in PL/pgSQL?
easy
A. FOREACH element IN ARRAY arr LOOP ... END LOOP;
B. FOREACH element FROM arr LOOP ... END LOOP;
C. FOREACH element ON arr LOOP ... END LOOP;
D. FOREACH element OVER arr LOOP ... END LOOP;

Solution

  1. Step 1: Recall FOREACH syntax

    The correct syntax uses 'IN ARRAY' to specify the array to loop over.
  2. Step 2: Match syntax options

    Only FOREACH element IN ARRAY arr LOOP ... END LOOP; uses 'IN ARRAY' correctly; others use invalid keywords.
  3. Final Answer:

    FOREACH element IN ARRAY arr LOOP ... END LOOP; -> Option A
  4. Quick Check:

    FOREACH ... IN ARRAY ... is correct syntax [OK]
Hint: Use 'IN ARRAY' to loop over arrays with FOREACH [OK]
Common Mistakes:
  • Using FROM, ON, or OVER instead of IN ARRAY
  • Omitting LOOP or END LOOP keywords
  • Trying to use FOREACH outside PL/pgSQL
3. Consider the following PL/pgSQL block:
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?
medium
A. Syntax error
B. 24
C. 12
D. 0

Solution

  1. Step 1: Understand the loop iteration

    The FOREACH loops over arr elements: 2, 4, and 6.
  2. Step 2: Calculate the sum

    sum starts at 0, then adds 2 + 4 + 6 = 12.
  3. Final Answer:

    12 -> Option C
  4. Quick Check:

    2 + 4 + 6 = 12 [OK]
Hint: Sum array elements by adding each in FOREACH loop [OK]
Common Mistakes:
  • Assuming FOREACH does not add elements
  • Confusing sum initialization
  • Expecting syntax error due to RAISE NOTICE
4. Identify the error in this PL/pgSQL snippet:
DECLARE
  arr text[] := ARRAY['a', 'b', 'c'];
  ch text;
BEGIN
  FOREACH ch IN arr LOOP
    RAISE NOTICE '%', ch;
  END LOOP;
END;
medium
A. Variable 'ch' must be declared as integer, not text.
B. Array declaration syntax is incorrect.
C. RAISE NOTICE cannot print variables inside loops.
D. FOREACH must use 'IN ARRAY' before the array variable.

Solution

  1. Step 1: Check FOREACH syntax

    FOREACH requires 'IN ARRAY' before the array variable to iterate properly.
  2. Step 2: Identify the error

    The code uses 'IN arr' instead of 'IN ARRAY arr', causing syntax error.
  3. Final Answer:

    FOREACH must use 'IN ARRAY' before the array variable. -> Option D
  4. Quick Check:

    FOREACH ... IN ARRAY ... is correct syntax [OK]
Hint: Always write 'FOREACH var IN ARRAY arr' [OK]
Common Mistakes:
  • Omitting 'ARRAY' keyword in FOREACH
  • Wrong variable type for array elements
  • Misunderstanding RAISE NOTICE usage
5. You want to write a PL/pgSQL function that takes an integer array and returns the count of even numbers using FOREACH. Which of the following code snippets correctly implements this?
hard
A. 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;
B. CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOREACH val FROM arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql;
C. CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOR val IN ARRAY arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql;
D. CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOREACH val ON ARRAY arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql;

Solution

  1. 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.
  2. Step 2: Verify logic for counting even numbers

    Inside the loop, it checks if val is even and increments count correctly.
  3. Final Answer:

    FOREACH val IN ARRAY arr LOOP with IF val % 2 = 0 logic -> Option A
  4. Quick Check:

    FOREACH ... IN ARRAY ... and correct IF condition [OK]
Hint: Use 'FOREACH val IN ARRAY arr' and check val % 2 = 0 [OK]
Common Mistakes:
  • Using 'FROM' or 'ON ARRAY' instead of 'IN ARRAY'
  • Confusing FOREACH with FOR loops
  • Missing RETURN statement or wrong logic