Site icon Database Tutorials

DISTINCT Clause in SQL Server(TSQL)

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.

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.

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.

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.

As you might expect, only ANKARA and ISTANBUL have returned as a result because we will only read one of the repeated records.

Exit mobile version