Controlling String Case Sensitivity for MIN( ) and MAX( )

Controlling String Case Sensitivity for MIN() and MAX()

7.7.1 Problem

MIN( ) and MAX( ) select strings in case sensitive fashion when you don't want them to, or vice versa.

7.7.2 Solution

Alter the case sensitivity of the strings.

7.7.3 Discussion

When applied to string values, MIN( ) and MAX( ) produce results determined according to lexical sorting rules. One factor in string sorting is case sensitivity, so MIN( ) and MAX( ) are affected by that as well. In Chapter 6, we used a textblob_val table containing two columns of apparently identical values:

mysql> SELECT tstr, bstr FROM textblob_val;
| tstr | bstr |
| aaa | aaa |
| AAA | AAA |
| bbb | bbb |
| BBB | BBB |

However, although the values look the same, they don't behave the same. bstr is a BLOB column and is case sensitive. tstr, a TEXT column, is not. As a result, MIN( ) and MAX( ) will not necessarily produce the same results for the two columns:

mysql> SELECT MIN(tstr), MIN(bstr) FROM textblob_val;
| MIN(tstr) | MIN(bstr) |
| aaa | AAA |

To make tstr case sensitive, use BINARY:

mysql> SELECT MIN(BINARY tstr) FROM textblob_val;
| MIN(BINARY tstr) |
| AAA |

To make bstr not case sensitive, you can convert the values to a given lettercase:

mysql> SELECT MIN(LOWER(bstr)) FROM textblob_val;
| MIN(LOWER(bstr)) |
| aaa |

Unfortunately, doing so also changes the displayed value. If that's an issue, use this technique instead (and note that it may yield a somewhat different result):

mysql> SELECT @min := MIN(LOWER(bstr)) FROM textblob_val;
mysql> SELECT bstr FROM textblob_val WHERE LOWER(bstr) = @min;
| bstr |
| aaa |
| AAA |

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-2020.
If you may any questions please contact us: flylib@qtcs.net