Distinct Keyword in SQL

Sometimes the query results in duplicate values which simply increases the result list and does not give the clear picture about the result. User will be intended to see the different set of values out of query rather than duplicate values in the query. Consider the query to see who all have borrowed particular book so far from library below. This lists all the borrower irrespective of the number of times they have borrowed. But here it is sufficient to display borrower names only once to indicate that he has borrowed it.

SELECT * FROM BOOK_LOAN WHERE ISBN = 70608451;

Hence we need to use DISTINCT keyword above to show the different borrowers. But all the columns of BOOK_LOAN do not have duplicate values. Only when borrower name is considered, we have duplicate values. If we use DISTINCT on above query, we will not get different set of values.

Hence we can use DISTINCT keyword to see the different values of borrower names like below.

SELECT DISTINCT BRWR_ID, ISBN FROM BOOK_LOAN WHERE ISBN = 70608451;

That means DISTINCT keyword eliminates the duplicate values from all the columns listed in the SELECT list than individual columns.

Translate ยป