Home >Database >Mysql Tutorial >How Can I Use DISTINCT and ORDER BY Together in a Single SQL 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.
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.
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:
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!