This PL/SQL script checks whether a given number is a prime number using a simple loop and conditional logic. A must-know example for SQL developers and interview candidates.
PL/SQL Code to Check Prime Number
DECLARE
num NUMBER := 29;
i NUMBER := 2;
is_prime BOOLEAN := TRUE;
BEGIN
IF num <= 1 THEN
is_prime := FALSE;
ELSE
WHILE i <= SQRT(num) LOOP
IF MOD(num, i) = 0 THEN
is_prime := FALSE;
EXIT;
END IF;
i := i + 1;
END LOOP;
END IF;
IF is_prime THEN
DBMS_OUTPUT.PUT_LINE(num || ' is a Prime Number');
ELSE
DBMS_OUTPUT.PUT_LINE(num || ' is Not a Prime Number');
END IF;
END;
How It Works
- Starts loop from 2 to √n
- Uses
MOD(num, i)to check for divisibility - Boolean flag
is_primedetermines the result
FAQs
What is the best way to check primes in PL/SQL? Use loop up to square root for optimal performance. What if the number is negative? It will be marked as not prime.
Explore More PL/SQL Programs
Published by SQLQueries.in | Last updated: July 26, 2025