I have a table which has job listings, which when displayed are normally ordered by the created_at field descending. I am in the process of adding a “featured” boolean flag which would add the ability for customers to get more visibility to their job listing. I’d like to have the featured listings pinned to the top of the search results if the job is less than X days old. How would I modify by existing query to support this?
Jobs.where("expiration_date >= ? and published = ?", Date.today, true).order("created_at DESC")
Current query pulls back all current, published jobs, ordered by created_at.
Unlike some other databases (like Oracle) PostgreSQL has a fully functional
booleantype. You can use it directly in anORDER BYclause without applying aCASEstatement – those are great for more complex situations.Sort order for
booleanvalues is:If you
ORDER BY bool_expressionDESC, you invert the order to:If you want
TRUEfirst andNULLlast, use theNULLS LASTclause ofORDER BY:Of course,
NULLS LASTis only relevant iffeaturedorcreated_atcan beNULL. If the columns are definedNOT NULL, then don’t bother.Also,
FALSEwould be sorted beforeNULL. If you don’t want to distinguish between these two, you are either back to aCASEstatement, or you can throw inNULLIF()orCOALESCE().Performance
Note, how I used:
and not:
In the first example, the expression to the right is a constant that is calculated once. Then an index can be utilized to look up matching rows. Very efficient.
The latter cannot usually be used with an index. A value has to be computed for every single row, before it can be checked against the constant expression to the right. Don’t do this if you can avoid it. Ever!