0

This seems rather simple but it has been giving me a headache. I have a column in my events table that is called 'date_time' and it's type is datetime.

I need to write a query that will get events by day.

Example of table

============================
| id |      date_time      |
============================
| 5  | 2009-03-27 14:16:00 |
============================

Now I need to get the event with the Id = 5, except I only have a date (unix timestamp) to work with. I have tried many things such as converting to mysql format and selecting between 2009-03-27 00:00:00 and 2009-03-28 00:00:00 but I couldn't get it to work.

What is the best way to do this?

Thanks muchly.

0

3 Answers 3

8
SELECT * FROM table
WHERE date_time BETWEEN '2009-03-27 00:00:00' AND '2009-03-27 23:59:59'

Should do it.

Alternatively, try this:

SELECT * FROM table WHERE DATE(date_time) = '2009-03-27'

The DATE() function extracts the date part of the datetime column.

Sign up to request clarification or add additional context in comments.

2 Comments

The DATE() function approach probably forces a table scan.
I chose your second example. Thanks :)
0
select * from table WHERE date(date_time) = '2009-03-27' works for me

if you have an unix timestamp you could also do

select * from table WHERE UNIX_TIMESTAMP(date_time) = your_timestamp

1 Comment

Your UNIX_TIMEESTAMP approach won't work, because a UNIX_TIMESTAMP is to the second.
0

BETWEEN isn't safe if timestamps include fractional seconds. This is always safe:

SELECT *
FROM table
WHERE date_time >= '2009-03-26 00:00:00' AND date_time < '2009-03-27 00:00:00'

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.