SQL SELECT DISTINCT Statement: The SELECT DISTINCT
statement in SQL is used to return only distinct (unique) values from a column or a combination of columns. This helps eliminate duplicate rows in the result set.
Syntax for SQL SELECT DISTINCT Statement:
SELECT DISTINCT column1, column2, ...
FROM table_name;
column1, column2, ...
: The columns from which you want to retrieve unique values.table_name
: The name of the table from which to retrieve the data.
Example:
Consider a table called Customers
with the following data:
CustomerID | FirstName | LastName | City |
1 | John | Doe | New York |
2 | Jane | Smith | Los Angeles |
3 | John | Doe | New York |
4 | Mary | Johnson | Chicago |
5 | Jane | Smith | Los Angeles |
If you want to get a list of unique cities where customers live, you can use SELECT DISTINCT
:
SELECT DISTINCT City
FROM Customers;
Result:
City |
New York |
Los Angeles |
Chicago |
The SELECT DISTINCT
statement returns only unique cities from the Customers
table, so even though “New York” and “Los Angeles” appear more than once in the table, they only appear once in the result.
Example with Multiple Columns:
If you want to find unique combinations of FirstName
and LastName
, you can do:
SELECT DISTINCT FirstName, LastName
FROM Customers;
Result:
FirstName | LastName |
John | Doe |
Jane | Smith |
Mary | Johnson |
In this case, the SELECT DISTINCT
statement eliminates duplicate pairs of first and last names.