The ORDER BY
clause is used with the SELECT
statement to retrieve data from a table sorted by a specific field. It allows you to specify the field name to sort by and the sort direction, either ascending (ASC
) or descending (DESC
).
The basic syntax of the ORDER BY
clause is:
Let's create a SQL query using the ORDER BY
clause in a SELECT
statement. We will then execute this query by passing it to the PHP mysqli_query()
function to retrieve the sorted data. Consider the following persons table inside the demo database:
+----+------------+-----------+----------------------+ | id | first_name | last_name | email | +----+------------+-----------+----------------------+ | 1 | Peter | Parker | peterparker@mail.com | | 2 | John | Rambo | johnrambo@mail.com | | 3 | Clark | Kent | clarkkent@mail.com | | 4 | John | Carter | johncarter@mail.com | | 5 | Harry | Potter | harrypotter@mail.com | +----+------------+-----------+----------------------+
The PHP code below retrieves all records from the persons table and sorts them based on the first_name column in ascending alphabetical order.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution with order by clause
$sql = "SELECT * FROM persons ORDER BY first_name";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After ordering the results, the dataset will appear as follows:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email |
+----+------------+-----------+----------------------+
| 3 | Clark | Kent | clarkkent@mail.com |
| 5 | Harry | Potter | harrypotter@mail.com |
| 2 | John | Rambo | johnrambo@mail.com |
| 4 | John | Carter | johncarter@mail.com |
| 1 | Peter | Parker | peterparker@mail.com |
+----+------------+-----------+----------------------+
Tip: By default, the ORDER BY
clause sorts results in ascending order. To sort records in descending order, use the DESC
keyword.