MySQL
SQL Query
String Functions
Database Management
Text Search

MySQL query String contains

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

MySQL is a widely used open-source relational database management system. One common task when working with MySQL is to query data based on whether a string contains certain substrings. In this article, we will explore different methods to perform string containment checks in MySQL using various functions and operators. Additionally, we will cover performance considerations and use cases.

Methods for String Containment Checks

Using LIKE Operator

The LIKE operator is one of the most straightforward methods for checking if a string contains a substring in MySQL. The percent sign (%) acts as a wildcard, matching zero or more characters.

sql
SELECT * FROM employees WHERE name LIKE '%John%';

In this example, any record where the name field contains "John" will be returned. The use of % before and after "John" allows the query to match any occurrence of "John" within the string.

Using INSTR() Function

The INSTR() function returns the position of the first occurrence of a substring within a string. If the substring is not found, it returns 0.

sql
SELECT * FROM employees WHERE INSTR(name, 'John') > 0;

This query will return records where "John" is part of the name, as INSTR() will return a positive integer indicating its position.

Using LOCATE() Function

Functionally similar to INSTR(), the LOCATE() function returns the position of the first occurrence of a substring.

sql
SELECT * FROM employees WHERE LOCATE('John', name) > 0;

The difference between INSTR() and LOCATE() lies in the order of arguments; LOCATE() takes the substring first.

Using REGEXP Operator

For complex pattern matching, the REGEXP operator allows regular expressions, providing a powerful way to search strings.

sql
SELECT * FROM employees WHERE name REGEXP 'John';

This example finds records where name contains the pattern "John". Regular expressions can be crafted to match much more complex patterns if necessary.

Performance Considerations

When performing string searches in MySQL, especially on large datasets, performance can become an issue. The choice of method can affect query speed.

  1. Indexes: While basic indices may speed up string searches, methods like LIKE '%substring%' can't effectively use standard B-tree indexes because of the leading wildcard. Full-text indexes can be beneficial for text-based searches.
  2. Use of Full-Text Indexes: Available in InnoDB and MyISAM tables, full-text indexing is tailored for match searches on a text column.
sql
   CREATE FULLTEXT INDEX name_idx ON employees(name);
   SELECT * FROM employees WHERE MATCH(name) AGAINST('John');
  1. Substring Functions: Functions like INSTR() and LOCATE() are marginally faster than LIKE searches without leading % because they don't trigger full table scans when indexed properly.

Examples and Use Cases

Filtering Data

Often, string containment checks help filter database entries. For example, fetching employees whose titles include "Engineer".

sql
SELECT * FROM employees WHERE title LIKE '%Engineer%';

Validation

Ensuring data integrity sometimes involves validation against known substrings.

sql
SELECT * FROM users WHERE email LIKE '%.edu';

This query examines if emails belong to educational institutions without capturing malformed entries.

Pattern Recognition

Using regex, complex patterns can be searched, such as finding records with specific alphanumeric combinations:

sql
SELECT * FROM orders WHERE product_code REGEXP '[A-Z]{3}[0-9]{2}';

Summary Table

Below is a summary of key points regarding string containment checks in MySQL:

MethodDescriptionPerformanceUse Case
LIKEUses wildcards to match patternsBest for small tables Limited by wildcard usageSimple substring searches
INSTR()Finds the position of first substringSlightly faster due to direct substring identificationMid-sized datasets With simple patterns
LOCATE()Similar to INSTR() with different syntaxSimilar to INSTR()Similar to INSTR()
REGEXPUses regular expressions for complex patternsPotentially slow on large tables unless indexedComplex pattern recognition
Full-Text IndexIndexes text columns for better performanceFast for text-heavy fieldsLarge datasets with search-heavy operations

Understanding the appropriate scenario to use each method allows for efficient query writing and database performance optimization. By leveraging the correct function or operator, you can ensure your MySQL queries remain both effective and performant.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.