Skip to content
Advertisement

How to push value selected from db as first if it is equal with value in other column?

I am doing autocomplete query system for cities and I have problem, that I want to prioritize main city of region from another results showed for exact phrase for ex. “%Trenc%”.

If city and region are the same, I would like to place it as first result and then everything other.

  1. Trencin
  2. Trenc

My idea is create another column in db as “Priority” and all main cities mark as “main.” But is it possible to do it just by SQL or JS?

This is my code:

Advertisement

Answer

You can use a CASE expression in the ORDER BY to ensure that records where city and region match come before all other records.

The 0 and 1 in the case expression are using for sorting. So when the city and region match, the case expression will result in 0, otherwise, the case expression will result in 1. Since 0 comes before 1, it means the rows where city and region match will come back first in the query result.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement