SQL LIKE Operator
The LIKE operator in SQL is used to search for a specified pattern in a column. It is commonly used with the WHERE clause to filter data based on partial matches.
📌 Syntax
SELECT column1, column2, ... FROM table_name WHERE column LIKE pattern;
🔹 Wildcards
%– Represents zero, one, or multiple characters._– Represents a single character.
📊 Example Table: users
id | name | age | city ---+---------+-----+--------- 1 | Alice | 22 | New York 2 | Bob | 30 | London 3 | Charlie | 18 | Sydney 4 | Diana | 27 | Toronto 5 | Ethan | 35 | Paris
🔍 Example 1: Names Starting with A
Find users whose names start with "A":
SELECT * FROM users WHERE name LIKE 'A%';
🔍 Example 2: Names Ending with "a"
SELECT * FROM users WHERE name LIKE '%a';
🔍 Example 3: Names Containing "ar"
SELECT * FROM users WHERE name LIKE '%ar%';
🔍 Example 4: Names with Second Letter "o"
SELECT * FROM users WHERE name LIKE '_o%';
⚡ Best Practices
- Use
LIKEfor flexible pattern matching in queries. - Consider using indexes with caution; leading
%may prevent index usage. - Combine with
NOT LIKEto exclude patterns. - Use
ILIKEin some databases for case-insensitive matching.
📝 Summary
The LIKE operator is powerful for filtering rows based on patterns. Wildcards such as % and _ make searches flexible. It is commonly used in reports, search features, and data validation.
🚀 Next Steps
Next, we will explore the IN Operator in SQL, which allows filtering rows based on a set of values.