PHP Order By
The ORDER BY
clause is used to sort the result set in ascending or descending order based on one or more columns.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...
Example
Consider a table named students
with columns name
, age
, and total_marks
. The following query retrieves the name and total marks of all the students sorted in descending order by their total marks:
SELECT name, total_marks
FROM students
ORDER BY total_marks DESC;
Output
The above query generates output in the following format:
+------+-------------+
| name | total_marks |
+------+-------------+
| John | 900 |
| Mary | 820 |
| Paul | 780 |
| Jane | 720 |
+------+-------------+
Explanation
In the above example, the ORDER BY
clause is used to sort the result set in descending order based on the total_marks
column.
Use
The ORDER BY
clause is used to sort the result set in ascending or descending order based on one or more columns. It is extensively used in applications where data needs to be displayed in a sorted order.
Important Points
- The
ORDER BY
clause should always be the last clause in a select statement. - The
ASC
keyword is optional because sorting in ascending order is the default behavior. - The
DESC
keyword is used to sort the result set in descending order.
Summary
The ORDER BY
clause is used to sort the result set in ascending or descending order based on one or more columns. It is a powerful tool that allows developers to retrieve data in a sorted order, which is essential in many applications.