views:

238

answers:

4

I'm working with a database that has date information stored as a Unix timestamp ( int(11) ) and what I want to do is only return entries from the past X days, the past 90 days for example.

What I've come up with is:

SELECT * FROM mytable WHERE category=1 AND 
FROM_UNIXTIME( time ) > DATE_SUB(now(), INTERVAL 91 DAY)

Where 'time' is the int(11) in the db. This seems to be working fine, but just wondering what others think of this.

+2  A: 
SELECT * FROM mytable WHERE category=1 AND 
time > (UNIX_TIMESTAMP() - ((60*60*24)*90))

or simply

SELECT * FROM mytable WHERE category=1 AND time > (UNIX_TIMESTAMP() - (86400*90))

this is just comparing a number (seconds in this case)

Question Mark
Thanks, just tried this out, seems to work just fine as well.
A: 

Just thinking aloud... wouldn't doing it the other way around cause less work for the DB?

time > UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 91 DAY) )
Zed
TO_UNIXTIME apparently doesn't exist with my version of mysql :)
Oops... I meant unix_timestamp :)
Zed
A: 

This query is bound to cause you headaches down the way as MySQL needs to do the conversion of dates for every row making use of indexes impossible. Unix timestamps are numbers, so instead of converting a timestamp to another date format, convert your lookup dates to unix timestamps.

code_burgar
My test queries are executing in the neighborhood of 0.0046 seconds. Both my original query and the query from the first answer above, there's really not much difference in terms of time.
I'm sure they are, but try loading 100-500k test records into the table and then check your execution times. Also, the 0.0046 might be exec time of a cached query if you have more than a few rows, try changing some params and rerunning the query
code_burgar
My test query was a SELECT *, I just changed it to some random columns and it executed in 0.0044 seconds. I changed the query to go back a year (on those same random columns), it's returned 599 records in 0.0025 sec - the fastest query yet. Unfortunately, I don't have any test records, only the records that are in the db (but it's fairly good-sized).
A: 

What is the reason for storing the timestamp as an int ? I would use the mysql DATETIME data type because you can use the many Date Time functions mysql has.

If you do not have control over the data type of this field I would convert your date to the unix timestamp int before you do your query and compare it that way.

Mark Robinson
It's the way it was done and I'm not comfortable changing it at this point. The queries are executing in the neighborhood of 0.0046 seconds so doesn't seem to be a performance problem?