SQL Wildcards

What are SQL Wildcards?

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.

Common SQL Wildcards

  • %: 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'.

Using Wildcards in SQL

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.

Combining Wildcards with Other Conditions

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".

Case Sensitivity with Wildcards

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%';

Wildcards in Popular Databases

Most relational database management systems (RDBMS) support wildcards:

  • MySQL
  • PostgreSQL
  • Microsoft SQL Server
  • Oracle Database
  • SQLite