SQL’s `LIKE` operator is the simplest way to search for records where a column contains a given string, without matching an exact value. Unlike `=` (which requires exact equality), `LIKE` uses wildcards—`%` matches any sequence of characters, and `_` matches a single character—to filter patterns. This makes it ideal for tasks like finding customer names with partial matches, log entries with keywords, or product descriptions containing certain terms. What you’ll need depends on your database type, but the method itself is universal across SQL dialects (MySQL, PostgreSQL, SQL Server, Oracle, etc.).
What You'll Need
- Access to a database (via command-line tools, IDEs like MySQL Workbench, or application code).
- A table with the column(s) you want to search.
- Basic knowledge of SQL syntax (though a simple `SELECT` is enough for this task).
- Wildcards (`%` and `_`) to define search patterns.
Step-by-Step
- Choose the column to search. Start by identifying which column in your table contains the text you want to filter. For example, if you’re looking for customer names in a `customers` table, you’d use the `name` column.
-
Write the basic `SELECT` query.
Begin with `SELECT` followed by the column(s) you want to retrieve and `FROM` your table. For instance:
SELECT name FROM customers;This retrieves all names from the table (no filtering yet). -
Add the `LIKE` operator with wildcards.
Replace the `=` in your query with `LIKE` and surround your search term with single quotes. Use `%` to match any sequence of characters before or after your term, and `_` for a single character.
Example 1: Find names containing "Smith"
SELECT name FROM customers WHERE name LIKE '%Smith%';This finds all names with "Smith" anywhere in them (e.g., "John Smith," "Smithers," "Smithville"). Example 2: Find names starting with "Jo"SELECT name FROM customers WHERE name LIKE 'Jo%';Example 3: Find names with exactly 5 charactersSELECT name FROM customers WHERE name LIKE '___%';(Each `_` matches one character; `%` matches everything after.) -
Test partial matches (optional).
If you want to refine results further, combine `LIKE` with other conditions. For example:
SELECT name FROM customers WHERE name LIKE '%Smith%' AND age > 30;This finds names with "Smith" *and* customers over 30. - Run the query in your database client. Paste your query into your tool (e.g., MySQL Command Line, PostgreSQL `psql`, or a GUI like DBeaver). Press Enter to execute. Note: If you’re using an IDE or web-based tool, look for a "Run Query" button or equivalent.
Common Mistakes
-
Case sensitivity issues.
Most databases treat `'%Smith%'` and `'%SMITH%'` as different unless you enable case-insensitive comparison. To fix:
- MySQL: Use `WHERE LOWER(name) LIKE '%smith%';
- PostgreSQL: Use `WHERE name ILIKE '%smith%';
- SQL Server: Use `WHERE name LIKE '%smith% COLLATE SQL_Latin1_General_CP1_CI_AS';
-
Wildcards at the start/end.
If your pattern starts with `%` (e.g., `LIKE '%Smith'`), the query will return empty results because `%` consumes all characters. Use `_%` instead to match names *starting* with "Smith":
SELECT name FROM customers WHERE name LIKE '_Smith%'; - Overusing wildcards. Excessive `%` can lead to performance issues in large tables. For critical searches, use exact matches (`=`), full-text search, or indexes.
- Quoting the wildcard incorrectly. Wildcards (`%` and `_`) are not treated as strings, so they don’t need quotes. If you accidentally use `'%'`, your query will fail.
Tips
- Use `%` sparingly. Replace `%` with specific letters to narrow results. For example, `LIKE 'Jo%'` (not `%Jo%`) is faster than `LIKE '%John%'` if you know the name starts with "Jo."
- Combine with `ILIKE` (PostgreSQL) or `LIKE COLLATE` (SQL Server). These options make searches case-insensitive without modifying your query logic.
-
Add a WHERE condition.
Filter by other columns (e.g., `WHERE status = 'active'`) to reduce irrelevant matches.
SELECT name FROM customers WHERE name LIKE '%Smith%' AND status = 'active'; - Test with a small subset. Run a query on a limited table (e.g., 10 rows) to debug patterns before scaling to full datasets.
-
Leverage indexes.
If you frequently search columns like `name`, create an index to speed up `LIKE` queries:
CREATE INDEX idx_name ON customers(name);(Syntax varies by DBMS; check your database’s documentation.)
Troubleshooting
If your `LIKE` query fails, check these steps in order:
-
Basic syntax errors.
Verify your query matches the format `SELECT ... FROM table WHERE column LIKE 'pattern';`. Common mistakes:
- Missing single quotes around the pattern.
- Using `=` instead of `LIKE`.
- Forgetting `WHERE` before the condition.
-
Case sensitivity.
If results are empty or incorrect, try converting the column to uppercase/lowercase:
SELECT name FROM customers WHERE UPPER(name) LIKE '%SMITH%';(Use `LOWER()` in MySQL, `ILIKE` in PostgreSQL, or `COLLATE` in SQL Server.) -
Empty results from wildcards.
If `LIKE '%Smith%'` returns nothing, check for:
- No matching data in the column.
- Case mismatch (e.g., "SMITH" vs. "smith").
- Hidden characters (e.g., extra spaces or special symbols).
-
Performance issues.
For large tables, optimize by:
- Using indexes on frequently searched columns.
- Reducing the number of `%` characters (e.g., `LIKE 'Jo_'` instead of `LIKE '%Jo%'`).
- Breaking complex queries into smaller steps.
-
Database-specific errors.
Consult your DBMS’s error messages. For example:
- MySQL: Check for `mysql_error` or `Warning: 1054` (unknown column).
- PostgreSQL: Look for `ERROR: column does not exist`.
Frequently Asked Questions
How do I search for exact phrase matches with LIKE?
Use `LIKE '...%'` to match the end of a string, but for exact phrases, combine `LIKE` with `REGEXP` (MySQL) or `~` (PostgreSQL). For example:
- MySQL:
SELECT * FROM table WHERE name REGEXP 'John Smith'; - PostgreSQL:
SELECT * FROM table WHERE name ~ 'John Smith';
Can I use LIKE with numbers?
Yes, but be precise. For example:
- Find ages between 25 and 30:
SELECT * FROM table WHERE age BETWEEN 25 AND 30; - Find IDs starting with 10:
SELECT * FROM table WHERE id LIKE '10%';
Why does my LIKE query return no results?
Check for these causes:
- Incorrect column/tables name (e.g., misspelled `name` vs. `Name`).
- Case sensitivity (e.g., searching for "Smith" but the data is stored as "Smiths").
- Hidden characters or extra spaces in your search pattern.
- No data matches your criteria (e.g., searching for "ghost" in a table with no entries containing "ghost").
How do I search for patterns in multiple columns?
Combine `LIKE` with `OR` to search across columns. For example:
SELECT * FROM table
WHERE name LIKE '%Smith%'
OR address LIKE '%Smith%';
What’s the difference between LIKE and CONTAINS in some databases?
`LIKE` uses wildcards and is flexible for text matching. Most databases (e.g., PostgreSQL) have a `CONTAINS` function for full-text search, which:
- Uses word boundaries (`\b`) for better matching.
- Supports tokenization (e.g., finds "Smith" even if separated by punctuation).
- Returns a ranked list of matches (useful for prioritizing relevant results).
Example (PostgreSQL):
SELECT * FROM table WHERE name @@ plainto_tsquery('english', 'smith');
How can I optimize LIKE queries for large tables?
Apply these optimizations:
- Create indexes on frequently searched columns:
CREATE INDEX idx_name ON table(name); - Avoid `LIKE '%%'` (double `%`)—it’s inefficient.
- Use exact matches (`=`) or full-text search when possible.
- Limit the number of rows returned with `LIMIT`.
For example, replace:
SELECT * FROM large_table WHERE name LIKE '%Smith%';
with:
SELECT name FROM large_table WHERE name LIKE '%Smith%' AND id < 1000000 LIMIT 100;
(Assuming `id` is indexed and you only need the first 100 matches.)