The MySQL ORDER BY clause allows you to sort the records in the result set.



The ORDER BY Keyword

Syntax:

SELECT column_name()
FROM table_name
ORDER BY column_name() ASC or DESC

The following example selects all the data stored in the "employee" table, and sorts the result by the "salary" column:

Example:

<?php
// Database connection establishment
    $con=mysqli_connect("example.com","alex","qwerty","db_name");
    
// Check connection
if (mysqli_connect_errno($con)) {
    echo "MySQL database connection failed: " . mysqli_connect_error();
}


$query = mysqli_query($con,"SELECT * FROM employee ORDER BY salary");    

while($row = mysqli_fetch_array($query)) {
    echo $row["FirstName"]." ".$row["LastName"]." ".$row["salary"]."<br>";
}
?>

Program Output:

FirstName LastName Salary
David Crosby 9000
Neha Dutta 7000
  • The ORDER BY keyword sort the records in ascending order by default.
  • If you want to sort the records in descending order, you can use the DESC keyword.
  • It is also possible to order by more than one column.


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram