MySQL : ORDER BY Keyword

In MySQL, the ORDER BY keyword is used to sort the result set returned by a SELECT statement based on one or more columns. It allows you to specify the order in which rows should appear in the result set. Here's how the ORDER BY keyword is used:


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

 

Where:

  • column1, column2, etc. are the names of the columns you want to retrieve.
  • table_name is the name of the table from which you want to retrieve data.
  • ORDER BY specifies the sorting order.
  • ASC specifies ascending order (default if not specified).
  • DESC specifies descending order.

You can specify multiple columns in the ORDER BY clause to sort the result set by multiple columns. Rows are sorted based on the first column specified, and if there are ties, they are then sorted based on the second column, and so on.

Here are some examples:

1. Sorting by a Single Column:

SELECT * FROM employees ORDER BY last_name;

This query will retrieve records from the employees table and sort them in ascending order based on the last_name column.

2. Sorting by Multiple Columns:

SELECT * FROM employees ORDER BY department, salary DESC;

This query will retrieve records from the employees table and sort them first by department in ascending order, and then by salary in descending order within each department.

3. Sorting by Expression:

SELECT * FROM products ORDER BY price * quantity DESC;

This query will retrieve records from the products table and sort them based on the result of the expression price * quantity in descending order.

The ORDER BY keyword is a powerful tool for organizing the results of your queries in MySQL. It allows you to control the presentation of your data based on specific criteria.