Why use the BETWEEN operator when we can do without it?

前端 未结 11 856
孤独总比滥情好
孤独总比滥情好 2020-12-09 17:31

As seen below the two queries, we find that they both work well. Then I am confused why should we ever use BETWEEN because I have found that BETWEEN behaves differently in d

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 18:13

    BETWEEN can help to avoid unnecessary reevaluation of the expression:

    SELECT  AVG(RAND(20091225) BETWEEN 0.2 AND 0.4)
    FROM    t_source;
    
    ---
    0.1998
    
    SELECT  AVG(RAND(20091225) >= 0.2 AND RAND(20091225) <= 0.4)
    FROM    t_source;
    
    ---
    0.3199
    

    t_source is just a dummy table with 1,000,000 records.

    Of course this can be worked around using a subquery, but in MySQL it's less efficient.

    And of course, BETWEEN is more readable. It takes 3 times to use it in a query to remember the syntax forever.

    In SQL Server and MySQL, LIKE against a constant with non-leading '%' is also a shorthand for a pair of >= and <:

    SET SHOWPLAN_TEXT ON
    GO
    SELECT  *
    FROM    master
    WHERE   name LIKE 'string%'
    GO
    SET SHOWPLAN_TEXT OFF
    GO
    
    
    |--Index Seek(OBJECT:([test].[dbo].[master].[ix_name_desc]), SEEK:([test].[dbo].[master].[name] < 'strinH' AND [test].[dbo].[master].[name] >= 'string'),  WHERE:([test].[dbo].[master].[name] like 'string%') ORDERED FORWARD)
    

    However, LIKE syntax is more legible.

提交回复
热议问题