Ignore duplicate entries in MySQL select using DISTINCT keyword

Contributor Icon Contributed by qmchenry Date Icon July 3, 2006  
Tag Icon Tagged: MySQL

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.

Previous recipe | Next recipe |
 
  • I;ve experimented with both GROUP BY and DISTINCT fucntions in select statements, for some reason, distinct doesn't behave the way it should, for me when the array is fetched in a loop
  • mistat
    Works a charm - just what I was looking for - thanks!
  • maverick
    How do you select query with multiple columns unique distinct values from a single column?

    statement:
    select givenname, party from presidents;

    I want only the givenname to be distinct and not the party?
  • tayeb
    hey maverick i was just wondering if u got the answer to ur question ????
    am having the same problem ...
    thanx
  • some weird distinct in mysql 5.0.1 version :(
blog comments powered by Disqus