Search code examples
mysqlperformancedatabase-performancequery-performance

Combine 2 update querys in a single query - performance


Im programming a favourite function.

For example we have multiple adresses and can choose one as favourite.

At the moment i got 2 querys to do this job:

UPDATE userdata
SET maindata = 0
WHERE 
cid = :id;

UPDATE userdata
SET maindata = 1
WHERE 
cid = :id AND id = :id2
LIMIT 1

In the first query i make all adresses as "no favourite" and in the second one i make the new choosen adress the favourite one.

Is there any way to imrpove this query or rewrite both into 1 ? Or even a better solution ?


Solution

  • If you want a single query you could use a case when (or an if)

    update  userdata 
    set maindate = case when id = :id2 then 1 
                    else 0 end 
    where  cid = :id;
    

    for performance Be sure you have a proper index on userdata columns (cid, id)

    and the number of rows scanned should be the same for the first wuary ..but in this way you avoid the second ..

    eventually try create a composite index

     create index myidx1 on userdata(cid, id)