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.
First, let’s create a table as below and add a few records to this table.
CREATE TABLE [dbo].[Provinces](
[Province] [varchar](50) NULL,
[County] [varchar](50) NULL,
[Street] [varchar](50) NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Provinces] VALUES ('ISTANBUL','BESIKTAS','Street1'),('ISTANBUL','KADIKOY','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.
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.
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.
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.