Update with Case When you need to where?

10
UPDATE bethadba.FOFILHOS

SET CPF = CASE

WHEN CODI_EMP = 61  AND I_EMPREGADOS = 156  AND i_filhos = 1 THEN '00551366133'
WHEN CODI_EMP = 57  AND I_EMPREGADOS = 290  AND i_filhos = 1 THEN '00636170993'
WHEN CODI_EMP = 61  AND I_EMPREGADOS = 333  AND i_filhos = 2 THEN '01056262958'

END

COMMIT

I have developed this SQL to insert some CPF numbers in the registry of some dependents, as far as I know, it is not necessary to put the WHERE because inside the WHEN already specifies where to update the lines.

A coworker figured out that if it works that way it will hurt and buggy all dependents, I told him I would not brag.

Can anyone tell me for sure whether or not to have WHERE?

Bank: Sybase SQL Anywhere 16.

    
asked by anonymous 11.06.2018 / 19:20

2 answers

5

Considering a generic table, what is the difference between

Update tabela set campo= case when id=1 then 'abc' end

and

Update set campo='abc' where id=1

?

In terms of the result of the operation, none. The two code structures will update campo when id equals 1.

In terms of performance, the structure with case is much slower than the structure with where .

A update will first create a recordset using as a criterion the expression defined in where , before proceeding with the update itself. A update without where applies the change to all records in the table.

See an example of 5000 lines in PostgreSQL running in SQL Fiddle Example 1

update tabela set campo=555 where id =1000;

As an execution plan you can see:

QUERY PLAN
Update on tabela (cost=0.28..8.30 rows=1 width=14)
-> Index Scan using tabela_pkey on tabela (cost=0.28..8.30 rows=1 width=14)
Index Cond: (id = 1000)

Now with case ,

Example 2

update tabela set campo=case when  id =1000 then 555 end;

Execution Plan:

QUERY PLAN
Update on tabela (cost=0.00..85.50 rows=5000 width=14)
-> Seq Scan on tabela (cost=0.00..85.50 rows=5000 width=14)

Note that in the first case an Index Scan was used and in the second case a Seq Scan is done.

We can also note that in the first case the query is applied on 1 register (rows=1) , while the second is on 5000 (rows=5000) registers.

Another factor is danger to perform an improper upgrade.

Maybe not your case, but just to explain why this technique is dangerous, imagine this situation:

Example 3

update tabela set campo=case when  id =1000 then 555 else 0 end;

Congratulations! You successfully updated the id 1000 and toast you gained the update of the other 4999 records with the value zero.

    
27.07.2018 / 16:57
3

At first it will have no impact, unless there are other FOFILHOS with those conditions. But if CODI_EMP is used as ID , do this UPDATE using WHERE , we usually use WHEN to update more than one line and from what I saw you want to reach those 3 only, so make a WHERE for each line.

    
11.06.2018 / 19:35