DISTINCT Keyword in SQL Server SELECT statement is used to return only unique records from a database table.
Syntax: SELECT DISTINCT Column _name FROM Table_name.
Example: Consider following scenario. Let say we have a sales order header tables containing Customer related purchase information. From this table we have to retrieve all the customers’ id (Note: in this post queries are executed on adventure works database. Click this to know how to get Adventure Work Database.)
Query: SELECT DISTINCT CustomerID FROM [AdventureWorks2014].[Sales].[SalesOrderHeader];
Result: Missing Image 1
We can combine multiple columns with DISTINCT keyword.
Syntax: SELECT DISTINCT COL1, COL2, COL3, ...COLN FROM table_name
Now uniqueness will be measure on the basis of all the listed column
Example: Let’s assume as per our requirement we have to find list down all the available product Class, Style and its Product line from product table. Execute below query to achieve our goal.
Query: SELECT DISTINCT ProductLine,Class,Style FROM [AdventureWorks2014].[Production].[Product]
WHERE ProductLine IS NOT NULL AND Class IS NOT NULL AND Style IS NOT NULL;
Result:Missing Image 2
Still having queries on distinct keyword. Leave a comment we revert back ASAP.
Interview Question: How to remove duplicate records from a database table?
Please login to post your valuable comments.
Get the latest vLemonn news first