Main Content

Getting a list of unique values from a MySQL column

Archive - Originally posted on "The Horse's Mouth" - 2005-04-14 07:13:19 - Graham Ellis

Would you like to get a list of all the different values in a column? Use the DISTINCT keyword. Here's an example:


mysql> select * from train;
+-------+--------+-------------+-----+
| time | length | destination | tid |
+-------+--------+-------------+-----+
| 07:05 | 1 | Salisbury | 1 |
| 08:18 | 2 | Swindon | 2 |
| 09:05 | 2 | Southampton | 3 |
| 05:45 | 1 | Swindon | 4 |
| 10:35 | 12 | Plymouth | 10 |
| 13:49 | 2 | Swindon | 6 |
| 14:20 | 2 | Salisbury | 7 |
| 17:07 | 1 | Swindon | 8 |
| 18:18 | 1 | Salisbury | 9 |
| 13:00 | 6 | Windsor | 11 |
+-------+--------+-------------+-----+
10 rows in set (0.04 sec)

mysql> select distinct destination from train;
+-------------+
| destination |
+-------------+
| Salisbury |
| Swindon |
| Southampton |
| Plymouth |
| Windsor |
+-------------+
5 rows in set (0.08 sec)

mysql>


See More on SQL module.