How to Use the SQL SELECT DISTINCT Statement

SQL Tutorials

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:

FROM Customers;

Read: Best Certifications for Database Administrators

Ronnie Payne
Ronnie Payne
Ronnie Payne has a background in e-commerce marketing and web development, having acted as a digital marketing consultant and operator of several online stores. He specializes in e-commerce, Internet marketing, content marketing, and web design.
Previous article
Next article

Get the Free Newsletter!

Subscribe to Cloud Insider for top news, trends & analysis

Latest Articles