LIKE operator in MySQL gives us the flexibility to search for data entries which we are not completely sure with. This is applies in cases, were suppose we need to find all names starting with “Jo”, or ending with “en” etc. We cannot apply normal “=” operator with the search query.
MySQL provides two wildcard characters for using with LIKE operator;
1. Percentage (%)
2. Underscore (_)
“%” matches any string of zero or more characters.
“_” matches any single character.
Please see the examples for more details;
Suppose we need to get all the users with their name starting with “A”. The query would be;
SELECT name FROM users WHERE name LIKE ‘A%’;
Here the % means 0 or more characters. See some more sample queries.
Select all names starting with ‘A’ and ending with ‘N’
SELECT name FROM users WHERE name LIKE ‘A%N’;
Select all names where the names should start with ‘T’ and end with ‘M’, but should only have 1 character between them. In this case, we cannot apply “%” operator since this will match more than one character. So we use the second wild card, “_”. The query will look like;
SELECT name FROM users WHERE name LIKE “T_M”;
Select all names where the second letter is b;
SELECT names FROM users WHERE name LIKE ‘_b%’;