In SQL, wildcard characters are special symbols used with the LIKE
operator in SELECT
, UPDATE
, DELETE
, and INSERT
statements to perform pattern matching in strings. They allow you to search for or manipulate data based on a specified pattern rather than an exact match.
Here are the commonly used wildcard characters in SQL:
Percentage sign (%): Represents zero or more characters in a string.
Underscore (_): Represents a single character in a string.
Let's explore each wildcard character with examples:
Example 1: To find all names that start with 'J', you can use:
SELECT * FROM employees WHERE first_name LIKE 'J%';
This will match any first_name
that starts with 'J', followed by zero or more characters.
Example 2: To find all names that end with 'son', you can use:
SELECT * FROM employees WHERE last_name LIKE '%son';
This will match any last_name
that ends with 'son', preceded by zero or more characters.
Example 3: To find all names that have exactly five characters and start with 'A', you can use:
SELECT * FROM employees WHERE first_name LIKE 'A____';
This will match any first_name
that starts with 'A' and is followed by exactly four more characters.
Example 4: To find all names that have 'e' as the third character, you can use:
SELECT * FROM employees WHERE last_name LIKE '__e%';
This will match any last_name
where 'e' is the third character, preceded by any two characters.
Wildcards can be used in combination with each other and with regular characters to create more complex patterns for matching. However, it's important to use them judiciously, as pattern matching with wildcards can sometimes lead to slower query performance, especially with large datasets.