Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: How to get rows where the date is older than X years?

Tags:

sql

sql-server

Question

I would like to pull all assets from a database which is a certain amount of years old, in this case years. Is this statement correct?

Background

The database is called AssetRegister

The table is called dbo.Assets

the column is called AcquiredDate

Statement so far

SELECT * FROM dbo.Assets WHERE AcquiredDate < '2008-01-01'
like image 425
Dan Cundy Avatar asked Nov 18 '14 08:11

Dan Cundy


People also ask

How can I get previous date record in SQL Server?

To get yesterday's date, you need to subtract one day from today's date. Use GETDATE() to get today's date (the type is datetime ) and cast it to date . In SQL Server, you can subtract or add any number of days using the DATEADD() function. The DATEADD() function takes three arguments: datepart , number , and date .

How do you find age difference in SQL?

We can find the age of a person from their date of birth by using this formula: SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),'DATE_OF_BIRTH')), '%Y') + 0 AS age; In the above formula, we are first finding the difference between the current date (NOW()) and the date of birth (in YYYY-MM-DD) using the DATEDIFF() function.

How do I sort descending dates in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


2 Answers

SELECT * FROM dbo.Assets                  
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8

For an performance optimized query look at @Horaciuxs answer.

like image 95
juergen d Avatar answered Oct 22 '22 11:10

juergen d


The answer by @Juergen bring the right results:

SELECT * FROM dbo.Assets                  
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8

But, the SQL optimizer can't use an index on AcquiredDate, even if one exists. It will literally have to evaluate this function for every row of the table.

For big tables is recommended to use:

DECLARE @limitDate Date
SELECT @limitDate=DATEADD(year,-8,GETDATE()) --Calculate limit date 8 year before now.

SELECT * FROM dbo.Assets                  
WHERE AcquiredDate <= @limitDate

Or simply:

SELECT * FROM dbo.Assets                  
    WHERE AcquiredDate <= DATEADD(year,-8,GETDATE())
like image 30
Horaciux Avatar answered Oct 22 '22 11:10

Horaciux