11. MySQL: LIKE Operator & Wildcards
The LIKE operator in MySQL is combined with wildcards to search for specific patterns in data. The operator is used in the WHERE clause of a SQL statement and can be used with any data type such as strings or numbers. The wildcards are used as a placeholder for one or more characters in the search pattern.
LIKE OPERATOR:
We use the LIKE operator in a WHERE clause to search for some specific patterns in our mentioned column.
There are two wildcards that are used with the LIKE operator.
We can also use the AND or OR operators with the LIKE operator.
Syntax:
SELECT column_1, column_2,
FROM table_name
WHERE column LIKE WILDCARD;
WILDCARDS:
% -> represents zero, one, or multiple characters
_ -> represents one single character.
We will be using the country table here:
SELECT * FROM country;
Output:
- Let's get all the names of the country that start with the letter 'A', So here we will be using % after the letter 'a'.
As we see from the Wildcards point #1 that % represents multiple characters.
SELECT * FROM country
WHERE country LIKE 'a%';
Output:
So here we see that the 'a' here is not upper case yet it shows us the proper result
- Let's get all the names of the country that end with 'a'.
SELECT * FROM country
WHERE country LIKE '%a';
Output:
- Let's find some countries which have the letters 'ra' in any position.
SELECT * FROM country
WHERE country LIKE '%ra%';
Output:
- Let's find some countries which have the letter 'w' in the third position
SELECT * FROM country
WHERE country LIKE '__w%';
Output:
So here we used 2 '_" which represents single characters.
- Let's find some country names which start with 'n' and are at least 6 characters in length
SELECT * FROM country
WHERE country LIKE 'n_____%';
Output:
- Let's see countries that start with 'i' and end with 'a'.
SELECT * FROM country
WHERE country LIKE 'i%a';
Output:
Overall, the LIKE operator and wildcards in MySQL are powerful tools that allow you to search for specific patterns in data, which can be useful in many different scenarios.
Whether you're searching for data that is similar but not exact or data that contains a specific pattern, the LIKE operator and wildcards in MySQL can help you find the information you need.
'll meet again tomorrow!
To see more examples, you can always refer w3 schools; it has always been my go-to website to understand things.
References: w3schools.com/mysql/default.asp
*****All the outputs provided are a snippet of the actual result.
Subscribe to my newsletter
Read articles from Nikhil Shenoy directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Nikhil Shenoy
Nikhil Shenoy
Aspiring to become an excellent developer and a better human being.