sqlsql-server

How to get the date 30 days before today's date from database


Consider I have a table named Products.

ProductID ProductName ExpDate
1001 Coca Cola 2021-6-6
1002 Pepsi 2021-5-8

I want to get the ExpDate from each of the Products and get the 30 days before that date.

For example, the first one ExpDate is 2021-6-6, so minus 30 days = 2021-5-5.


Solution

  • You can use DateAdd function to subtract 30 days from a date field.

       Select ProductName, ExpDate, dateadd(day,-30,ExpDate) as '30Daysbefore' 
       from Products