We have all see the questions regarding this. A person new to SQL Server asks how to filter a query and someone less new makes a suggestion like this:DELETE FROM dbo.DateTimeCRUDTestWHERE MONTH(InsertDate) = MONTH(GETDATE())-1 AND YEAR(InsertDate) = YEAR(GETDATE())
And then someone who has read Ben-Gan or has more experience states that you should not perform opperations on columns in a WHERE clause because it degrades performance by not allowing SQL Server to use the index properly. On my own PC I populated a database with more than 94000 rows. Dates ranged from the current datetime back to the early 1700. I used PowerShell to populate the tables.#You need SQLPSX to run this.$MyNumber = 100000for($i=0; $i -lt $MyNumber; $i++){ $MyDate = ([datetime]::now).AddDays(-$i) -f "YYYYMMDD" Set-SqlData -dbname TestDb -sqlserver "(local)" -qry "INSERT INTO DateTimeCRUDTest(Description,InsertDate) VALUES('Some text to add a little realism - $MyDate', '$MyDate')" }I then ran these queries without an index:USE TestDbGODELETE FROM dbo.DateTimeCRUDTestWHERE InsertDate BETWEEN DATEADD(MONTH,datediff(month,0,getdate())-1,0) AND DATEADD(day,-1,DATEadd(MONTH,datediff(month,0,GETDATE()),0))--RESTORE DBUSE TestDbGODELETE FROM dbo.DateTimeCRUDTestWHERE MONTH(InsertDate) = MONTH(GETDATE())-1 AND YEAR(InsertDate) = YEAR(GETDATE())
.0431 seconds and .0415 seconds respectively. Not a huge change. I added an index to the datetime column and got .037 and .026 respectively. Not a big variation, but the "wrong query" was running faster.I then ran these two:USE TestDbGODELETE FROM dbo.DateTimeCRUDTestWHERE InsertDate BETWEEN DATEADD(MONTH,datediff(month,0,DATEADD(YEAR,-100,getdate()))-1,0) AND DATEADD(day,-1,DATEadd(MONTH,datediff(month,0,DATEADD(YEAR,-100,getdate())),0))USE TestDbGODELETE FROM dbo.DateTimeCRUDTestWHERE MONTH(InsertDate) = MONTH(GETDATE())-1 AND YEAR(InsertDate) = YEAR(GETDATE())-100
.020 seconds for the qury that did not opperate on the column in the WHERE clause and .30 seconds for the one that did.Why would this be? And are these variations really a big deal in the average environment?===http://www.ElementalSQL.com/