
For an instructor lead, in-depth look at learning SQL click below.
SQL, or Structured Query Language, is a powerful language used for managing and manipulating relational databases. One of the more advanced features in SQL is pattern matching— a versatile tool that lets you locate specific patterns in your data. In this post, we’ll dive deep into pattern matching in SQL.
WHAT IS PATTERN MATCHING?
Pattern matching in SQL is a technique used to find rows that match a specific pattern. This is performed under the LIKE operator, and uses wildcard characters that represent unknown characters.
WILDCARDS IN SQL
A wildcard character is used to substitute any other character(s) in a string. In SQL, there are two wildcard characters you can use:
‘%’ – represents zero, one, or multiple characters
‘_’ – represents a single character
USING THE LIKE OPERATOR
The behavior of the LIKE operator is defined as follows:
|
1 2 3 4 5 6 7 8 |
Column LIKE 'abc' --exactly 'abc' Column LIKE 'abc%' --starts with 'abc' Column LIKE '%abc' --ends with 'abc' Column LIKE '%abc%' --contains 'abc' Column LIKE '_bc' --'abc', 'bbc', 'cbc', etc. Column LIKE 'a_c' --'abc', 'acc', etc. |
EXAMPLES OF SQL PATTERN MATCHING
Suppose we have a table named Customers, and we want to search all customers whose name contains ‘John’. Notice we use the ‘%’ wildcard to represent zero or more characters.
|
1 2 3 4 5 |
SELECT * FROM Customers WHERE Name LIKE '%John%'; |
It will return all rows where ‘John’ is found anywhere in the Name field.
Alternatively, let’s find all customers whose name starts with ‘John’:
|
1 2 3 4 5 |
SELECT * FROM Customers WHERE Name LIKE 'John%'; |
Lastly, we can even use the ‘_’ wildcard to match any single character, for example, to find all two-letter country codes:
|
1 2 3 4 5 |
SELECT * FROM Countries WHERE Code LIKE '__'; |
CONCLUSION
Pattern matching in SQL might seem tricky at first, but it’s a powerful tool that can make your queries more flexible and effective. Understanding how to leverage wildcards will give you the ability to manipulate your data in new and exciting ways, enhancing your data management skills significantly.
