Ignore duplicate entries in MySQL select using DISTINCT keyword

Sometimes every occurance of a value which may be duplicated multiple times in a result set is not needed. For example, if making a pulldown menu list of options, each option should be seen only once. The DISTINCT keyword in a select statement eliminates duplication in the result set.

The column party from the presidents sample table has many repeats in it. To select a list of the parties from the table, use:

SELECT DISTINCT party FROM presidents;

This returns a result set that looks like:

| party |
| no party |
| Federalist |
| Democratic-Republican |
| Democratic |
| Whig |
| Republican |

Using the DISTINCT keyword on queries with multiple columns will return unique combinations of values on all of the columns. For example, the query

SELECT DISTINCT givenname, party FROM presidents;

returns 36 out of a possible 43 rows. Each row is a unique combination of first name and political party.

Αφήστε μια απάντηση

Η ηλ. διεύθυνσή σας δεν δημοσιεύεται. Τα υποχρεωτικά πεδία σημειώνονται με *