MySQL

Fetch Distinct or Unique Rows

The SELECT returns all matched rows but what if you did not want every occurrence of every value? For example, suppose you wanted the vendor ID of all vendors with products in your products table:

SELECT vend_id
FROM products;

The above code returns the following output:

+---------+
| vend_id |
+---------+
|       1 |
|       1 |
|       1 |
|       2 |
|       2 |
|       3 |
|       3 |
|       3 |
|       3 |
|       3 |
|       3 |
|       3 |
|       5 |
|       5 |
+---------+

The SELECT statement returned 14 rows even though there are only 4 vendors in that list because there are 14 products listed in the products table. So how could you retrieve a list of distinct values?

The solution is to use the DISTINCT keyword which, as its name implies, instructs MySQL to only return distinct values.

SELECT DISTINCT vend_id
FROM products;

SELECT DISTINCT vend_id tells MySQL to only return distinct (unique) vend_id rows, and so only 4 rows are returned, as seen in the following output. When you use the DISTINCT keyword, it must be placed directly in front of the column names.

The DISTINCT keyword applies to all columns, not just the one it precedes. If you were to specify SELECT DISTINCT vend_id, prod_price, all rows would be retrieved unless both of the specified columns were distinct.

+---------+
| vend_id |
+---------+
|       1 |
|       2 |
|       3 |
|       5 |
+---------+