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?
The database is called AssetRegister
The table is called dbo.Assets
the column is called AcquiredDate
SELECT * FROM dbo.Assets WHERE AcquiredDate < '2008-01-01'
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 .
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.
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.
SELECT * FROM dbo.Assets
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8
For an performance optimized query look at @Horaciuxs answer.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With