MySQL DISTINCT ORDER BY: Remove Duplicates & Sort

In MySQL, you can use the DISTINCT keyword to remove duplicates and the ORDER BY keyword to sort.

The specific grammar is as follows:

SELECT DISTINCT column_name1, column_name2...
FROM table_name
ORDER BY column_name1 ASC/DESC;

The DISTINCT keyword is used to remove duplicate rows, column_name1, column_name2… represent the names of the columns to be queried, table_name represents the name of the table to be queried, and the ORDER BY keyword is used to specify the column for sorting and can choose ascending (ASC) or descending (DESC) order.

For example, assuming there is a table called students, with columns for name and age, if we want to sort the table by the name column and remove duplicate rows, we can use the following query:

SELECT DISTINCT name, age
FROM students
ORDER BY name ASC;

This will give you the query results that are sorted by the name column and remove duplicate rows.

bannerAds