Order By Clause in MySQL
In this tutorial, we will explore the ORDER BY
clause in MySQL. The ORDER BY
clause is used in SQL to sort the results in ascending or descending order. It sorts the records in a result set based on one or more columns.
Understanding the ORDER BY Clause
The ORDER BY
clause can be used in select statements, update, insert, or delete statements. In select statements, the ORDER BY
clause is used after the WHERE
clause. Here is the basic syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Here, ASC
denotes ascending and DESC
denotes descending order. If you don't specify, ASC
is taken as default.
How to Use the ORDER BY Clause
Let's take a look at some examples to understand how it works. Suppose we have a table Employees
with the following data:
ID | Name | Age | City |
---|---|---|---|
1 | John | 33 | New York |
2 | Sara | 28 | Los Angeles |
3 | David | 45 | Houston |
4 | Alice | 30 | Seattle |
If we want to order the data by Age
, we can do the following:
SELECT * FROM Employees ORDER BY Age;
This will return the data sorted by Age
in ascending order:
ID | Name | Age | City |
---|---|---|---|
2 | Sara | 28 | Los Angeles |
4 | Alice | 30 | Seattle |
1 | John | 33 | New York |
3 | David | 45 | Houston |
If you want to sort the data in descending order, you can use DESC
:
SELECT * FROM Employees ORDER BY Age DESC;
This will return:
ID | Name | Age | City |
---|---|---|---|
3 | David | 45 | Houston |
1 | John | 33 | New York |
4 | Alice | 30 | Seattle |
2 | Sara | 28 | Los Angeles |
Sorting by Multiple Columns
You can also sort the results by multiple columns. For example, you can sort the Employees
table first by Age
and then by Name
:
SELECT * FROM Employees ORDER BY Age, Name;
This will return:
ID | Name | Age | City |
---|---|---|---|
2 | Sara | 28 | Los Angeles |
4 | Alice | 30 | Seattle |
1 | John | 33 | New York |
3 | David | 45 | Houston |
Conclusion
The ORDER BY
clause is a powerful tool in MySQL that allows you to sort your results based on the values in one or more columns. This can make your data more meaningful and easier to understand. Always remember to place the ORDER BY
clause at the end of your query to ensure that it operates on the final result set. It's also important to note that the ORDER BY
clause can cause your queries to run more slowly, especially on large tables, so use it judiciously.