PostgreSQL LIKE Operator
What is LIKE?
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. It's essential for pattern matching and text searching in PostgreSQL.
Basic Syntax
Wildcard Characters
PostgreSQL LIKE supports two wildcard characters:
Basic LIKE Examples
Example 1: Starts With
Example 2: Ends With
Example 3: Contains
Example 4: Exact Length with Underscore
Combining Wildcards
Case Sensitivity
LIKE (Case-Sensitive)
ILIKE (Case-Insensitive)
NOT LIKE
Finds rows that don't match the pattern:
Escaping Special Characters
When you need to search for literal % or _ characters:
LIKE with Multiple Conditions
OR Conditions
AND Conditions
Performance Considerations
1. Leading Wildcard Performance
2. Use Indexes
3. Full-Text Search Alternative
For complex text searches, consider full-text search:
Practical Examples
Example 1: Email Validation
Example 2: Phone Number Patterns
Example 3: Product Search
Example 4: File Management
LIKE with Other Clauses
With JOIN
With GROUP BY
With Subqueries
Advanced Patterns
Pattern 1: Multiple Word Search
Pattern 2: Exclude Patterns
Pattern 3: Complex Email Filtering
SIMILAR TO (SQL Standard)
PostgreSQL also supports SIMILAR TO for regex-like patterns:
Regular Expressions (More Powerful)
For complex patterns, use regex operators:
Common Mistakes and Solutions
Mistake 1: Forgetting Wildcards
Mistake 2: Case Sensitivity Issues
Mistake 3: Performance with Leading Wildcard
Best Practices
- Use ILIKE for Case-Insensitive: More readable than LOWER() with LIKE
- Avoid Leading Wildcards: They prevent index usage
- Create Appropriate Indexes: Use expression indexes for case-insensitive searches
- Consider Full-Text Search: For complex text searching
- Escape Special Characters: When searching for literal
%or_ - Use Specific Patterns: More specific patterns are faster
- Test Performance: Profile queries with EXPLAIN ANALYZE
Summary
The LIKE operator is essential for pattern matching:
- Uses
%(zero or more characters) and_(exactly one character) - LIKE is case-sensitive, ILIKE is case-insensitive
- NOT LIKE excludes matching patterns
- Leading wildcards prevent index usage
- Consider full-text search for complex patterns
- Use ESCAPE for literal wildcard characters
- Regular expressions provide more powerful pattern matching
Mastering LIKE is crucial for effective text searching and filtering in PostgreSQL.