Web design and hosting, database, cloud and social media solutions that deliver business results
  • Business Solutions
    • Robotic Process Automation
    • Software
    • Database Consultancy Services
      • Data Integration
      • Datawarehouse Services
      • Power BI
      • Server Upgrade and DBA Services
    • Web Site Design Services
      • Logo Design
      • Payment Gateways
      • Web Localisation and Translation
      • Web Site Optimisation
      • Web Site Security
      • Technical Tools
    • Cloud Services
      • Amazon Web Services
      • Google Cloud Services
      • Microsoft Azure
    • Microsoft Office
    • Social Media Management and Advice Services
  • Academy
    • Our Test Environment
    • Learning Databases
      • The Basics
      • Get Open Query
      • SQL Server Data
      • SQL Server Maintenance
      • Using SQL Server Dates
      • Using SQL Server Functions
      • Using SQL Server Pivot-Unpivot
      • Technical Tools
    • Learning Web Design
      • Building Ousia Content Management System
      • Using ASP-NET
      • Using CSS
      • Using JavaScript
    • Learning Cloud and IT Services
      • Task Scheduler Error 2147943645
      • Requesting SSL and Generation of PFX file in OpenSSL Simple Steps
    • Using Social Media
      • Asking for a Google Review
      • Changing a Facebook account from personal to business
      • Choosing where to focus Social Media effort
      • Social Media Image Sizes
      • Using Meta Data to set Social Media Images
  • About Us
    • Blog
      • Building an entry level gaming machine
      • Google Core Update Jan 2020
      • Hot Chilli Internet Closure
      • How To Choose Content For Your Website Adverts Leaflets
      • Preventing Online Scam
      • Skimmers of the gig economy
      • The most annoying things about websites on the Internet
      • Top 5 websites for free Vector Graphics
    • Careers
      • Translator English-Portuguese
      • Translator English-Spanish
    • Portfolio
    • Team
      • Adrian Anandan
      • Ali Al Amine
      • Ayse Hur
      • Chester Copperpot
      • Deepika Bandaru
      • Gavin Clayton
      • Sai Gangu
      • Suneel Kumar
      • Surya Mukkamala
English (EN-GB)English (EN-US)Español (ES)हिंदी (HI)italiano (IT)日本語 (JA)

SQL WHERE clauses with date intervals - which way is best?

Examining the way dates are handled within SQL server WHERE clauses, and how best to use them

Context

Using SQL Server Data

Due to the Data Protection Act, certain data should be removed from systems at set times, in most instances it is seven years.

When investigation this at a client site, they were getting strange results when we checked the query sent to us.

SQL

SELECT *FROM AccountsWHERE DATEDIFF(YEAR,ClosedDate,GETDATE())>=7

Create a test table

Now this brought up what looked like the correct volume, however upon further inspection there were more accounts than if I did a static date seven years previous, so why did it do it?

I have built the following code to investigate it.

SQL

DECLARE @Records TABLE (RecordID INT,RecordClosed DATETIME)DECLARE @InsRecID INT = 1DECLARE @InsRecDate DATE=DATEADD(YEAR,-8,GETDATE())WHILE @InsRecDate      INSERT INTO @Records      SELECT @InsRecID,@InsRecDate      SET @InsRecID = @InsRecID+1      SET @InsRecDate=DATEADD(DAY,1,@InsRecDate)ENDDECLARE @DateFrom DATE=DATEADD(YEAR,-7,GETDATE())SELECT MAX(RecordClosed) FROM @RecordsSELECT MAX(RecordClosed) FROM @Records WHERE DATEDIFF(YEAR,RecordClosed,getdate())>=7SELECT MAX(RecordClosed) FROM @Records WHERE RecordClosed<@DateFromSELECT MAX(RecordClosed) FROM @Records WHERE RecordClosed<=@DateFromSELECT MAX(RecordClosed) FROM @Records WHERE DATEDIFF(DAY,RecordClosed,getdate())/365.25>7

Testing

This will bring up the following results when run on 21/03/2013

Results

2007-03-21 00:00:00.000

2006-12-31 00:00:00.000

2006-03-20 00:00:00.000

2006-03-21 00:00:00.000

2006-03-21 00:00:00.000

What is correct?

The first record is just the biggest date in the temp table, so that is fine.

The second record has picked up all accounts up to the end of 2006, this could have been a potential issue as too much data would have been removed. DATEDIFF on the year is purely checking the year is 7 years ago.

The third and fourth records are the one we want, dependent on whether you want to include the day seven years ago as in or out.

The fifth record, although correct when run, is using leap year calculations, and for the sake of accuracy could not be trusted if you had to be specific.

Speed difference

While checking the records, I ran it on the system checking 2,500,000 records for 3 and 5 above.

Statement 5 returned our result in 6 seconds, Statement 3 in only 3 seconds, so not only were we now sure that we were accurate, but we were also processing the records quicker.

Try to use a proper date when querying dates, hope this helps someone scratching their head.

Author

Was this helpful?

Please note, this commenting system is still in final testing.
Copyright Claytabase Ltd 2020

Registered in England and Wales 08985867

Site Links

RSSLoginLink Cookie PolicySitemap

Social Media

facebook.com/Claytabaseinstagram.com/claytabase/twitter.com/Claytabaselinkedin.com/company/claytabase-ltd

Get in Touch

+15125961417info@claytabase.comClaytabase USA, 501 Congress Avenue, Suite 150, Austin, Texas, 78701, United States

Partnered With

The settings on this site are set to allow all cookies. These can be changed on our Cookie Policy & Settings page.
By continuing to use this site you agree to the use of cookies.
Ousia Logo
Logout
Ousia CMS Loader