Home > Database > Mysql Tutorial > How to Sort a MySQL Table by Multiple Columns (Rating and Date)?

How to Sort a MySQL Table by Multiple Columns (Rating and Date)?

Linda Hamilton
Release: 2024-12-17 18:53:17
Original
217 people have browsed it

How to Sort a MySQL Table by Multiple Columns (Rating and Date)?

Sorting MySQL Tables by Multiple Columns

Question:

How can I order a MySQL table by multiple columns, specifically by highest ratings first and then by most recent date?

Answer:

To sort a MySQL table by two columns, use the ORDER BY clause with multiple columns. By default, sorting is ascending, but you can add the DESC keyword to both columns to sort in descending order:

ORDER BY article_rating DESC, article_time DESC
Copy after login

This will sort the table by the article_rating column in descending order (highest ratings first) and then by the article_time column in descending order (most recent date first).

Example:

Consider the following 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

Using the ORDER BY clause with multiple columns:

SELECT * FROM articles ORDER BY article_rating DESC, article_time DESC
Copy after login

Will produce the following sorted 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

The above is the detailed content of How to Sort a MySQL Table by Multiple Columns (Rating and Date)?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template