SQL Wildcards
In SQL, wildcards are special characters that are used in conjunction with the LIKE
operator to perform pattern matching in queries. They allow you to search for data that matches a specific pattern rather than an exact value. The three commonly used wildcards in SQL are:
- % (Percentage Sign): The percentage sign represents zero, one, or multiple characters. It can be used to match any sequence of characters in a specific position within a string. For example, if you want to find all customers whose names start with “J”, you can use the following query:sql
SELECT * FROM customers WHERE name LIKE 'J%';
This query will return all rows from the customers
table where the name starts with the letter “J” followed by zero, one, or multiple characters.
_ (Underscore): The underscore represents a single character. It can be used to match any single character in a specific position within a string. For example, if you want to find all products with a three-letter code where the second letter is “A”, you can use the following query:
sql
SELECT * FROM products WHERE code LIKE '__A%';
This query will return all rows from the products
table where the code
column has a three-character code, and the second character is “A”.
[ ] (Square Brackets): Square brackets are used to specify a range or set of characters to match. For example, if you want to find all customers whose names start with either “A”, “B”, or “C”, you can use the following query:
sql
SELECT * FROM customers WHERE name LIKE '[ABC]%';
This query will return all rows from thecustomers
table where the name starts with either “A”, “B”, or “C”.
These wildcards can be combined to create more complex patterns. Additionally, SQL also supports the ESCAPE
clause, which allows you to specify an escape character to treat wildcards as regular characters. This can be useful when you want to search for data that contains the actual wildcard characters.