0
0
PostgreSQLquery~10 mins

LOOP, WHILE, FOR iterations in PostgreSQL - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a simple FOR loop that iterates from 1 to 5.

PostgreSQL
DO $$ BEGIN
  FOR i IN 1..[1] LOOP
    RAISE NOTICE 'Number: %', i;
  END LOOP;
END $$;
Drag options to blanks, or click blank then click option'
A0
B10
C1
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using 10 instead of 5 causes the loop to run too many times.
Using 0 or 1 as the upper limit will not loop five times.
2fill in blank
medium

Complete the code to create a WHILE loop that counts down from 3 to 1.

PostgreSQL
DO $$ DECLARE
  counter INTEGER := 3;
BEGIN
  WHILE counter > [1] LOOP
    RAISE NOTICE 'Count: %', counter;
    counter := counter - 1;
  END LOOP;
END $$;
Drag options to blanks, or click blank then click option'
A4
B3
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as the condition causes the loop to stop too early.
Using 3 or 4 causes the loop to never run or run incorrectly.
3fill in blank
hard

Fix the error in the FOR loop that should iterate over an array of integers.

PostgreSQL
DO $$ DECLARE
  numbers INTEGER[] := ARRAY[2, 4, 6];
  num INTEGER;
BEGIN
  FOR num IN [1] LOOP
    RAISE NOTICE 'Value: %', num;
  END LOOP;
END $$;
Drag options to blanks, or click blank then click option'
AUNNEST(numbers)
BSELECT * FROM numbers
C1..array_length(numbers, 1)
Dnumbers
Attempts:
3 left
💡 Hint
Common Mistakes
Using the array name directly does not work in FOR loops.
Using SELECT * FROM numbers is invalid because numbers is not a table.
Using 1..array_length(numbers, 1) loops over indexes, not values.
4fill in blank
hard

Fill both blanks to create a FOR loop that sums numbers from 1 to 4.

PostgreSQL
DO $$ DECLARE
  total INTEGER := 0;
BEGIN
  FOR i IN [1] LOOP
    total := total [2] i;
  END LOOP;
  RAISE NOTICE 'Sum: %', total;
END $$;
Drag options to blanks, or click blank then click option'
A1..4
B+
C-
D5..10
Attempts:
3 left
💡 Hint
Common Mistakes
Using 5..10 loops over wrong numbers.
Using - subtracts instead of adds.
5fill in blank
hard

Fill all three blanks to create a WHILE loop that multiplies a number by 2 until it is greater than 20.

PostgreSQL
DO $$ DECLARE
  val INTEGER := [1];
BEGIN
  WHILE val [2] [3] LOOP
    RAISE NOTICE 'Value: %', val;
    val := val * 2;
  END LOOP;
END $$;
Drag options to blanks, or click blank then click option'
A1
B<=
C20
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Starting val at 20 or higher causes no loop iterations.
Using > 20 as condition causes loop to never run.