MySQL DISTINCT Clause

The DISTINCT clause filters and removes duplicate records from the resultset; hence, unique records will be left. For example, if one cell value is repeated multiple times in that same column, that value will be shown only once in the resultset. Please note that the DISTINCT clause only removes the duplicate values from the resultset and NOT the database.

MySQL DISTINCT Clause

The above figure demonstrates the working of MySQL SELECT DISTINCT, as it excluding all the duplicate records and fetching only single instances of each type.

Syntax:

SELECT DISTINCT column_names FROM Table_Name;

Let’s look at the following example

Assuming that we have a database called – ‘w3wiki‘ and a table called – ‘employees‘ in it. Fetching the data without using the DISTINCT keyword fetches us all the records that are present in the ‘employees‘ table. (Our table contains redundant values)

Without DISTICT Clause

But when we apply the distinct keyword using the following query:

SELECT DISTINCT * FROM employees;

Output

with DISTINCT clause

MySQL DISTINCT Clause

MySQL is a relational database management system that can store data and we can query the stored data using SQL. SQL is a standard language to manipulate the database. The data fetching process can be applied with many filters as we might need only some specific data, or we might want to exclude some data then we can apply a filter using something called – ‘CLAUSE‘ in SQL. In this article, we’ll be discussing the ‘DISTINCT‘ clause.

Similar Reads

MySQL DISTINCT Clause

The DISTINCT clause filters and removes duplicate records from the resultset; hence, unique records will be left. For example, if one cell value is repeated multiple times in that same column, that value will be shown only once in the resultset. Please note that the DISTINCT clause only removes the duplicate values from the resultset and NOT the database....

MySQL and NULL Values

In general, using DISTINCT comes very handy when the result set or the target table doesn’t contain the NULL values. But, assuming the target table contains the NULL values. See what happens...

DISTINCT Keyword in Case of Multiple Columns

Although DISTINCT fetches the unique records from a table it may not always amount to be useful in certain scenarios when we have to find unique records from multiple columns. For example, consider the below scenario:-...

Conclusion

In this article, we’ve discussed the overall working of a DISTINCT clause in MySQL. It helps us in fetching all the unique records without modifying the table and getting a non-redundant result set. DISTINCT is a result filtering clause that fetches only unique records from the table. When the table contains NULL values we must specify further filtering using WHERE clause and IS NOT NULL comparison operator. DISTINCT doesn’t work properly when multiple columns are grouped together to fetch unique records hence we must use GROUP BY clause....

Contact Us