Home >Database >Mysql Tutorial >How Can I Use DISTINCT and ORDER BY Together in a Single SQL SELECT Statement?

How Can I Use DISTINCT and ORDER BY Together in a Single SQL SELECT Statement?

Susan Sarandon
Susan SarandonOriginal
2025-01-07 09:16:41391browse

How Can I Use DISTINCT and ORDER BY Together in a Single SQL SELECT Statement?

Using DISTINCT and ORDER BY in a Single SELECT Statement

When working with SQL queries, it can be desirable to both remove duplicate values using DISTINCT and sort the results using ORDER BY. However, attempting to use these clauses together in a single statement can result in unexpected behavior. This article will address this issue and provide a solution to properly achieve both filtering and sorting.

Problem Statement

Consider the following query:

SELECT Category FROM MonitoringJob ORDER BY CreationDate DESC;

This query will return results ordered by the CreationDate column in descending order. However, if there are duplicate values in the Category column, they will not be removed.

To remove duplicates, one might try using the DISTINCT keyword:

SELECT DISTINCT Category FROM MonitoringJob ORDER BY CreationDate DESC;

However, this query will fail with an error, as ORDER BY is not allowed on non-aggregated columns when DISTINCT is used.

Solution

To solve this issue, use an aggregate function along with a GROUP BY clause to group the results by the Category column. This will allow the DISTINCT keyword to remove duplicate category values while still allowing the ORDER BY clause to sort the results by the CreationDate column.

SELECT DISTINCT Category, MAX(CreationDate) 
FROM MonitoringJob 
GROUP BY Category 
ORDER BY MAX(CreationDate) DESC, Category;

In this query:

  • MAX(CreationDate) is the aggregate function used to sort the results by the latest CreationDate for each category.
  • GROUP BY Category groups the results by the Category column, allowing DISTINCT to remove duplicate category values.
  • ORDER BY MAX(CreationDate) DESC, Category sorts the results first by the latest CreationDate within each category and then alphabetically by the Category name.

The above is the detailed content of How Can I Use DISTINCT and ORDER BY Together in a Single SQL SELECT Statement?. 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