Python MySQL – LIKE() operator
In this article, we will discuss the use of LIKE operator in MySQL using Python language.
Sometimes we may require tuples from the database which match certain patterns. For example, we may wish to retrieve all columns where the tuples start with the letter ‘y’, or start with ‘b’ and end with ‘l’, or even more complicated and restrictive string patterns. This is where the LIKE Clause comes to the rescue, often coupled with the WHERE Clause in SQL.
There are two kinds of wildcards used to filter out the results:
- The percent sign (%): Used to match zero or more characters. (Variable Length)
- The underscore sign (_): Used to match exactly one character. (Fixed Length)
SELECT column1, column2, …,columnn
WHERE columnn LIKE pattern;
The following are the rules for pattern matching with the LIKE Clause:
Pattern Meaning ‘a%’ Match strings which start with ‘a’ ‘%a’ Match strings with end with ‘a’ ‘a%t’ Match strings which contain the start with ‘a’ and end with ‘t’. ‘%wow%’ Match strings which contain the substring ‘wow’ in them at any position. ‘_wow%’ Match strings which contain the substring ‘wow’ in them at the second position. ‘_a%’ Match strings which contain ‘a’ at the second position. ‘a_ _%’ Match strings which start with ‘a’ and contain at least 2 more characters.
In order to use LIKE operations we are going to use the below table:
Below are various examples that depict how to use LIKE operator in Python MySQL.
Program to display rows where the address starts with the letter G in the itdept table.
Here we display all the rows where the name begins with the letter H and ends with the letter A in the table.
In this program, we display all the rows having three-lettered addressees in the table.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course