SQL Cookbook Lesson
How to use DISTINCT in SQL
Learn how to use DISTINCT in SQL with examples and explanations from SQLPad.
Problem
You want to select unique rows from a SQL table by eliminating duplicate data entries.
Sample data
Consider we have a table called 'Employees' with the following data:
| id | name | job_title |
|---|---|---|
| 1 | John | Developer |
| 2 | Mary | Designer |
| 3 | John | Developer |
| 4 | Alice | Manager |
| 5 | Mary | Designer |
Solution
The DISTINCT clause is used to remove duplicate values from the result set of a SELECT statement in SQL.
MySQL Solution
SELECT DISTINCT name, job_title FROM Employees;
PostgreSQL Solution
SELECT DISTINCT name, job_title FROM Employees;
Explanation
The DISTINCT clause works the same way in both MySQL and PostgreSQL. When applied, it ensures that the result set of the SELECT statement only includes unique rows.
In our example, the SQL statement selects unique combinations of 'name' and 'job_title' from the 'Employees' table. After executing the above SQL statement, you'll get the following result:
| name | job_title |
|---|---|
| John | Developer |
| Mary | Designer |
| Alice | Manager |
As you can see, duplicate rows are eliminated from the result set. John, who appeared twice as a 'Developer', now only appears once. The same goes for Mary as a 'Designer'.