Why UNION is faster than OR

I have a problem when I need to find records that either have a dimension that matches the value or do not have this dimension at all. I solved this problem with 3 or 4 different approaches, using joins, using not inand using not exists. However, the request was extremely slow every time. Then I tried to split the request into two, and they both work very fast (3 seconds). But combining queries using uses ORtakes> 5 minutes.

Reading on SO I tried UNION, which is very fast, but very inconvenient for the script that I use.

So, 2 questions: 1: Why is the UNION so much faster? (Or why ORso slow)? 2: Is there a way to get MSSQL to use a different approach for a statement ORthat is fast?

Thank.

+5
source share
2 answers

, OR , . , , , , OR, , UNION. , - , OR. , .

, UNION ALL, UNION, .

+4

SQL Server UNION, UNION. - WHERE, . UNION :

SELECT * FROM dbo.MyView WHERE <cond1>
UNION ALL
SELECT * FROM dbo.MyView WHERE <cond2>

UNION ALL , . UNION, SQL Server , .

0

All Articles