Unofficial Hacker News companion — get notified on comment replies, and more.

Why MySQL OR is slower than IN (opens external site)

22 points by millspore 3 days ago | www.percona.com | 14 comments on HN | Vote on HN (opens Hacker News) |

View full thread · View on Hacker News

Comment thread (10)

  1. Why can't consecutive OR statements with common columns be reduced to IN? (I say consecutive since I assume ordering matters).

    WHERE id = 1 OR id = 2... Should be abled to be reduced to WHERE id IN (1,2...)

    However WHERE id = 1 OR name = 'John' OR id = 2 Maybe can't be reduced to WHERE id IN (1,2) OR name = 'John'

    Replies (2)
    1. Why does order of the OR operands matter?
      Replies (2)
      1. With a perfect optimizer and perfect knowledge of ordinality and statistics, I think performance would be the same. However in practice, I do not believe it always reorders predicates reliably for optimal performance.

        My experience is that order does matter in MySQL and especially in DWH environments where the optimizer may not be aware of things like partitioning.

        Replies (2)
        1. The hypergraph optimizer orders expensive predicates last (where “expensive” is stuff like subqueries). The old (default) optimizer only does reordering more-or-less by accident, AFAIK.
          Replies (1)
          1. > where “expensive” is stuff like subqueries

            Subqueries aren't always going to be more expensive

            Replies (1)
            1. This is true, but the optimizer considers them so. They're more expensive than e.g. adding two ints.

              Of course, if they're rewritten to a semijoin or similar, they won't be subqueries anymore or indeed not conditions at all, so sorting them is not applicable.

        2. Now I'm really confused. Your orignal comment reads like reordering changes semantics, so the two id= checks cannot be fused since reordering would be required for that. But now it sounds like reordering keeps semantics and is "just" left on the table by a simple optimizer, which isn't really relevant because the original comment is about a hypothetical optimization anyway...
          Replies (1)
          1. It is only about optimization yes. But the way it works today, but it is not guaranteed that collapsing the ORs to INs is optimal when it reorders _other_ predicates.
      2. OR short-circuiting, evaluation stops when one of the statements is true. So it might influence performance?
    2. It certainly could, and MySQL has a number of such rewrites, just not that specific one AFAIK. (You'd need to worry about things like picking out the IN part from a series of tests within the OR trees if there are other conditions in there, but it's certainly possible.)