SQL query to check if date is close to today

Here is the table:

orders(id, item, deliveryDate, courier_id)

I would like to write a request that will return all orders for this courier with a delivery date that is within a month today. How to do it?

+4
source share
3 answers

In T-SQL:

 SELECT * FROM orders WHERE deliveryDate BETWEEN GETDATE() AND GETDATE() + 30 AND courier_id = @CourierID 

EDIT

While the period in this decision is about a month, itโ€™s not exactly one month, as Uncle Brad carefully observed. If you need to be precise, you must calculate one month from the current date as follows: DATEADD(month, 1, GETDATE()) . This replaces GETDATE() + 30 in the above query.

+1
source

Most servers use the whole part of the date for several days.

In this example, I use "Now ()" as a server function that returns the current date. You should look right in the documentation for the server you are using.

(also the designation? as the value of the courier identifier)

 Select * From orders Where Now() - deliveryDate < 30 And courier_id = ? 

If your server does not spend days, you can see its date conversion functions.

+1
source

If MySQL

DATE_ADD

 SELECT * FROM orders WHERE deliveryDate BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 1 MONTH); 
0
source

Source: https://habr.com/ru/post/1343398/


All Articles