Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by most matched records first

Tags:

sql

postgresql

Given the following query:

select * from users 
where first_name ilike '%foo%' 
OR last_name ilike '%bar%' 
OR nickname ilike '%foobar%'

Returns:

 first_name| last_name   |  nickname
----------------------------------------
  Foo      | ABC         |   abcd
  Foo      | DEF         |   efgh
  Foo      | BAR         |   ijkl
  AMD      | Bar         |   foobar
  Foo      | Bar         |   foobar2

Question:

How to sort most relevant (matched) values first? I mean by most matched that matches more than one pattern inside Where .. OR

Expected Result:

 first_name| last_name   |  nickname
----------------------------------------
  Foo      | Bar         |   foobar2
  Foo      | BAR         |   ijkl
  AMD      | Bar         |   foobar
  Foo      | ABC         |   abcd
  Foo      | DEF         |   efgh
like image 888
Moamen Naanou Avatar asked Apr 16 '18 08:04

Moamen Naanou


People also ask

Does WHERE OR ORDER BY come first in SQL?

The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name. Use ASC to sort the records in ascending order or use DESC for descending order.

What is the order of SQL SELECT?

Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY.

Can we use ORDER BY and WHERE clause in one query?

You can use the WHERE clause with or without the ORDER BY statement. You can filter records by finite values, comparison values or with sub-SELECT statements.

How to use ORDER BY in SQL with WHERE clause?

SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.


1 Answers

Order it by the number of hits:

... ORDER BY (first_name ILIKE '%foo%')::integer 
           + (last_name  ILIKE '%bar%')::integer
           + (nickname   ILIKE '%foobar%')::integer DESC
like image 158
Laurenz Albe Avatar answered Sep 21 '22 15:09

Laurenz Albe