Bird
0
0

You want to sum all elements of an integer array nums using FOREACH. Which code correctly does this?

hard📝 Application Q8 of 15
PostgreSQL - PL/pgSQL Fundamentals
You want to sum all elements of an integer array nums using FOREACH. Which code correctly does this?
DECLARE
  nums integer[] := ARRAY[5, 10, 15];
  total integer := 0;
BEGIN
  FOREACH n IN ARRAY nums LOOP
    -- What goes here? --
  END LOOP;
  RAISE NOTICE '%', total;
END;
Atotal := n;
Btotal := total + n;
Ctotal := total * n;
Dtotal := total - n;
Step-by-Step Solution
Solution:
  1. Step 1: Understand summing logic

    To sum, add each element to total inside the loop.
  2. Step 2: Choose correct operation

    total := total + n; adds n to total, accumulating sum correctly.
  3. Final Answer:

    total := total + n; -> Option B
  4. Quick Check:

    Sum requires adding each element [OK]
Quick Trick: Add each element to total inside FOREACH [OK]
Common Mistakes:
  • Replacing total instead of adding
  • Multiplying instead of adding
  • Subtracting elements by mistake

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes