What’s the SQL Distinct Statement and How Does it Work?

What's the SQL Distinct Statement and How Does it Work?

*This post may contain affiliate links. As an Amazon Associate we earn from qualifying purchases.

The SQL DISTINCT statement is frequently used in Java programming. What it is and how it works is a common question you will encounter in an interview as you pursue a programming career. Here is a comprehensive explanation of what the DISTINCT SQL statement entails.

What is the SQL DISTINCT Statement?

The DISTINCT is used to select only specific values from a certain column in a database table. The clause is also used to eliminate duplicates returned by a SELECT statement. A statement that has duplicates is sometimes caused by an ineffective query or a poor database design or both. Issuing the query without the DISTINCT statement produces many unnecessary or unwanted rows. The keyword is therefore used to limit what is returned to the user.

How Does the DISTINCT Clause Work?

In SQL, several fields may be added to the DISTINCT clause to remove rows where all the selected fields are identical. We will use a car table to illustrate how the DISTINCT statement works.

Car Make Model Year Color
Ford Fusion Titanium 2013 Black
Audi A3 Sedan 2015 Blue
Mercedes C-Class 2010 Red

If you want to select a list of specific colors from all rows in the table, you can use this SQL statement:

FROM cars;

The SELECT keyword comes?before the DISTINCT keyword and will display dissimilar color values. This is the result of the statement:


If you want to get distinct combinations of values from several columns for instance Year and Color of the cars on the table, you can use this SQL Query:

FROM Cars;

This will be the result:

Year Color
2015 Blue
2013 Black
2015 Red

If you carefully look at the result displayed above, you will notice that color blue appears more than once. Despite the duplication for that column, the values are unique.ConclusionThis explanation on SQL DISTINCT statement and how it works will show interviewers you know your way around SQL?programming. This way, you can go into the interview room feeling confident and ready to answer any question concerning DISTINCT SQL statement. Also, share your thoughts about our answer to this question.

Recent Posts