16

I am running a query with below condition in SQL Server 2008.

Where FK.DT = CAST(DATEADD(m, DATEDIFF(m, 0, getdate()), 0) as DATE)  

Query takes forever to run with above condition, but if just say

Where FK.DT = '2013-05-01' 

it runs great in 2 mins. FK.DT key contains values of only starting data of the month.

Any help, I am just clueless why this is happening.

11
  • 5
    What is the data type of DT? Is the column indexed? Did you look at actual execution plans with the expression and with the string literal, and compare them? What happens if you add OPTION (RECOMPILE) to the statement? Aug 14, 2013 at 20:47
  • Also, please add both execution plans (XML format). Aug 14, 2013 at 20:51
  • Bets on DT being varchar? Aug 14, 2013 at 20:55
  • 1
    @GarethD while I agree, note that this happens for conversions to DATETIME, but not to DATE. Try this: SET LANGUAGE FRENCH; DECLARE @d DATE = '2013-05-01', @dt DATETIME = '2013-05-01'; SELECT @d, @dt; Aug 14, 2013 at 21:05
  • 2
    @t-clausen.dk you mean like the second option on Aaron's answer?
    – Lamak
    Aug 14, 2013 at 21:11

2 Answers 2

25

This could work better:

Where FK.DT = cast(getdate() + 1 - datepart(day, getdate()) as date)

Unless you are running with trace flag 4199 on there is a bug that affects the cardinality estimates. At the time of writing

SELECT DATEADD(m, DATEDIFF(m, getdate(), 0), 0), 
       DATEADD(m, DATEDIFF(m, 0, getdate()), 0)

Returns

+-------------------------+-------------------------+
| 1786-06-01 00:00:00.000 | 2013-08-01 00:00:00.000 |
+-------------------------+-------------------------+

The bug is that the predicate in the question uses the first date rather than the second when deriving the cardinality estimates. So for the following setup.

CREATE TABLE FK
(
ID INT IDENTITY PRIMARY KEY,
DT DATE,
Filler CHAR(1000) NULL,
UNIQUE (DT,ID)
)

INSERT INTO FK (DT)
SELECT TOP (1000000) DATEADD(m, DATEDIFF(m, getdate(), 0), 0)
FROM master..spt_values o1, master..spt_values o2
UNION ALL
SELECT               DATEADD(m, DATEDIFF(m, 0, getdate()), 0)

Query 1

SELECT COUNT(Filler)
FROM FK
WHERE FK.DT = CAST(DATEADD(m, DATEDIFF(m, 0, getdate()), 0) AS DATE)  

Plan 1

Estimates that the number of matching rows will be 100,000. This is the number that match the date '1786-06-01'.

But both of the following queries

SELECT COUNT(Filler)
FROM FK
WHERE FK.DT = CAST(GETDATE() + 1 - DATEPART(DAY, GETDATE()) AS DATE)

SELECT COUNT(Filler)
FROM FK
WHERE FK.DT = CAST(DATEADD(m, DATEDIFF(m, 0, getdate()), 0) AS DATE)  
OPTION (QUERYTRACEON 4199)

Give this plan

Plan 2

Due to the much more accurate cardinality estimates the plan now just does a single index seek rather than a full scan.

11
  • Thanks so much this worked, what's the difference here, even my function was also doing same, would like to know for reference. Aug 14, 2013 at 21:22
  • 2
    @t-clausen.dk - No problem. Looks like an interesting estimation bug. I took the liberty of editing a demo into your answer. Aug 15, 2013 at 12:28
  • 6
    And @MikaelEriksson pointed out in the Database Administrators chat that this is a fixed bug but you need trace flag 4199 enabled to get the fix. Aug 15, 2013 at 13:18
  • 7
    Very sorry I doubted you. Updated my answer. Aug 15, 2013 at 13:30
  • 1
    Also blogged about this. Sep 8, 2013 at 21:54
13

In most cases, the below probably applies. In this specific case, this is an optimizer bug involving DATEDIFF. Details here and here. Sorry for doubting t-clausen.dk, but his answer simply wasn't an intuitive and logical solution without knowing about the existence of the bug.

So assuming DT is actually DATE and not something silly like VARCHAR or - worse still - NVARCHAR - this is probably because you have a plan cached that used a very different date value when first executed, therefore chose a plan catering to a very different typical data distribution. There are ways you can overcome this:

  1. Force a recompile of the plan by adding OPTION (RECOMPILE). You might only have to do this once, but then the plan you get might not be optimal for other parameters. The downside to leaving the option there all the time is that you then pay the compile cost every time the query runs. In a lot of cases this is not substantial, and I'll often choose to pay a known small cost rather than sometimes have a query that runs slightly faster and other times it runs extremely slow.

    ...
    WHERE FK.DT = CAST(... AS DATE) OPTION (RECOMPILE);
    
  2. Use a variable first (no need for an explicit CONVERT to DATE here, and please use MONTH instead of shorthand like m - that habit can lead to real funny behavior if you haven't memorized what all of the abbreviations do, for example I bet y and w don't produce the results you'd expect):

    DECLARE @dt DATE = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0);
    
    ...
    WHERE FK.DT = @dt;
    

    However in this case the same thing could happen - parameter sniffing could coerce a sub-optimal plan to be used for different parameters representing different data skew.

  3. You could also experiment with OPTION (OPTIMIZE FOR (@dt = '2013-08-01')), which would coerce SQL Server into considering this value instead of the one that was used to compile the cached plan, but this would require a hard-coded string literal, which will only help you for the rest of August, at which point you'd need to update the value. You could also consider OPTION (OPTIMIZE FOR UNKNOWN).

14
  • Thanks so much for reply, FK.DT is actually a date field.I tried the too before, but same issue query kept on running and this filed is not an index filed. Aug 14, 2013 at 21:01
  • 1
    @user2158642 What is "tried the too"? And if you're querying on this column frequently, why don't you consider indexing it? Typically this is why we have indexes - to make our queries more efficient and predictable. Seeing the actual (not estimated) plans for the two versions of the query (one slow, one fast) will certainly help us not make stabbing guesses at the air... Aug 14, 2013 at 21:03
  • Sorry for typo i meant tried that one as well using . I will ask my DBA to create an index on this filed, does it have to clustered or non-clustered? Aug 14, 2013 at 21:05
  • 1
    @user2158642 one more time: we can only tell what "bombs" means if you collect the actual execution plans in both cases, and show them to us. Otherwise we can't really help you except throw potential solutions in your general direction. Do you want specific help, or generic help? Aug 14, 2013 at 21:15
  • 2
    @user2158642 Yes, that is the point. If you had used 3 months earlier on your original query, you would've probably also "fixed" your issue. It didn't have to do with rewriting the way you were calculating the date, it has to do with changing the date
    – Lamak
    Aug 14, 2013 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.