SQL SELECT DISTINCT

The SQL SELECT DISTINCT statement is used to return only distinct (different) values in the result set. It helps to eliminate duplicate rows in a query result and ensures that only unique records are displayed.

Syntax

The basic syntax for SELECT DISTINCT is:

SELECT DISTINCT column_name
FROM table_name;
        
You can use SELECT DISTINCT with multiple columns to retrieve unique combinations of those columns.

Example

Consider a table Orders with columns CustomerID and Product. We want to retrieve a list of distinct products ordered by customers.

Code Example


-- Retrieve distinct products ordered by customers
SELECT DISTINCT Product FROM Orders;

-- Retrieve unique combinations of CustomerID and Product
SELECT DISTINCT CustomerID, Product FROM Orders;
            

Output

Product
Laptop
Phone
Tablet

Explanation

- The SELECT DISTINCT Product query retrieves only the unique products from the Orders table.
- If the same product has been ordered by different customers multiple times, it will appear only once in the result.
- You can also use SELECT DISTINCT with multiple columns to get unique combinations of values. For example, SELECT DISTINCT CustomerID, Product will return unique pairs of customers and the products they ordered.