π§ SQL Wildcards β Pattern Matching with LIKE, %, and _
π§² Introduction β What are SQL Wildcards?
SQL wildcards are special symbols used with the LIKE operator to perform flexible pattern matching in string comparisons. They help you search unknown or variable character sequences.
π― In this guide, you’ll learn:
- Common SQL wildcards and their functions
- How to use
%
and_
in patterns - Wildcard examples in real SQL queries
- Best practices and case-sensitivity notes
β 1. Supported Wildcards in SQL (with LIKE)
Wildcard | Description | Example | Matches |
---|---|---|---|
% | Zero or more characters | 'A%' | Alice, Adam, Albert |
_ | Exactly one character | 'A_' | Al, An, Ax |
[charlist] | Any single character in a set (SQL Server) | '[ABC]%' | Amy, Ben, Carl |
[^charlist] | Any single character not in set (SQL Server) | '[^ABC]%' | Mike, John, Steve |
β οΈ The [charlist]
and [^charlist]
are supported in SQL Server only.
π€ 2. Using %
β Match Any Number of Characters
SELECT * FROM customers
WHERE last_name LIKE 'Sm%';
β Matches Smith, Smiley, Smallwood, etc.
π‘ 3. Using _
β Match Exactly One Character
SELECT * FROM employees
WHERE code LIKE 'A_1';
β Matches A11, AB1, AC1, etc.
π’ 4. Combine Multiple Wildcards
SELECT * FROM products
WHERE sku LIKE 'X_12%';
β Matches X1120, XA123, XT1200, etc.
π 5. Using Wildcards in NOT LIKE
SELECT * FROM cities
WHERE name NOT LIKE 'New%';
β Excludes cities starting with “New” (e.g., New York).
π 6. Wildcard Notes by SQL Dialect
- MySQL / PostgreSQL / SQLite: Use
%
and_
only. - SQL Server: Supports extended wildcard sets with
[charlist]
,[^charlist]
.
π‘ Use ILIKE
in PostgreSQL for case-insensitive matching.
π Best Practices
β Recommended | β Avoid This |
---|---|
Use % wisely β avoid leading % | Leading % reduces index efficiency |
Use _ when you know exact position | Overusing wildcards reduces specificity |
Escape special characters if needed | Forgetting to handle % , _ in literal text |
π Summary β Recap & Next Steps
SQL wildcards are vital for pattern-based filtering in search forms, partial matches, and text mining operations.
π Key Takeaways:
%
matches zero or more characters_
matches a single character- Use with
LIKE
and optionallyNOT LIKE
- SQL Server supports
[ ]
and[^ ]
character sets
βοΈ Real-World Relevance:
Used in search engines, CRM systems, dashboards, and any app with partial input filtering.
β FAQ β SQL Wildcards
β What is the difference between %
and _
?
β
%
matches any number of characters, _
matches one character.
β Can I use wildcards without LIKE?
β No. Wildcards must be used with the LIKE
or NOT LIKE
clause.
β Are wildcards case-sensitive?
β Depends on the database. PostgreSQL is case-sensitive; MySQL isnβt by default.
β Can I use wildcards with numbers?
β Yes. Numeric values are converted to strings for matching.
β How do I escape wildcard characters?
β Use ESCAPE keyword. Example:
WHERE comment LIKE '%50\%%' ESCAPE '\';
Share Now :