Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Comments] Clean up your queries and simplify logic with CROSS APPLY #5

Open
chadbaldwin opened this issue Jan 17, 2021 · 3 comments
Open
Labels

Comments

@chadbaldwin
Copy link
Owner

https://chadbaldwin.net/2021/01/07/use-cross-apply-to-clean-up-queries.html

@gonsalu
Copy link

gonsalu commented Jan 22, 2021

Something to note is that this technique doesn't work if the expression includes window functions, as it changes the window to operate in.

@chadbaldwin
Copy link
Owner Author

chadbaldwin commented Jan 22, 2021

@gonsalu it's funny you mention that, because Adam Machanic has a really cool method he calls the "parallel apply pattern", which you can use to improve parallelism on queries using windowing functions that have a bad plan. Itzik Ben-Gan mentions it in his windowing functions book and credits Adam, but I couldn't find it online. I asked Adam if it was online anywhere and he sent me this video from a PASS presentation he did:

https://youtu.be/_IRWvlSQxS8

I'd watch it while you have the chance before PASS takes down their YouTube channel. Adam presents the pattern at 54:00, but I'd suggest watching the whole thing, tons of great info there.

@gonsalu
Copy link

gonsalu commented Jan 22, 2021

Thanks for sharing, but that's not quite what I was trying to highlight.

For example, let's say you have the following query:

SELECT expr1 = ROW_NUMBER() OVER (ORDER BY (SELECT 1))
     , expr2 = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) * -1
  FROM sys.objects

The result set will look like:

expr1    expr2
-----    -----
    1       -1
    2       -2
    3       -3
...

If you try to use CROSS APPLY to have the ROW_NUMBER() window function as a common expression:

SELECT expr1 = X.rn
     , expr2 = X.rn * -1
  FROM sys.objects
 CROSS APPLY (SELECT rn = ROW_NUMBER() OVER (ORDER BY (SELECT 1))) AS X

Then, the result set will look like the table below, which might not be the expected result.

expr1    expr2
-----    -----
    1       -1
    1       -1
    1       -1
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants