Data Insertion & Automated Calculations πΒΆ
Prerequisites: PL/SQL Basics, SQL DML (INSERT)
Mentor's Note: Why do math manually when the database can do it for you? Using PL/SQL to calculate tax or allowances during insertion ensures your data is always accurate and consistent! π‘
π The Scenario: The Automated Accountant πΌΒΆ
Imagine you are building a Payroll System for a small company in Surat.
- The Logic: When you hire a new employee, you only enter their Basic Salary. π¦
- The Magic: The database automatically calculates:
- HRA (Home Rent Allowance) = 15% π
- DA (Dearness Allowance) = 50% π²
- PF (Provident Fund) = 12% π‘οΈ
- The Result: You save the Net Pay instantly without using a calculator. β
π Concept ExplanationΒΆ
1. Variables for MathΒΆ
We declare local variables in the DECLARE section to hold temporary math results before pushing them into the table.
2. The & SubstitutionΒΆ
We use the ampersand & symbol to ask the user for input at runtime.
π¨ Visual Logic: The Payroll PipeΒΆ
graph LR
A[Input: Basic Salary π₯] --> B{Accountant Logic βοΈ}
B -- "x 0.15" --> C[HRA π ]
B -- "x 0.50" --> D[DA π²]
B -- "x 0.12" --> E[PF π‘οΈ]
C --> F[Final Calculation]
D --> F
E --> F
F --> G[INSERT INTO TABLE β
]
π» Implementation: The Payroll LabΒΆ
-- π Scenario: Hiring a new developer
-- π Action: Auto-calculating HRA, DA, and PF
DECLARE
v_emp_id NUMBER := &ID;
v_name VARCHAR2(50) := '&Name';
v_basic NUMBER := &Basic_Salary;
v_hra NUMBER;
v_da NUMBER;
v_pf NUMBER;
v_net NUMBER;
BEGIN
-- βοΈ 1. Logic: Perform the math
v_hra := v_basic * 0.15; -- 15%
v_da := v_basic * 0.50; -- 50%
v_pf := v_basic * 0.12; -- 12%
v_net := (v_basic + v_hra + v_da) - v_pf;
-- π₯ 2. Database Action: Insert everything
INSERT INTO employee_payroll (emp_id, emp_name, basic, hra, da, pf, net_pay)
VALUES (v_emp_id, v_name, v_basic, v_hra, v_da, v_pf, v_net);
DBMS_OUTPUT.PUT_LINE('Success! Net Pay for ' || v_name || ' is βΉ' || v_net);
COMMIT;
END;
/
π Sample Dry RunΒΆ
Input: Basic = 10,000
| Component | Math | Value | Status |
|---|---|---|---|
| Basic | Input | 10,000 | π¦ |
| HRA | 10,000 * 0.15 | 1,500 | π |
| DA | 10,000 * 0.50 | 5,000 | π² |
| PF | 10,000 * 0.12 | 1,200 | π‘οΈ |
| NET | (10k + 1.5k + 5k) - 1.2k | 15,300 | β |
π Complexity AnalysisΒΆ
- Time Complexity: \(O(1)\) - Math and single insertion are constant time operations. β±οΈ
- Space Complexity: \(O(1)\) - Only uses a fixed set of local variables. πΎ
π― Practice ProblemsΒΆ
Easy Level π’ΒΆ
- Add a "Special Bonus" of βΉ500 to the Net Pay if the Basic Salary is less than βΉ5,000.
Medium Level π‘ΒΆ
- Modify the block to print an error if the user enters a negative Basic Salary.
π‘ Interview Tip πΒΆ
"Interviewers often ask: 'Should calculations happen in the app or the database?' Answer: Business logic like tax is often safer in the database because it ensures all apps (Mobile, Web, Desktop) follow the exact same rules!"