MySQL DISTINCT clause
DISTINCT clause in MySQL is used in the
SELECT statement to eliminate duplicate rows from the result set. It allows you to retrieve unique values from a specified column or a combination of columns.
The basic syntax for using the
DISTINCT clause is as follows:
SELECT DISTINCT column1, column2, ... FROM table;
column2, and so on represent the columns from which you want to retrieve distinct values. The
DISTINCT keyword is placed before the column list to indicate that you want only unique values.
Let’s consider an example to illustrate the usage of the
DISTINCT clause. Suppose we have a table named
employees with columns
department. If we want to retrieve a list of unique departments from the table, we can write the following query:
SELECT DISTINCT department FROM employees;
In this example, the
DISTINCT keyword is used to retrieve unique values from the
department column. The result set will contain only one instance of each distinct department.
DISTINCT clause can be combined with other clauses, such as
JOIN, to perform more complex queries. For instance, you can use it with the
ORDER BY clause to sort the unique values in a specific order:
SELECT DISTINCT department FROM employees ORDER BY department ASC;
In this case, the result set will contain unique departments sorted in ascending order.
It’s important to note that the
DISTINCT keyword operates on all columns specified in the
SELECT statement. If you want to retrieve distinct combinations of values from multiple columns, you can include all those columns in the
Keep in mind that using the
DISTINCT clause can have performance implications, especially when dealing with large datasets. It may require additional processing to identify and eliminate duplicate rows. So, use it judiciously when necessary.
In summary, the
DISTINCT clause in MySQL is used to retrieve unique values from one or more columns in a table. It eliminates duplicate rows from the result set, allowing you to work with distinct values.