A common exercise for learning any new programming language is to print a multiplication table (e.g., the "5 times table"). This is a perfect task for learning how to use loops and print formatted output in PL/SQL.
This simple guide will show you the basic concepts and a complete program to solve this problem.
What You Need to Know
To write this program, you will use a few basic PL/SQL concepts:
- Enabling Output: You must run this command once in your SQL tool (like SQL*Plus or SQL Developer) to see the printed results:
SET SERVEROUTPUT ON; - Anonymous Block: We will write our code in a
DECLARE...BEGIN...END;block. - Variables: We'll need a variable to hold the number for which we want to print the table (e.g.,
n NUMBER := 7;). - FOR Loop: We will use a loop to iterate from 1 to 10 (or any other number you choose) to create the table.
- Printing the Result: We use
DBMS_OUTPUT.PUT_LINE()inside the loop to print each line. - Concatenation (
||): We'll use the||operator to build a nicely formatted string for each line of the table.
PL/SQL Program: Print a Multiplication Table
This program will print the multiplication table for the number stored in the n variable, from 1 to 10.
PL/SQL Program
SET SERVEROUTPUT ON;
DECLARE
-- The number for which to print the table
n NUMBER := 8;
BEGIN
-- We don't need to declare 'i'.
-- The FOR loop automatically creates it as an integer.
-- Loop from 1 to 10
FOR i IN 1..10 LOOP
-- Print each line of the table by joining the strings and
-- calculating the result (n * i) inside the statement.
DBMS_OUTPUT.PUT_LINE(
n || ' x ' || i || ' = ' || (n * i)
);
END LOOP;
END;
/
Result (for n := 8)
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80
Program Explanation
DECLAREsection: We create one variable,n, and assign it the value8. This is the number our table will be based on.BEGINsection: The program's logic starts.FOR i IN 1..10 LOOP: This is our loop. It will run 10 times.- The first time,
iwill be1. - The second time,
iwill be2. - ...and so on, until
iis10.
- The first time,
DBMS_OUTPUT.PUT_LINE(...): This line runs inside the loop. It builds and prints a new string every time the loop iterates.n || ' x ' || i || ' = ' || (n * i): This is the string concatenation.- When
iis1, it builds:'8' || ' x ' || '1' || ' = ' || (8 * 1), which becomes'8 x 1 = 8'. - When
iis2, it builds:'8' || ' x ' || '2' || ' = ' || (8 * 2), which becomes'8 x 2 = 16'. - This continues until the loop finishes at
i = 10.
- When
END LOOP;: This signals the end of the loop block.END;and/: This signals the end of the PL/SQL program and tells the SQL tool to execute it.

