Query in sql server 2012 with datetime between takes too long with millisecond difference

2.2k views Asked by At

I have a strange issue with a database and a query in sql server 2012.

in the records, are one column that is of type datetime (not datetime2) and stores the values in the format 'YYYY-MM-dd HH:mm:ss.ttt' but i have a problem... if i make this query:

SELECT *
FROM table1 cg 
INNER JOIN table2 mv ON cg.mv_id = mv.mv_id 
FULL JOIN table3 fu ON cg.fu_id = fu.fu_id 
FULL JOIN table4 cl ON cg.cl_id = cl.cl_id 
INNER JOIN table5 so ON mv.so_id = so.so_id 
WHERE  mv.su_id = 1 AND (mv.mv_fecha >= '2013-09-02 17:46:03.571' AND mv.mv_fecha <= '2013-09-04 23:59:59.999')

Then takes like 10 seconds, but if i change the mv.mv_fecha >= '2013-09-02 17:46:03.571' to '2013-09-02 17:46:03.572' (note that i change millisecond 571 to 572) then the query takes like 4 minutes! and i'ts only with this record.. and if i make any query passing that millisecond, the query takes that loooong time. I must specify that casually there is a record in the table2 with a mv_fecha like '2013-09-02 17:46:03.573' but even if there is a record with that datetime, the query wont retrieve it because it's a record with su_id = 2 (and in the query the su_id filtered is 1).

What's going on???

UPDATE: I have some theory with table1.. and it's that table1 have thousands of records and it's a table that doesn't contain any index in it?... could be that the problem?

UPDATE 2: This is the execution plan of the query:

Execution Plan

1

There are 1 answers

2
Devart On

Please try this query -

SELECT *
FROM Table1 cg
JOIN table2 mv ON cg.mv_id = mv.mv_id
FULL JOIN table3 fu ON cg.fu_id = fu.fu_id
FULL JOIN table4 cl ON cg.cl_id = cl.cl_id
JOIN table5 so ON mv.so_id = so.so_id
WHERE mv.su_id = 1
    AND CAST(mv.mv_fecha AS DATETIME2) BETWEEN '20130902 17:46:03.572' AND '20130904 23:59:59.999')