Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Select records for the same day between particular data range [closed]

I need to check the SQL date range between some values. Example. To check records added between last 2 to 1 hours.

Is the below query correct:

SELECT * 
FROM tablename 
WHERE dtdatetime BETWEEN DATEADD(hh, -1, GETDATE()) AND DATEADD(hh, -2, GETDATE())

Could you please provide suggestions.

like image 777
Jay Avatar asked Oct 10 '13 13:10

Jay


People also ask

How do I select a specific date range in SQL?

SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN '2001-03-01 11:00:00' AND '2005-03-01 22:00:00';

How do I get only yesterday records in SQL?

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 I select records between two dates in SQL?

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2005-02-28 21:00:00' AND '2008-12-25 00:00:00';

Which operator is used to display records between specified range of values?

The SQL BETWEEN Operator The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.


1 Answers

  • don't use lazy shorthand like hh. Here's why.
  • don't use BETWEEN. Here's why. It requires the first argument to be the smaller one anyway - your problem is actually that you are saying WHERE 2 BETWEEN 3 AND 1 and it will only return true if you flip it to WHERE 2 BETWEEN 1 AND 3. Go ahead and try it - the smaller argument needs to be first. But really, just stop using BETWEEN for date range queries anyway.

Here is what your query should look like:

WHERE dtdatetime >= DATEADD(HOUR, -2, GETDATE())
  AND dtdatetime <  DATEADD(HOUR, -1, GETDATE());

Note that this will give different results depending on what time you run it during the current hour. For example if you run it at 12:32 it will give data >= 10:32 and < 11:32. If you want data >= 10:00 and < 11:00, whether it is run at 12:04 or 12:32 or 12:59, then you want this instead:

DECLARE @TopOfHour DATETIME;
SET @TopOfHour = DATEADD(HOUR, DATEPART(HOUR, GETDATE()), DATEDIFF(DAY, 0, GETDATE()));

SELECT ...
WHERE dtdatetime >= DATEADD(HOUR, -2, @TopOfHour)
  AND dtdatetime <  DATEADD(HOUR, -1, @TopOfHour);
like image 107
Aaron Bertrand Avatar answered Oct 18 '22 12:10

Aaron Bertrand