DISTINCT clause
In SQL, the DISTINCT
operator is used to remove duplicate rows from the result set of a query. It is often used with the SELECT
statement to retrieve unique or distinct values from a specific column or combination of columns.
The DISTINCT
operator works by comparing the values in the specified columns and removing any duplicate rows from the query result, so that each row in the result set is unique.
The basic syntax of using DISTINCT
with the SELECT
statement is as follows:
SELECT DISTINCT column1, column2, ...
FROM table_name;
Here's an example to illustrate its usage:
Suppose we have a table named "Orders" with a column named CustomerID
. We want to retrieve a list of distinct customer IDs from the table.
SELECT DISTINCT CustomerID
FROM Orders;
In this example, the DISTINCT
operator is used to retrieve unique customer IDs from the "Orders" table. It will remove any duplicate occurrences of the same CustomerID
in the result set.
The DISTINCT
operator can be used with one or more columns. For instance, if you want to retrieve distinct combinations of two columns:
SELECT DISTINCT column1, column2
FROM table_name;
Here's an example using the "Employees" table, retrieving distinct combinations of FirstName
and LastName
:
The DISTINCT
operator is a useful tool when you want to eliminate duplicate rows and focus on unique values in your query results. However, it is important to use it judiciously, as it may impact query performance when dealing with large datasets. In some cases, using GROUP BY
and aggregate functions like COUNT
, SUM
, or AVG
might be more efficient if you need to group data and also eliminate duplicates.