CREATE TABLE [MyLog](
[RecordID] [int] IDENTITY(1,1) NOT NULL,
[LogTimeStamp] [datetime] NOT NULL,
[Duration] [decimal](12, 4) NOT NULL,
[SessionID] [varchar](40) NOT NULL,
[IP] [varchar](24) NOT NULL,
[Request] [varchar](80) NULL,
[Response] [varchar](80) NULL,
[Error] [varchar](255) NULL,
[Description] [varchar](80) NULL,
CONSTRAINT [PK_MyLog] PRIMARY KEY CLUSTERED
) ON [PRIMARY]
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [SK_MyLog_LogTimeStamp] ON MyLog
) ON [PRIMARY]
I would execute the following SQL statement;
DELETE MyLog WHERE DATEDIFF(DAY, LogTimeStamp, GETDATE()) > 30
It's pretty simple, use the DateDiff() function to compare the timestamp field with the current date and if it's older than 30 days, delete that record. I implemented that code in the first go around of the code, about two years ago. This week, I was in that area code for some maintenance and I took another look at that statement. That WHERE clause jumped right out at me. For every row in that table, both the DateDiff() and GetDate() functions are going to be called. SQL Server will need to compare every value of LogTimeStamp to see if it is older than 30 days ago. In this case, MyLog has an index on LogTimeStamp, but it will has to read the entire index. GetDate() is a nondeterministic function, it's going to get re-evaluated for each row in the database. Since the actual date comparison is against a constant value, I decided to evaluate the comparision date first and change the WHERE clause to a simpler expression.
DECLARE @PurgeDate smalldatetime
SELECT @PurgeDate = DATEADD(DAY, -30, GETDATE())
DELETE MyLog WHERE LogTimeStamp < @PurgeDate
I added a smalldatetime variable and assigned to it date of 30 days ago with the DateAdd() and GetDate() functions. Now SQL Server can use the value of @PurgeDate to jump into the index and jump out when the date condition no longer matches the criteria. By I implemented this on SQL Server 2005 and when I evaluated the estimated execution plans for each delete statement, I was surprised to see identical plans. Both sets of statements spent the same percentage of time doing scanning and deleting.
When I did the same evaluation on SQL Server 2000, I saw different results. The first delete statement spent 73% of the time scanning the index and 27% actually deleting rows from the table. The second delete statement spent 19% of the time scanning and 81% of the time deleting rows. On table that could have a large number of rows, it turned out to be big performance saving on SQL Server 2000 installations.
It's pretty cool that the SQL Server 2005 parser is smart enough to optimize code and recognize a constant expression when it sees it. My code would have seen a nice little performance boost by moving from SQL Server 2000 to SQL Server 2005. It's still a better thing to pull constant expressions out of the WHERE clause when you can do that.
SQL formatting courtesy of The Simple-Talk SQL Prettifier for SQL Server.