mysql
  1. mysql-order-by

ORDER BY - MySQL Clauses

In MySQL, the ORDER BY clause is used to sort the result set in ascending or descending order based on one or more columns.

Syntax

The syntax for the ORDER BY clause is as follows:

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

In this syntax, column1, column2, etc. are the columns to be selected from the table, table_name is the name of the table, condition is the filter condition (optional), and ASC or DESC denotes the order of sorting (ascending or descending).

Example

Consider the following example:

SELECT name, age, city
FROM customers
WHERE age > 25
ORDER BY age DESC, city ASC;

This query selects the names, ages, and cities of customers whose age is greater than 25. The result set is sorted in descending order of age and ascending order of city.

Output

The output of the above example may look something like this:

+--------+-----+--------------+
| name   | age | city         |
+--------+-----+--------------+
| John   | 50  | Los Angeles |
| Alice  | 30  | New York     |
| Bob    | 28  | New York     |
| David  | 28  | San Francisco|
+--------+-----+--------------+

Explanation

In the example above, we used the ORDER BY clause to sort the result set based on the age and city columns. The DESC keyword is used to sort the age column in descending order, while the ASC keyword is used to sort the city column in ascending order.

Use

The ORDER BY clause is useful when you want to sort the result set based on one or more columns in a specific order. You can sort the result set by a single column or multiple columns, and you can specify the order of sorting as either ASC or DESC.

Important Points

  • The ORDER BY clause is always the last clause in a SQL statement.
  • You can sort the result set based on a single column or multiple columns by separating the column names with commas.
  • By default, the sorting order is ascending. You can specify a descending order by using the DESC keyword.

Summary

In this tutorial, we discussed the ORDER BY clause in MySQL. We covered the syntax, example, output, explanation, use, and important points of the ORDER BY clause. You can use the ORDER BY clause to sort the result set based on one or more columns in a specific order.

Published on: