← Back to Chapters

MySQL Regular Expression

? MySQL Regular Expression

? Quick Overview

MySQL allows the use of regular expressions using REGEXP or RLIKE to perform advanced pattern matching. This approach is more flexible than the LIKE operator.

? Key Concepts

  • Pattern matching using regex
  • Case-insensitive matching by default
  • Supports character classes, anchors, and quantifiers

? Syntax / Theory

? View Code Example
// Basic REGEXP syntax in MySQL
SELECT column_name
FROM table_name
WHERE column_name REGEXP 'pattern';

? Code Example 1: Matching Specific Words

? View Code Example
// Match names starting from A to M
SELECT *
FROM employees
WHERE name REGEXP '^[A-M]';

? Code Example 2: Matching Patterns

? View Code Example
// Match product codes like 123-AB
SELECT *
FROM products
WHERE product_code REGEXP '^[0-9]{3}-[A-Za-z]{2}$';

? Code Example 3: Using NOT REGEXP

? View Code Example
// Exclude names starting with A to M
SELECT *
FROM employees
WHERE name NOT REGEXP '^[A-M]';

? Code Example 4: Multiple Patterns

? View Code Example
// Match only letters OR only numbers
SELECT *
FROM products
WHERE product_code REGEXP '^[A-Za-z]+$|^[0-9]+$';

? Live Output / Explanation

The queries return rows only when the column value satisfies the given regular expression pattern.

? Use Cases

  • Email validation
  • Phone number verification
  • Filtering structured product codes

✅ Tips & Best Practices

  • Use anchors (^, $) for precise matching
  • Test regex patterns before deployment
  • Use BINARY for case-sensitive matches

? Try It Yourself

  • Find emails matching name@domain format
  • Match phone numbers with exactly 10 digits
  • Exclude product codes with special characters