7.3.1 Problem
You need to determine the smallest or largest of a set of values.
7.3.2 Solution
Use MIN( ) to find the smallest value, MAX( ) to find the largest.
7.3.3 Discussion
Finding smallest or largest values is somewhat akin to sorting, except that instead of producing an entire set of sorted values, you select only a single value at one end or the other of the sorted range. This kind of operation applies to questions about smallest, largest, oldest, newest, most expensive, least expensive, and so forth. One way to find such values is to use the MIN( ) and MAX( ) functions. (Another way to address these questions is to use LIMIT; see the discussions in Recipe 3.17 and Recipe 3.19.)
Because MIN( ) and MAX( ) determine the extreme values in a set, they're useful for characterizing ranges:
mysql> SELECT -> MIN(t) AS earliest, MAX(t) AS latest, -> MIN(size) AS smallest, MAX(size) AS largest -> FROM mail; +---------------------+---------------------+----------+---------+ | earliest | latest | smallest | largest | +---------------------+---------------------+----------+---------+ | 2001-05-11 10:15:08 | 2001-05-19 22:21:51 | 271 | 2394482 | +---------------------+---------------------+----------+---------+
mysql> SELECT MIN(miles) AS shortest, MAX(miles) AS longest -> FROM driver_log; +----------+---------+ | shortest | longest | +----------+---------+ | 79 | 502 | +----------+---------+
mysql> SELECT MIN(pop) AS 'fewest people', MAX(pop) AS 'most people' -> FROM states; +---------------+-------------+ | fewest people | most people | +---------------+-------------+ | 453588 | 29760021 | +---------------+-------------+
mysql> SELECT MIN(name), MAX(name) FROM states; +-----------+-----------+ | MIN(name) | MAX(name) | +-----------+-----------+ | Alabama | Wyoming | +-----------+-----------+
MIN( ) and MAX( ) need not be applied directly to column values. They also work with expressions or values that are derived from column values. For example, to find the lengths of the shortest and longest state names, do this:
mysql> SELECT MIN(LENGTH(name)) AS shortest, MAX(LENGTH(name)) AS longest -> FROM states; +----------+---------+ | shortest | longest | +----------+---------+ | 4 | 14 | +----------+---------+
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