I need a SQLite query that searches 1 field only using LIKE.
Basic example:
SELECT name FROM table WHERE name LIKE "%John%" ORDER BY name LIMIT 10;
The problem is that I want the result to be ordered in this way:
The following query achieves the expected result, but is slow:
SELECT name FROM table WHERE name LIKE "%John%" ORDER BY CASE WHEN name = "John"
THEN 1 ELSE 2 END, CASE WHEN name LIKE "John%" THEN 1 ELSE 2 END, name LIMIT 10;
The query above is slower (or I tested it incorrectly) than the alternative of using 3 separate queries (one for exact match, one for starts with and one for contains).
Are there any other alternatives?
Introduction to SQLite LIKE operator Note that you can also use the LIKE operator in the WHERE clause of other statements such as the DELETE and UPDATE . The percent sign % wildcard matches any sequence of zero or more characters.
The keyword ILIKE can be used instead of LIKE to make the match case insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension. The operator ~~ is equivalent to LIKE , and ~~* corresponds to ILIKE .
To be case insensitive on firstname , write this: select * from tbl where firstname='john' COLLATE NOCASE and lastname='doe' . It's specific to that one column, not the entire where clause.
Double-quotes in SQLite identifiers are escaped as two double quotes. SQLite identifiers preserve case, but they are case-insensitive towards ASCII letters. It is possible to enable unicode-aware case-insensitivity.
Try in this way :
SELECT name
FROM table
WHERE name LIKE "%John%"
ORDER BY (CASE WHEN name = "John" THEN 1 WHEN name LIKE "John%" THEN 2 ELSE 3 END),name LIMIT 10 ;
It should suffice to order on your equivalence tests:
ORDER BY name = "John" DESC, name LIKE "John%" DESC
ORDER BY clauses are evaluated from left to right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With