Jigar Dhaduk
Jigar Dhaduk

Reputation: 662

LIKE query by best match by column

I have a table named customers and running query as below

SELECT * FROM customers WHERE email LIKE '%ab%' OR first_name LIKE '%ab%';

The result is as below.

------+-------+-------+------- +
|      email    | first_name   |
+-----+-------+-------+------- +
| [email protected] |   xyz        |
| [email protected] |   abc        |
+-----+-------+-------+--------+

What I need is, the first_name is best match for search keyword. So I need that row first.

Upvotes: 0

Views: 95

Answers (1)

Luuk
Luuk

Reputation: 14999

You might want to add an order by:

SELECT * 
FROM customers 
WHERE email LIKE '%ab%' OR first_name LIKE '%ab%'
ORDER BY CASE WHEN first_name LIKE '%ab%' THEN 1 ELSE 2 END;

Upvotes: 2

Related Questions