alice_schizoid
alice_schizoid

Reputation: 33

count function inside case statement

Problem statement:

If the number of courses an instructor teaches is less than 1 then update the salary to 30000 else to 35000 - using one command. The code I wrote results in an error, could you please tell why it's not working and how I can improve it. Thanks in advance :D

UPDATE using oracle sql

schema:

instructor -> id, name, dept_name, salary

teaches -> id, course_id, semester, year

update i
set i.salary = case
when count(t.course_id) < 1 then 30000
else 35000
from (select * from instructor i inner join teaches t on i.id = t.id)  

Upvotes: 3

Views: 250

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1270713

I wouldn't recommend count(*) in the subquery. count(*) < 1 is really saying that no row exists. You are using an aggregation when exists is appropriate -- and that is a performance hit.

So a better approach is:

update instructor i
     set salary = (select case when exists (select 1 from teaches t where t.id_instructor = i.id_instructor)
                          then 30000 else 35000
                   end);

If you are learning SQL, you should be learning the best way to do things.

Upvotes: 1

Prabhath Amaradasa
Prabhath Amaradasa

Reputation: 503

update i
set i.salary = (case when t.id  IS NULL  then 30000 else 35000 END)
from  instructor i
LEFT OUTER  join teaches t on i.id = t.id

Upvotes: 0

Littlefoot
Littlefoot

Reputation: 143023

Here's an example; I created my own tables (as you didn't provided yours), I hope it'll make sense.

SQL> create table instructor (id_instructor number, salary number);

Table created.

SQL> insert into instructor values (1, 100);

1 row created.

SQL> insert into instructor values (2, 100);

1 row created.

SQL>
SQL> create table teaches (id_instructor number, id_course number);

Table created.

SQL> insert into teaches values (1, 1);

1 row created.

SQL> insert into teaches values (1, 2);

1 row created.

SQL>

As teacher ID = 2 teaches "nothing", his salary should be 30000. On the other hand, teacher ID = 2 teaches 2 classes so he'll get 35000.

SQL> update instructor i set
  2    i.salary = (select case when count(*) < 1 then 30000
  3                            else 35000
  4                       end
  5                from teaches t
  6                where t.id_instructor = i.id_instructor);

2 rows updated.

SQL> select * from instructor;

ID_INSTRUCTOR     SALARY
------------- ----------
            1      35000
            2      30000

SQL>

Upvotes: 1

Related Questions