Search code examples
postgresqlstored-proceduresplpgsqlrankingpostgresql-9.1

Postgresql: Calculate rank by number of true OR clauses


I need to order/rank the results of a PostgreSQL query by the number of OR-clauses that are true. For example, given a query like

SELECT * FROM mytable WHERE cond1 OR cond2 OR cond3 ORDER BY rank DESC

should rank results based on the number of fulfilled conditions. Also approaches that solve this issue with views/stored procedures are very welcome!


Solution

  • Repeat the conditions and add them:

    SELECT * FROM mytable 
    WHERE fld = 'A' OR fldB = CURRENT_DATE OR fldC = 7
    ORDER BY
       (fld = 'A')::int + (fldB = CURRENT_DATE)::int + (fldC = 7)::int  
    DESC