Home >Database >Mysql Tutorial >How to Sort a MySQL Table by Two Columns?

How to Sort a MySQL Table by Two Columns?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 00:01:09297browse

How to Sort a MySQL Table by Two Columns?

Sorting MySQL Tables by Two Columns

To order a MySQL table by two columns, you need to specify both sorting criteria in the ORDER BY clause, separated by commas. By default, sorting is in ascending order. To sort in descending order, use the DESC keyword.

Consider the following example: You have an articles table with columns named article_rating and article_time. To sort the table in descending order by rating, then in descending order by date, use the following query:

ORDER BY article_rating DESC, article_time DESC

This will result in articles with higher ratings appearing first, and within each rating group, articles with more recent dates will appear first.

For instance, if you had the following data in your articles table:

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

The query above would produce the following 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

By specifying both sorting criteria in the ORDER BY clause, you can effectively order your table by multiple columns, ensuring the desired ordering of your data.

The above is the detailed content of How to Sort a MySQL Table by Two Columns?. 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