How to Use the ORDER BY Keyword in MySQL

08/04/2021

Contents

In this article, you will learn how to use the ORDER BY keyword in MySQL.

Using the ORDER BY keyword in MySQL

The ORDER BY keyword in MySQL is used to sort the result set of a query in ascending or descending order based on one or more columns.

Syntax

The basic syntax of the ORDER BY keyword in MySQL is as follows:

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC;

In this syntax, column_name is the name of the column you want to sort the result set by, table_name is the name of the table, and ASC or DESC specifies the sort order, either ascending or descending.

Examples

Suppose we have a table called “employees” with columns “id”, “name”, and “salary”. We want to select all employees and sort them in descending order based on their salary.

SELECT name, salary
FROM employees
ORDER BY salary DESC;

And suppose we have a table called “products” with columns “id”, “name”, “price”, and “category”. We want to select all products and sort them in ascending order based on their price, and then by their name in ascending order.

SELECT name, price
FROM products
ORDER BY price ASC, name ASC;

In this example, the result set will be sorted in ascending order based on the “price” column first, and then by the “name” column in ascending order. The query will return the names and prices of all products, sorted by price and then by name.

Sorting by multiple columns

You can also sort the result set by multiple columns. Here is an example:

SELECT name, category, price
FROM products
ORDER BY category ASC, price DESC;

In this example, the result set will be sorted first by the “category” column in ascending order, and then by the “price” column in descending order. The query will return the names, categories, and prices of all products, sorted by category and then by price.

Sorting by expressions

You can also sort the result set by expressions. Here is an example:

SELECT name, price, price * 0.8 AS discounted_price
FROM products
ORDER BY price * 0.8 DESC;

In this example, the result set will be sorted based on the result of the expression price * 0.8. The query will return the names, prices, and discounted prices (which are calculated using the expression) of all products, sorted by the discounted price in descending order.

Limiting the result set

You can also limit the number of rows returned in the result set using the LIMIT keyword. Here is an example:

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 5;

In this example, the result set will be sorted in descending order based on the “price” column, and only the top 5 rows will be returned.