PL/SQL Constants πΒΆ
Prerequisites: PL/SQL Variables
Mentor's Note: A constant is a variable that cannot be changed once it is created. It is a "Fixed Rule". If you try to change it, Oracle will throw an error. π‘
π The Scenario: The Tax Rule βοΈΒΆ
Imagine you are writing a billing program. - Variable: The "Order_Total" changes for every customer. π - Constant: The "GST_Tax_Rate" is fixed at 18% for everyone. ποΈ - The Protection: You make the tax rate a constant so nobody can accidentally change it to 5% or 50% by mistake.
π» 1. Declaration SyntaxΒΆ
You use the CONSTANT keyword. You must assign a value immediately.
DECLARE
-- Syntax: name CONSTANT type := value;
c_tax_rate CONSTANT NUMBER(3, 2) := 0.18;
c_pi CONSTANT NUMBER := 3.14159;
BEGIN
DBMS_OUTPUT.PUT_LINE('Tax Rate is: ' || (c_tax_rate * 100) || '%');
-- β This would cause a compilation error:
-- c_tax_rate := 0.05;
END;
/
π‘οΈ 2. Why use Constants? (Architect's Note)ΒΆ
- Safety: Prevents accidental "data corruption" in your logic.
- Readability: It's easier to understand
price * c_tax_ratethanprice * 0.18. If the rate changes next year, you only change it in one place (the declaration). - Optimization: The PL/SQL compiler can sometimes optimize code better when it knows a value will never change.
π¨ Visual Logic: Fixed vs. FluidΒΆ
| Type | Box Analogy | Usage |
|---|---|---|
| Variable | A cardboard box (Open) π¦ | Usernames, Balances, Counters |
| Constant | A glass display case (Locked) π | Pi, Conversion Rates, Version Numbers |