PHP PHP Tutorial PHP Forms PHP Advanced PHP OOP PHP MySQL Database PHP XML PHP - AJAX



PHP MySQL Order By

PHP MySQL Order By is a clause used in SQL statements to sort the result set in ascending or descending order based on one or more columns. It is used to organize the data in a more meaningful way and make it easier to read and analyze.

The syntax for using the Order By clause in MySQL is as follows:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

The Order By clause can be used with one or more columns. If multiple columns are used, the sorting is done based on the first column, and if there are any ties, the sorting is done based on the second column, and so on.

The ASC keyword is used to sort the result set in ascending order, and the DESC keyword is used to sort the result set in descending order.

Examples

Let's take a look at some examples of using the Order By clause in PHP MySQL:

Example 1: Sorting by a Single Column

In this example, we will sort the result set of a table called "employees" by the "last_name" column in ascending order:

SELECT first_name, last_name, salary
FROM employees
ORDER BY last_name ASC;

This will return a result set sorted by the "last_name" column in ascending order.

Example 2: Sorting by Multiple Columns

In this example, we will sort the result set of a table called "employees" by the "last_name" column in ascending order, and then by the "salary" column in descending order:

SELECT first_name, last_name, salary
FROM employees
ORDER BY last_name ASC, salary DESC;

This will return a result set sorted by the "last_name" column in ascending order, and then by the "salary" column in descending order.

Example 3: Sorting by a Calculated Column

In this example, we will sort the result set of a table called "employees" by a calculated column called "total_salary", which is the sum of the "salary" and "bonus" columns:

SELECT first_name, last_name, salary, bonus, (salary + bonus) AS total_salary
FROM employees
ORDER BY total_salary DESC;

This will return a result set sorted by the "total_salary" column in descending order.

Conclusion

PHP MySQL Order By is a powerful clause that allows you to sort the result set of a SQL query in ascending or descending order based on one or more columns. It is a useful tool for organizing data and making it easier to read and analyze.

References

Activity