Go Back   CodingForums.com > :: Server side development > MySQL

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-04-2013, 02:36 AM   PM User | #1
shaunthomson
New Coder

 
Join Date: May 2012
Posts: 88
Thanks: 51
Thanked 0 Times in 0 Posts
shaunthomson is an unknown quantity at this point
Finding rows younger than certain date?

Hi guys

Just wondering which data type would be more efficient when querying to find all records in a table that are less than 31 days old? DATE, DATETIME, TIMESTAMP or INT (Unix time stamp)?

ie how should I store my data for the fastest retrieval on that query?

Cheers!
shaunthomson is offline   Reply With Quote
Old 02-04-2013, 09:21 PM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,168
Thanks: 59
Thanked 3,993 Times in 3,962 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
DATE, DATETIME, TIMESTAMP should all be the same:
Code:
SELECT * FROM table WHERE datefield >= DATE_SUB( CURDATE(), INTERVAL 31 DAY )
If you use a UNIX timestamp (that is, an INT to hold a UNIX/Linux timestamp value) then you have to convert it:
Code:
SELECT * FROM table WHERE FROM_UNIXTIME(intfield) >= DATE_SUB( CURDATE(), INTERVAL 31 DAY )
though realistically you *can* use the INT and get the same performance by just inverting that:
Code:
SELECT * FROM table WHERE intfield >= UNIX_TIMESTAMP( DATE_SUB( CURDATE(), INTERVAL 31 DAY ) )
See it? By converting the DATE_SUB result to a unix time, you only have to do that conversion *ONCE* when the query is built and so the time for the WHERE clause is just as fast as when using a DATETIME, et al.

There are other cases, though, where you really would have to use FROM_UNIXTIME() on each INT field value, and so then you do pay a penalty.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Users who have thanked Old Pedant for this post:
shaunthomson (02-05-2013)
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 04:22 AM.


Advertisement
Log in to turn off these ads.