Ignore duplicate entries in MySQL select using DISTINCT keyword

Home -> Database -> MySQL

15487 views

From the computer of: qmchenry (338 recipes)
Created: Jul 03, 2006


Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

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.

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.





Related recipes:

  Display a list of databases on a MySQL server
  Solve: Can't connect to local MySQL server through socket /tmp/mysql.sock
  Connect to a MySQL server using the mysql command
  Determine the version of MySQL server
  Select a MySQL database to use
  Create a basic MySQL table
  Describe the column structure of a MySQL table
  Create a MySQL database
  Drop or delete a table in MySQL
  Use regular expressions in MySQL SELECT statements

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.