Wildcards in SQL are special characters that allow you to substitute for unknown characters in a string. They are commonly used in conjunction with the LIKE
operator to search for specific patterns in data.
%
: Represents zero, one, or multiple characters. For example, WHERE name LIKE 'M%'
finds all names starting with 'M'._
: Represents a single character. For example, WHERE name LIKE 'A_'
finds names like 'Al', 'An', but not 'Aaron'.Wildcards can be used in the WHERE
clause to filter results based on pattern matching.
Example: To find all products that contain the word "book" in their name:
SELECT * FROM Products
WHERE ProductName LIKE '%book%';
This query returns any product with "book" anywhere in its name.
Wildcards can be combined with other conditions using AND
or OR
.
Example: To find all employees whose name starts with 'L' and have an 'a' in the second position:
SELECT Name FROM Employees
WHERE Name LIKE 'L_a%';
This will return names like "Laeeque".
Wildcards are case-sensitive in some database systems. For example, in PostgreSQL, LIKE
is case-sensitive by default, whereas in MySQL, it is not. To perform a case-sensitive search, you might use:
SELECT Name FROM Employees
WHERE BINARY Name LIKE 'J%';
Most relational database management systems (RDBMS) support wildcards: