18

I have SQL script that selects everything from current day.

SELECT  [ClientID] from [logs] where Date > CONVERT (date, SYSDATETIME())

Date is type of DateTime.

How to get everything within last 3 days? I suppose I need subtract 3 days from function SYSDATETIME() result, but how?

Tharif
  • 13,794
  • 9
  • 55
  • 77
vico
  • 17,051
  • 45
  • 159
  • 315

7 Answers7

22
SELECT  [ClientID] from [logs] where Date > DATEADD(day, -3, CONVERT (date, SYSDATETIME()))
Backs
  • 24,430
  • 5
  • 58
  • 85
14

Use GETDATE() : Yes, it gets date from system!

Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

Query:

SELECT  [ClientID] from [logs] where ( Date  > GETDATE() - 3)

More Reference:

GETDATE Detailed Documentation

Tharif
  • 13,794
  • 9
  • 55
  • 77
4

For mysql use this:

SELECT DATE_ADD(CURRENT_DATE, INTERVAL - 3 DAY);
Tharif
  • 13,794
  • 9
  • 55
  • 77
anirban karak
  • 732
  • 7
  • 20
1

Use BETWEEN

SELECT ClientID 
FROM logs
WHERE Date BETWEEN SYSDATETIME() AND SYSDATETIME() - 3
Matt
  • 14,906
  • 27
  • 99
  • 149
1

In my case:

select * from Table where row > now() - INTERVAL 3 day;

So you can fetch all of 3 days ago!

Fabio Mendes Soares
  • 1,357
  • 5
  • 20
  • 30
amir avira
  • 31
  • 4
0

Using BETWEEN is nice. I also prefer the DATEADD function. But be aware of the fact that the SYSDATETIME function (or I would us GETDATE()) also includes the time which would mean that events before the current time but within the three day period may not be included. You may have to convert both sides to a date instead of datetime.

Tom
  • 747
  • 5
  • 16
0
SELECT  [ClientID] from [logs] where Date > DATEADD(day, -3, SYSDATETIME())
Madhivanan
  • 13,470
  • 1
  • 24
  • 29