MySQL : Wildcards

In MySQL, wildcard characters are special symbols used with the LIKE operator to perform pattern matching in queries. They allow you to search for strings that match a specified pattern rather than exact matches. Here are the commonly used wildcard characters in MySQL:

% (Percent Sign):

The % wildcard matches any sequence of zero or more characters.

Example:

SELECT * FROM products WHERE product_name LIKE '%apple%';

This query will retrieve all products with the word 'apple' anywhere in their name.

_ (Underscore):

The _ wildcard matches any single character.

Example:

SELECT * FROM customers WHERE phone_number LIKE '12345_';

This query will retrieve customers with phone numbers starting with '12345' followed by any single digit.

 [character_list] (Character List):

The [character_list] wildcard matches any single character within the specified list of characters.

Example:

SELECT * FROM products WHERE product_code LIKE 'P[123]%';

This query will retrieve products with product codes starting with 'P' followed by either '1', '2', or '3'.

[^character_list] (Negated Character List):

The [^character_list] wildcard matches any single character not in the specified list of characters.

Example:

SELECT * FROM products WHERE product_code LIKE 'P[^123]%';

This query will retrieve products with product codes starting with 'P' followed by any character except '1', '2', or '3'.

Wildcard characters are extremely useful for performing flexible searches and pattern matching in your database queries. However, it's essential to use them judiciously, as wildcard searches can sometimes lead to slower query performance, especially on large datasets.