The ORDER BY keyword is used to sort data in a recordset.
The ORDER BY keyword is used to sort data in a recordset.
The ORDER BY keyword sorts records in ascending order by default.
If you want to sort in descending order, use the DESC keyword.
SELECT column_name(s)FROM table_nameORDER BY column_name(s) ASC|DESC
To learn more about SQL, visit our SQL tutorials.
The following example selects all data stored in the "Persons" table and sorts the results based on the "Age" column:
<?php$con=mysqli_connect("localhost","username","password","database");//Detect connection if (mysqli_connect_errno()){ echo "Connection failed: " . 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 33Peter Griffin 35
You can sort based on multiple columns. When sorting by multiple columns, the second column is used only if the first column has the same value:
SELECT column_name(s)FROM table_nameORDER BY column1, column2