views:

93

answers:

4

I have a table with one DateTime column. I want to find the rows with lowest time which their times are more than a variable myTime. How can I do that? What kind of index will increase the performance?

+1  A: 
SELECT DateTime1
FROM Table1
WHERE DateTime1 = (
    SELECT MIN(DateTime1)
    FROM Table1
    WHERE DateTime1 > @myTime);

or:

SELECT T1.DateTime1
FROM Table1 AS T1
JOIN (
    SELECT MIN(DateTime1) AS DateTime1
    FROM Table1
    WHERE DateTime1 > @myTime) AS T2
ON T1.DateTime1 = T2.DateTime1;

Run both to see which is fastest. Use an index on DateTime1.

Test data to check it works:

CREATE TABLE Table1 (DateTime1 NVARCHAR(100) NOT NULL);
INSERT INTO Table1 (DateTime1) VALUES
('2010-02-01 17:53'),
('2010-02-01 17:55'),
('2010-02-01 17:55'),
('2010-02-01 17:56');
Mark Byers
A: 
DECLARE @temp datetime

SET @temp = (SELECT GETDATE())

SELECT MyCol, MyCol2 FROM MyTable WHERE MyColWithDate > @temp ORDER BY MyColWithDate ASC

Regarding the index it depends can you tell us more info about what you are trying to do. Otherwise you could index MyColWithDate for the above example.

JonH
I want all of them with the LOWEST time.
Shayan
+1  A: 

Something like this then...

DECLARE @temp datetime

SET @temp = (SELECT GETDATE())

Select myCol from MyTable where MyColWithDate IN (SELECT top 1 MyCol, MyCol2 FROM MyTable WHERE MyColWithDate > @temp ORDER BY MyColWithDate ASC)

or I'd probably go with the MIN

Select myCol from MyTable where MyColWithDate IN (SELECT MIN(MycolWithDAte) FROM MyTable WHERE MyColWithDate > @temp GROUP BY MyColWithDate)
Sam
But this is inefficient. Any built-in method?
Shayan
Have you looked at the OVER clause? http://msdn.microsoft.com/en-us/library/ms189461.aspx
Sam
And why do you say it's inefficient? The subquery is executed one time and returns one value which is then used for one more query.
Sam
+2  A: 

Using TOP (SQL Server 2000+)


SELECT t.*
  FROM TABLE t
 WHERE t.date_time_col = (SELECT TOP 1
                                 x.date_time_col
                            FROM TABLE x
                           WHERE CONVERT(hh, x.date_time_col, 8) < @myTime
                        ORDER BY x.date_time_col)

Using MIN


SELECT t.*
  FROM TABLE t
 WHERE t.date_time_col = (SELECT MIN(x.date_time_col)
                            FROM TABLE x
                           WHERE CONVERT(hh, x.date_time_col, 8) < @myTime)

Neither will use an index, assuming one exists on the DATETIME column, because of the use of a function - the data type is being changed.

OMG Ponies
+1 for index info.
Sam