Sie sind auf Seite 1von 7

CASE is a very important in plsql and can be used very efficiently to

implement various business logics.

CASE expression with Aggregate functions


CASE expressions outside the SELECT list.

And you can even use it to order the results conditionally

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'

WHEN 'SYSTEM' THEN 'The owner is SYSTEM'

ELSE 'The owner is another value'

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

WHEN owner='SYS' THEN 'The owner is SYS'

WHEN owner='SYSTEM' THEN 'The owner is SYSTEM'

ELSE 'The owner is another value'

END

FROM all_tables;

Note:- Can you create a CASE statement that evaluates more then two different fields.

SELECT

empid,

CASE

WHEN LENGTH(name)>3 and name='sudhir' and empid=2 and dep_id=20

THEN name

ELSE 'No Name'

END "cooect myname"

FROM

employee;
select * from Employee;

EMPID, HIRE_DATE, NAME, DEP_ID

8 22-MAR-99 khusbu 20

7 23-APR-55 dkfdf 21

1 23-SEP-12 ramk 20

4 13-NOV-13 ram kumar 21

2 24-SEP-12 sudhir 20

1. Simple Case

SELECT

empid,

CASE

WHEN LENGTH(name)>4

THEN name

ELSE 'No Name'

END "cooect myname"

FROM

Employee;

--Output

8 khusbu
7 dkfdf

1 No Name

4 ram kumar

2 sudhir

2. Nested case mean case within another case

SELECT

empid,

CASE

WHEN LENGTH(name)>4 then

case

when name='sudhir' then

'sudhir kalu'

end

ELSE 'No Name'

END "cooect myname" or END as cooectmyname or END cooectmyname—without space

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

THEN DECODE(name,'sudhir','sudhir kalu','ramk','ramkalu')

ELSE 'No Name'

END "cooect myname"

FROM

employee;

8 null

7 null

1 ramkalu

4 null

2 sudhir kalu

A good example of using case in query-


SELECT department_id, COUNT(

CASE TO_CHAR(hire_date, 'YYYY')

WHEN '2014' THEN 1

END) AS "2014", COUNT(

CASE TO_CHAR(hire_date, 'YYYY')

WHEN '2015' THEN 1

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

when 100 then 'Ram'

when 101 then 'kumar'

end) name

from employees;

Das könnte Ihnen auch gefallen