A common task for new programmers is to compare several values to find the largest or smallest. In Oracle PL/SQL, you can easily find the greatest of three numbers using conditional logic.
This simple guide will show you the basic building blocks 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: Before you can see any printed results, you must run this command once in your SQL tool (like SQL*Plus or SQL Developer):
SET SERVEROUTPUT ON; - Anonymous Block: We will write our code in a
DECLARE...BEGIN...END;block. This is the standard way to run a simple PL/SQL script. - Variables: We need to
DECLAREvariables to hold our three numbers (n1,n2,n3) and a fourth variable (max_num) to store the largest value we find. - Conditional Logic (
IFstatement): This is the core of the program. We will use anIF...ELSIF...THEN...ELSEblock to compare the numbers. - Printing the Result: We use
DBMS_OUTPUT.PUT_LINE()to print the final answer to the screen.
PL/SQL Program: Find Greatest of Three Numbers
This program finds the largest of three hardcoded numbers (n1, n2, n3) and prints the result.
PL/SQL Program
SET SERVEROUTPUT ON;
DECLARE
-- Define our three numbers
n1 NUMBER := 25;
n2 NUMBER := 10;
n3 NUMBER := 45;
-- A variable to hold the largest number
max_num NUMBER;
BEGIN
-- Start the logic to find the greatest number
-- Check if n1 is greater than or equal to both n2 and n3
IF (n1 >= n2 AND n1 >= n3) THEN
max_num := n1;
-- If n1 isn't the greatest, check if n2 is
ELSIF (n2 >= n1 AND n2 >= n3) THEN
max_num := n2;
-- If neither n1 nor n2 is the greatest, then n3 must be
ELSE
max_num := n3;
END IF;
-- Print the final result to the screen
DBMS_OUTPUT.PUT_LINE('The greatest number is: ' || max_num);
END;
/
Result
The greatest number is: 45
Program Explanation
DECLAREsection: We create four variables.n1,n2, andn3are given default values of25,10, and45.max_numis declared to store our final result.BEGINsection: The program starts.IF (n1 >= n2 AND n1 >= n3) THEN: The first check is to see ifn1(25) is the largest.25 >= 10is TRUE.25 >= 45is FALSE.- Since
TRUE AND FALSEisFALSE, the code inside thisIFblock is skipped.
ELSIF (n2 >= n1 AND n2 >= n3) THEN: The first check failed, so it tries the next "else if" block. It checks ifn2(10) is the largest.10 >= 25is FALSE.- The code inside this
ELSIFblock is skipped.
ELSE: Since all previous checks (IFandELSIF) failed, theELSEblock automatically runs. This block assumes that if neithern1norn2was the greatest,n3must be.max_num := n3;: Themax_numvariable is set to the value ofn3(45).END IF;: The conditional logic block is closed.DBMS_OUTPUT.PUT_LINE(...): The program prints the final string, concatenating the text with the value stored inmax_num(45).

