Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Syntax of PL/pgSQL
Function parameters
Handling exceptions
Summary

Instruction

Brilliant! You already know how to create and use IF statements, so let's move on to the next topic: loops. We'll start with the WHILE loop.

A WHILE loop repeats a sequence of statements as long as the given expression evaluates to true. See the example below:

CREATE FUNCTION print_preceding()
RETURNS void AS $$
DECLARE
  counter smallint := 10;
BEGIN
  WHILE counter > 0 LOOP
    RAISE NOTICE 'Current counter value: %', counter;
    counter := counter - 1;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

The counter is initially set to 10, and the current counter value is printed in the WHILE loop. The counter value is decreased by 1 in each iteration until it's equal to 0.

The final output will look like this:

Current counter value: 10
Current counter value: 9
Current counter value: 8
Current counter value: 7
Current counter value: 6
Current counter value: 5
Current counter value: 4
Current counter value: 3
Current counter value: 2
Current counter value: 1

Exercise

Create a WHILE loop that prints (by raising notices) the square of integer from 1 to 10, inclusive. The final output should look like this:

1 to the power of 2 is equal to: 1
2 to the power of 2 is equal to: 4
3 to the power of 2 is equal to: 9
4 to the power of 2 is equal to: 16
5 to the power of 2 is equal to: 25
6 to the power of 2 is equal to: 36
7 to the power of 2 is equal to: 49
8 to the power of 2 is equal to: 64
9 to the power of 2 is equal to: 81
10 to the power of 2 is equal to: 100

Name the function print_squares.

Stuck? Here's a hint!

Use the power(counter, 2) function.