In MySQL, how do I do a date query? - mysql

I want to do SELECT count(*) FROM users where created_at within 3 days ago
Created_at is datetime column.

Use for a date three days ago:
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);
Check the DATE_ADD documentation.
Or you can use:
WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )

Related

SELECT date BETWEEN dates with interval

I have a date column in my database. I use SELECT COUNT to calculate the rows between today and 15 days ago:
SELECT count(date) as date
FROM `inv`
WHERE user_id='2'
AND date BETWEEN CURDATE() - INTERVAL 15 DAY
AND CURDATE()
This SQL statement is working. But now I want use SELECT COUNT to calculate the rows between today(-15 days) and 30 days ago. But I am getting an error when I try the following statement:
SELECT count(date) as date
FROM `inv`
WHERE user_id='2'
AND date BETWEEN date(CURDATE(),INTERVAL -15 day)
AND date(CURDATE(),INTERVAL -30 day)
Also I want to know how I can SELECT the rows where the date is more than 30 days ago. Can someone help me with this?
You can use the below to get rows between 15 to 30 days old.
SELECT count(date) as date
FROM `inv`
WHERE user_id=2
AND date BETWEEN CURDATE() - INTERVAL 30 DAY
AND CURDATE() - INTERVAL 15 DAY
Similarly you can use below to get rows that are older than 30 days.
SELECT count(date) as date
FROM `inv`
WHERE user_id=2
AND date < CURDATE() - INTERVAL 30 DAY
Try This
SELECT * FROM "table name" WHERE "user_id=2"
BETWEEN CURDATE() - INTERVAL 30 DAY
AND CURDATE() - INTERVAL 15 DAY

Get number of entries per multiple date intervals using single query

SELECT COUNT(*) FROM `table` WHERE `datetime` > SUBDATE(NOW(), INTERVAL 1 DAY)
This will get number of entries during last day. But is it possible to get number of entries for multiple intervals without having to send variation of this query multiple times (INTERVAL 1 DAY, INTERVAL 1 WEEK, INTERVAL 1 MONTH, ...)?
You need CASE WHEN expression to accomplish that.
SELECT
COUNT(CASE WHEN DATE(`datetime`) >= CURDATE() - INTERVAL 1 DAY AND DATE(`datetime`) < CURDATE() THEN 1 END) AS lastDay,
COUNT(CASE WHEN DATE(`datetime`) >= CURDATE() - INTERVAL 7 DAY AND DATE(`datetime`) < CURDATE() THEN 1 END ) AS lastSevenDays,
COUNT(*) AS lastThirtyDays
FROM `table`
WHERE
DATE(`datetime`) >= CURDATE() - INTERVAL 30 DAY
How to use CASE WHEN expression
Note: If your requirement is to get result of last day, last 7 days and last 30 days then go with this query.
EDIT:
If you have an index on datetime field then the above query will fail to use that index. Please use the query given below in order to utilize the index on datetime.
SELECT
COUNT(CASE WHEN DATE(`datetime`) >= CURDATE() - INTERVAL 1 DAY AND DATE(`datetime`) < CURDATE() THEN 1 END) AS lastDay,
COUNT(CASE WHEN DATE(`datetime`) >= CURDATE() - INTERVAL 7 DAY AND DATE(`datetime`) < CURDATE() THEN 1 END ) AS lastSevenDays,
COUNT(*) AS lastThirtyDays
FROM `table`
WHERE
`datetime` >= (NOW() - INTERVAL 30 DAY - INTERVAL HOUR(NOW()) HOUR - INTERVAL MINUTE(NOW()) MINUTE - INTERVAL SECOND(NOW()) SECOND)

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')

select dates that are between current date and 3 month from the current date in mysql

I want to select all dates that are between the current date and 3 months before.
I tried using this query but it isn't working right.
$sql = mysql_query("
SELECT *
FROM date
WHERE d_date BETWEEN NOW() AND NOW() - INTERVAL 3 MONTH
");
Please if you could help me write the right syntax.
You need to swap your bounaries, and it will work:
SELECT * FROM date
WHERE d_date BETWEEN now() - INTERVAL 3 MONTH AND now()
For example, this query returns true (SQLFiddle):
SELECT (now() - interval 1 month)
BETWEEN now() - interval 3 month AND now()
SELECT * FROM Table
WHERE anydate_col BETWEEN NOW() AND DATE_ADD( NOW() , INTERVAL +3 MONTH)

how to use curdate() in where clause against unixtimestamp (bigint) column

I am trying to pull records in the past 7 days. This is my select statement that I have been trying to get to work:
select from_unixtime(time,'%m/%d/%y') as fdate, from_unixtime(time,'%h:%m:%s') as ftime
from mdl_log
where from_unixtime(time,'%y-%m-%d') between curdate() and curdate() - INTERVAL 7 DAY
I have tried various incarnations of the where clause like
where time between curdate() and curdate() - INTERVAL 7 DAY
and
where from_unixtime(time,'%yyyy-%mm-%dd') between curdate() and curdate() - INTERVAL 7 DAY
and
where date(time) between curdate() and curdate() - INTERVAL 7 DAY
select curdate() - results in the date showing in this format 2012-11-08
You were almost there with your last incarnation. However, you need to compare apples to apples. Since time is an integer, you need to convert it for MySQL date/time functions to use.
WHERE DATE(FROM_UNIXTIME(time)) between CURDATE() and CURDATE() - INTERVAL 7 DAY
Given your use case, you really only need FROM_UNIXTIME():
WHERE FROM_UNIXTIME(time) between CURDATE() and CURDATE() - INTERVAL 7 DAY