How to Perform Multi-Column Sorting in MySQL?
Dec 31, 2024 pm 02:16 PMMulti-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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

What is SQLite? Comprehensive overview

Run MySQl in Linux (with/without podman container with phpmyadmin)

Running multiple MySQL versions on MacOS: A step-by-step guide

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)?

How do I configure SSL/TLS encryption for MySQL connections?
