CASE Statement in PL/SQL
The CASE statement in PL/SQL is used to execute a sequence of statements based on a selector value. There are two types of CASE statements in PL/SQL:
- Simple CASE Statement
- Searched CASE Statement
The simple CASE statement compares an expression to a set of simple expressions to determine the result.
Syntax:
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
ELSE resultN
END;
Example:
DECLARE
grade CHAR(1) := 'B';
result VARCHAR2(20);
BEGIN
result := CASE grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Good'
WHEN 'C' THEN 'Fair'
WHEN 'D' THEN 'Poor'
ELSE 'Fail'
END;
DBMS_OUTPUT.PUT_LINE('Result: ' || result);
END;
The searched CASE statement evaluates a set of boolean expressions to determine the result.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE resultN
END;
Example:
DECLAREscore NUMBER := 85;
result VARCHAR2(20);
BEGIN
result := CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
WHEN score >= 70 THEN 'C'
WHEN score >= 60 THEN 'D'
ELSE 'F'
END;
DBMS_OUTPUT.PUT_LINE('Grade: ' || result);
END;
Using CASE Statement in SQL Queries
Example:
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
salary NUMBER,
department_id NUMBER
);
INSERT INTO employees (employee_id, first_name, last_name, salary, department_id) VALUES (1, 'John', 'Doe', 5000, 10);
INSERT INTO employees (employee_id, first_name, last_name, salary, department_id) VALUES (2, 'Jane', 'Smith', 6000, 20);
INSERT INTO employees (employee_id, first_name, last_name, salary, department_id) VALUES (3, 'Emily', 'Jones', 7000, 10);
INSERT INTO employees (employee_id, first_name, last_name, salary, department_id) VALUES (4, 'Michael', 'Brown', 8000, 30);
INSERT INTO employees (employee_id, first_name, last_name, salary, department_id) VALUES (5, 'Sarah', 'Davis', 9000, 20);
SELECT employee_id,
first_name,
last_name,
salary,
CASE
WHEN salary > 10000 THEN 'High'
WHEN salary > 5000 THEN 'Medium'
ELSE 'Low'
END AS salary_level
FROM employees;
Comments
Post a Comment