How do I create future dates in SQL? For example, I want to be able to use my date range and show everything for just next month (purchase orders), then another for two months out, etc. I have used the fn NOW() for the current date/time but this doesn't help me at all for showing records for next month, etc.
Thanks
This is for a SQL query that in doing in SQL Server 2008 R2.
If you use MySQL you can use:
SELECT date_col FROM your_table
WHERE date_col BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 1 MONTH)
For MS-SQL (it should work):
SELECT date_col FROM your_table
WHERE date_col BETWEEN GETDATE() AND DATEADD(Month, 1, GETDATE())
For Oracle (it should work):
SELECT date_col FROM your_table
WHERE date_col BETWEEN SYSDATE AND add_months(SYSDATE, 1)
You can use the DATEADD function to create dates relative to another date. The following call will generate a date exactly one month in the future:
DATEADD(month, 1, GETDATE())
You can use negative numbers to go back as well as forward. There are many other increments you can use, e.g. year, day, week, quarter, millisecond etc.
Related
I want to get the records of last month based on my table [Sales], variable "SoldDate" in SQL Server.
For example, if today is 29/09/2021, I want to get the data for 01/08/2021-31/08/2021
The "SoldDate" variable is in the format 2018-04-11 00:00:00.000.
I would really appreciate your help! I have no idea how to get this to work :(
You can use eomonth() :
SELECT DATEADD(DAY, 1, EOMONTH(SoldDate, -2)) AS StartDate, EOMONTH(SoldDate, -1) AS EndDate
The best way to search through an indexed table is to calculate what date range you need, and filter on that. You can use DATEADD and EOMONTH for this. Note that since you have a time component, you cannot just use EOMONTH
SELECT *
FROM YourTable
WHERE SoldDate >= DATEADD(day, 1, EOMONTH(GETDATE(), -2))
AND SoldDate < DATEADD(day, 1, EOMONTH(GETDATE(), -1))
EOMONTH gives you the end of a month, the second parameter denotes how many months to shift.
Note correct use of the half-open interval >= AND <, this dealls correctly with the time component.
Running MS SQL Server 2008
I have this query:
select count(*) from dbo.study
where study_datetime >= (GETDATE() -1)
that comes back with all of yesterdays exams written to my study table. How would I make it come back with everything done 'today' up to the current time I asked for it? For example I would everything for today from 00:00:00.000 - current time
my values in the 'study_datetime' column look like: 2014-05-06 10:40:31.000
I can't seem to figure this one out. I have tried replacing the '-1' with a '0' but I get back 0 results.
thanks
unfortunately there is no trunc() like in oracle, but since you have the 2008 version you can use:
select count(*) from dbo.study
where study_datetime >= cast(getDate() As Date)
If I understand well (values from same day), I think you can use DATEDIFF function, using the day as datepart.
select count(*) from dbo.study
where datediff(dd, study_datetime, GETDATE()) = 0
and study_datetime <= GETDATE() -- if you need a check for the "future" (datetime after GETDATE() )
To get everything that strictly happened today, just use:
select count(*) from dbo.study
where study_datetime >= cast(getDate() As Date)
and study_datetime < cast(DATEADD(day,1,getdate()) as Date)
When you're working with continuous data, it's almost always better to switch to using semi-open intervals, to ensure that data falls into one and exactly one interval. Usually, when you want "all day", you don't want to exclude things that occurred during the final minute of the day (at e.g. 23:59:37.223 or even at 23:59:59.993). So you'd normally write your query to be >= midnight at the start of the day and < midnight at the start of the following day (note the different types of comparisons)
This is usually a far better idea than trying to compute the last moment of today and use <= (or BETWEEN) for your comparisons.
select count(*) from dbo.study
where study_datetime between :2014-05-06 00:00:00 and :2014-05-06 23:59:59.
It might help you
How do you check if a date is within this or the prior calendar year.
I.E. December 31, This Year > myDate > January 1, Last Year
The standard SQL way is to use EXTRACT:
select *
from t
where extract(year from t.thedate) = extract(year from CURRENT_TIMESTAMP) or
extract(year from t.thedate) = extract(year from CURRENT_TIMESTAMP) - 1
Not all databases support these functions; but all do have a way of extracting the date somehow. For instance, many support the year function.
You can do something like this
SELECT * FROM YourTable
WHERE TO_DATE("FROM-DATE") < DateColumn AND TO_DATE("END-DATE") > DateColumn
This is in Oracle, pretty sure MySQL SQLite or other databases have this function,
In SQL Server you could do this:
DECLARE #yourDate DATETIME;
SELECT #yourDate = '2012-06-02';
SELECT CASE YEAR(#yourDate)
WHEN YEAR(GETDATE()) THEN 'Same Year'
WHEN YEAR(GETDATE()) - 1 THEN 'Last Year'
ELSE 'Other Year'
END AS YourColumn;
You can also easily expand this if you had to look for future dates, or more than one year in the past.
Other RDBMS will offer similar functionality to check the year for your dates.
For SQL Server, you could use DATEDIFF:
WHERE DATEDIFF(year,myDate,CURRENT_TIMESTAMP) in (0,1)
DATEDIFF(year,... effectively computes the number of year transitions between the dates (or to put it another way, the number of new year's eves at midnight).
For larger tables where indexes may help your query, we'd need to instead transform CURRENT_TIMESTAMP and compare myDate against those computed values:
WHERE myDate >= DATEADD(year,DATEDIFF(year,'20010101',CURRENT_TIMESTAMP),'20000101') AND
myDate < DATEADD(year,DATEDIFF(year,'20010101',CURRENT_TIMESTAMP),'20020101')
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
I know about DATEDIFF(d, date1, date2), but I am not looking to subtract two dates, rather an amount of days from a date.
For example:
"2010-04-13" - 4 = "2010-04-09"
Is that possible with mySQL?
date_sub(date,interval 4 day);
Yes. See http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_adddate
SELECT DATE_ADD('2008-01-02', 31);
Results in:
'2008-02-02'
To subtract, just use a negative number, or use DATE_SUB
This will subtract 2 days from a date in a table, and show both dates.
SELECT
[Date]
,DATEADD(DAY, -2, [Date]) AS [NewDate]
FROM
[YourTable]
yes. Mysql has plenty of date functions. Just google mysql datetime functions and you'll get the list. Date subtraction ones among them