Difference between IN and ANY operators in SQL

后端 未结 10 1834
無奈伤痛
無奈伤痛 2020-12-23 11:14

What is the difference between IN and ANY operators in SQL?

10条回答
  •  我在风中等你
    2020-12-23 11:57

    IN - It is easy to understand. The query should select only those values which are specified in 'IN' clause. Now, let us understand 'ANY' with a query. ANY means it should be greater or less than any of the values in the list.

    Assume a Orders table which has OrderID from 1 to 10

    Observer the below query:
    select OrderID from Orders
    where OrderID < ANY (3,5,7)

    The answer to above query is :
    OrderID
    1,2,3,4,5,6

    Explanation :The query says find OrderIDs which are less than ANY of the specified values. So the database searches and includes OrderID as follows:
    Is 1<3- Yes hence OrderID 1 is included
    Is 2<3- Yes hence OrderID 2 is included
    Is 3<3- No, is 3<5 -Yes (as 5 is specified value), hence OrderID 3 is included
    Is 4<3- No, is 4<5 -Yes, hence OrderID 4 is included
    Is 5<3- No, is 5<5 -No, is 5<7(as 5 is specified value)-Yes hence OrderID 5 is included
    Is 6<3- No, is 6<5 -No, is 6<7-Yes hence OrderID 6 is included
    Is 7<3- No, is 7<5 -No, is 7<7-No hence OrderID 7 is NOT included as no more values in specified list to compare
    Is 8<3- No, is 8<5 -No, is 8<7-No hence OrderID 8 is NOT included as no more values in specified list to compare
    Is 9<3- No, is 9<5 -No, is 9<7-No hence OrderID 9 is NOT included as no more values in specified list to compare
    Is 9<3- No, is 9<5 -No, is 9<7-No hence OrderID 9 is NOT included as no more values in specified list to compare


    Apply the same logic for greater than
    select OrderID from Orders
    where OrderID > ANY (3,5,7)

    The answer to above query is :
    OrderID
    4,5,6,7,8,9,10

提交回复
热议问题