Eliminating Duplicates from a Query Result

14.5.1 Problem

You want to select rows in a query result in such a way that it contains no duplicates.

14.5.2 Solution

Use SELECT DISTINCT.

14.5.3 Discussion

Rows in query results sometimes contain duplicate rows. This is particularly common when you select only a subset of the columns in a table, because that reduces the amount of information available that might otherwise distinguish one row from another. To obtain only the unique rows in a result, eliminate the duplicates by adding the DISTINCT keyword. That tells MySQL to return only one instance of each set of column values. For example, if you select the name columns from the cat_mailing table without using DISTINCT, several duplicates occur:

mysql> SELECT last_name, first_name
 -> FROM cat_mailing ORDER BY last_name, first_name;
+-----------+-------------+
| last_name | first_name |
+-----------+-------------+
| Baxter | Wallace |
| BAXTER | WALLACE |
| Baxter | Wallace |
| Brown | Bartholomew |
| Isaacson | Jim |
| McTavish | Taylor |
| Pinter | Marlene |
| Pinter | Marlene |
+-----------+-------------+

With DISTINCT, the duplicates are eliminated:

mysql> SELECT DISTINCT last_name, first_name
 -> FROM cat_mailing ORDER BY last_name;
+-----------+-------------+
| last_name | first_name |
+-----------+-------------+
| Baxter | Wallace |
| Brown | Bartholomew |
| Isaacson | Jim |
| McTavish | Taylor |
| Pinter | Marlene |
+-----------+-------------+

An alternative to DISTINCT is to add a GROUP BY clause that names the columns you're selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns:

mysql> SELECT last_name, first_name FROM cat_mailing
 -> GROUP BY last_name, first_name;
+-----------+-------------+
| last_name | first_name |
+-----------+-------------+
| Baxter | Wallace |
| Brown | Bartholomew |
| Isaacson | Jim |
| McTavish | Taylor |
| Pinter | Marlene |
+-----------+-------------+

14.5.4 See Also

SELECT DISTINCT is discussed further in Recipe 7.5.

Using the mysql Client Program

Writing MySQL-Based Programs

Record Selection Techniques

Working with Strings

Working with Dates and Times

Sorting Query Results

Generating Summaries

Modifying Tables with ALTER TABLE

Obtaining and Using Metadata

Importing and Exporting Data

Generating and Using Sequences

Using Multiple Tables

Statistical Techniques

Handling Duplicates

Performing Transactions

Introduction to MySQL on the Web

Incorporating Query Resultsinto Web Pages

Processing Web Input with MySQL

Using MySQL-Based Web Session Management

Appendix A. Obtaining MySQL Software

Appendix B. JSP and Tomcat Primer

Appendix C. References



MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2005
Pages: 412
Authors: Paul DuBois

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net