PHP/MySQL -> Using wildcards in MySQL LIKE operator

The use of wildcards inside LIKE function can save a lot of effort when you write query that looks for some pattern in character string. The wildcards are:

% substitute for unlimited amount of characters at the BEGINING/END of the string.
_ substitute for one character inside square brakets

Look for Customer names that begins with "A" and fifth char is "n":
SELECT CustomerID, CustomerName
FROM Customers
WHERE CustomerName LIKE 'A___n%';

The result will be like this:
CustomerIDCustomerName
14Antonella Musentah
23Alain Fishborn
26Arian Aspin


Look for Customer names that does not begins with "A":
SELECT CustomerID, CustomerName
FROM Customers
WHERE CustomerName NOT LIKE 'A%';

The result will be like this:
CustomerIDCustomerName
16Valentina Mazepa
20Patrick Swayze
21Marlon Zeana
25Xena Aspin


Look for Customer names that have characters "ic" and "a" somewhere inside:
SELECT CustomerID, CustomerName
FROM Customers
WHERE CustomerName LIKE '%ic%a%';

The result will be like this:
CustomerIDCustomerName
13Aida Yespica
20Patrick Swayze


Look for Customer names that starts with "M" and have characters "a" or "e" somewhere inside:
SELECT CustomerID, CustomerName
FROM Customers
WHERE CustomerName LIKE 'M%' AND
(
CustomerName LIKE '%a%' OR CustomerName LIKE '%e%'
);

The result will be like this:
CustomerIDCustomerName
21Marlon Zeana


Look for Customer names that have length of 11 characters exactly:
SELECT CustomerID, CustomerName
FROM Customers
WHERE CustomerName LIKE '___________';

The result will be like this:
CustomerIDCustomerName
26Arian Aspin



sqlexamples.info