English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP MySQL ORDER BY

In this tutorial, you will learn how to sort and display data in MySQL tables in ascending or descending order using PHP.

Result Set Sorting

ORDER BYThe clause can be combined withSELECTThe statements can be combined to view data in a table sorted by a specific field. The ORDER BY clause allows you to define the field name for sorting and the direction of ascending or descending order.

The basic syntax of this clause can be given in the following way:

SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

Let's use the ORDER BY clause in the SELECT statement to perform an SQL query, and then we will execute the query by passing it to the PHP mysqli_query() function to obtain sorted data. Consider the following persons table in the demonstration database:

+----+------------+-----------+----------------------+
| id | first_name | last_name | email |
+----+------------+-----------+----------------------+
|  1 | Peter | Parker | [email protected] |
|  2 | John | Rambo | [email protected] |
|  3 | Clark | Kent | [email protected] |
|  4 | John | Carter | [email protected] |
|  5 | Harry | Potter | [email protected] |
+----+------------+-----------+----------------------+

The following PHP code selects all rows from the persons table,first_nameThe results are sorted in alphabetical order by column.

Example: Procedural Approach

<?php
/* Attempt to connect to the MySQL server. Assume you are running MySQL.
Server with default settings (user 'root' without password) */
$link = mysqli_connect("localhost", "root", "", "demo");
 
//Check connection
if($link === false){
    die("Error: Unable to connect. " . mysqli_connect_error());
}
 
//Attempt to execute SELECT query using 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 the result set
        mysqli_free_result($result);
    } else{
        echo "No records found matching your query.";
    }
} else{
    echo "Error: Unable to execute $sql. " . mysqli_error($link);
}
 
//Close the connection
mysqli_close($link);
?>

Example: Object-oriented method

<?php
/* Attempt to connect to the MySQL server. Assume you are running MySQL.
Server with default settings (user 'root' without password) */
$mysqli = new mysqli("localhost", "root", "", "demo");
 
//Check connection
if($mysqli === false){
    die("Error: Unable to connect. " . $mysqli->connect_error);
}
 
//Attempt to select and execute the query with ORDER BY clause
$sql = "SELECT * FROM persons ORDER BY first_name";
if($result = $mysqli->query($sql)){
    if($result->num_rows > 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 = $result->fetch_array()){
            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>";
        // Release the result set
        $result->free();
    } else{
        echo "No records found matching your query.";
    }
} else{
    echo "Error: Unable to execute $sql. " . $mysqli->error;
}
 
//Close the connection
$mysqli->close();
?>

Example: PDO method

<?php
/* Attempt to connect to the MySQL server. Assume you are running MySQL.
Server with default settings (user 'root' without password) */
try{
    $pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
    //Set PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("Error: Unable to connect. " . $e->getMessage());
}
 
//Attempt to select and execute the query
try{
    $sql = "SELECT * FROM persons ORDER BY first_name";
    $result = $pdo->query($sql);
    if($result->rowCount() > 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 = $result->fetch()){
            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>";
        //Release the result set
        unset($result);
    } else{
        echo "No records found matching your query.";
    }
} catch(PDOException $e){
    die("Error: Unable to execute $sql. ". $e->getMessage());
}
 
//Close the connection
unset($pdo);
?>

After sorting the results, the result set will look like this:

+----+------------+-----------+----------------------+
| id | first_name | last_name | email |
+----+------------+-----------+----------------------+
|  3 | Clark | Kent | [email protected] |
|  5 | Harry | Potter | [email protected] |
|  2 | John | Rambo | [email protected] |
|  4 | John | Carter | [email protected] |
|  1 | Peter | Parker | [email protected] |
+----+------------+-----------+----------------------+

Tip:By default, the ORDER BY clause sorts the results in ascending order. To sort the records in descending order, you can use the DESC keyword.