Sorting Result Sets


# Get a list of alphabetically sorted book names SELECT title FROM book ORDER BY title; # Sort alphabetically but with an exception SELECT name FROM status   ORDER BY name='default' DESC, name; 



When you fetch rows from MySQL, they are returned to you in a haphazard order that might or might not fit your needs. Thankfully, MySQL allows you to specify in which order the rows should be returned.

The order is specified using the ORDER BY clause. The clause accepts a list of one or more expressions (which can just be column names). For every row, the expressions in the ORDER BY clause are evaluated. Then the resulting values are put into a list that is then sorted. The rows are then returned according to this order.

Sound complex? Here is a simplified version of the steps laid out for you:

  1. A query is sent to the server, like so:

    SELECT * FROM book ORDER BY title;

  2. For every row that is returned, the appropriate value of the title column is put into a list, like the following:

    Green Eggs and Ham (Row 1) In the Night Kitchen (Row 2) How to Be a Grouch (Row 3) Jacob Two-Two Meets the Hooded Fang (Row 4) 

    Additionally, the server knows to which row the title corresponds.

  3. The list is sorted alphabetically and is not case-sensitive, but you can specify other types of sorting, if you want:

    Green Eggs and Ham (Row 1) How to Be a Grouch (Row 3) In the Night Kitchen (Row 2) Jacob Two-Two Meets the Hooded Fang (Row 4) 

  4. The rows are returned in the same order as the sorted list.



MySQL Phrasebook. Essential Code and Commands
MySQL Phrasebook
ISBN: 0672328399
EAN: 2147483647
Year: 2003
Pages: 130

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net