2

I have a table called barcode_log, and these are all the datas from the table.

All results

And now if I run this query

SELECT * FROM `barcode_log` WHERE barcode_log.assign_time BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE;

I get this result

query result

But it should return all the rows as all the data is within this month only. And assign_time field is stored as datetime. Any idea what i am doing wrong??

4
  • Is BETWEEN inclusive? Because this might work tomorrow. You are comparing dates, not times. Commented Oct 5, 2016 at 8:00
  • 1
    Perhaps taking just the date of barcode_log.assign_time might work: WHERE DATE(barcode_log.assign_time) BETWEEN ... Commented Oct 5, 2016 at 8:01
  • @BartFriederichs , yes between is inclusive. Commented Oct 5, 2016 at 8:10
  • @BartFriederichs, Yes, that works too. Thanks! Commented Oct 5, 2016 at 8:29

3 Answers 3

2

You are ignoring the time part (hh:mm:ss).

If the end day is set to the end timestamp of the current date then you can get the data of current day's too.

BETWEEN is inclusive

SELECT
    *
FROM
    `barcode_log`
WHERE
    barcode_log.assign_time BETWEEN DATE_SUB(
        CURRENT_DATE,
        INTERVAL 30 DAY
    )
AND TIMESTAMP(CONCAT(CURDATE(),' ','23:59:59'));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This worked. Didn't know about BETWEEN being inclusive.
SELECT 2 BETWEEN 2 AND 3; - This simplest example shows between's inclusive behavior very well.
2

While the accepted answer works, there is a simpler solution. Just take the date part of the datetime column:

SELECT 
     * 
FROM 
    `barcode_log` 
WHERE 
    DATE(barcode_log.assign_time) 
    BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE;

1 Comment

Nice way to handle this through the date part. But one potential problem is index on assign_time field cannot be used (if any).
0

There is another way around: CAST() on barcode_log.assign_time field.

SELECT * 
FROM `barcode_log` 
WHERE CAST(barcode_log.assign_time AS DATE)
BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE;

This excludes time from comparison and works fine for your purpose.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.