Get date of 3 days ago - sql

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?

SELECT [ClientID] from [logs] where Date > DATEADD(day, -3, CONVERT (date, SYSDATETIME()))

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

For mysql use this:
SELECT DATE_ADD(CURRENT_DATE, INTERVAL - 3 DAY);

Use BETWEEN
SELECT ClientID
FROM logs
WHERE Date BETWEEN SYSDATETIME() AND SYSDATETIME() - 3

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.

SELECT [ClientID] from [logs] where Date > DATEADD(day, -3, SYSDATETIME())

In my case:
select * from Table where row > now() - INTERVAL 3 day;
So you can fetch all of 3 days ago!

Related

SQL date comparision in yyyy/mm/dd

Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this
d.date_begin >= DATEADD(day,-7, GETDATE())
is not working :), i'm TERRIBLE at convert and data type..
This will work if you want records from 7 days ago up to and including today's records
CAST(d.date_begin AS DATE) >= CAST(DATEADD(day,-7, GETDATE()) AS DATE)
where DATEDIFF(month,Your_date_column,getdate()) < 3
SQL server 2012 onwards, if date_begin is of datatype date
where d.date_begin >= cast(DATEADD(day,-7, GETDATE()) as date)
This will get anything in the last 7 days, regardless of time
You should store date/time values using native formats. Ok, sometimes we cannot. But you can easily convert your values to the correct format:
where cast(replace(d.date_begin, '/', '') as date) >= DATEADD(day, -7, GETDATE())
I should note that SQL Server is pretty good about conversions, so your initial code should not generate any errors -- unless you have unusual internationalization settings.
Or, actually, a better way to do this is to convert the current value to a string:
where d.date_begin >= format(dateadd(day, -7, getdate()), 'yyyy/MM/dd')
This is better because it is "sargable", meaning that SQL Server can use an index on the column if available.
SELECT * FROM tbl_name
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
Don't manipulate d.date_begin. Making calculation on a column while comparing can give bad performance. You should manipulate getdate() to get the same format as d.date_begin. In this case it works because the format is yyyy/MM/dd - the comparison will give the same result as if both columns were date columns.
WHERE
d.date_begin >= convert(char(10),DATEADD(day,-7, GETDATE()), 111)

Get tomorrows date

I am trying to get tomorrows date in a sql statement for a date comparison but it is not working.
Below is my code:
select *
from tblcalendarentries
where convert(varchar,tblcalendarentries.[Start Time],101)
= convert(varchar, GETDATE() +1, 101)
To get tomorrows date you can use the below code that will add 1 day to the current system date:
SELECT DATEADD(day, 1, GETDATE())
GETDATE()
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.
DATEADD(datepart , number , date)
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
So adding this to your code in the WHERE clause:
WHERE CONVERT(VARCHAR, tblcalendarentries.[Start Time], 101) =
CONVERT(VARCHAR, DATEADD(DAY, 1, GETDATE()), 101);
First off, GETDATE() will get you today's date in the following format:
2013-04-16 10:10:02.047
Then using DATEADD(), allows you to add (or subtract if required) a date or time interval from a specified date. So the interval could be: year, month, day, hour, minute etc.
Working with Timezones?
If you are working with systems that cross timezones, you may also want to consider using GETUTCDATE():
GETUTCDATE()
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
Try the below:
SELECT GETDATE() + 1
This adds one day to current date
Specify size of varchar in convert()
where convert(varchar(11),tblcalendarentries.[Start Time],101) = convert(varchar(11), GETDATE() +1, 101)
I would write:
where
DATEADD(day,DATEDIFF(day,0,tblcalendarentries.[Start Time]),0) =
DATEADD(day,DATEDIFF(day,0,GETDATE()),1)
This avoids converting dates to strings entirely, whilst also removing the time portion from both values.

Auto-computed column in SQL Server 2012

Is it possible for a column in to be auto-calculated by SQL Server 2012 itself?
For example: I have three columns START_DATE, END_DATE and DURATION.
I want to get the duration by doing this :
DURATION = END_DATE - START_DATE
So I get the duration in number of days.
Is it possible for SQL Server 2012 to do it automatically on record creation ?
Yes, sure - just define Duration to be a computed column:
ALTER TABLE dbo.YourTable
ADD Duration AS DATEDIFF(DAY, START_DATE, END_DATE) PERSISTED
and off you go. Now Duration will always show the difference (in days) between these two other columns. The value computed will be stored along side your other column values, if you use the PERSISTED keyword. This column will be updated if any of the two "dependent" columns changes, too.
Update: if you want to get the difference between a date and today, you can use
ALTER TABLE dbo.YourTable
ADD Duration AS DATEDIFF(DAY, START_DATE, GETDATE())
but unfortunately, since the GETDATE() function is non-deterministic (after all - it's return value changes every time you call it), you cannot use the PERSISTED keyword. This means: every time you access the column (ask for its value), the calculation will be done again.
In your Table Design, enter any of these in (Formula) under Computed Column Specification for your required result.
For Date Difference:
CAST(job_end - job_start) AS TIME(0))
For Time Duration:
SUBSTRING(CONVERT(VARCHAR(20),(END_DATE-START_DATE),120),12,8)
Similarly you can compute for Second, Minute, Hour, Month, Year differences.
Syntax for using DATEDIFF:
DATEDIFF ( datepart , startdate , enddate )
For your Reference:
DATEDIFF(SECOND, GETDATE(), GETDATE() + 1) AS SecondDifference
DATEDIFF(MINUTE, GETDATE(), GETDATE() + 1) AS MinuteDifference
DATEDIFF(HOUR, GETDATE(), GETDATE() + 1) AS HourDifference
DATEDIFF(DAY, GETDATE(), GETDATE() + 1) AS DayDifference
DATEDIFF(WEEK, GETDATE(), GETDATE() + 1) AS WeekDifference

SQL Server datetime in query

In an event management database I have list of all events with a field startdate
What I want to do is not to show events passed by an hour. Only events which have not passed by current date and time.
My date and time is in this format 2011-08-24 17:30:00.000
Any kind of help is appreciated
I read that as you want data where startdate is before a specific date;
select
*
from T
where startdate < dateadd(hour, -1, '2011-08-24 17:30:00.000')
SELECT *
From EventTable
WHERE startdate > DATEADD(HOUR, -1, GETDATE())
GetDate() - Returns the current database system timestamp as a
datetime value.
DATEADD(datepart , number , date ) - Returns a specified date
with the specified number interval (signed integer) added to a
specified datepart of that date.

DATEDIFF Getting the previous month

I want to get the previous month relative to the current date
SELECT datediff(mm,-1,2-2-2011)
This query gives 67 which is a wrong value .. where i went wrong ?
You can use DATEADD
eg.
SELECT DATEADD(month, -1, GETDATE())
This 2-2-2011 is not a valid date literal - you are subtracting 2 from 2 and then 2011 from the result - proper date literals are '2-2-2011' and #2-2-2011#. You can use GETDATE() to get the current date, instead of relying on a literal.
Nor should you be using DATEDIFF - it gives you the difference between dates.
You should be using DATEADD to calculate new dates.
Try this:
SELECT DATEADD(mm,-1, GETDATE())
This will get the date a month ago.
If you just want the month, you need to also use DATEPART:
SELECT DATEPART(mm, SELECT DATEADD(mm,-1, GETDATE()))
SELECT datepart(mm, dateadd(mm,-1,'2011/1/1') )
If you want the month before the current month, you want
SELECT MONTH(DATEADD(mm, -1, GETDATE()))
If you want the date for a month before the current date, you want
SELECT DATEADD(mm, -1, GETDATE())
BTW, SELECT datediff(mm,-1,2-2-2011) computes the number of months between day -1 and day -2011, which is 67 (2010 / 30). That's nowhere near what you seem to actually want.
You need to use DATEADD - not DATEDIFF
DATEDIFF calculates the difference between two dates - it doesn't add day or months to an existing date....
Also, you need to put your dates into single quotes: use '2-2-2011' instead of simply 2-2-2011.
And lastly: I would strongly recommend using the ISO-8601 date format YYYYMMDD (here: 20110202) - it will work regardless of the language and regional settings on your SQL Server - your date format will BREAK on many servers due to language settings.
DATEDIFF calculates the difference between your stating and ending dates
every date previous to the current date has a positive number and every date next to the current date has negative number, this works in geting your specific date weather it a day,month,year or hour to understand this better below is the syntax of datediff
DATEDIFF (your datetime type, your starting date,your ending date)
the function does (your ending date)-(your starting date)
in your case the below datediff will work just pefectly
SELECT DATEDIFF (month,[you_date_or_datetime_column],GETDATE()) = 1
You can use DATEADD try this code
For previous month
SELECT DATEADD(month, -1, GETDATE())
For 7 day previous
$date = date('Y-m-d',strtotime("-7 days"));
SELECT * FROM users WHERE `date` LIKE '%$date%'
$date varibale get previous date date