Skip to content
Advertisement

Replace conditional subquery in Order By (Performance consideration)

I have a ratings table (t2) I’m using to sort queries by lower_bound DESC. The problem is, the default value of lower_bound has to be null or 0. When a rating occurs, the row is updated with Wilson’s rating algo. This means that new entries get ordered before all other entries in a lower_bound DESC sort even though they have no rating yet (null or 0 is less than say, 0.2 and less is more in Wilson’s rating algorithm).

To solve this, I added an IF statement and subquery which selects the row with the biggest lower_bound value and adds +1 to it. That way, new entries that have a null value for lower_bound are ordered last. It works but I want to avoid these kinds of queries wherever possible for performance reasons.

Can this ORDER BY be done in a more efficient manner, presumably without the subquery?

SELECT
    t1.*, t2.stars as rating
FROM
    table1 t1
JOIN
    table2 t2
    ON
        t2.user_id = t1.id
WHERE
    NOT t1.is_ready
ORDER BY
    IF(t2.lower_bound = NULL, (select lower_bound from t2 order by lower_bound asc)+1, t2.lower_bound)
        DESC

Advertisement

Answer

I think you can write your ORDER BY clause more efficiently by ordering first by whether t2.lower_bound IS NULL and then by the actual value i.e.

ORDER BY t2.lower_bound IS NULL, t2.lower_bound DESC

this will ensure that all entries with a NULL lower_bound value are sorted last, since t2.lower_bound IS NULL will be 1 for them while it is 0 for the non-NULL values.

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