Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP MySQL Order By keyword


May 11, 2021 PHP


Table of contents


PHP MySQL Order By Keywords

You can sort the set of records in the MySQL database, read this section.

ORDER BY keywords are used to sort data in a record set.


ORDER BY keywords

ORDER BY keywords are used to sort data in a record set.

ORDER BY keywords sort records in ascending order by default.

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

Grammar

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

To learn more about SQL, visit our SQL tutorial.

Instance

The following example picks up all the data stored in the Persons table and sorts the results according to the Age column:

<?php
 $con=mysqli_connect("example.com","peter","abc123","my_db");
 // Check connection
 if (mysqli_connect_errno())
 {
 echo "Failed to connect to MySQL: " . 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 results will output:

Glenn Quagmire 33
Peter Griffin 35



Sort by two columns

You can sort by more than one column. When sorted by more than one column, the second column is used only if the values of the first column are the same:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2