# using case in order by clause causes sort by character instead of integer

**URL:** <https://forums.percona.com/t/using-case-in-order-by-clause-causes-sort-by-character-instead-of-integer/1588>\
**Category:** Other MySQL® Questions\
**Created:** [January 4, 2011, 10:11am UTC](https://forums.percona.com/t/using-case-in-order-by-clause-causes-sort-by-character-instead-of-integer/1588 "2011-01-04T10:11:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![iberkner](https://avatars.discourse-cdn.com/v4/letter/i/c67d28/32.png) [@iberkner](https://forums.percona.com/u/iberkner)\
**Post date:** [January 4, 2011, 10:11am UTC](https://forums.percona.com/t/using-case-in-order-by-clause-causes-sort-by-character-instead-of-integer/1588/1 "2011-01-04T10:11:49Z")

</div>

We recently updated some code in which we use a “case” statement within an order clause, as follows:

order by  
case d.wo  
when ‘e’ then a.location  
when ‘a’ then c.w  
when ‘r’ then RAND()  
end asc";

where a.location is a tinyint.

Sorting directly by a.location works fine, values are sorted correctly, i.e. 1…9,10,11… etc.

Using the case statement as above, treats “a.location” as a character and causes the sort order to change, i.e. 1,10,11,2,3…9 etc.

I tried forcing a cast in the case statement on a.location but that did not work. Any suggestions? is this a bug?

---

<div class="post-metadata">

**Author:** ![xaprb](https://avatars.discourse-cdn.com/v4/letter/x/49beb7/32.png) [@xaprb](https://forums.percona.com/u/xaprb)\
**Post date:** [January 4, 2011, 10:18am UTC](https://forums.percona.com/t/using-case-in-order-by-clause-causes-sort-by-character-instead-of-integer/1588/2 "2011-01-04T10:18:47Z")

</div>

What is the type of c.w?

---

<div class="post-metadata">

**Author:** ![iberkner](https://avatars.discourse-cdn.com/v4/letter/i/c67d28/32.png) [@iberkner](https://forums.percona.com/u/iberkner)\
**Post date:** [January 4, 2011, 10:29am UTC](https://forums.percona.com/t/using-case-in-order-by-clause-causes-sort-by-character-instead-of-integer/1588/3 "2011-01-04T10:29:33Z")

</div>

varchar
