Case Statement
Case Statement
1. Different ways to write CASE statement(ELSE clause within the CASE statement is optional)
You could use the CASE statement in a SQL statement as follows: (includes the expression clause)
SELECT table_name,
CASE owner
WHEN 'SYS' THEN 'The owner is SYS'
END
FROM all_tables;
Or you could write the SQL statement using the CASE statement like this: (omits the expression clause)
SELECT table_name,
CASE
END
FROM all_tables;
Note:- Can you create a CASE statement that evaluates more then two different fields.
SELECT
empid,
CASE
THEN name
FROM
employee;
select * from Employee;
8 22-MAR-99 khusbu 20
7 23-APR-55 dkfdf 21
1 23-SEP-12 ramk 20
2 24-SEP-12 sudhir 20
1. Simple Case
SELECT
empid,
CASE
WHEN LENGTH(name)>4
THEN name
FROM
Employee;
--Output
8 khusbu
7 dkfdf
1 No Name
4 ram kumar
2 sudhir
SELECT
empid,
CASE
case
'sudhir kalu'
end
FROM
employee;
8 null
7 null
1 No Name
4 null
2 sudhir kalu
3. We can’t use IF THEN ELSE for condition check in CASE instead use DECODE function as
SELECT
empid,
CASE
WHEN LENGTH(name)>3
FROM
employee;
8 null
7 null
1 ramkalu
4 null
2 sudhir kalu
END) AS "2015"
FROM employees
GROUP BY department_id
ORDER BY department_id;
Note:- A very strange thing found here while using CASE. If we use for naming the case column as
number like 2015 then have to put in “” “” like “2015” else will give error. But in string nothing have to
give and it works as below
select
(case employee_id
end) name
from employees;