Skip to Content
MySQL Cookbook, 2nd Edition
book

MySQL Cookbook, 2nd Edition

by Paul DuBois
November 2006
Intermediate to advanced
977 pages
30h 42m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook, 2nd Edition

Introduction

This chapter covers sorting, an operation that is extremely important for controlling how MySQL displays results from SELECT statements. Sorting is performed by adding an ORDER BY clause to a query. Without such a clause, MySQL is free to return rows in any order, so sorting helps bring order to disorder and makes query results easier to examine and understand. (Sorting is also performed implicitly when you use a GROUP BY clause, as discussed in Controlling Summary Display Order.)

You can sort rows of a query result several ways:

  • Using a single column, a combination of columns, or even parts of columns

  • Using ascending or descending order

  • Using the result of an expression

  • Using case-sensitive or case-insensitive string comparisons

  • Using temporal ordering

The driver_log table is used for several examples in this chapter; it contains columns for recording daily mileage logs for a set of truck drivers:

mysql>SELECT * FROM driver_log;
+--------+-------+------------+-------+
| rec_id | name  | trav_date  | miles |
+--------+-------+------------+-------+
|      1 | Ben   | 2006-08-30 |   152 |
|      2 | Suzi  | 2006-08-29 |   391 |
|      3 | Henry | 2006-08-29 |   300 |
|      4 | Henry | 2006-08-27 |    96 |
|      5 | Ben   | 2006-08-29 |   131 |
|      6 | Henry | 2006-08-26 |   115 |
|      7 | Suzi  | 2006-09-02 |   502 |
|      8 | Henry | 2006-09-01 |   197 |
|      9 | Ben   | 2006-09-02 |    79 |
|     10 | Henry | 2006-08-30 |   203 |
+--------+-------+------------+-------+

Many other examples use the mail table (used in earlier chapters):

mysql>SELECT ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Cookbook, 3rd Edition

MySQL Cookbook, 3rd Edition

Paul DuBois
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
MySQL Cookbook

MySQL Cookbook

Paul DuBois
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal

Publisher Resources

ISBN: 059652708XSupplemental ContentErrata Page