MySQL Cookbook Free Open Book

MySQL Cookbook

Previous Section Next Section

4.7 Pattern Matching with SQL Patterns

4.7.1 Problem

You want to perform a pattern match rather than a literal comparison.

4.7.2 Solution

Use the LIKE operator and a SQL pattern, described in this section. Or use a regular expression pattern match, described in Recipe 4.8.

4.7.3 Discussion

Patterns are strings that contain special characters. These are known as metacharacters because they stand for something other than themselves. MySQL provides two kinds of pattern matching. One is based on SQL patterns and the other on regular expressions. SQL patterns are more standard among different database systems, but regular expressions are more powerful. The two kinds of pattern match uses different operators and different sets of metacharacters. This section describes SQL patterns; Recipe 4.8 describes regular expressions.

SQL pattern matching uses the LIKE and NOT LIKE operators rather than = and != to perform matching against a pattern string. Patterns may contain two special metacharacters: _ matches any single character, and % matches any sequence of characters, including the empty string. You can use these characters to create patterns that match a wide variety of values:

  • Strings that begin with a particular substring:

    mysql> SELECT name FROM metal WHERE name LIKE 'co%';
    +--------+
    | name   |
    +--------+
    | copper |
    +--------+
  • Strings that end with a particular substring:

    mysql> SELECT name FROM metal WHERE name LIKE '%er';
    +--------+
    | name   |
    +--------+
    | copper |
    | silver |
    +--------+
  • Strings that contain a particular substring anywhere:

    mysql> SELECT name FROM metal WHERE name LIKE '%er%';
    +---------+
    | name    |
    +---------+
    | copper  |
    | mercury |
    | silver  |
    +---------+
  • Strings that contain a substring at a specific position (the pattern matches only if pp occurs at the third position of the name column):

    mysql> SELECT name FROM metal where name LIKE '_ _pp%';
    +--------+
    | name   |
    +--------+
    | copper |
    +--------+

A SQL pattern matches successfully only if it matches the entire comparison value. Thus, of the following two pattern matches, only the second succeeds:

'abc' LIKE 'b'
'abc' LIKE '%b%'

To reverse the sense of a pattern match, use NOT LIKE. The following query finds strings that contain no i characters:

mysql> SELECT name FROM metal WHERE name NOT LIKE '%i%';
+---------+
| name    |
+---------+
| copper  |
| gold    |
| lead    |
| mercury |
+---------+

SQL patterns do not match NULL values. This is true both for LIKE and NOT LIKE:

mysql> SELECT NULL LIKE '%', NULL NOT LIKE '%';
+---------------+-------------------+
| NULL LIKE '%' | NULL NOT LIKE '%' |
+---------------+-------------------+
|          NULL |              NULL |
+---------------+-------------------+

In some cases, pattern matches are equivalent to substring comparisons. For example, using patterns to find strings at one end or the other of a string is like using LEFT( ) or RIGHT( ):

Pattern match

Substring comparison

str LIKE 'abc%'

LEFT(str,3) = 'abc'

str LIKE '%abc'

RIGHT(str,3) = 'abc'

If you're matching against a column that is indexed and you have a choice of using a pattern or an equivalent LEFT( ) expression, you'll likely find that the pattern match is faster. MySQL can use the index to narrow the search for a pattern that begins with a literal string; with LEFT( ), it cannot.

Using Patterns with Non-String Values

Unlike some other databases, MySQL allows pattern matches to be applied to numeric or date values, which can sometimes be useful. The following table shows some ways to test a DATE value d using function calls that extract date parts and using the equivalent pattern matches. The pairs of expressions are true for dates occurring in the year 1976, in the month of April, or on the first day of the month:

Function value test

Pattern match test

YEAR(d) = 1976

d LIKE '1976-%'

MONTH(d) = 4

d LIKE '%-04-%'

DAYOFMONTH(d) = 1

d LIKE '%-01'

    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
    Chapter 4. Working with Strings
    4.1 Introduction
    4.2 Writing Strings That Include Quotes or Special Characters
    4.3 Preserving Trailing Spaces in String Columns
    4.4 Testing String Equality or Relative Ordering
    4.5 Decomposing or Combining Strings
    4.6 Checking Whether a String Contains a Substring
    4.7 Pattern Matching with SQL Patterns
    4.8 Pattern Matching with Regular Expressions
    4.9 Matching Pattern Metacharacters Literally
    4.10 Controlling Case Sensitivity in String Comparisons
    4.11 Controlling Case Sensitivity in Pattern Matching
    4.12 Using FULLTEXT Searches
    4.13 Using a FULLTEXT Search with Short Words
    4.14 Requiring or Excluding FULLTEXT Search Words
    4.15 Performing Phrase Searches with a FULLTEXT Index
    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