A Complete Guide to the MySQL NOT LIKE Operator

This article provides an in-depth look at the MySQL NOT LIKE operator, including its syntax, usage, and practical examples.

Posted on

The Art of Exclusion in Pattern Matching

In the world of database queries, sometimes what you don’t want is just as important as what you do want. The MySQL NOT LIKE operator serves as your trusty filter for excluding records that match specific patterns. Think of it as a bouncer for your data, keeping out unwanted string patterns while letting everything else through.

While the LIKE operator gets most of the attention for pattern matching, its negative counterpart NOT LIKE plays an equally crucial role in data filtering. Whether you’re cleaning datasets, implementing search functionality, or validating inputs, NOT LIKE helps you write queries that say, “Show me everything except this particular pattern.”

Understanding the Basic Syntax

The NOT LIKE operator follows the same pattern-matching rules as its positive counterpart, simply reversing the logic. The basic structure is straightforward:

SELECT columns
FROM table
WHERE column_name NOT LIKE pattern;

Let’s start with a simple example from a product database:

SELECT product_name
FROM products
WHERE product_name NOT LIKE '%discount%';

This query returns all products whose names don’t contain the word “discount” anywhere in the text. The percent signs (%) serve as wildcards meaning “any number of characters.”

Common Pattern Matching Techniques

Just like with LIKE, NOT LIKE supports two main wildcard characters:

  • % matches any sequence of characters (including none)
  • _ matches exactly one character

Here’s how you might use these in practice:

Excluding specific prefixes:

SELECT username
FROM users
WHERE username NOT LIKE 'temp_%';

Filtering out precise patterns:

SELECT email
FROM contacts
WHERE email NOT LIKE '%.test@%';

Combining multiple exclusions:

SELECT file_name
FROM documents
WHERE file_name NOT LIKE '%.tmp'
AND file_name NOT LIKE '%~%';

Case Sensitivity Considerations

An important nuance of NOT LIKE is its case sensitivity behavior, which depends on your MySQL collation settings. For case-insensitive searches, you might need to explicitly specify:

SELECT product_code
FROM inventory
WHERE product_code NOT LIKE '%a%' COLLATE utf8mb4_general_ci;

Or for case-sensitive matching:

SELECT log_entry
FROM system_logs
WHERE log_entry NOT LIKE '%ERROR%' COLLATE utf8mb4_bin;

Practical Use Cases

Let’s explore some real-world scenarios where NOT LIKE proves invaluable:

Data cleaning:

DELETE FROM customer_data
WHERE phone_number NOT LIKE '+%'
AND phone_number NOT LIKE '%@%';

Content moderation:

SELECT comment_text
FROM user_comments
WHERE comment_text NOT LIKE '%http://%'
AND comment_text NOT LIKE '%https://%';

Quality control:

SELECT sensor_readings
FROM iot_devices
WHERE sensor_readings NOT LIKE '%error%'
AND sensor_readings NOT LIKE '%calibration%';

Combining NOT LIKE with Other Operators

The true power emerges when you combine NOT LIKE with other SQL operators:

With logical operators:

SELECT *
FROM articles
WHERE title NOT LIKE '%draft%'
AND (publish_date IS NOT NULL OR author = 'admin');

In subqueries:

SELECT employee_name
FROM staff
WHERE employee_id NOT IN (
    SELECT user_id
    FROM system_logs
    WHERE action NOT LIKE '%login%'
);

With regular expressions:

SELECT *
FROM products
WHERE description NOT LIKE '%limited edition%'
AND description REGEXP '^[A-Z]';

Performance Implications

While NOT LIKE is incredibly useful, it’s important to understand its performance characteristics:

  • NOT LIKE operations generally can’t use standard indexes
  • Leading wildcards (%pattern) force full table scans
  • Complex patterns with multiple wildcards are resource-intensive

For better performance on large tables, consider:

-- Add a computed column for frequently filtered patterns
ALTER TABLE products
ADD COLUMN has_discount_flag TINYINT(1) GENERATED ALWAYS AS
(CASE WHEN product_name LIKE '%discount%' THEN 1 ELSE 0 END);

-- Then query using the indexed computed column
SELECT product_name
FROM products
WHERE has_discount_flag = 0;

Edge Cases and Gotchas

Watch out for these common pitfalls when using NOT LIKE:

NULL values behave unexpectedly:

-- This won't return rows where the column is NULL
SELECT *
FROM table
WHERE column NOT LIKE '%pattern%';

-- To include NULLs, you need:
SELECT *
FROM table
WHERE column NOT LIKE '%pattern%' OR column IS NULL;

Escaping special characters:

-- To search for literal percent signs
SELECT *
FROM discounts
WHERE description NOT LIKE '%\%%' ESCAPE '\';

Empty strings:

-- An empty string doesn't match any pattern
SELECT *
FROM products
WHERE description NOT LIKE '%sale%';
-- This includes rows where description is empty

Mastering Negative Pattern Matching

The MySQL NOT LIKE operator is a powerful tool for exclusionary pattern matching that every database professional should have in their toolkit. While it shares the same pattern-matching capabilities as LIKE, its negative logic opens up different query possibilities that are essential for data cleaning, validation, and selective retrieval.

Remember that NOT LIKE is just one tool among many - sometimes a combination of other operators or even regular expressions might better serve your needs. The key is understanding its behavior with different patterns, case sensitivity, and NULL values to avoid unexpected results.

When performance matters, consider complementing NOT LIKE with indexed computed columns or full-text search alternatives. Used judiciously, this operator can help you write more precise, efficient queries that filter data exactly how you need it.