Hi all wonder if someone could advise a more efficient way to select rows from a table that has roughly 60 millions records in it. Each row has a date stored as a nvarchar, for example ‘20110527030000.106’. I want to select all rows that are 3 months or older based on this date field, so for example i’m only interested in the first part of the date field; ‘20110527’. I have the following code to do that, however its a bit slow and wondering if there was a better way?
DECLARE @tempDate varchar(12)
SET @tempDate = convert(varchar(12),DATEADD(m,-3,GETDATE()),112)
SELECT *
FROM [TABLE A]
WHERE SUBSTRING([DATE_FIELD],0,8) < @tempDate
Your query not only it can’t use any index on
[DATE_FIELD]and does a full scan but it also applies theSUBSTRING()function to all values of the (date_field column of the) table.Don’t apply any function on the column so the index of
[DATE_FIELD]can be used and the function is only applied once, at the calculation of@tempDate:The
<comparison works forvarcharvalues. The following will evaluate toTrue:Is there any reason that the
datetimeis not stored asdatetimetype?