๐งฉ SQL LIKE โ Pattern Matching with Wildcards in SQL
๐งฒ Introduction โ Why Use SQL LIKE?
The LIKE operator in SQL is used to search for specific patterns in string values. It’s a powerful tool for performing partial matches, flexible filtering, and simple text analysis.
๐ฏ In this guide, you’ll learn:
- How to use
LIKEwith%and_wildcards - Combine
LIKEwithWHEREand logical conditions - Handle case-sensitivity across different databases
- Real-world examples of pattern matching
โ 1. Basic LIKE Syntax
SELECT * FROM users WHERE name LIKE 'A%';
โ Returns names starting with “A”.
๐ง 2. Pattern Matching Wildcards
| Symbol | Meaning | Example | Matches |
|---|---|---|---|
% | Zero or more characters | 'J%' | John, Jake, Jasmine |
_ | Exactly one character | 'J_n' | Jon, Jan, Jim |
๐งช 3. Examples of SQL LIKE Patterns
-- Names that start with A
SELECT * FROM employees WHERE name LIKE 'A%';
-- Emails ending with '.com'
SELECT * FROM contacts WHERE email LIKE '%.com';
-- Cities with 'new' in the middle
SELECT * FROM locations WHERE city LIKE '%new%';
-- Postal codes that are exactly 5 digits
SELECT * FROM addresses WHERE postal_code LIKE '_____' -- five underscores
๐ 4. Using NOT LIKE
SELECT * FROM products WHERE name NOT LIKE '%apple%';
โ Returns all products that do not contain “apple”.
โ ๏ธ 5. Case Sensitivity in LIKE
- MySQL: Case-insensitive by default (unless BINARY keyword used)
- PostgreSQL: Case-sensitive by default
- SQL Server: Depends on the collation
๐ก Use ILIKE in PostgreSQL for case-insensitive matching.
๐ง 6. LIKE with Logical Operators
SELECT * FROM users
WHERE name LIKE 'A%' OR name LIKE 'B%';
โ
Combines multiple LIKE patterns using OR.
๐ Best Practices
| โ Do This | โ Avoid This |
|---|---|
Use % and _ precisely | Overusing % at both ends for large tables |
Use ILIKE in PostgreSQL if needed | Assuming all LIKE queries are case-insensitive |
| Optimize indexed columns | Ignoring performance impact of wildcards |
๐ Summary โ Recap & Next Steps
SQL LIKE is your go-to tool for performing text pattern matching. With % and _, you can construct expressive search filters across a wide variety of string data.
๐ Key Takeaways:
%matches any number of characters;_matches exactly one- Combine LIKE with
WHERE,NOT, andORfor flexible searches - Behavior varies based on RDBMS case sensitivity settings
โ๏ธ Real-World Relevance:
Used in search bars, product filters, customer lookup, and data cleansing operations.
โ FAQ โ SQL LIKE
โ What is the difference between LIKE and =?
โ
LIKE supports pattern matching; = checks for an exact match.
โ Does LIKE support case-insensitive search?
โ
Depends on your database engine. Use ILIKE for PostgreSQL.
โ Can I use LIKE with numbers?
โ Yes, but numbers are implicitly cast as strings.
โ Can I match only one character?
โ
Use _ (underscore) to match exactly one character.
โ What is the performance impact of LIKE?
โ
It can be slow with leading % wildcards unless indexed or optimized.
Share Now :
