SQL DISTINCT Clause | Fetch Only Unique Values

The SQL DISTINCT Clause along with the SELECT Query fetches only the unique values of a column or a combination of columns. It is helpful when there are duplicate values in a table and you want to select only the unique ones. In this article, we will discuss the SQL DISTINCT Clause. Also, we will discuss an example of using it.

Syntax

SELECT DISTINCT column1, column2 FROM table_name;

This query will return all the distinct combinations of column1 and column2 from the table. Also, we can also enclose the column names in brackets to fetch only that column.

SELECT DISTINCT (column1) FROM table_name;

SELECT DISTINCT column1 FROM table_name;

Demo Table

For instance, consider the demo table to refer to all the queries in this article.

+----+--------+--------+------------+-------+
| id | name   | salary | experience | team  |
+----+--------+--------+------------+-------+
|  1 | David  |  20000 |          5 | Alpha |
|  2 | Monica |  25000 |          6 | Beta  |
|  3 | John   |  15000 |          3 | Beta  |
|  4 | Mary   |  18000 |          4 | Gamma |
|  5 | Ross   |  30000 |          8 | Alpha |
+----+--------+--------+------------+-------+

Example Without SQL DISTINCT

For instance, consider a case without using the distinct clause. In this case, all the rows from the table are selected no matter if there are duplicates.

mysql> SELECT team FROM employees;

The query fetches all the rows from the database.

+-------+
| team  |
+-------+
| Alpha |
| Beta  |
| Beta  |
| Gamma |
| Alpha |
+-------+

Example With SQL DISTINCT

On the other hand, by using the distinct clause, the query only selects the unique values from the table.

mysql> SELECT DISTINCT (team) FROM employees;

Since there are duplicate entries in the column team, only the unique values are returned.

+-------+
| team  |
+-------+
| Alpha |
| Beta  |
| Gamma |
+-------+

Conclusion

In conclusion, we discussed the SQL DISTINCT Clause. You can read more about it on Wikipedia. Also, you can read more articles on SQL on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *