Skip to content
Advertisement

postgresql conditionally generating value for each row

I am trying to implement a simple search functionalitu over links.name column. I would like to match keywords against name values and wanted to get the names with more matchings on the top of result. What I want/tried to do is

declare matchings integer := 0
select if "keyword1" ~* name then matchings := matchings + 1 end if
       if "keyword2" ~* name then matchings := matchings + 1 end if
       ... so on for all keywords given ..
       as matchings_count from links order by matchings_count;

What is the correct syntax of doing this? Not bothering about performance since links contain only 1200 rows and not going to increase more than 1500. Any inputs will be appreciated. Thanks in advance.

Advertisement

Answer

In Postgres, you can convert a boolean to a number and add them up:

select l.*,
       ( ("keyword1" ~* name)::int +
         ("keyword2" ~* name)::int +
         . . .
       ) as num_matches         
from links l
order by num_matches desc;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement