MySQL - select data from database between two dates - mysql

I have saved the dates of a user's registration as a datetime, so that's for instance 2011-12-06 10:45:36. I have run this query and I expected this item - 2011-12-06 10:45:36 - will be selected:
SELECT `users`.* FROM `users` WHERE created_at >= '2011-12-01' AND
created_at <= '2011-12-06'
But is not. Exist any elegant way, how to select this item? As a first idea that I got was like 2011-12-06 + 1, but this doesn't looks very nice.

Your problem is that the short version of dates uses midnight as the default. So your query is actually:
SELECT users.* FROM users
WHERE created_at >= '2011-12-01 00:00:00'
AND created_at <= '2011-12-06 00:00:00'
This is why you aren't seeing the record for 10:45.
Change it to:
SELECT users.* FROM users
WHERE created_at >= '2011-12-01'
AND created_at <= '2011-12-07'
You can also use:
SELECT users.* from users
WHERE created_at >= '2011-12-01'
AND created_at <= date_add('2011-12-01', INTERVAL 7 DAY)
Which will select all users in the same interval you are looking for.
You might also find the BETWEEN operator more readable:
SELECT users.* from users
WHERE created_at BETWEEN('2011-12-01', date_add('2011-12-01', INTERVAL 7 DAY));

SELECT users.* FROM users WHERE created_at BETWEEN '2011-12-01' AND '2011-12-07';

You need to use '2011-12-07' as the end point as a date without a time default to time 00:00:00.
So what you have actually written is interpreted as:
SELECT users.*
FROM users
WHERE created_at >= '2011-12-01 00:00:00'
AND created_at <= '2011-12-06 00:00:00'
And your time stamp is: 2011-12-06 10:45:36 which is not between those points.
Change this too:
SELECT users.*
FROM users
WHERE created_at >= '2011-12-01' -- Implied 00:00:00
AND created_at < '2011-12-07' -- Implied 00:00:00 and smaller than
-- thus any time on 06

Another alternative is to use DATE() function on the left hand operand as shown below
SELECT users.* FROM users WHERE DATE(created_at) BETWEEN '2011-12-01' AND '2011-12-06'

Have you tried before and after rather than >= and <=? Also, is this a date or a timestamp?

Searching for created_at <= '2011-12-06' will search for any records that where created at or before midnight on 2011-12-06
. You want to search for created_at < '2011-12-07'.

Maybe use in between better. It worked for me to get range then filter it

You can use MySQL DATE function like below
For instance, if you want results between 2017-09-05 till 2017-09-09
SELECT DATE(timestamp_field) as date FROM stocks_annc WHERE DATE(timestamp_field) >= '2017-09-05' AND DATE(timestamp_field) <= '2017-09-09'
Make sure to wrap the dates within single quotation ''
Edit:
A better solution would be this. It would make sure that it uses the index if any exists.
select date(timestamp_field) as date from stocks_annc where time_stamp_field >= '2022-01-01 00:00:00' and time_stamp_field <= '2022-01-10 00:00:00'
Hope this helps.

Related

How can I add days to a date in MYSQL in a query

I am trying to add 5 days to a date in MYSQL in a query. This is what I have done:
SELECT * FROM sales INNER JOIN partner on user_id = idpartner WHERE DATE((end_date) + 5) >= DATE(NOW()) ORDER BY end_date ASC LIMIT 0,50000
But this is not showing the list of sales which has ended. Can someone please tell me where I am making a mistake.
It looks like you want rows where end_date is later than five days ago.
The best way to get that is with
WHERE end_date >= CURDATE() - INTERVAL 5 DAY
The business of adding integers to dates doesn't work in MySQL (it's an Oracle thing). So you need to use the INTERVAL n unit syntax.
You'll notice that my WHERE clause above is functionally equivalent to
WHERE DATE(end_date) + INTERVAL 5 DAY >= DATE(NOW())
But, the first formulation is superior to the second for two reasons.
if you mention end_date in a WHERE clause without wrapping it in computations, your query can exploit an index on that column and can run faster.
DATE(NOW()) and CURDATE() both refer to the first moment of today (midnight). But CURDATE() is a bit simpler.
To fix the original query, you can use DATE_ADD with the INTERVAL keyword:
SELECT
*
FROM
sales
INNER JOIN
partner ON user_id = idpartner
WHERE
DATE_ADD(end_date, INTERVAL 5 DAY) >= DATE(NOW())
ORDER BY end_date ASC
LIMIT 0 , 50000
Said that, I wouldn't recommend applying functions such as DATE_ADD on columns, as it means that the database won't be able to use an index on end_date. Therefore, I would modify the query to:
SELECT
*
FROM
sales
INNER JOIN
partner ON user_id = idpartner
WHERE
end_date <= DATE_ADD(DATE(NOW()), INTERVAL 5 DAY)
ORDER BY end_date ASC
LIMIT 0 , 50000
As you can see, in the second alternative all functions are applied on constants and not on columns (end_date).
You can try
DATE_ADD() here is the
Link
Select DATE_ADD(DATE_FORMAT(NOW(),'%Y-%m-%d'),INTERVAL 1 DAY) FROM DUAL

Need to build a quuerly groupby

Hi I am trying to build a query not getting my desired result please help me.
Here is my table:
SELECT count(*)
FROM
t_user_segment
WHERE
updatedOn
BETWEEN '2015-11-03 00:00:00' AND '2015-11-03 23:59:59'
i want to get data here from here of field updatedon from last 5days to current date.
Check below answer if it useful
SELECT count(*) as cnt, date(updatedOn) as updatedOnDate FROM t_user_segment
WHERE updatedOnDate >= DATE_SUB(CURRENT_DATE, INTERVAL 5 DAY) group by updatedOnDate;

Query results based on the current date

I am trying to figure out how to select results based on the current date. The script will be ran daily but I am unsure of how to do it automatically.
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
What I am trying now
SELECT * FROM Orders WHERE OrderDate=NOW() - INTERVAL 1 DAY
SELECT *
FROM Orders
WHERE OrderDate >= DATE(NOW())
AND OrderDate < DATE(NOW()) + INTERVAL 1 DAY
EDIT
I always tend to write the above style of query when I expect the column that I am checking against to have a time component as well.
If your OrderDate column does not have a time component, then as Lennart pointed out, you can simply do:
SELECT *
FROM Orders
WHERE OrderDate = DATE(NOW())
EDIT 2: Mihai's comment on your question is also relevant. You can simply use CURDATE() instead of DATE(NOW()).
You could do
SELECT * FROM Orders WHERE (OrderDate > DATE_SUB(NOW(),INTERVAL 1 DAY))

match timestamp with date in MYSQL using PHP

I have a table
id user Visitor timestamp
13 username abc 2014-01-16 15:01:44
I have to 'Count' total visitors for a 'User' for last seven days group by date(not timestamp)
SELECT count(*) from tableA WHERE user=username GROUPBY __How to do it__ LIMIT for last seven day from today.
If any day no visitor came so, no row would be there so it should show 0.
What would be correct QUERY?
There is no need to GROUP BY resultset, you need to count visits for a week (with unspecified user). Try this:
SELECT
COUNT(*)
FROM
`table`
WHERE
`timestamp` >= (NOW() - INTERVAL 7 DAY);
If you need to track visits for a specified user, then try this:
SELECT
DATE(`timestamp`) as `date`,
COUNT(*) as `count`
FROM
`table`
WHERE
(`timestamp` >= (NOW() - INTERVAL 7 DAY))
AND
(`user` = 'username')
GROUP BY
`date`;
MySQL DATE() function reference.
Try this:
SELECT DATE(a.timestamp), COUNT(*)
FROM tableA a
WHERE a.user='username' AND DATEDIFF(NOW(), DATE(a.timestamp)) <= 7
GROUP BY DATE(a.timestamp);
i think it's work :)
SELECT Count(*)
from table A
WHERE user = username AND DATEDIFF(NOW(),timestamp)<=7

MySql - get days remaining

Users can sign up for a premium listing for a specified number of days, e.g. 30 days.
tblPremiumListings
user_id days created_date
---------------------------------
1 30 2013-05-21
2 60 2013-06-21
3 120 2012-06-21
How would I select records where there are still days remaining on a premium listing.
SELECT *
FROM tblPremiumListings
WHERE created_date + INTERVAL `days` DAY >= CURDATE()
It's easiest to read with INTERVAL
select *
from tblPremiumListings
where created_date + interval days day >= now();
But I would also change the table to instead of created_date and days instead store end_date. That way the query is
select *
from tblPremiumListings
where end_date >= now();
The benefit of doing like this is that you can put an index on end_date and quickly find all ended premium listings, with your original table you'll always have to do a full table scan to find the records with expired listing.
SELECT * FROM
tblPremiumListings
WHERE (DATEDIFF(NOW(), created_date) - days) <= 0
See if it solves your problem
One way to get the result:
SELECT t.user_id
, t.days
, t.created_date
FROM tblPremiumListings t
WHERE t.created_date + INTERVAL t.days DAY > DATE(NOW())
You may want a >= comparison operator (instead of >) depending on how you define days remaining.
NOTE: the access plan for this query will be full scan of all rows, since MySQL won't be able to do a range scan on an index. For large sets, having a column that can be indexed to satisfy the query may improve performance, e.g.
WHERE t.expire_date > DATE(NOW())
Try this one...
SELECT * FROM
tblPremiumListings
WHERE DATE_ADD(created_date, days)>DATE(NOW())