Select Distinct in SQL Server
The SELECT DISTINCT statement in SQL Server is used to retrieve unique values from a column or combination of columns in a table. It eliminates duplicate rows and returns only distinct values. Here's the basic syntax for using SELECT DISTINCT:
SELECT DISTINCT column1, column2, ...
FROM table_name
WHERE condition;
Let's break down the components of the SELECT DISTINCT statement:
-
SELECT DISTINCT: Specifies that the query should return distinct values.
-
column1, column2, ...: The columns you want to retrieve distinct values from. You can specify one or more columns.
-
FROM table_name: Specifies the table from which to retrieve the data.
-
WHERE condition: Optional clause that allows you to specify conditions to filter the rows before applying the distinct operation.
Here are some examples of using SELECT DISTINCT in SQL Server:
1- Retrieve distinct values from a single column:
SELECT DISTINCT Country
FROM Customers;
This example retrieves distinct values from the "Country" column in the "Customers" table.
2- Retrieve distinct values from multiple columns:
SELECT DISTINCT FirstName, LastName
FROM Employees;
In this example, distinct combinations of "FirstName" and "LastName" are retrieved from the "Employees" table.
3- Retrieve distinct values with a condition:
SELECT DISTINCT City
FROM Customers
WHERE Country = 'USA';
This example retrieves distinct values from the "City" column in the "Customers" table where the "Country" is 'USA'.
The SELECT DISTINCT statement is useful when you want to retrieve unique values from one or more columns in a table. It allows you to eliminate duplicate rows and focus on distinct values. Keep in mind that using SELECT DISTINCT can have performance implications, especially when working with large datasets, as it requires extra processing to identify and remove duplicate values.