Easy Tutorial
❮ Func Error User Error Func Cal Jdtogregorian ❯

PHP MySQL Order By Keyword


The ORDER BY keyword is used to sort the data in a record set.


ORDER BY Keyword

The ORDER BY keyword is used to sort the data in a record set.

The ORDER BY keyword sorts the records in ascending order by default.

If you want to sort the records in descending order, use the DESC keyword.

Syntax

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

To learn more about SQL, visit our SQL Tutorial.

Example

The following example selects all data stored in the "Persons" table and sorts the result by the "Age" column:

<?php
$con=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");

while($row = mysqli_fetch_array($result))
{
    echo $row['FirstName'];
    echo " " . $row['LastName'];
    echo " " . $row['Age'];
    echo "<br>";
}

mysqli_close($con);
?>

The above result will output:

Glenn Quagmire 33
Peter Griffin 35

Sorting by Two Columns

You can sort by multiple columns. When sorting by multiple columns, the second column is only used if the values of the first column are the same:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
❮ Func Error User Error Func Cal Jdtogregorian ❯