Geek University

SQL SELECT DISTINCT statement

As you have seen, SELECT returns all matched rows. But what if you do not want same values to be shown? The solution is to use the SQL SELECT DISTINCT statement which, as its name implies, instructs the database to only return distinct (different) values. The syntax is:

SELECT DISTINCT column_name1,column_name2 FROM table_name;

We will use the Customer table to illustrate the SQL SELECT DISTINCT Statement:

+----+------------+-------------------+---------+-------+-------+
| id | name       | address           | city    | state | zip   |
+----+------------+-------------------+---------+-------+-------+
|  1 | Bill Smith | 123 Main Street   | Hope    | CA    | 98765 |
|  2 | Mary Smith | 123 Dorian Street | Harmony | AZ    | 98765 |
|  3 | Bob Smith  | 123 Laugh Street  | Hope    | CA    | 98765 |
+----+------------+-------------------+---------+-------+-------+

We’ll start with a simple SQL SELECT DISTINCT statement, as follows:

SELECT DISTINCT CITY FROM CUSTOMER;

This will produce the following result:

+---------+
| city    |
+---------+
| Hope    |
| Harmony |
+---------+

Notice how only the different values were returned and Hope was not listed twice.

Subscribe to our Newsletter

Like us on Facebook

Share on Twitter

top
Developed by Signum Soft