The DISTINCT keyword in MySQL is used to eliminate duplicate rows from the result set of a query. It ensures that only unique values are returned for the specified columns. Here's an example of using the DISTINCT clause:
Consider a table called employees with the following structure:
Syntax:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10,2)
);
Suppose we want to retrieve the DISTINCT departments from the employees table. We can use the DISTINCT keyword as follows:
Syntax:
SELECT DISTINCT department FROM employees;
In the above example, the DISTINCT keyword is applied to the department column. This query will return only unique department names from the employees table.
You can also use the DISTINCT keyword with multiple columns:
Syntax:
SELECT DISTINCT name, department FROM employees;
In the above example, the query will return unique combinations of the name and department columns.
It's important to note that the DISTINCT keyword operates on the selected columns and considers all selected columns as a group. If you use DISTINCT with multiple columns, it will evaluate the uniqueness of the combinations of those columns.
Remember to adjust the column names and table name in the examples based on your specific scenario. The DISTINCT clause can be used in combination with other clauses like ORDER BY, WHERE, or LIMIT to further refine your query results.