In a previous tutorial, we discussed how to use the SQL SELECT statement to return values from a table. In today’s database programming tutorial, we will learn how to use the SELECT DISTINCT statement to return only distinct – or unique – values from a table.
You can read about regular SELECT SQL statements in our tutorial: How to Use the SQL SELECT Statement.
SQL SELECT DISTINCT Statement and Syntax
The SELECT DISTINCT statement is used for cases where you only want to return values that are unique, distinct, or different from one another. For instance, if you have a table with data containing the following columns:
- FirstName
- LastName
- SocialSecurity
you might want to return only information where the FirstName column contains only names that appear once in the table. For instance, if there are multiple instances of “Ronnie”, you would get no result. However, let’s say there was only one instance of a name like “Dorjan”, then you would get the record for “Dorjan”.
Since social security numbers are unique already, you likely would have rare occasion to use a SELECT DISTINCT on the SocialSecurity column, as all records will likely already be unique by their very nature. You could use it on that column to verify no two people have the same social security numbers, however.
The syntax for using SELECT DISTINCT is:
SELECT DISTINCT ColumnOne, ColumnTwo, Column3 FROM table_example;
Here is some sample code showing how to use SELECT DISTINCT in SQL to return all unique values from the FirstNamecolumn in a table named Customers:
SELECT DISTINCT FirstName FROM Customers;