|
Posted by Alex Kuznetsov on 01/12/07 16:49
Emin wrote:
> Dear Experts,
>
> I have a fairly simple query in which adding a where clause slows
> things down by at least a factor of 100. The following is the slow
> version of the query
>
> -------------------------
> SELECT * FROM
> ( Select x.event_date From x FULL OUTER JOIN y
> ON x.event_date = y.event_date
> ) innerQ
> WHERE ( innerQ.event_date >= {ts '1980-01-01 00:00:00'} )
> ------------------------
>
> Removing the where clause makes the query run quickly. This seems
> extremely strange because it seems like SQL Server should simply be
> able to take the results of innerQ and discard anything with a date
> that doesn't match. If I instead split the query into two pieces where
> I create a temp table and put innerQ into that and then do the select *
> WHERE (...) from the temp table things work fine.
>
> Any thoughts on what SQL Server might be doing to make things slow and
> how I can fix it?
>
> Thanks,
> -Emin
Emin,
Before investigating why it is slow, you need to make sure it is
correct.
Note that your WHERE clause filters out all the rows with NULL
event_date, so your FULL OUTER JOIN effectively becomes a LEFT OUTER
JOIN.
If you actually need FULL OUTER JOIN, you can either push down the
predicate manually (preferred)
SELECT * FROM
( Select x.event_date From
(Select x.event_date From x WHERE event_date >= {ts '1980-01-01
00:00:00'})
x FULL OUTER JOIN y
ON x.event_date = y.event_date
) innerQ
or allow nulls in your WHERE clause (logically equivalent _only_ if
x.event_date is not nullable)
SELECT * FROM
( Select x.event_date From x FULL OUTER JOIN y
ON x.event_date = y.event_date
) innerQ
WHERE ( innerQ.event_date >= {ts '1980-01-01 00:00:00'} OR
innerQ.event_date IS NULL)
Note that your expectations regarding
"SQL Server should simply be
able to take the results of innerQ and discard anything with a date
that doesn't match"
are incorrect - the optimizer can rewrite your query as it wishes.
Generally speking, it accepts WHAT to do, but it decides by itself HOW
to do it.
-----------------------
Alex Kuznetsov
http://sqlserver-tips.blogspot.com/
http://sqlserver-puzzles.blogspot.com/
[Back to original message]
|