8

All,

I have a MYSQL table with a column called timestamp. It is of DATETIME datatype and has values like "10/1/2009 3:25:08 PM', "10/1/2009 3:30:05 PM', "10/4/2009 3:40:01 PM', etc..

I want to write a SQL query to select all the values in the timestamp field occuring between two dates.. something like this:

select timestamp from tablename where timestamp >= userStartDate and timestamp <= userEndDate

The userInput dates will not have time portions. Can you please suggest the correct MySQL Query Syntax for this? Thanks

Quassnoi
  • 413,100
  • 91
  • 616
  • 614
Jake
  • 25,479
  • 31
  • 107
  • 168

4 Answers4

15
SELECT timestamp
FROM   tablename
WHERE  timestamp >= userStartDate
       AND timestamp < userEndDate + INTERVAL 1 DAY

This will select every record having date portion between userStartDate and userEndDate, provided that these fields have type of DATE (without time portion).

If the start and end dates come as strings, use STR_TO_DATE to convert from any given format:

SELECT timestamp
FROM   tablename
WHERE  timestamp >= STR_TO_DATE('01/11/2010', '%m/%d/%Y')
       AND timestamp < STR_TO_DATE('01/12/2010', '%m/%d/%Y') + INTERVAL 1 DAY
Quassnoi
  • 413,100
  • 91
  • 616
  • 614
8
SELECT timestamp
 FROM  myTable
 WHERE timestamp BETWEEN startDate AND endDate

For best results when using BETWEEN with date or time values, you should use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

- http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 1
    If both `startDate` and `endDate` are `Jan 11, 2010`, this will select only records with `timestamp = Jan 11, 2010 00:00:00`, not all records having `Jan 11` in the date portion. – Quassnoi Jan 11 '10 at 21:39
  • You're right, Quassnoi. If that's possible with the users data, add 24 hours (as you did in your example). I had assumed the user would be using dateTime values within the query itself. – Sampson Jan 11 '10 at 21:52
4

The userInput dates will not have timestamps. You can convert user input to timestamp with:

mysql> SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
        -> 1196440219

Your query can become:

select timestamp from tablename 
where timestamp >= UNIX_TIMESTAMP(userStartDate)
and timestamp <= UNIX_TIMESTAMP(userEndDate)
Yada
  • 30,349
  • 24
  • 103
  • 144
2

If your looking to query an event between two timestamps, for a calendar or something where the start and end are stored as a timestamp you can use this

$qry = "SELECT * 
        FROM `table` 
        WHERE '$today_start' >= `event_start` 
            AND '$today_start' <= `event_end`";
Pete Carter
  • 2,691
  • 3
  • 23
  • 34
Milk Man
  • 1,256
  • 13
  • 21