Getting Started with Adobe After Effects - Part 6: Motion Blur
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.
Loading

1st Prize - Apple iPad


SQLServer Quiz 2011 - The best and bad uses of the TSQL APPLY operator

  • APPLY operator appeared in SQL Server 2005 and allows T-SQL to invoke a table value function for each row in an outer record set. However we found the situation when people used this operator correctly or not. In your opinion, what are the situations where we can use the TSQL APPLY operator and the situations where a "traditionnal" operator is more efficient ?

    Posted on 03-08-2011 00:00 |
    David Barbarin
    202 · 1% · 230

8  Answers  

Subscribe to Notifications
  • Score
    7

    CROSS APPLY is similar to INNER JOIN and OUTER APPLY is similar to LEFT OUTER JOIN

    Cases where "traditional" JOIN operator is more efficient:

    If there are fields in left and right table you can JOIN ON.

    APPLY can be used in such scenario, and execution path would be similar to JOIN ON, but I would go with JOIN for the simplicity of the TSQL code.

    Cases where APPLY is a good choice:

    When there is no field (or calculation on any field(s)) in right (second) table that can be used for direct JOIN ON for requested business logic (without sub-queries).

    Instead, value(s) from left table are used to find out corresponding set of rows in right table. For the simplicity of the code that part is usually implemented by creating table value function with values from from left (first) table passed as parameter(s). So, it is not existence of table value function itself, but the reason (as described above) for the existence of that function is important.

    Even if there is a way for such cases to build queries in traditional way (using sub-queries), or not so traditional way (using windows funtions), the APPLY syntax provides a better performance.

    Replied on Mar 8 2011 1:53AM  . 
    Igor Zakharov
    158 · 1% · 300
  • Score
    7

    What is the APPLY Operator?

    The APPLY operator allows T-SQL to invoke a table value function for each row in an outer record set. For each row in the outer record set, the table value function is evaluated to determine if any rows are returned. If any rows are returned from the table value function then those rows are joined using a UNION ALL operation to the row in the outer record set. The columns returned from the table value function are merged with the columns of the row in the outer record set to produce the final set of columns returned. The APPLY operator lets you easily join columns from a table value function with the columns of the outer record set.

    What is a Table Value Function?

    A table value function can take two forms. This first form, is the one most people think of, which is a user or system defined function that returns a table data type. But a table value function can also be an inline table value function. An inline table value function has no function body, it is just the result set of a parameter driven SELECT statement

    When?

    The APPLY operator is just one of the many T-SQL enhancements introduced with SQL Server 2005. Having the APPLY operator now allows you to join columns from a record set with records returned from a table value function. Being able to accomplish this allows you to more easily write a set based solution when you need to return data from a table value function based on rows in an outer table.

    APPLY operator is not an ANSI operator but rather an extension of SQL Server T-SQL (available in SQL Server 2005 and above), so if you plan to port your database to some other DBMS take this into your considerations.


    Replied on Mar 8 2011 2:42AM  . 
    indika saminda kannangara
    184 · 1% · 251
  • Score
    8

    There are two reasons for using the APPLY operator.

    The first (apparently the reason MS created this extension to ANSI SQL) is to allow the passing of columns from the current join set as parameters to a table value UDF. The efficiency of this use will be very much dependent on the UDF in question. If it is an in-line UDF, then the join plan will likely be very good. If it is a multi-statement UDF, then the efficiency of the join will be very dependant on the logic and structure of the procedural code in the UDF.

    The second use of the APPLY operator is to create a join from two two tables which are not stand-alone, i.e. the query uses values from the parent table to fully define the contents of the joined table, so the contents of the joined table cannot be known not known until the corresponding row from the parent table has been selected. This would be the case, for example, when the joined table is a derived table expression, maybe just returning a limited number of rows witht he TOP operator. The APPLY operator offers the flexibility of a JOIN without needing the ON clause.

    If a query involving the APPLY operator can be recast as a JOIN, then it is probably better to do so (although the execution plans may be identical, as the query optimiser may do this behind the scenes), but for the two cases above, the APPLY operator is the only choice.

    Replied on Mar 16 2011 5:54AM  . 
    Tony Bater
    310 · 0% · 137
  • Score
    8

    Cross-Apply is nothing more than another way to create correlated sub-queries but with a booster... it can be made to return multiple rows for each correlation. Some simple proper uses are that it can be used for the application of UDF's that return multiple rows (hopefully iTVF's and not mTVF's) and can be used for such oddities as an "un-Cross-Tab" or "unPiviot".

    Improper uses include many of the same things that improper uses of correlated sub-queries would be. An example of this is using it to do "previous row aggregations" such as running total which would require a "Triangular Join" as part of the aggregation.

    As has already been mentioned, it could be used to accomplish "regular" and outer joins... unless there's a multi-row requirement involved, it's generally a better idea from a readability standpoint to use a regular join just as it is for a correlated subquery. Simple WHERE NOT EXISTS or WHERE NOT IN or even an EXCEPT would also be preferrable for "subtractive" joins rather than using Cross-Apply for the same reasons.

    Replied on Mar 16 2011 9:18AM  . 
    Jeff Moden
    166 · 1% · 291
  • Score
    9

    SQLServer Quiz 2011 - The best and bad uses of the TSQL APPLY operator

    Answer:

    What is APPLY operator?

    The APPLY operator allows us to invoke a table valued function for each row returned by an outer expression query. Basically, SQL Server allows us to join table and table valued function in such a way that for each record returned from outer query, we can call table valued function to retrieve data. This operator was not available in versions prior to SQL Server 2005 and was done using a derived table/view. We can use APPLY in the FROM clause of a query, similar to the way we use the JOIN relational operator. The difference between join and APPLY operator becomes evident when you have a table-valued expression on the right side and you want this table-valued expression to be evaluated for each row from the left table expression.APPLY operator can be used in two different ways and they are CROSS APPLY and OUTER APPLY.

    CROSS APPLY: It is like an inner join. Returns only those rows from the outer query, for which table valued function returns some data.

    OUTER APPLY: Its behavior is similar to outer join. It returns all the rows from the outer query irrespective of data returned by table function. If table function returns data then column values pertaining to table function will be not null otherwise it will contain null values.

    Example:

    Let us take two tables Territories and Region as an example. Following query has same result set and execution plan is also the same.

    --Using CROSS APPLY
    
    SELECT * FROM  Region r
     CROSS APPLY 
       ( 
       SELECT * FROM Territories t
       WHERE t.RegionID = r.RegionID
       ) t1
    GO 
    
    ---Using INNER JOIN
    SELECT * FROM Region r
     INNER JOIN Territories t   ON t. RegionID = r. RegionID
    

    Now let us see where APPLY operator is really required in some situations. Let us create a table-valued function that accepts RegionID as its parameter and returns all the Territories that are belong to this region. Following is the table-valued function:

    --Table-valued Function 
    CREATE FUNCTION dbo.fn_GetTerritoriesOfRegion(@RegionID AS INT)  
    RETURNS TABLE 
    AS 
    RETURN 
       ( 
       SELECT * FROM Territories t 
       WHERE t.RegionID = @RegionID
       ) 
    GO
    

    The following query selects data from Region table and uses CROSS APPLY to join with the function we created. It passes the RegionID for each row from the outer table expression , in our exxample, Region table and evaluates the function for each row similar to a correlated subquery.

    SELECT * FROM Region r
    CROSS APPLY dbo.fn_GetTerritoriesOfRegion(r.RegionID) 
    GO
    

    The following query uses the OUTER APPLY in place of CROSS APPLY and hence unlike CROSS APPLY which returned only correlated data, the OUTER APPLY returns non-correlated data as well, placing NULLs into the missing columns.

    SELECT * FROM Region r
    OUTER  APPLY dbo.fn_GetTerritoriesOfRegion(r.RegionID) 
    GO
    

    Now let us try using traditional join to query the table-valued function.

    SELECT * FROM Territories t
    INNER JOIN fn_GetTerritoriesOfRegion(r.RegionID) r  ON 1=1
    

    We get following error:

    Msg 4104, Level 16, State 1, Line 2

    The multi-part identifier "r.RegionID" could not be bound.

    Msg 4104, Level 16, State 1, Line 2

    The multi-part identifier "r.RegionID" could not be bound.

    This is because with JOINs the execution context of outer query is different from the execution context of the function, and we cannot bind a value or variable from the outer query to the function as a parameter. Hence the APPLY operator is required for such queries. Therefore, APPLY operator is required when you have to use table-valued function in the query, but it can also be used with an inline SELECT statements.

    The main advantages using APPLY Operator are:

    • Allows us to join two table expressions.
    • Use of APPLY is necessary if we have table-valued expression on right part.
    • Use of APPLY operator boost the performance of our query.

    Traditional operators are used when there are no table-valued function and when the performance issue is acceptable.

    Reference: http://msdn.microsoft.com/en-us/library/ms345147(v=sql.90).aspx

    Thank you,

    Abi Chapagai

    Replied on Mar 17 2011 7:04PM  . 
    Abi Chapagai
    69 · 3% · 808
  • Score
    8

    Using the APPLY operator is another way of a correlated sub-query with a few differences: Unlike a "standard" correlated sub-query, the APPLY operator can return multiple rows as well as multiple columns. For example, we could write a function to validate and split the value in a column holding multiple e-mail addresses per person. We could then return the data using a query like:

    SELECT p.PersonID, p.Email, v.mailIsValid, v.Username, v.Domain
    FROM PersonEmail p
    CROSS APPLY dbo.ValidateEmail(p.Email) v
    

    From my point of view the APPLY operator is useful when a rather complex business requirement is used in various code sections that can be written as a table-valued function (iTVF instead of mTVF, preferrably) to avoid rewriting the code snippet each and every time. This will not only help readability, it will also improve maintainability since the business requirement is stored in one place only.

    Another useful scenario is to replace a scalar-valued function with a table-valued function. Instead of calling the scalar function for each row in the query, using APPLY together with a TVF will apply the function to the result set improving performance significantly.

    I would rather use a "traditional" operator if this operator is "obvious", e.g. I would not "hide" a INNER/LEFT/OUTER/CROSS JOIN or a (NOT) EXISTS or any other kind of "direct joins".

    I would also not use the APPLY operator if it would lead to accidental/hidden triangular joins (like Jeff already mentioned).

    As with many other alternatives, it's important to test for a given scenario if the APPLY operator really provide a benefit.

    Replied on Mar 23 2011 2:43PM  . 
    lmu92
    0 · 0% · 0
  • Score
    9

    You can't use the APPLY operator to do what FULL or RIGHT outer joins do. APPLY always refers to what's on its LEFT side like the LEFT outer join do, so you must pay close attention where you put it even if it's a CROSS APPLY that could be replaced by some INNER JOIN which might be moved inside the query.

    APPLY may allow you to join to a table function (which is its most known usage) whose parameter(s) depends on other tables/sets. APPLY may allow you to easilly obtain summary data (GROUP BY) or ranking data on subsets of fields/tables because the grouping/ranking logic would be focused inside the APPLY clause. APPLY may allow you to make a JOIN to a limited (TOP) and potentially ordered set of data. APPLY may allow you to reduce repetitions a lot when dealing with mathematical/logical operations (you may use APPLY to store the restult of a complex formula into a simple field of the resulting set which could be reused latter).

    When not to use APPLY ? When INNER/LEFT/CROSS Join would already do the job. Because in such case APPLY would create an overhead on the query length and possibly (I don't know and it doesn't matter at this point) an overhead in the query execution.

    Replied on Apr 5 2011 6:36AM  . 
    Sergejack
    41 · 4% · 1393
  • Score

    Apply operator provides a way to get table value result set for each row. here we have 2 type of apply operator 1st one is Cross apply that is similar like inner joins and 2nd is Outer apply that is like outer join (Left joins). Suppose format of apply is like this

    select * from [Table1] cross/outer apply [fun1(para1)]

    in case of Cross apply we will get only those row for which fun1 gives any output result set. but in case of outer apply it shows all rows of table1 with data of fun1 or Null if not getting any result set from fun1.

    the APPLY operator can be a useful tool when you want to evoke a table-valued function for each row returned by a table expression (Table1). You simply use the operator to join the outer table to the function. If you want to include only those rows from the outer table for which the function returns data, use the CROSS APPLY operator. If you want to return all rows from the outer table, regardless of whether or not the function returns data for a row, use the OUTER APPLY operator.

    Here you can see a good article on apply http://www.mssqltips.com/tip.asp?tip=1958 you can see some other links that shows the performance issue of apply over traditional joins http://explainextended.com/2009/07/16/inner-join-vs-cross-apply/ http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/07/07/using-cross-apply-to-optimize-joins-on-between-conditions.aspx

    Replied on Apr 8 2011 12:30AM  . 
    Alok Chandra Shahi
    70 · 2% · 800

Your Answer


Sign Up or Login to post an answer.
Please note that your answer will not be considered as part of the contest because the competition is over. You can still post an answer to share your knowledge with the community.

Copyright © Rivera Informatic Private Ltd.