I need a SQL query to compare 2 dates based on their year and month only.
I.e. one date is 2017-07-12 and the second date is 2017-07-30.
Since they both share same month and year, I need to get them in my WHERE query.
I know how to do it with DATEFORMAT (converting both to the form of yyy-mm-01). I would like to know if there is a cleaner way.
You can compare their month and year using the Month() and Year() functions:
WHERE YEAR(date1)=YEAR(date2) AND MONTH(date1) = MONTH(date2);
Some good information on the mysql date and time functions page in their manual.
The MySQL function EXTRACT() can be used for this purpose:
WHERE EXTRACT(YEAR_MONTH FROM date1) = EXTRACT(YEAR_MONTH FROM date2)
EXTRACT(YEAR_MONTH FROM '2017-07-12') returns '201707'.
Related
I understand the syntax for the current date will change from GETDATE() to SYSDATE().
How do we write the difference between the date from c.end column and the current date in terms of years in MySQL?
Do we use TIMESTAMPDIFF() ?
There are many ways to get current year from MySQL, you just have to extract it using YEAR() function like this:
SELECT YEAR(NOW());
NOW() returns todays date + time in this format 'YYYY-MM-DD HH:MM:SS' so with YEAR(), you're just taking the year value from NOW(). Apply the same thing to the date field in your table like YEAR(C.END_DT) and do a subtraction between those year values. A simple query like this should work:
SELECT YEAR(NOW()) - YEAR(C.END_DT)
FROM mytable C;
But if you still want to use DATEDIFF, you can write something like this:
SELECT FROM_DAYS(DATEDIFF(NOW(),C.END_DT)) FROM mytable C;
DATEDIFF here return the differences in total days and using FROM_DAYS(), it will return the total year, month and day from the specific date in the comparison.
Refer to this updated fiddle
What is the best way to compare just the year and month portion of a date?
Currently, I'm doing something like this:
DATE_FORMAT(`date`, "%Y-%m") <= "2015-12"
Is it safe to do it as strings, assuming the date formats are sortable?
Or would it be better to cast them as integers first?
CONVERT(DATE_FORMAT(`date`, "%Y%m"), UNSIGNED INTEGER) <= 201512
EDIT: This also works:
DATE_FORMAT(`date`, "%Y-%m") BETWEEN '2014-06' AND '2015-12'
EDIT 2: Another example of use case would be returning all rows where the date is in any one of several YEAR-MONTH strings. For example, this also works:
DATE_FORMAT(`date`, "%Y-%m") IN ('2014-06', '2014-09', '2014-12', '2015-03')
Neither. MySQL provides builtin functions to extract year, month, day, etc. Use them. Don't roll your own in any way.
I have this query where I provide to-date & from date.
SELECT *
FROM sales
WHERE date between to-date AND from-date;
Now I want to execute this query with following parameters
to-date = Oct-2015
some-other-date = Oct-2015
That is I want records of the whole month.
How would I do that in a query where I have to and from dates provided it will work for both scenarios where months can be same and different as well.
Update:
dataType for column date is date
You can find the first day of the month containing any given timestamp with an expression like this. For example by using the timestamp NOW(), this finds the first day of the present month.
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW()))
That's handy, because then you can use an expression like
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW())) - INTERVAL 1 MONTH
to find the beginning of the previous month if you like. All sorts of date arithmetic become available.
Therefore, you can use an expression like the following to find all records with item_date in the month before the present month.
WHERE item_date>=(DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))- INTERVAL 1 MONTH
AND item_date < (DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))
Notice that we cast the end of a range of time as an inequality (<) to the moment just after then end of the range of time.
You may find this writeup useful. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
It's often useful to create a stored function called TRUNC_MONTH() to perform the conversion of the arbitrary timestamp to the first day of the month. It makes your SQL statements easier to read.
select * from sales
where from-date >= 1-Oct-2015
and to-date <= 1-Nov-2015
Update
select * from sales
where date >= from-date
and date <= to-date
Here is SQLFIDDLE
You Can get month from your both to and from dates and find records of that month
SELECT * FROM sales
WHERE MONTH('2002-01-03') AND MONTH('2002-01-3')
SqlFiddle of Using Month Function
I am trying to select records from a database only if they match today's date. The format for the date in the database is 2012-06-20 9:30:00 I am using the statement SELECT id FROMnewsreportsWHERE DATE(newsdate) = CURDATE() but it doesn't not return any records for today?
Screenshot of column with dates
http://img135.imageshack.us/img135/8399/2347f03df0394cd898c7fc5.png
DATE_FORMAT(NOW(),'%Y-%m-%d') = FORMAT_DATE(NOW(newsdate), '%Y-%m-%d')
Or better:
DATE(newsdate) = DATE(NOW())
The best way is to store the additional column with 2001-09-11 date format and compare this one
Example, thanks to #Conrad Frix
It looks like the curdate function is going to give you something different than the date format you've got in the database.
Take a look at the docs here
MySQL Date and Time Functions
It's supposed to return a date in this format:
2008-11-11
So, you could either search for a date range between curdate() and curdate() + INTERVAL 1 DAY (untested), or store the dates in the curdate() format.
How do I extract the month and date from a mySQL date and compare it to another date?
I found this MONTH() but it only gets the month. I looking for month and year.
in Mysql Doku:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract
SELECT EXTRACT( YEAR_MONTH FROM `date` )
FROM `Table` WHERE Condition = 'Condition';
While it was discussed in the comments, there isn't an answer containing it yet, so it can be easy to miss.
DATE_FORMAT works really well and is flexible to handle many different patterns.
DATE_FORMAT(date,'%Y%m')
To put it in a query:
SELECT DATE_FORMAT(test_date,'%Y%m') AS date FROM test_table;
If you are comparing between dates, extract the full date for comparison. If you are comparing the years and months only, use
SELECT YEAR(date) AS 'year', MONTH(date) AS 'month'
FROM Table Where Condition = 'Condition';
SELECT * FROM Table_name Where Month(date)='10' && YEAR(date)='2016';
You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?
There should also be a YEAR().
As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)
Or you could use multiple comparisons (i.e. years first, then months).