0

The MySQL table I'm working with has date and time as separate columns. Dates are in the format of "y-m-d" and "hh:mm:ss" for time. How exactly do I search for the rows in between two times if they are in different days? (For example the rows between 2013-01-15 12:00:00 and 2013-01-17 17:00:00)

Right now, I'm using a bad workaround assuming that the time difference will be at most one day but that will not always be the case. There probably is an easy way of accomplishing this but I just can't figure out what. Thanks!

3
  • Can you not alter the schema to combine the columns into a single DATETIME or TIMESTAMP type column? Commented Jan 16, 2013 at 8:03
  • Strongly suggest you modify your data to DATETIME. Commented Jan 16, 2013 at 8:06
  • Is it really that much faster that way? Changing the tables would take a really long time since lots of machines are writing to the database with this structure but I might ask for a change if it will really make a difference. Commented Jan 16, 2013 at 8:33

2 Answers 2

2

concatenate the fields using CONCAT

SELECT  *
FROM    tableName
WHERE   CONCAT(dateCol, ' ', timeColumn) BETWEEN
            '2013-01-15 12:00:00' AND '2013-01-17 17:00:00'

but I recommend that you (if possible) to alter the table by combining the two columns with datatype DateTime so you can take advantage of the indexes. The query above which uses CONCAT requires full table scan which is very poor in performance for large databases.

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

Comments

1

JW.'s answer can be sped up by first using the index to narrow down the search space and then trimming the results down to the correct set.

select * from births
where date between '2013-01-15' and '2013-01-17' -- use index
and concat(date, ' ', time) between '2013-01-15 12:00:00' and '2013-01-17 17:00:00' 
;

See this SQL Fiddle for more details.

1 Comment

Awesome thanks to you both! The table I'm using is indeed very large and this indexing made it work reasonably.

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.