SQL SELECT DISTINCT Statement with example

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:

CustomerIDFirstNameLastNameCity
1JohnDoeNew York
2JaneSmithLos Angeles
3JohnDoeNew York
4MaryJohnsonChicago
5JaneSmithLos 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:

FirstNameLastName
John Doe
Jane Smith
Mary Johnson

In this case, the SELECT DISTINCT statement eliminates duplicate pairs of first and last names.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *