Sub topic 9
Using CASE in SELECT, WHERE, ORDER BY, GROUP BY and UPDATE
Assume you know basic SELECT, WHERE, ORDER BY, GROUP BY, aggregate functions, and Oracle data types such as NUMBER, VARCHAR2, and DATE. A CASE expression returns one value chosen from several alternatives. You can place it wherever an SQL expression is allowed.
CASE in SELECT
Use CASE in the select list to calculate a label or derived value for each row.
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees;Oracle evaluates the WHEN conditions from top to bottom. It returns the result for the first true condition. Therefore, the order matters. A salary of 12000 skips the first two conditions and returns High.
A simple CASE is useful when one expression is compared with fixed values:
SELECT employee_id,
CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
WHEN 50 THEN 'Shipping'
ELSE 'Other'
END AS department_label
FROM employees;CASE in WHERE
A CASE expression in WHERE must produce a value that the condition can compare. It does not directly return a complete condition.
SELECT employee_id, salary
FROM employees
WHERE CASE
WHEN salary >= 10000 THEN 1
ELSE 0
END = 1;This is equivalent to WHERE salary >= 10000. In real queries, use the direct condition when it is clear. Use CASE when the returned value depends on several rules.
CASE in ORDER BY
CASE can define a business order instead of the default alphabetical or numeric order.
SELECT employee_id, job_id
FROM employees
ORDER BY CASE job_id
WHEN 'AD_PRES' THEN 1
WHEN 'AD_VP' THEN 2
ELSE 3
END,
employee_id;Presidents appear first, vice presidents next, and all other jobs follow. The second sort key breaks ties.
CASE in GROUP BY
The expression in the GROUP BY clause creates the groups. Repeat the expression there rather than relying on its select-list alias.
SELECT CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band,
COUNT(*) AS employee_count
FROM employees
GROUP BY CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END
ORDER BY salary_band;Each salary band becomes one group. The COUNT(*) reports the number of employees in each group.
CASE in UPDATE
In an UPDATE, CASE can assign different values in one statement.
UPDATE employees
SET salary = CASE
WHEN salary < 5000 THEN salary * 1.10
WHEN salary < 10000 THEN salary * 1.05
ELSE salary
END
WHERE department_id = 50;The WHERE clause limits the affected rows. The ELSE salary branch preserves salaries outside the defined bands. Review the result before committing a real update.
Exercise
Write a query that counts employees with salaries of at least 10000 and employees below 10000 for each department.
Show answer
SELECT departmentid, SUM(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) AS highearners, SUM(CASE WHEN salary < 10000 THEN 1 ELSE 0 END) AS otherearners FROM employees GROUP BY departmentid;