SQL SELECT DISTINCT Statement
What is the SELECT DISTINCT Statement?
The SELECT DISTINCT statement is used to return only distinct (different) values from a column in a database table. This helps avoid duplicates in the result set.
Example
Select all the different states from the “Customers” table:
SELECT DISTINCT State FROM Customers;
This statement returns unique states by filtering out duplicate entries in the “State” column.
Output:
| State |
|---|
| Maharashtra |
| West Bengal |
| Telangana |
| Punjab |
| Delhi |
Syntax
SELECT DISTINCT column1, column2, ... FROM table_name;
Use this syntax to fetch distinct values from one or more columns in a specified table.
Demo Database
Below is a selection from the “Customers” table used in the examples:
| CustomerID | CustomerName | ContactName | State |
|---|---|---|---|
| 1 | Shree Tiffins | Ravi Kumar | Maharashtra |
| 2 | Kolkata Sweets | Aarti Kapoor | West Bengal |
| 3 | Hyderabad Biryani House | Ali Khan | Telangana |
| 4 | Punjab Dhaba | Sandeep Singh | Punjab |
| 5 | Delhi Delights | Neha Sharma | Delhi |
SELECT Example Without DISTINCT
If you omit the DISTINCT keyword, all values, including duplicates, will be returned:
SELECT State FROM Customers;
Output:
| State |
|---|
| Maharashtra |
| West Bengal |
| Telangana |
| Punjab |
| Delhi |
| Maharashtra |
| West Bengal |
Count Distinct
By using the DISTINCT keyword with the COUNT function, you can return the number of unique states:
SELECT COUNT(DISTINCT State) FROM Customers;
Output:
This statement returns the number of unique states in the Customers table, which is 5.
