How to get rows of last minute of every month? - mysql

I have a table that one of its column, named 'date', is of type DATETIME. I need to select all the rows that their date is the last minute of a month, for example:
31-12-17 23:59:00
30-11-17 23:59:00
How can I achieve this in one query?

You could use LAST_DAY to get the last day of the month and DATE_FORMAT to get the time to compare.
SELECT * FROM <table_name>
WHERE DATE_FORMAT(LAST_DAY(<date_time_col>),"%d")=DATE_FORMAT(<date_time_col>,"%d")
AND DATE_FORMAT(<date_time_col>,"%H:%i")='23:59';
Detailed Explanation :
So, basically, to get the correct row we need to get the last day of the month AND last minute of the day
LAST_DAY will help use to get the last day of the month for the given date-time. And DATE_FORMAT will help to get the date. Now, we will combine them together, to get the last date of the given date-time.
DATE_FORMAT(LAST_DAY(<date_time_col>),"%d")
Above will return 29, if last day of the month is 29-02-2018.
Now, we need to check, if given date-time has last minute of the day ? We can again make use of DATE_FORMAT to extract time from the given date-time. Here, we will only concentrate on hour and minute (as per OP question). So, it should be
DATE_FORMAT(<date_time_col>,"%H:%i")
Above will return 23:59, if given date-time is 29-02-2018 23:59:00.

You can use LAST_DAY to get the last day of each month:
SELECT LAST_DAY(mydate)
returns:
2031-12-31
2030-11-30
Then use the STR_TO_DATE in order to get the last minute of the last day of each month:
SELECT STR_TO_DATE(CONCAT(LAST_DAY(mydate),
' ',
'23:59:00'),
'%Y-%m-%d %H:%i:%s') AS last_min
returns:
last_min
--------------------
2031-12-31T23:59:00Z
2030-11-30T23:59:00Z
2030-11-30T23:59:00Z
You can now use last_min to compare with your actual datetime value.
If you want to get records whose datetime falls within the last minute interval, then you can additionally use DATE_ADD to get the next minute of the above datetime values:
SELECT DATE_ADD(last_min,
INTERVAL 1 MINUTE) AS next_min
returns:
next_min
---------------------
2032-01-01T00:00:00Z
2030-12-01T00:00:00Z
2030-12-01T00:00:00Z
Using the above expressions you can build a predicate that checks for dates within the desired interval.
Demo here

SELECT * FROM table WHERE DATE(date) = LAST_DAY(date) AND HOUR(date) = 23 AND MINUTE(date) = 59;
Since this query won't use any index, it might be slow in a large table.

A more efficient solution could be as follows:
SELECT * FROM mytable WHERE mydate IN
(
'2017-01-31 23:59:00',
'2017-03-31 23:59:00',
'2017-04-30 23:59:00',
'2017-05-31 23:59:00',
'2017-06-30 23:59:00',
'2017-07-31 23:59:00',
'2017-08-31 23:59:00',
'2017-09-30 23:59:00',
'2017-10-31 23:59:00',
'2017-11-30 23:59:00',
'2017-12-31 23:59:00'
)
OR mydate = '2017-03-01 00:00:00'- INTERVAL 1 MINUTE;

Related

How to find next date from time in mysql

I want to know is it possible in mysql query.. when I say give me date when it is 9am.. the return answer is depends upon current time when it is 8am it give me today's date. when it is 10pm it gives me tomorrow date. how it is possible in mysql query.
You can use SUBSTRING_INDEX(CURTIME(), ':', 1) to get the hours of current time.
As I understood you want to get tomorrow date, if it is 10pm or later
Example given:
SELECT
CASE
WHEN SUBSTRING_INDEX(CURTIME(), ':', 1) >= 22
THEN DATE_ADD(CURDATE(), INTERVAL 1 DAY)
ELSE CURDATE()
END
Source: http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/sql/sql_dates.asp.html
You can get the hour value from a given datetime expression, using HOUR function. CURDATE() function is used to return the current date. You can add/subtract 'integers' to it get the date corresponding to current date +/- 'integer days' . Assuming that the time >= 10 pm returns next day:
SELECT IF(HOUR(`datetime_field`) > 22, CURDATE(), CURDATE() + 1);
You could just add 2 hours
SELECT DATE(DATE_ADD(NOW(), INTERVAL 2 HOUR));
This will then return tomorrow’s date for anytime after 10pm.

Get records for last 2 days

I am trying to create a query to get the records for last two days. In my table there is a field called dates. Values are as below:
05-08-2018 08:05:22
05-08-2018 10:15:42
dd-mm-yyyy hh:ii:ss
I have created the query.
SELECT id,title,description, dates
FROM post_feed where `dates` BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE()
ORDER BY dates DESC LIMIT 100
When I run the query it return 0 records. It looks like issue with date format.
Seems like your dates are stored as varchar. You must convert them to date (e.g. by using STR_TO_DATE) before you can perform any comparison.
Assuming for example that today is Aug-05 and you want results for Aug-04 and 05 (inclusive):
SELECT id, title, description, dates
FROM post_feed
WHERE STR_TO_DATE(dates, '%d-%m-%Y') BETWEEN CURRENT_DATE - INTERVAL 1 DAY AND CURRENT_DATE
ORDER BY dates DESC
LIMIT 100
SQL Fiddle
Try this WHERE clause:
WHERE STR_TO_DATE(dates, '%d-%m-%Y %H:%i:%s') BETWEEN DATE_ADD(CURDATE(), INTERVAL -2 DAY) AND CURDATE()
Your second date is before your first date. Put greater date at first place & put lesser date at second place.
SELECT id,title,description, dates
FROM post_feed where CAST(`dates`as date) BETWEEN CURDATE() AND CURDATE() - INTERVAL 1 DAY
ORDER BY dates DESC LIMIT 100
Fix your data! Your query doesn't work because the "date" value are stored as text/varchar. This is easily fixed:
update post_feed
set dates = str_to_date(date, '%Y-%m-%d %H:%i:%s')
alter table post_feed
modify column datetime;
Voila! Your queries will now work.

Select all MySQL records in the last day that are between a time range of 7am and midnight

I have this query
SELECT * FROM `timeclock_timecard`
WHERE `clock_in_datetime` > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
which can get record in the last day but I need to limit to records created after 7AM
Any help please?
SELECT * FROM `timeclock_timecard`
WHERE `clock_in_datetime` > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
and hour(`clock_in_datetime`) > 7;
Added one more filter condition to check for the hour.
Your query was almost correct, because CURDATE() only gives the date you can just subtract 17 hours to get the correct result. fiddle.
SELECT * FROM `timeclock_timecard`
WHERE `clock_in_datetime` >= DATE_SUB(CURDATE(), INTERVAL 17 HOUR)
To get the entries of the current day, we can add 7 hours (CURDATE() has time 0:00).
SELECT * FROM `timeclock_timecard`
WHERE `clock_in_datetime` >= DATE_ADD(CURDATE(), INTERVAL 7 HOUR)
To get only rows from yesterday, with a time value of 7AM or later, we can add 7 hours to the expression.
If we only up until midnight of today (just rows from yesterday), we can add another condition, the datetime is less than midnight today.
For example:
SELECT t.*
FROM `timeclock_timecard` t
WHERE t.`clock_in_datetime` >= DATE(NOW()) + INTERVAL -1 DAY + INTERVAL 7 HOUR
AND t.`clock_in_datetime` < DATE(NOW())
If you want to exclude the exact 7:00:00 AM value, change the >= to just >.
FOLLOWUP
Q: What I actually want is between about 5-6am TODAY and mindnight TODAY so anytime during today that I run the report for today I will get only timeclock data from users who clocked in/out today only and not include yesterdays data.
A: The predicates are going to be of the form
WHERE t.`clock_in_datetime` >= expr1
AND t.`clock_in_datetime` < expr2
You just need to find the expressions expr1 and expr2 that return the appropriate datetime values.
Just use a simple SELECT statement to test:
SELECT DATE(NOW()) + INTERVAL 5 HOUR AS `start`
, DATE(NOW()) + INTERVAL 1 DAY AS `end`
Q: I also modified my select to take in account my datetime is in UTC and my result needs to get todays records using local timezone.
SELECT * , CONVERT_TZ( clock_in_datetime , '+00:00', '-4:00' ) FROM `timeclock_timecard`
A: Personally, I would do the timezone conversion on the exprN values, not the column values. Having predicates on bare columns allows MySQL to make effective use of an index; wrapping the columns in expressions prevents MySQL from using an index.
If the MySQL system clock is UTC, and your datetime values stored in the table are in a different timezone, yes, use the MySQL CONVERT_TZ function.
Again, using a simple SELECT statement to develop and test the expressions:
SELECT CONVERT_TZ( DATE(NOW()) + INTERVAL 5 HOUR, '+0:00', to_tz) AS `start`
, CONVERT_TZ( DATE(NOW()) + INTERVAL 1 DAY , '+0:00', to_tz) AS `end`
Where to_tz is the timezone of the values in the table.
Once you get expressions start and end returning the values you need, then use those expressions in the predicates of the query of the timecard table.

How to get first day of every corresponding month in mysql?

I want to get first day of every corresponding month of current year. For example, if user selects '2010-06-15', query demands to run from '2010-06-01' instead of '2010-06-15'.
Please help me how to calculate first day from selected date. Currently, I am trying to get desirable using following mysql select query:
Select
DAYOFMONTH(hrm_attendanceregister.Date) >=
DAYOFMONTH(
DATE_SUB('2010-07-17', INTERVAL - DAYOFMONTH('2010-07-17') + 1 DAY
)
FROM
hrm_attendanceregister;
Thanks
Is this what you are looking for:
select CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') as DATE);
You can use the LAST_DAY function provided by MySQL to retrieve the last day of any month, that's easy:
SELECT LAST_DAY('2010-06-15');
Will return:
2010-06-30
Unfortunately, MySQL does not provide any FIRST_DAY function to retrieve the first day of a month (not sure why). But given the last day, you can add a day and subtract a month to get the first day. Thus you can define a custom function:
DELIMITER ;;
CREATE FUNCTION FIRST_DAY(day DATE)
RETURNS DATE DETERMINISTIC
BEGIN
RETURN ADDDATE(LAST_DAY(SUBDATE(day, INTERVAL 1 MONTH)), 1);
END;;
DELIMITER ;
That way:
SELECT FIRST_DAY('2010-06-15');
Will return:
2010-06-01
There is actually a straightforward solution since the first day of the month is simply today - (day_of_month_in_today - 1):
select now() - interval (day(now())-1) day
Contrast that with the other methods which are extremely roundabout and indirect.
Also, since we are not interested in the time component, curdate() is a better (and faster) function than now(). We can also take advantage of subdate()'s 2-arity overload since that is more performant than using interval. So a better solution is:
select subdate(curdate(), (day(curdate())-1))
This is old but this might be helpful for new human web crawlers XD
For the first day of the current month you can use:
SELECT LAST_DAY(NOW() - INTERVAL 1 MONTH) + INTERVAL 1 DAY;
You can use EXTRACT to get the date parts you want:
EXTRACT( YEAR_MONTH FROM DATE('2011-09-28') )
-- 201109
This works well for grouping.
You can use DATE_FORMAT() function in order to get the first day of any date field.
SELECT DATE_FORMAT(CURDATE(),'%Y-%m-01') as FIRST_DAY_CURRENT_MONTH
FROM dual;
Change Curdate() with any other Date field like:
SELECT DATE_FORMAT(purchase_date,'%Y-%m-01') AS FIRST_DAY_SALES_MONTH
FROM Company.Sales;
Then, using your own question:
SELECT *
FROM
hrm_attendanceregister
WHERE
hrm_attendanceregister.Date) >=
DATE_FORMAT(CURDATE(),'%Y-%m-01')
You can change CURDATE() with any other given date.
There are many ways to calculate the first day of a month, and the following are the performance in my computer (you may try this on your own computer)
And the winner is LAST_DAY(#D - interval 1 month) + interval 1 day
set #D=curdate();
select BENCHMARK(100000000, subdate(#D, (day(#D)-1))); -- 33 seconds
SELECT BENCHMARK(100000000, #D - INTERVAL (day(#D) - 1) DAY); -- 33 seconds
SELECT BENCHMARK(100000000, cast(DATE_FORMAT(#D, '%Y-%m-01') as date)); -- 29 seconds
SELECT BENCHMARK(100000000, LAST_DAY(#D - interval 1 month) + interval 1 day); -- 26 seconds
I'm surprised no one has proposed something akin to this (I do not know how performant it is):
CONCAT_WS('-', YEAR(CURDATE()), MONTH(CURDATE()), '1')
Additional date operations could be performed to remove formatting, if necessary
use date_format method and check just month & year
select * from table_name where date_format(date_column, "%Y-%m")="2010-06"
SELECT LAST_DAY(date) as last_date, DATE_FORMAT(date,'%Y-%m-01') AS fisrt_date FROM table_name
date=your column name
The solutions that use last_day() and then add/subtract a month and a day are not interchangeable.
Example:
date_sub(date_add(last_day(curdate()), interval 1 day), interval 3 month)
always works for any supplied number of months you want to go back
date_add(date_sub(last_day(now()), interval 3 month), interval 1 day)
will fail in some cases, for instance if your current month has 30 days and the month you're subtracting back to (and then adding a day) has 31.
date_add(subdate(curdate(), interval day(?) day), interval 1 day)
change the ? for the corresponding date
This works fine for me.
date(SUBDATE("Added Time", INTERVAL (day("Added Time") -1) day))
** replace "Added Time" with column name
Use Cases:
If you want to reset all date fields except Month and Year.
If you want to retain the column format as "date". (not as "text" or "number")
Slow (17s):
SELECT BENCHMARK(100000000, current_date - INTERVAL (day(current_date) - 1) DAY);
SELECT BENCHMARK(100000000, cast(DATE_FORMAT(current_date, '%Y-%m-01') as date));
If you don't need a date type this is faster:
Fast (6s):
SELECT BENCHMARK(100000000, DATE_FORMAT(CURDATE(), '%Y-%m-01'));
SELECT BENCHMARK(100000000, DATE_FORMAT(current_date, '%Y-%m-01'));
select big.* from
(select #date := '2010-06-15')var
straight_join
(select * from your_table where date_column >= concat(year(#date),'-',month(#date),'-01'))big;
This will not create a full table scan.

Select mysql query between date?

How to select data from mysql table past date to current date? For example, Select data from 1 january 2009 until current date ??
My column "datetime" is in datetime date type. Please help, thanks
Edit:
If let say i want to get day per day data from 1 january 2009, how to write the query? Use count and between function?
select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()
or using >= and <= :
select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()
All the above works, and here is another way if you just want to number of days/time back rather a entering date
select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
You can use now() like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:
This WILL include records from 2019-12-02:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'
This WON'T include records from 2019-12-02:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'