How to do : "Between TODAY AND TODAY-7"? - mysql

I need to find the account created for the current day, et for the last 7 days.
To find my results for today, it works, and I do this :
SELECT * FROM `account` where DATE(created_at) = DATE(NOW())
But I don't know how to do to get the last 7days account.
I tried something like this, but without success :
SELECT * FROM `account` where DATE(created_at) BETWEEN DATE(NOW()) AND DATE(NOW()-7)
Have you an idea ?

in mysql:
SELECT * FROM `account`
WHERE DATE(created_at) > (NOW() - INTERVAL 7 DAY)

Try:
BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()

If created_at has an index and you wouldn't like to prevent the optimiser from using it, I would recommend the following pattern (assuming created_at contains both date and time):
WHERE created_at >= CURRENT_DATE - INTERVAL 7 DAY
AND created_at < CURRENT_DATE + INTERVAL 1 DAY
This spans the range from the day exactly one week ago till today (inclusive), so 8 days in total.

also have a look at MySQL functions ADDDATE(), DATE_ADD(), DATE_SUB()
e.g.
ADDDATE(DATE(NOW()), -7)

Related

comparing dates by month and year in mysql

I have a table containing data about events and festivals with following columns recording their start and end dates.
Start_Date
End_Date
date format is in YYYY-MM-DD. I need to fetch event details with the following condition.
Need to fetch all events which start with a current month and there end dates can be anything say currentDate+next30days.
I am clear about end date concept. but not sure how I can fetch data whose start dates are in a current month.
For this, I need to compare current year and current month against the Start_Date column in my database.
Can anyone help me to point out as how I can do that?
select * from your_table
where year(Start_Date) = year(curdate())
and month(Start_Date) = month(curdate())
and end_date <= curdate() + interval 30 day
I don't like either of the other two answers, because they do not let the optimizer use an index on start_date. For that, the functions need to be on the current date side.
So, I would go for:
where start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
All the date functions are on curdate(), which does not affect the ability of MySQL to use an index in this case.
You can also include the condition on end_date:
where (start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
) and
end_date <= date_add(curdate(), interval 30 day)
This can still take advantage of an index.
DateTime functions are your friends:
SELECT
*
FROM
`event`
WHERE
(MONTH(NOW()) = MONTH(`Start_Date`))
AND
(`End_Date` <= (NOW() + INTERVAL 30 DAY))
AND
(YEAR(NOW()) = YEAR(`Start_Date`))
Comparing the year and month separately feels messy. I like to contain it in one line. I doubt it will make a noticeable difference in performance, so its purely personal preference.
select * from your_table
where LAST_DAY(Start_Date) = LAST_DAY(curdate())
and end_date <= curdate() + interval 30 day
So all I'm doing is using the last_day function to check the last day of the month of each date and then comparing this common denominator. You could also use
where DATE_FORMAT(Start_Date ,'%Y-%m-01') = DATE_FORMAT(curdate(),'%Y-%m-01')

Return row count between 2 dates always returns 0

wonder if any aficionados can help me. I am trying to get the number of records between two dates, I made this query really simple using some posts i found on here, it always returns 0.
date_added is a timestamp
SELECT COUNT(id)
FROM item
WHERE date_added >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND date_added <= NOW()
I also tried this:
SELECT COUNT(id)
FROM item
WHERE date_added BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND NOW()
What am I doing wrong?
Use DATE(NOW()) and DATE(date_added) for comparison of dates in mysql. It will give you date part of the timestamp.
For Example
CURDATE() is 2008-11-11 and
NOW() is 2008-11-11 12:45:34
One is date, other is timestamp. You should take either both dates or both timestamp. One solution I've told above.
I re ran this query this morning and it worked just fine, so I'm not sure what went wrong last night other than the hour. Thanks to everyone's input.
SELECT COUNT(id)
FROM item
WHERE date_added BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()
worked fine as did
SELECT COUNT(id)
FROM item
WHERE DATE(date_added) BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()
Hope that may be of use to someone.

MySQL query to get data for the last week

I want to run a MYSQL query to get data for the previous week. The datatype for the date column is DATETIME. Could anyone suggest?
SELECT *
FROM calendar
WHERE dt BETWEEN CURDATE()-INTERVAL 1 WEEK AND CURDATE();
Here is an another version:
SELECT * FROM table WHERE
YEARWEEK(`date`, 1) = YEARWEEK( CURDATE() - INTERVAL 1 WEEK, 1)
SELECT id FROM tbl
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
Here is the solution I find most reliable for getting data between the previus monday to the current monday. (That is what most people mean when the say past week, but not all, and that reflect in mysql).
SELECT
*
FROM
table
WHERE
date BETWEEN
(CURDATE() - INTERVAL 1 DAY) + INTERVAL -1 WEEK - INTERVAL WEEKDAY((CURDATE() - INTERVAL 1 DAY)) DAY
and
(CURDATE() - INTERVAL 1 DAY) + INTERVAL 0 WEEK - INTERVAL WEEKDAY((CURDATE() - INTERVAL 1 DAY)) DAY
It's also easy to change it for another week intervall
Make variable for current datetime - 1 week and make this query:
SELECT * FROM table WHERE date > $datatime

How do I get Timestamp minus 6 weeks in MySQL?

I have a field named timestamp. This is the last time a member was logged in.
I am looking to include a where clause in a query for something like
WHERE timestamp > todays date - 6 weeks
How would I do this?
I am trying to only include users that have logged in in the last 6 weeks.
Thanks
I find this syntax more readable than date_sub, but either way works.
WHERE timestamp >= NOW() - INTERVAL 6 WEEK
If you want to go by "Today" (midnight) instead "now" (current time), you would use this
WHERE timestamp >= DATE(NOW()) - INTERVAL 6 WEEK
where column>=date_sub(now(), interval 6 week)
This link demonstrates how you might acquire a timestamp of yesterday using the format DATE_ADD(CURDATE(), INTERVAL -1 DAY), therefore your query would probably be:
WHERE timestamp > DATE_ADD(CURDATE(), INTERVAL -42 DAY)
You can use between and now():
select somevalue
from yourtable
where yourtimestamp between now() - interval 1 day and now()
for TIMESTAMP there is a TIMESTAMPADD() function
SELECT TIMESTAMPADD(WEEK, -6, CURRENT_TIMESTAMP)
this will return the timestemp of 6 weeks ago
or in the case like the question
SELECT * FROM users
WHERE lastlogin > TIMESTAMPADD(WEEK, -6, CURRENT_TIMESTAMP)
Any luck yet. Have you tried:
>= DATE_SUB(NOW(), INTERVAL 6 WEEK)

Fetching rows added last hour

I keep a record of logins in a table. I have columns for id, ip, date and time. From that record of logins I wanna fetch logins made only in the last hour.
I'm sweeping through the MySQL docs on time and date functions, but I just can't seem to combine them correctly.
Can somebody help me?
Make use of the DATE_SUB() and NOW() functions:
select count(*) as cnt
from log
where date >= DATE_SUB(NOW(),INTERVAL 1 HOUR);
Hope it helps you : )
If you want to implement this into a cronjob, you need to specify the start and end.
For example, at 2pm, if you want to get the data for the past hour from 13:00:00 until 13:59:59, here's how to do it:
dateField BETWEEN
DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 HOUR), '%Y-%m-%d %H:00:00')
AND
DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 HOUR), '%Y-%m-%d %H:59:59')
it can be done easily using
select count(*) from logins where datetime>= NOW()- INTERVAL 1 HOUR
I recommend have one datetime column instead of date and time columns.
Suppose you have a datetime column called last_login:
SELECT id, ip_address, last_login
FROM mytable
WHERE last_login >= DATE_SUB(NOW(), interval 1 hour);
without the specifics, I think Date_Add() would work.. by adding to your where clause an add of NOW negative hours
(or Date_Sub() )
You can also use CURDATE()function
SELECT
count(*) AS TotalCount
FROM
tblName
WHERE
datetime >= DATE_SUB(CURDATE(), INTERVAL 1 HOUR)