Reputation: 3
I'm trying to fetch values between two dates, specifically 24hrs
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN 20190311 AND 20190312
This query works fine but, i don't want it for a constant date, i have checked and seen many format but none seems to work. please help
Upvotes: 0
Views: 341
Reputation: 31792
If you "want records from today alone" - a simple way would be:
WHERE accnum = '1534610376'
AND DATE(tdate) = CURRENT_DATE()
However - To utilize an index, a column should not be wrapped into a function. So an efficient way would be
WHERE accnum = '1534610376'
AND tdate >= CURRENT_DATE()
AND tdate < CURRENT_DATE() + INTERVAL 1 DAY
A good index for this query would be INDEX(accnum, tdate)
.
Upvotes: 1
Reputation: 1305
I suggest you to put your date between quots like this:
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN '20190311' AND '20190312'
After, you can define a user defined function like this :
CREATE FUNCTION BetweenDate(@toCompare VARCHAR(30), @rightDate DATE, @leftDate DATE)
RETURNS TABLE
AS
BEGIN
RETURN (
SELECT *
FROM transactions
WHERE accum = @toCompare AND tdate BETWEEN @rightDATE AND @leftDate
)
END;
Upvotes: 0