Wildcards in SQL

When we write queries, we might not know the whole details about the data we are searching for. Sometimes we may require list of records ranging between some categories. If the values are of number type, then we can use arithmetic operators like =, !=, <, <=, >, or >=. But if it is a character type then these arithmetic operators will not work. We need some special operators to compare strings. We might not know whole string, probably part of the string is known or we might need to find the records which contains/ start/ends with some characters or string. This can be compared using wild cards. There are two wild cards โ€“ โ€˜_โ€™ to compare single character and โ€˜%โ€™ to compare zero or more characters.

Suppose we want to list all the categories whose ID starts with โ€˜Dโ€™. Then the query can be written using โ€˜%โ€™, since we donโ€™t know how many characters can occur after โ€˜Dโ€™.

SELECT * FROM CATEGORY WHERE CATEGORY_ID LIKE ‘D%’;

 

Consider a query to get the categories whose ID starts with โ€˜DBMSโ€™. Also imagine that you know what length of category ID is.ย  Then we can write query as

SELECT * FROM CATEGORY WHERE CATEGORY_ID LIKE 'DBMS_____';

OR

SELECT * FROM CATEGORY WHERE CATEGORY_ID LIKE 'DBMS%';

 

When we use โ€˜_โ€™ to compare the characters, it compares only single character. Hence we have to specify it as many times as the characters are. Whereas โ€˜%โ€™ compares zero or more characters in the string. Hence it is enough to specify it only once in the string.

Consider below query which searches for the publisher Id which has 45 in it and ends with any two character/digits after 45. It will strictly search for the strings ending with 2 characters after 45.

SELECT * FROM PUBLISHER WHERE PUB_ID LIKE โ€˜%45__โ€™;

Above query has not listed publisher โ€“ Pearson, as it does not have any characters after 45. But the same can be retrieved by using โ€˜%โ€™ like below.

Let us consider some other examples: Write a query to find the book names starting with โ€˜Databaseโ€™

SELECT * FROM BOOKS WHERE BOOK_NAME LIKE โ€˜Database%โ€™;

Write a query to find the book names ending with โ€˜Databasesโ€™.

SELECT * FROM BOOKS WHERE BOOK_NAME LIKE โ€˜%Databasesโ€™;

Write a query to find the book names containing โ€˜Databaseโ€™.

SELECT * FROM BOOKS WHERE BOOK_NAME LIKE โ€˜%Database%โ€™;

Find the books which belong to category IDs starts with DBMS_10.

SELECT b.*, bc.CATEGORY_ID 
	FROM BOOKS b, BOOK_CATEGORY bc
WHERE b.ISBN = bc.ISBN
AND bc.CATEGORY_ID LIKE 'DBMS_10__';

Translate ยป