Few words about: APPLY operator

APPLY operator is very useful feature that is not very common, so I would like to introduce you into one of the most powerful tools in TSQL.

So let’s begin by showing some theory about JOIN operators. INNER JOIN and OUTER JOINS (RIGHT,LEFT, FULL) are very common and they work in very similar manner, as you can see in the picture below, JOINS must have two sets that are predefined – query engine have to know about rows from both sides before it executes the query.

Image

APPLY operator doesn’t need to have predefined table from both sides! Image below can help you to understand how it works:

Image

Continue reading

Few words about: LAG and LEAD TSQL functions

In SQL SERVER 2012 we’ve got some new functions that can be useful in our daily work, today I would like to present my two favorite ones: LAG and LEAD.

LAG function is working only with OVER( ORDER BY) clause and access data from previous row. LEAD functions works in very similar way – it’s return data from next row. I hope next example will be good way to understand how it works.

Continue reading