Fetch data between two date in mysql - mysql

This is my query
WHERE id = 14 AND start_time BETWEEN '2019-10-24 00:00:00' AND '2019-12-12 23:59:59'
ORDER BY created_date LIMIT 0 , 10
When I run this query then it returns me data of this data also. -> 2019-10-23T19:23:41.000Z
Issue: When I pass the 2019-10-24 then why it gives me data of 2019-10-23 date?
Note: start_time has a data type -> datetime in db.

It's not a issue by the way it's correct output.
Try this way
DATE_FORMAT(start_time, "%Y-%m-%d %H:%i:%s") as start_time
Due to diffrent formate, It may confused you.

use less than or equal to '<=' or greater than or equal to '>=' operator instead of BETWEEN.
Use this condition in your query.
WHERE id = 14 AND DATE(start_time) >= DATE('2019-10-24 00:00:00') AND DATE(start_time) <= DATE('2019-12-12 23:59:59') ORDER BY created_date LIMIT 0 , 10
OR
WHERE id = 14 AND DATE(start_time) >= '2019-10-24' AND DATE(start_time) <= '2019-12-12') ORDER BY created_date LIMIT 0 , 10

Related

Search for a single date in a DATETIME or TIMESTAMP column

I have a problem retrieving data from a table between two dates.
Everything works as it should when two dates differ from each other, but when I want to search for all records from today, it searche nothing:
SELECT * from exampletable where created_date >= '2022-10-28' AND created_date<= '2022-10-28'
To get all records for a single day using a TIMESTAMP or DATETIME type column you have these options:
WHERE DATE(created_date) = '2022-10-28'
However - Wrapping a column into a function you will loose the ability to use an index.
Other ways which can use an index:
WHERE created_date BETWEEN '2022-10-28 00:00:00' AND '2022-10-28 23:59:59'
WHERE created_date >= '2022-10-28'
AND created_date < '2022-10-29'
WHERE created_date >= '2022-10-28'
AND created_date < '2022-10-28' + INTERVAL 1 DAY
Your query
where created_date >= '2022-10-28' AND created_date <= '2022-10-28'
is equivalent with
where created_date = '2022-10-28'
If created_date is of type DATETIME or TIMESTAMP it is the same as
where created_date = '2022-10-28 00:00:00'
and the query would only return records with the exact time of 00:00:00.

MySQL not showing value when using <= condition

i have records in my database like this
*just example
id
Name
created_at
1
Jono
2020-03-21 12:20:00
2
Abi
2020-03-25 12:20:00
3
Iko
2020-03-30 12:20:00
then i have simple query like this
SELECT * FROM `transaksi` WHERE `created_at` >= '2020-03-21' AND `created_at` <= '2020-03-30'
but that query only show id no 1 and 2 which is the date is < 2020-03-30
so my question is
why the third data which is still in range is not showing?
i have try something like this too
SELECT * FROM `transaksi` WHERE `created_at` >= DATE('2020-03-21') AND `created_at` <= DATE('2020-03-30')
but still have same issue
any sugestion?
thanks
This is the logical query you want here:
SELECT *
FROM transaksi
WHERE created_at >= '2020-03-21' AND created_at < '2020-04-01';
To explain what the above is actually saying, let's rewrite it using timestamp literals, with full H:M:S components:
SELECT *
FROM transaksi
WHERE created_at >= '2020-03-21 00:00:00' AND created_at < '2020-04-01 00:00:00';
Both of these queries will retain any record having a created date on or after midnight of 21-March-2020 and strictly before midnight of 1st-April-2020. The right side condition then includes the entire day of 31-March-2020.
You have to apply mysql DATE() function on created_at column to get date only without time.
SELECT *
FROM `transaksi`
WHERE DATE(`created_at`) >= '2020-03-21'
AND DATE(`created_at`) <= '2020-03-30'
SQL DEMO

Get count of rows + last row inserted

I have this sql :
SELECT count(*) as nb, data_type, rawValue, createdAt
FROM my_table WHERE data_type in('t','r', 'b')
AND CreatedAt >= DATE_SUB(NOW(), interval 24 HOUR)
AND CreatedAt <= NOW() AND device=27 AND id=462
group by data_type order by createdAt DESC ;
Now I get data like this :
nb data_type rawValue createdAt
20 t test 2018-08-01 07:30:30
20 r test 2018-08-01 08:30:30
For data_type = t I have rows from 2018-08-01 10:10:23 but is getting the first value and not the last by createdAt. Can you help me please ? Thx in advance.
it seems db is mysql,
when you will use aggregate function then selection column should be in group by clause . we know now() is returned todays present date time as you given interval 24 hour so just notice when selected is that records fall in this duration or not,because your query is almost ok except group by clause columns, i puts those column in group by clauses
As you expect 1 row per data_type so i changes like below
select T.nd,T.data_type,A.rawValue,T.createdAt from
(
SELECT count(*) as nb, data_type,
max(createdAt) as createdAt
FROM table WHERE data_type in('t','r', 'b')
AND CreatedAt >= DATE_SUB(NOW(), interval 24 HOUR)
AND CreatedAt <= NOW() AND device=27 AND id=462
group by data_type
) as T left join table A
on T.createdAt=A.createdAt
and T.data_type=A.data_type
where A.data_type in ('t','r', 'b')
AND A.CreatedAt >= DATE_SUB(NOW(), interval 24 HOUR)
AND A.CreatedAt <= NOW() AND device=27 AND id=462
It would be great if you share your tables sample data and expected output

WHERE returning too many rows for data NOT BETWEEN two dates

I want to return data that is not between current date and the last 7 days.
My SELECT statement appears ok, but it is also returning the current day's data.
SELECT
customer.id AS id,
customer.customer_id AS customer_id,
customer.name AS name,
customer.phone1 AS phone1,
customer.location_area AS location_area,
sales.post_date AS post_date
FROM
sales
INNER JOIN
customer
ON
sales.customer_id = customer.customer_id
WHERE
post_date
NOT BETWEEN
CAST( DATE_SUB(NOW(), INTERVAL 7 DAY) AS DATE )
AND
CAST( NOW() AS DATE )
ORDER BY
sales.id
DESC
LIMIT 30
Please note the customer_id field used in the ON clause is not a primary key in any of the two referenced tables.
What might be missing in my query?
This problem is usually confusion about the different meanings of DATE datatypes on the one hand and TIMESTAMP or DATETIME data types on the other.
Let's say NOW() is 1-April-2017 09:35. And, let's say you have a row in your sales table with a post_date value of 1-April-2017 08:20. Let's say your post_date column has the data type DATETIME.
Then your WHERE clause looks like this after values are applied.
WHERE '2017-04-01 08:20' NOT BETWEEN CAST( '2017-03-25 09:35' AS DATE )
AND CAST( '2017-04-01 09:35' AS DATE )
Applying the CAST operations, we get.
WHERE '2017-04-01 08:20' NOT BETWEEN '2017-03-25'
AND '2017-04-01'
Finally, when comparing a DATETIME or TIMESTAMP to a DATE value, the DATE value is interpreted as having a time of midnight. So your query looks like this:
WHERE '2017-04-01 08:20' NOT BETWEEN '2017-03-25 00:00:00'
AND '2017-04-01 00:00:00'
And, guess what? '2017-04-01 08:20' is after '2017-04-01 00:00:00'.
What you need is this:
WHERE
NOT (
post_date >= CURDATE() - INTERVAL 7 DAY --on or after midnight 2016-3-25
AND post_date < CURDATE() + INTERVAL 1 DAY --before midnight 2016-04-02
)
Please notice that this expression encompasses eight days total.
You can't use BETWEEN for this kind of comparison because you need < for the end of the range, and BETWEEN uses <= for the ends of all its ranges.
Also, CURDATE() is much easier to read than CAST(NOW() AS DATE).

Calculate difference between first and last result

I have got a table with two columns. The first one ("val") is a integer, the second a timestamp ("ts").
Now I want to calculate the difference between the first and the last value of a given timespan.
SELECT MAX(val) - MIN(val) AS difference WHERE ts >= '2015-01-01 00:00:00' AND ts <= '2015-01-07 23:59:59'
This one is not sufficient, because in the course of time the values can exceed/undercut the first and the last value.
Example:
Day 1: 100
Day 2: 120
Day 3: 110
Day 4: 98
Day 5: 105
Day 6: 112
Day 7: 110
The difference is 110 (Day 7) minus 100 (Day 1) = 10. Not Max(val) = 120 minus Min(val) = 98 = 22
Thanks!
Join to a subquery that returns the first and last dates and join using those, and use some simple arithmetic to calculate the difference using sum():
select sum(val * case ts when ts1 then -1 else 1 end) diff
from data
join (select min(ts) ts1, max(ts) ts2
from data
where ts between ? and ?) x
on ts in (ts1, ts2)
See demo (demo schema has been simplified to isolate the essence of the solution).
One method is to use two subqueries, one that gets the first value and one that gets the last value:
SELECT ((SELECT val
FROM table t
WHERE ts >= '2015-01-01 00:00:00' AND ts <= '2015-01-07 23:59:59'
ORDER BY val DESC
LIMIT 1
) -
(SELECT val
FROM table t
WHERE ts >= '2015-01-01 00:00:00' AND ts <= '2015-01-07 23:59:59'
ORDER BY val ASC
LIMIT 1
)
) as difference