SQL efficiency - [=] vs [in] vs [like] vs [matches]

后端 未结 4 2132
不知归路
不知归路 2021-02-19 09:11

Just out of curiosity, I was wondering if there are any speed/efficiency differences in using [=] versus [in] versus [like] versus [

相关标签:
4条回答
  • 2021-02-19 09:35

    normally the "in" statement is used when there are several values to be compared. The engine walks the list for each value to see if one matches. if there is only one element then there is no difference in time vs the "=" statement.

    the "like" expression is different in that is uses pattern matching to find the correct values, and as such requires a bit more work in the back end. For a single value, there wouldn't be a significant time difference because you only have one possible match, and the comparison would be the same type of comparison that would occur for "=" and "in".

    basically, no, or at least the difference is so insignificant that you wouldn't notice.

    0 讨论(0)
  • 2021-02-19 09:49

    The best practice for any question about what would be faster, is to measure. SQL engines are notoriously difficult to predict. You can look at the output of EXPLAIN PLAN to get a sense of it, but in the end, only measuring the performance on real data will tell you what you need to know.

    In theory, a SQL engine could implement all three of these exactly the same, but they may not.

    0 讨论(0)
  • 2021-02-19 09:51

    it depends on the underlying SQL engine. In MS-SQL, for example (according to the query planner output), IN clauses are converted to =, so there would be no difference

    0 讨论(0)
  • 2021-02-19 09:56

    I will add to that also exists and subquery.

    But the performance depends on the optimizer of the given SQL engine.

    In oracle you have a lot of differences between IN and EXISTS, but not necessarily in SQL Server.

    The other thing that you have to consider is the selectivity of the column that you use. Some cases show that IN is better.


    But you have to remember that IN is non-sargable (non search argument able) so it will not use the index to resolve the query, the LIKE and = are sargable and support the index


    The best ? You should spend some time to test it in your environment

    0 讨论(0)
提交回复
热议问题