MySQL Order By

PHP MySQL ORDER BY

When you retrieve data from a database, the rows are returned in the order they were stored. To sort the result-set, you use the ORDER BY clause.


Sorting Results

The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, you use the DESC keyword.

ORDER BY Example

<?php
// Database connection code omitted...

// Select all users and sort them alphabetically by their lastname $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname ASC"; $result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>"; } } else { echo "0 results"; } ?>

Use Cases:


Exercise

?

Which keyword is used to reverse the default sorting order (from highest to lowest)?