Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite LIKE & ORDER BY Match query

Tags:

sql

sqlite

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:

  1. If the field is equal (e.g. "John")
  2. If the field starts with "John" (e.g. "John Doe")
  3. If the field contains "John" (e.g. "Jane John Doe")

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?

like image 382
bogdansrc Avatar asked Apr 09 '12 08:04

bogdansrc


People also ask

Can you use like in SQLite?

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.

What is the difference between like and Ilike?

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 .

How do I make SQLite case insensitive?

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.

How do I escape in SQLite?

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.


2 Answers

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 ;
like image 151
aleroot Avatar answered Sep 30 '22 09:09

aleroot


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.

like image 41
Emil Vikström Avatar answered Sep 30 '22 10:09

Emil Vikström