SQL Advanced | Wildcards

  • SQL wildcards can be used when searching for data in a database.
  • SQL wildcards can substitute for one or more characters when searching for data in a database.
  • SQL wildcards must be used with the SQL LIKE operator
  • With SQL, the following wildcards can be used:
Table describing SQL wildcards with symbols and their meanings

SQL Wildcard Examples

We have the following “Persons” table:

A table displaying data with columns for P_Id, LastName, FirstName, Address, and City, listing three persons with their respective details.

Using the % Wildcard

Now we want to select the persons living in a city that starts with “sa” from the “Persons” table. We use the following SELECT statement:

SELECT * FROM Persons
WHERE City LIKE 'sa%'

The result-set will look like this:

Table displaying persons' details including P_Id, LastName, FirstName, Address, and City.

Next, we want to select the persons living in a city that contains the pattern “nes” from the “Persons” table. We use the following SELECT statement:

SELECT * FROM Persons
WHERE City LIKE '%nes%'

The result-set will look like this:

A table displaying data of persons with columns for P_Id, LastName, FirstName, Address, and City, showing two entries.

Using the _ Wildcard

Now we want to select the persons with a first name that starts with any character, followed by “la” from the “Persons” table.
We use the following SELECT statement:

SELECT * FROM Persons
WHERE FirstName LIKE '_la'

The result-set will look like this:

P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes

Next, we want to select the persons with a last name that starts with “S”, followed by any character, followed by “end”, followed by any character, followed by “on” from the “Persons” table.

We use the following SELECT statement:

SELECT * FROM Persons
WHERE LastName LIKE 'S_end_on;

The result-set will look like this:

P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes

Using the [charlist] Wildcard

Now we want to select the persons with a last name that starts with “b” or “s” or “p” from the”Persons” table. We use the following SELECT statement:

SELECT * FROM Persons
WHERE LastName LIKE '[bsp]%'

The result-set will look like this:

A table displaying the results of a SQL query, showing columns for P_Id, LastName, FirstName, Address, and City, with entries for two individuals: Svendson Tove from Sandnes and Pettersen Kari from Stavanger.

Next, we want to select the persons with a last name that do not start with “b” or “s” or “p” from the “Persons” table. We use the following SELECT statement:

SELECT * FROM Persons
WHERE LastName LIKE '[!bsp]%'

The result-set will look like this:

A table displaying information on a person named Ola Hansen, including their ID, last name, first name, address, and city.

Leave a Reply

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading