MySQL ORDER BY
A tutorial on how to sort data outputted by a query.
Using the ORDER BY clause will allow you to sort your results any way you like. If you don't specify what order you want the output then it will most likely be sorted by whatever order they are in the database. Many times it will be sorted by the primary key in ascending order because that is usually the default setup of databases but not always. The ORDER BY clause sorts by ascending by default. If you want to specifiy descending then you can add 'DESC' after the column to be sorted by (example below). If you want to use the ORDER BY clause with the WHERE clause the ORDER BY clause will come after the WHERE clause. Also, you can specify secondary sorts if you want to sort by more than one criteria (example below). NULL values will appear first in the output with both ascending and descending sorts. Here is the syntax for a SELECT statement with a WHERE clause and an ORDER BY clause.
SELECT columns FROM tablename WHERE columnname = 'value' ORDER BY 'column'
SELECT columns FROM tablename WHERE columnname = 'value' ORDER BY 'column' DESC
The following examples will use the following database.
ORDER BY
MySQL Code
|
|
$query="SELECT firstname, lastname, age FROM users ORDER BY age";
| |
|
Results
|
|
| Martin |
Gross |
16 |
| John |
Smith |
17 |
| Eric |
Friedman |
27 |
| Brian |
Grossman |
31 |
| John |
Kennedy |
35 |
|
|
|
ORDER BY - DESCENDING
MySQL Code
|
|
$query="SELECT firstname, lastname, age FROM users ORDER BY age DESC";
| |
|
Results
|
|
| John |
Kennedy |
35 |
| Brian |
Grossman |
31 |
| Eric |
Friedman |
27 |
| John |
Smith |
17 |
| Martin |
Gross |
16 |
|
|
|
ORDER BY - multiple sorting
This example sorts first b first name and then by last name. You can see that there are two people named 'John' and that those two are then sorted by last name.
MySQL Code
|
|
$query="SELECT firstname, lastname, age FROM users ORDER BY firstname ASC, lastname ASC";
| |
|
Results
|
|
| Brian |
Grossman |
31 |
| Eric |
Friedman |
27 |
| John |
Kennedy |
35 |
| John |
Smith |
17 |
| Martin |
Gross |
16 |
|
|
|
WHERE query with ORDER BY clause
MySQL Code
|
|
$query="SELECT firstname, lastname, age FROM users WHERE age > '20' ORDER BY lastname ASC";
| |
|
Results
|
|
| Eric |
Friedman |
27 |
| Brian |
Grossman |
31 |
| John |
Kennedy |
35 |
|
|
|
Comments:
 |
please post comments
|
 |
admin November 21, 2006
|
|