SELECT DISTINCT

The SELECT DISTINCT statement in MySQL is used to retrieve unique values from a specified column or combination of columns in a table. It is particularly useful when you want to eliminate duplicate rows from the result set.

Syntax

Here’s the basic syntax of the SELECT DISTINCT statement:

SELECT DISTINCT column1, column2, ...
FROM table_name;

column1, column2, …: The columns for which you want to retrieve unique values.
table_name: The name of the table from which you want to select distinct values.

Example

For example, let’s say you have a table called employees with columns department and designation, and you want to find the distinct combinations of department and designation:

SELECT DISTINCT department, designation
FROM employees;

This query will return a result set containing unique combinations of the department and designation columns.

It’s important to note that DISTINCT operates on all the columns specified in the SELECT clause. If you want to retrieve distinct values from a single column, you can simply specify that column after the SELECT DISTINCT keywords:

SELECT DISTINCT column_name
FROM table_name;

Here’s an example where you want to retrieve distinct employee names from an employees table:

SELECT DISTINCT employee_name
FROM employees;

This query will return a list of unique employee names from the employee_name column.

In summary, the SELECT DISTINCT statement is a valuable tool when you want to retrieve unique values from one or more columns in a table, helping you filter out duplicate entries in your result set.