With Distinct Clause, you can return only one of the recurring records as a result when reading data from the table. In other words, if ISTANBUL value is repeated 5 times in a column called province, only one ISTANBUL value will be returned. Let us clarify the subject by making an example.
Example:
First, let’s create a table as below and add a few records to this table.
1 2 3 4 5 6 7 8 9 10 | USE [TestDB] GO CREATE TABLE [dbo].[Provinces]( [Province] [varchar](50) NULL, [County] [varchar](50) NULL, [Street] [varchar](50) NULL ) ON [PRIMARY] GO INSERT INTO [dbo].[Provinces] VALUES ('ISTANBUL','BESIKTAS','Street1'),('ISTANBUL','KADIKOY','Street2'), ('ISTANBUL','BASAKSEHIR','Street3'),('ANKARA','KIZILCAHAMAM','Street1'),('ANKARA','KIZILCAHAMAM','Street2') |
We added 5 records to the table. There are 2 different provinces, 4 different counties in these 5 records. Now let’s query the data in the Province table using the DISTINCT Clause as follows.
1 | SELECT DISTINCT * FROM [dbo].[Provinces] |
All records returned as a result because we read the data with *. Because there are no data sets in which all columns have the same values.
Change the query as follows and run it again.
1 | SELECT DISTINCT Province,County FROM [dbo].[Provinces] |
Although there are 5 records in the table, 4 records returned as a result. Because we read the first and second columns with DISTINCT Clause. In other words, we have read only one of the data sets in which 2 field’s values are the same. So, in these two columns, ANKARA, KIZILCAHAMAM repeated 2 times and only one of them returned as a result.
Now with DISTINCT, just read the Province column as follows.
1 | SELECT DISTINCT Province FROM [dbo].[Provinces] |
As you might expect, only ANKARA and ISTANBUL have returned as a result because we will only read one of the repeated records.