MySQL Cookbook Free Open Book

MySQL Cookbook

Previous Section Next Section

3.19 Choosing Appropriate LIMIT Values

3.19.1 Problem

LIMIT doesn't seem to do what you want it to.

3.19.2 Solution

Be sure you understand what question you're asking. It may be that LIMIT is exposing some interesting subtleties in your data that you have not considered or are not aware of.

3.19.3 Discussion

LIMIT n is useful in conjunction with ORDER BY for selecting smallest or largest values from a result set. But does that actually give you the rows with the n smallest or largest values? Not necessarily! It does if your rows contain unique values, but not if there are duplicates. You may find it necessary to run a preliminary query first to help you choose the proper LIMIT value.

To see why this is, consider the following dataset, which shows the American League pitchers who won 15 or more games during the 2001 baseball season:

mysql> SELECT name, wins FROM al_winner
    -> ORDER BY wins DESC, name;
+----------------+------+
| name           | wins |
+----------------+------+
| Mulder, Mark   |   21 |
| Clemens, Roger |   20 |
| Moyer, Jamie   |   20 |
| Garcia, Freddy |   18 |
| Hudson, Tim    |   18 |
| Abbott, Paul   |   17 |
| Mays, Joe      |   17 |
| Mussina, Mike  |   17 |
| Sabathia, C.C. |   17 |
| Zito, Barry    |   17 |
| Buehrle, Mark  |   16 |
| Milton, Eric   |   15 |
| Pettitte, Andy |   15 |
| Radke, Brad    |   15 |
| Sele, Aaron    |   15 |
+----------------+------+

If you want to know who won the most games, adding LIMIT 1 to the preceding query will give you the correct answer, because the maximum value is 21 and there is only one pitcher with that value (Mark Mulder). But what if you want the four highest game winners? The proper queries depend on what you mean by that, which can have various interpretations:

  • If you just want the first four rows, sort the records and add LIMIT 4:

    mysql> SELECT name, wins FROM al_winner
        -> ORDER BY wins DESC, name
        -> LIMIT 4;
    +----------------+------+
    | name           | wins |
    +----------------+------+
    | Mulder, Mark   |   21 |
    | Clemens, Roger |   20 |
    | Moyer, Jamie   |   20 |
    | Garcia, Freddy |   18 |
    +----------------+------+

    That may not suit your purposes because LIMIT imposes a cutoff that occurs in the middle of a set of pitchers with the same number of wins (Tim Hudson also won 18 games).

  • To avoid making a cutoff in the middle of a set of rows with the same value, select rows with values greater than or equal to the value in the fourth row. Find out what that value is with LIMIT, then use it in the WHERE clause of a second query to select rows:

    mysql> SELECT wins FROM al_winner
        -> ORDER BY wins DESC, name
        -> LIMIT 3, 1;
    +------+
    | wins |
    +------+
    |   18 |
    +------+
    mysql> SELECT name, wins FROM al_winner
        -> WHERE wins >= 18
        -> ORDER BY wins DESC, name;
    +----------------+------+
    | name           | wins |
    +----------------+------+
    | Mulder, Mark   |   21 |
    | Clemens, Roger |   20 |
    | Moyer, Jamie   |   20 |
    | Garcia, Freddy |   18 |
    | Hudson, Tim    |   18 |
    +----------------+------+
  • If you want to know all the pitchers with the four largest wins values, another approach is needed. Determine the fourth-largest value with DISTINCT and LIMIT, then use it to select rows:

    mysql> SELECT DISTINCT wins FROM al_winner
        -> ORDER BY wins DESC, name
        -> LIMIT 3, 1;
    +------+
    | wins |
    +------+
    |   17 |
    +------+
    mysql> SELECT name, wins FROM al_winner
        -> WHERE wins >= 17
        -> ORDER BY wins DESC, name;
    +----------------+------+
    | name           | wins |
    +----------------+------+
    | Mulder, Mark   |   21 |
    | Clemens, Roger |   20 |
    | Moyer, Jamie   |   20 |
    | Garcia, Freddy |   18 |
    | Hudson, Tim    |   18 |
    | Abbott, Paul   |   17 |
    | Mays, Joe      |   17 |
    | Mussina, Mike  |   17 |
    | Sabathia, C.C. |   17 |
    | Zito, Barry    |   17 |
    +----------------+------+

For this dataset, each method yields a different result. The moral is that the way you use LIMIT may require some thought about what you really want to know.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Using the mysql Client Program
    Chapter 2. Writing MySQL-Based Programs
    Chapter 3. Record Selection Techniques
    3.1 Introduction
    3.2 Specifying Which Columns to Display
    3.3 Avoiding Output Column Order Problems When Writing Programs
    3.4 Giving Names to Output Columns
    3.5 Using Column Aliases to Make Programs Easier to Write
    3.6 Combining Columns to Construct Composite Values
    3.7 Specifying Which Rows to Select
    3.8 WHERE Clauses and Column Aliases
    3.9 Displaying Comparisons to Find Out How Something Works
    3.10 Reversing or Negating Query Conditions
    3.11 Removing Duplicate Rows
    3.12 Working with NULL Values
    3.13 Negating a Condition on a Column That Contains NULL Values
    3.14 Writing Comparisons Involving NULL in Programs
    3.15 Mapping NULL Values to Other Values for Display
    3.16 Sorting a Result Set
    3.17 Selecting Records from the Beginning or End of a Result Set
    3.18 Pulling a Section from the Middle of a Result Set
    3.19 Choosing Appropriate LIMIT Values
    3.20 Calculating LIMIT Values from Expressions
    3.21 What to Do When LIMIT Requires the 'Wrong' Sort Order
    3.22 Selecting a Result Set into an Existing Table
    3.23 Creating a Destination Table on the Fly from a Result Set
    3.24 Moving Records Between Tables Safely
    3.25 Creating Temporary Tables
    3.26 Cloning a Table Exactly
    3.27 Generating Unique Table Names
    Chapter 4. Working with Strings
    Chapter 5. Working with Dates and Times
    Chapter 6. Sorting Query Results
    Chapter 7. Generating Summaries
    Chapter 8. Modifying Tables with ALTER TABLE
    Chapter 9. Obtaining and Using Metadata
    Chapter 10. Importing and Exporting Data
    Chapter 11. Generating and Using Sequences
    Chapter 12. Using Multiple Tables
    Chapter 13. Statistical Techniques
    Chapter 14. Handling Duplicates
    Chapter 15. Performing Transactions
    Chapter 16. Introduction to MySQL on the Web
    Chapter 17. Incorporating Query Resultsinto Web Pages
    Chapter 18. Processing Web Input with MySQL
    Chapter 19. Using MySQL-Based Web Session Management
    Appendix A. Obtaining MySQL Software
    Appendix B. JSP and Tomcat Primer
    Appendix C. References
    Colophone
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele