Home >Database >Mysql Tutorial >How to Perform Multi-Column Sorting in MySQL?

How to Perform Multi-Column Sorting in MySQL?

DDD
DDDOriginal
2024-12-31 14:16:16348browse

How to Perform Multi-Column Sorting in MySQL?

Multi-Column Sorting in MySQL

When working with MySQL databases, it is often necessary to sort data based on multiple criteria. For instance, you may need to order articles based on highest ratings first, followed by most recent publication date.

To achieve this, MySQL provides a simple solution:

Sorting by Two Columns

To sort a table by two columns, use the ORDER BY clause with multiple column names. However, note that default sorting is ascending. To specify descending order for both columns, add the keyword DESC to each order:

ORDER BY article_rating DESC, article_time DESC

With this modification, the SQL query will produce the desired output:

+================+=============================+==============+
| article_rating | article                     | article_time |
+================+=============================+==============+
| 50             | This article rocks          | Feb 4, 2009  |
+----------------+-----------------------------+--------------+
| 35             | This article is pretty good | Feb 1, 2009  |
+----------------+-----------------------------+--------------+
| 5              | This Article isn't so hot   | Jan 25, 2009 |
+================+=============================+==============+

Remember, if you only specify descending order for one column, the other column will still be sorted in ascending order by default.

The above is the detailed content of How to Perform Multi-Column Sorting in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn