# Strange Sorting/Updating Problem

**URL:** <https://forums.percona.com/t/strange-sorting-updating-problem/788>\
**Category:** Other MySQL® Questions\
**Created:** [June 4, 2008, 1:13pm UTC](https://forums.percona.com/t/strange-sorting-updating-problem/788 "2008-06-04T13:13:06Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Carsten\_H](https://avatars.discourse-cdn.com/v4/letter/c/d26b3c/32.png) [@Carsten\_H](https://forums.percona.com/u/Carsten_H)\
**Post date:** [June 4, 2008, 1:13pm UTC](https://forums.percona.com/t/strange-sorting-updating-problem/788/1 "2008-06-04T13:13:06Z")

</div>

Hello!

I’m using a mix of UPDATE and SELECT to pre-sort rows for a faster SELECT later on. This is my query:

SET @num = 0;UPDATE rel\_artist\_album LEFT JOIN ( SELECT raa.album\_id, CASE WHEN (a.is\_sampler = 0 AND a.is\_bootleg = 0 AND a.album\_fullength = 1 AND a.is\_movie = 0 AND a.is\_live = 0 AND a.is\_compilation = 0 AND a.is\_misc = 0) THEN 1 WHEN (a.is\_sampler = 0 AND a.is\_bootleg = 0 AND a.album\_fullength = 0 AND a.is\_movie = 0 AND a.is\_live = 0 AND a.is\_compilation = 0 AND a.is\_misc = 0) THEN 2 WHEN (a.is\_sampler = 0 AND a.is\_bootleg = 0 AND a.is\_movie = 1) THEN 3 WHEN (a.is\_sampler = 0 AND a.is\_bootleg = 0 AND a.is\_live = 1) THEN 4 WHEN (a.is\_sampler = 0 AND a.is\_bootleg = 0 AND a.is\_compilation = 1) THEN 5 WHEN (a.is\_sampler = 0 AND a.is\_bootleg = 0 AND a.is\_misc = 1) THEN 6 WHEN (a.is\_bootleg = 1) THEN 7 WHEN (a.album\_fullength = 1 AND a.is\_sampler = 1 AND a.is\_bootleg = 0) THEN 8 END AS sort\_col FROM rel\_artist\_album AS raa LEFT JOIN albums AS a ON raa.album\_id = a.album\_id WHERE raa.artist\_id = 541 ORDER BY sort\_col ASC, IF (a.is\_sampler = 1, a.album\_name, a.album\_year) ASC, a.album\_name ASC) AS oai ON oai.album\_id = rel\_artist\_album.album\_id SET rel\_artist\_album.album\_order = @num := @num +1 WHERE rel\_artist\_album.album\_id = oai.album\_id AND rel\_artist\_album.artist\_id = 541;

In most cases everything will be sorted right. But sometimes, if there are only very few rows to sort, the sorting goes wrong. If I take only the inner SELECT the value generated by the CASE is okay, but the UPDATE sorts the rows the other way.

Lets say, I have three rows and the inner SELECT sorts them like this (ID - sort\_col value):

1. 7825 - 1
2. 7826 - 1
3. 7824 - 2

But after the UPDATE the rows are ordered like this:

1. 7824
2. 7825
3. 7826

Is there anyone who faced a similar problem?
