Reputation: 8287
I'm in a dilemma about saving date and time values in MySQL's TIMESTAMP format vs in a custom UNSIGNED INT format. The main considerations here are speed of retrieval, appropriate range calculations in PHP and occasional formatting into human readable values.
The storage space required for each type and their ranges:
DATETIME 8 bytes '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP 4 bytes '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC
UNSIGNED INT 4 bytes (Maximum Value 4294967295)
I dont need the range of DATETIME at all. I'm torn between TIMESTAMP and UNSIGNED INT.
Arguments in favor of UNSIGNED INT:
The only advantage TIMESTAMP would give me is when I'm reading in the values from the mysql table manually and need to 'see' them.
Is there any compelling reason to use TIMESTAMP and not an UNSIGNED INT?
Upvotes: 51
Views: 32246
Reputation: 4833
As always it depends on what you need to save.
For example if you are consuming data from some API and it sends to you the time as a number (seconds, this is common in market data) then could be easier and faster just to store it as unsigned int instead of converting everytime to a string before inserting it.
Upvotes: 1
Reputation: 62359
Arguments for TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
or ON UPDATE CURRENT_TIMESTAMP
(one column per table only until MySQL 5.6.5)FROM_UNIXTIME()
function - it will make it easier to write queries that can use indexesIn PHP
>> date('Y-m-d h:i:s',4294967295);
'1969-12-31 11:59:59'
so the range is in fact the same
When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion
Upvotes: 33
Reputation: 33148
The only real use for TIMESTAMP is when you want that field to be updated automatically when the row is updated (which is the default behaviour for that field), or when data storage requirements are so strict that 4 bytes per row really makes a difference to you.
Really the comparison should be between DATETIME and UNSIGNED INT, and I'd recommend DATETIME because:
SELECT UNIX_TIMESTAMP(field) FROM table
, no need to select out the raw value and use strtotimePoint two alone really removes any reason to store in integers, in my opinion.
Upvotes: 10
Reputation: 10635
This might not be a "scientific" answer but I always find the way MySql handles conversion, arithmetics, comparsion, etc... on TIMESTAMP columns confusing. An UNSIGNED INT column is much more straight forward and I always know what to expect.
P.S. Perhaps one other thing in favor of TIMESTAMP column is its ability to be automatically set to current time after each update or insert but that is not something you can't live without.
Upvotes: 7