SQL Decision Logic (CASE & EXISTS) π§ ΒΆ
Prerequisites: Logical Operators, Subqueries
Mentor's Note: SQL isn't just for fetching data; it's for making decisions. The
CASEstatement is your SQL "If-Else", andEXISTSis the most efficient way to ask, "Is there someone in the other room?" π‘
π The Scenario: The VIP Upgrade πΒΆ
Imagine you are managing an airline database.
- CASE (If-Else): "IF a passenger has flown > 50 times, mark them as 'VIP'. ELSE, mark them as 'Regular'." β
- EXISTS (The Check): "Only show flights that EXIST in the boarding gate schedule." β
π» 1. The CASE Statement (The Decision Maker)ΒΆ
You can use CASE inside a SELECT statement to create custom labels based on data.
-- Scenario: Categorize salaries into levels
SELECT
emp_name,
salary,
CASE
WHEN salary >= 80000 THEN 'High Earner π°'
WHEN salary >= 40000 THEN 'Mid Level β¨'
ELSE 'Junior π'
END AS Pay_Grade
FROM employees;
π» 2. The EXISTS Operator (The Presence Check)ΒΆ
EXISTS is used to check if a subquery returns any result. It is incredibly fast because it stops looking as soon as it finds one match.
-- Scenario: Find departments that have at least one employee
SELECT dept_name
FROM departments D
WHERE EXISTS (
SELECT 1
FROM employees E
WHERE E.dept_id = D.id
);
π¨ Visual Logic: The FlowΒΆ
graph TD
A[Start Row] --> B{Salary >= 80k?}
B -- Yes --> C[Label: VIP]
B -- No --> D{Salary >= 40k?}
D -- Yes --> E[Label: Mid]
D -- No --> F[Label: Junior]
π Comparison: EXISTS vs INΒΆ
Which one should you use?
| Feature | IN Operator | EXISTS Operator |
|---|---|---|
| Best For | Small, hardcoded lists | Large tables/subqueries |
| Execution | Fetches all IDs first | Stops at 1st match (Fast!) β‘ |
| Logic | Checks value equality | Checks if record exists |
π‘ Pro TipΒΆ
"In modern databases like Oracle or PostgreSQL,
EXISTSis often faster thanINfor complex subqueries because it doesn't build a massive list of IDs in memory before checking them."