Home > DeveloperSection > Interviews > Why and how to use SQL DISTINCT Clause?

Posted on    September-30-2016 1:10 AM

 MSSQL Server SQL Server  SQL Server 2008 
Ratings:
 1 Answer(s)
  91  View(s)
Rate this:

Abhishek Srivasatava
Abhishek Srivasatava

Total Post:70

Points:350
Posted on    September-30-2016 1:10 AM

Distinct is used when unique result is needed from user side. It is used because after joining many tables there is chance of multiple rows for single data may come.

For example

Prsn table holding the Adhar number of person.

And we join this prsn table with prsn_buy_prod table. Let person buy 3 product so three rows will exist.

Program without distinct:

SELECT A.PRSN_ADHAR_NUM
FROM ADHAR A
LEFT JOIN PRSN_BUY_PROD B
ON A.PRSN_ADHAR_NUMNUM=B.PRSN_ADHAR_NUM_NUM
Where A.name= P Raturi
Output :
987456321
987456321
987456321
For the above program 3
rows will come for the single name P Raturi.

But if use distinct along with select statement in the above program then single record will come. 

SELECT DISTICT A.PRSN_ADHAR_NUM
FROM ADHAR A
LEFT JOIN PRSN_BUY_PROD B
ON A.PRSN_ADHAR_NUMNUM=B.PRSN_ADHAR_NUM_NUM
Where A.name= P Raturi
Output :
987456321

Don't want to miss updates? Please click the below button!

Follow MindStick