Order By Puzzle

From a question on Freenode.

SELECT * FROM theTable;
+----+----------+
| id | data     |
+----+----------+
|  1 | middle   |
|  2 | first    |
|  3 | showLast |
+----+----------+

Fair enough. Let’s order it by `data`.

SELECT * FROM theTable ORDER BY data;
+----+----------+
| id | data     |
+----+----------+
|  3 | showLast |
|  1 | middle   |
|  2 | first    |
+----+----------+

What??? Maybe the server didn’t quite understand.

SELECT * FROM theTable ORDER BY data ASC;
+----+----------+
| id | data     |
+----+----------+
|  3 | showLast |
|  1 | middle   |
|  2 | first    |
+----+----------+

How did that happen? I assure you I have not switched to some ‘reverse order’ collation.

SHOW CREATE TABLE theTable;
CREATE TABLE `thetable` (
  `id` int(11),
  `data` enum('showLast','middle','first')
)

Ah. `data` is an enum. ORDER BY on an enum orders by the enum index, not the string. You can order by CONCAT(data) or by CAST(data AS char). Are there better ways?

Comments

5 responses to “Order By Puzzle”

  1. Ronald Bradford Avatar

    One good reason not to use SET and ENUM, besides the point that the data requires DML statements and security to manage.

    I must admit, when I read your post I was initally stumped.

  2. Jay Pipes Avatar

    I was stumped too. Just one of many reasons why not to use ENUM/SET… :)

  3. Scott Noyes Avatar
    Scott Noyes

    There may be good reasons not to use ENUM, but this behavior isn’t one of them.

    Ronald, you claim that if you don’t know your data, you can’t make good design decisions about your database*. Surely the converse is true – if you don’t know your database, you have no business writing queries against it. That’s the job of an application that knows all about the structure and can properly escape and validate and convert and order results. Otherwise, we force our nice declarative SQL back into a procedural paradigm.

    One thing I do know is that PROCEDURE ANALYSE() sure is fond of enums.

    *http://blog.arabx.com.au/?p=310

  4. Enigme en mysql

    L’énigme en français

  5. […] short gotchas with MySQL stuff this week: the first, a sneaky ORDER BY quiz; the second involving an auto_increment puzzle. Go and see if you need to click his “Show Answer” […]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.