SQL Wildcards

SQL wildcards are used with the LIKE operator to search for specific patterns in a column. They allow for flexible searches and are particularly useful when you need to match partial strings.

Wildcard Characters

SQL provides two primary wildcard characters for pattern matching:

  • %: Represents zero or more characters. It can be used at the beginning, middle, or end of the pattern. Example: '%pattern%' matches any string containing 'pattern'.
  • _: Represents a single character. It is useful for matching a specific number of characters. Example: 'a_c' matches 'abc', 'adc', etc.

Examples

Here are some examples of how you can use wildcards with the LIKE operator:


-- Find all products with names starting with 'A'
SELECT * FROM Products
WHERE ProductName LIKE 'A%';

-- Find all customers whose names end with 'son'
SELECT * FROM Customers
WHERE CustomerName LIKE '%son';

-- Find all employees with names having exactly five letters
SELECT * FROM Employees
WHERE EmployeeName LIKE '_____' -- Five underscores

        

Combining Wildcards

You can combine wildcards to create more specific patterns. For example, you can use multiple wildcards to match strings with varying patterns:


-- Find all email addresses that end with 'example.com'
SELECT * FROM Users
WHERE Email LIKE '%@example.com';

-- Find all books with titles starting with 'The' and having exactly 4 characters after 'The'
SELECT * FROM Books
WHERE Title LIKE 'The____';