Date Functions in MySQL - mysql

Looking for some help regarding mysql date functions.
I am looking to show data for a time period of today to 8 days ago (I have been using this line of code in mysql WHERE TIME > CURDATE() - INTERVAL 8 DAY ) ) as well as the above time period but one year ago.

Try using
DATE_SUB with TIMESTAMPDIFF,
TIMESTAMP syntax,
TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2);
DATE_SUB syntax,
DATE_SUB(date, INTERVAL value unit);
Example,
SELECT TIMESTAMPDIFF(SECOND, DATE_SUB('2018-06-04 22:59:00', INTERVAL 10 DAY),
'2018-06-04 22:59:00');

Related

MySql date range search with month and day (any year)

For example, if i have search string "2017-12-14" then i need to find all rows that matches 7-day range: "%-12-11", "%-12-12", "%-12-13", "%-12-14", "%-12-15", "%-12-16", "%-12-17".
Is it possible to do with MySql only?
To select same day cross years you can use following trick.
get the list of last 7 days/1 week NOW() - INTERVAL 1 WEEK
get the DAYOFYEAR of that days
search the database for all values of the same day in year
.
SELECT * FROM timevalues
WHERE DAYOFYEAR(timefield) IN (
SELECT DAYOFYEAR(timefield)
FROM timevalues
WHERE DATE(timefield) BETWEEN NOW() - INTERVAL 1 WEEK AND NOW()
)
;
Note: Leap year is not taken into calculation!
According to my brief investigation according to the leap year it would be easier to extend the SQL query with tolerance of 1 day, ie to use - INTERVAL 8 DAY instead of 7 and then control the validity of the day outside the database during processing the data in a loop.
Yes, it is possible.
The function you are looking for is +/- INTERVAL expr unit. See MySQL Date and Time Functions
So to get 7 days back use - INTERVAL 7 DAY:
SELECT *
FROM tablename
WHERE DATE(timefield) BETWEEN '2017-12-14' - INTERVAL 7 DAY AND '2017-12-14'
According to your example would be enough to use -INTERVAL 1 WEEK:
SELECT *
FROM tablename
WHERE DATE(timefield) BETWEEN '2017-12-14' - INTERVAL 1 WEEK AND '2017-12-14'
And List of all possible units
MICROSECOND SECOND MINUTE HOUR DAY WEEK MONTH QUARTER YEAR
SECOND_MICROSECOND MINUTE_MICROSECOND MINUTE_SECOND HOUR_MICROSECOND
HOUR_SECOND HOUR_MINUTE DAY_MICROSECOND DAY_SECOND DAY_MINUTE DAY_HOUR
YEAR_MONTH

What is the right syntax for NOW() function

I'm trying to get all rows from DATE column
values from 10 days ago till today
i'm trying to undesrtand why this syntax isn't working:
select * from table WHERE date BETWEEN NOW() AND NOW() - INTERVAL 10 DAY ORDER BY date
You have to start with the lower value when using between
select *
from table
WHERE date BETWEEN NOW() - INTERVAL 10 DAY and NOW()
ORDER BY date
The problem is not related to the NOW() function but to the BETWEEN operator, the lower timestamp has to be specified first:
where date between now() - interval 10 day and now()
however, depending on your requirements, you might want to use this:
where date between current_date() - interval 10 day and current_date()
or just
where date>=current_date() - interval 10 day
now() returns a timestamp that contains date and time information, while current_date() returns just the current date without time information. If date is just a date column, without time information, using now() - interval 10 day you will get just the latest 9 days and not the latest 10 as you might expect.

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.

Data from current date to 30 days after current days

Why this query is not working
SELECT * FROM history WHERE DATE(date) < CURDATE() + 30
I am trying to get the data from 30 days but my query is not working.Why
What does +30 mean? Days? Years? Months? Hours? You need to use (the proper syntax) a format MySQL understands:
SELECT * FROM history WHERE DATE(date) < CURDATE() + INTERVAL 30 DAY
To get the data from today on to 30 days after current day, you've got to set an upper and an lower limit, so use:
SELECT * FROM history WHERE
date >= CURDATE()
AND
date < CURDATE() + INTERVAL 31 DAY
Please note that by not using a function on your date column you won't prohibit MySQL to use an index on this column.
The lower limit should be obvious, the upper limit means that you've got the complete day that's 30 days later than today. If you use + INTERVAL 30 DAY instead this last day is excluded from the result.
Because you're not using the right construct, try:
SELECT * FROM history WHERE DATE_ADD(date, INTERVAL 30 DAY);

Mysql time range query using extract

I'm trying to get an mysql query similar to date_trunc in psql.
Unfortunate Mysql do not have date_trunc function and I found I can use extract instead in Mysql.
What I want to do is write a script which i will run let say 10 minutes past each hour but I want to only select data from begin of an hour till end of this hour.
For example I will run script 12:10 and I want to display data from 11:00:00 till 11:59:59.
In PSQL query would look like that:
SELECT *
FROM data
WHERE time > ( date_trunc('hour',now()) - interval '1 hour' )
AND time <= ( date_trunc('hour',now()) ) ORDER BY time;
I was trying to use extract in similar fashion but I have no rows returned or error :/
Query below returns for example some narrowed data but it's like 2 hours each day from day one when database was started not last hour only:
SELECT *
FROM data
WHERE extract(hour from cr_date) between extract(hour from now()) - interval 1 hour)
AND extract(hour from now())
ORDER BY cr_date;
Any ideas how this can be achieved? or what I'm doing wrong in this query?
Hour is only an integer, so it's finding any matches between , for example, 9 and 10, regardless of the date.
I would recommend
select * FROM data
where cr_date >= date(now()) + INTERVAL hour(now())-1 HOUR
and cr_date <= date(now()) + INTERVAL hour(now()) HOUR
date(now()) returns midnight, and hour(now()) returns the number of hours since midnight
so, at 11:10 am, it should result in a results between midnight + 10 hours (10 am) and midnight + 11 hours (11 am)