When should I use cross apply over inner join?

前端 未结 14 1089
忘了有多久
忘了有多久 2020-11-22 06:51

What is the main purpose of using CROSS APPLY?

I have read (vaguely, through posts on the Internet) that cross apply can be more efficient when selectin

相关标签:
14条回答
  • 2020-11-22 07:40

    cross apply sometimes enables you to do things that you cannot do with inner join.

    Example (a syntax error):

    select F.* from sys.objects O  
    inner join dbo.myTableFun(O.name) F   
    on F.schema_id= O.schema_id
    

    This is a syntax error, because, when used with inner join, table functions can only take variables or constants as parameters. (I.e., the table function parameter cannot depend on another table's column.)

    However:

    select F.* from sys.objects O  
    cross apply ( select * from dbo.myTableFun(O.name) ) F  
    where F.schema_id= O.schema_id
    

    This is legal.

    Edit: Or alternatively, shorter syntax: (by ErikE)

    select F.* from sys.objects O  
    cross apply dbo.myTableFun(O.name) F
    where F.schema_id= O.schema_id
    

    Edit:

    Note: Informix 12.10 xC2+ has Lateral Derived Tables and Postgresql (9.3+) has Lateral Subqueries which can be used to a similar effect.

    0 讨论(0)
  • 2020-11-22 07:40

    I guess it should be readability ;)

    CROSS APPLY will be somewhat unique for people reading to tell them that a UDF is being used which will be applied to each row from the table on the left.

    Ofcourse, there are other limitations where a CROSS APPLY is better used than JOIN which other friends have posted above.

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