Skip to main content

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:

IDNameAgeCity
1John33New York
2Sara28Los Angeles
3David45Houston
4Alice30Seattle

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:

IDNameAgeCity
2Sara28Los Angeles
4Alice30Seattle
1John33New York
3David45Houston

If you want to sort the data in descending order, you can use DESC:

SELECT * FROM Employees ORDER BY Age DESC;

This will return:

IDNameAgeCity
3David45Houston
1John33New York
4Alice30Seattle
2Sara28Los 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:

IDNameAgeCity
2Sara28Los Angeles
4Alice30Seattle
1John33New York
3David45Houston

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.