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