May 16, 2021 SQLite
The LIKE operator for SQLite is the text value used to match the pattern specified by the wildcard. I f the search expression matches the pattern expression, the LIKE operator returns true, which is 1. There are two wildcards that are used with the LIKE operator:
Percent sign (%)
Underscores
A percent sign (%) represents zero, one or more numbers, or characters. A n underscore represents a single number or character. These symbols can be combined.
The basic syntax for % and s is as follows:
SELECT FROM table_name WHERE column LIKE 'XXXX%' or SELECT FROM table_name WHERE column LIKE '%XXXX%' or SELECT FROM table_name WHERE column LIKE 'XXXX_' or SELECT FROM table_name WHERE column LIKE '_XXXX' or SELECT FROM table_name WHERE column LIKE '_XXXX_'
You can use the AND or OR operator to combine N conditions. Here, XXXX can be any number or string value.
Here are some examples that demonstrate the difference between the LIKE clause with the '%' and ''operators:
Statement | describe |
---|---|
WHERE SALARY LIKE '200%' | Find any value starting with 200 |
WHERE SALARY LIKE '%200%' | Find any position containing arbitrary value of 200 |
WHERE SALARY LIKE '_00%' | Find any value of the second and third digits 00 |
WHERE SALARY LIKE '2_%_%' | Find any value starting with 2 starts and at least 3 characters length |
WHERE SALARY LIKE '%2' | Find any value ended with 2 |
WHERE SALARY LIKE '_2%3' | Find the second bit of 2, and any value ended at 3 |
WHERE SALARY LIKE '2___3' | The lookup length is 5 digits, and at any value ends at 3 out of 2 |
Let's take a practical example, assuming that the COMPANY table has the following records:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
Here's an example that shows all records in the COMPANY table that AGE starts with 2:
sqlite> SELECT * FROM COMPANY WHERE AGE LIKE '2%';
This results in the following:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
Here's an example that shows all records in the ADDRESS text in the COMPANY table that contain a hyphen (-):
sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%';
This results in the following:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 6 Kim 22 South-Hall 45000.0