Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write query with time between now and midnight of today in MySQL?

Tags:

mysql

I have query like below

SELECT * FROM programs where startTime between now() and now() + INTERVAL 1 DAY;

Is it possible to write query with time between now and midnight of today in MySQL?

Something like below

SELECT * FROM programs where startTime between now() and now() + midnight 12;
like image 751
Justin John Avatar asked Dec 06 '12 07:12

Justin John


People also ask

How can I get data between two dates and time in MySQL?

select *from yourTableName where yourColumnName between 'yourStartingDate' and curdate().

How do I write a TIMESTAMP in SQL query?

Syntax and Parameters: The basic syntax of “timestamp” data type in SQL is as follows : Timestamp 'date_expression time_expression'; A valid timestamp data expression consists of a date and a time, followed by an optional BC or AD.

What is the difference between now () and Current_date ()?

Current_date() will only give you the date. now() give you the datetime when the statement,procedure etc... started. sysdate() give you the current datetime.

How can I get current time in MySQL?

CURRENT_TIME() function in MySQL is used to check the current time. It returns the current time as a value in 'hh:mm:ss' or hhmmss format, depending on whether the function is used in string or numeric context.


2 Answers

I suggest you always use clopen (closed-open) intervals for dates and times comparisons. BETWEEN means closed intervals (from both sides). A very good explanation is in @Aaron Bertrand's blog post: What do BETWEEN and the devil have in common?. Here's a way to write the query:

SELECT * 
FROM programs 
WHERE startTime >= NOW() 
  AND startTime < CURRENT_DATE() + INTERVAL 1 DAY ;
like image 62
ypercubeᵀᴹ Avatar answered Nov 13 '22 09:11

ypercubeᵀᴹ


SELECT * FROM programs where startTime between now() and CURRENT_DATE() + INTERVAL 1 DAY;

Current date returns the beginning of the day, then we add 1 day to get to the end of it.

like image 23
Erik Ekman Avatar answered Nov 13 '22 07:11

Erik Ekman