Why to use TIMESTAMP instead of INT value? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the pros and cons of the various date/time field types in MySQL?
In many database, I saw they use TIMESTAMP type to store time value, my question is why don't use INT type to store $date->getTimestamp() value and then we could get time value easier?

Because when you treat a date as a date, and not as a number, you can do neat stuff like adding durations (DATE+1MONTH-1HOUR). TIMESTAMP, DATETIME etc are also optimized for dates, and will do native validation for you.

There can be many reasons, I'd say the most obvious (and straight forward one) is that the databse knows that the value is a TIMESTAMP (so Date/Time related), which is not the case for an INT.
This has several consequences, for example that Mysql is aware of timezones and automatically concerts the TIMESTAMP to UTC. That means the data is much more concrete, because it is clear what the data means. For the INT types you would need to take care of that your own, it would not be relative to the database any longer.
The next big difference is automatic initialization and updating. That means, if the row is inserted or changed, a TIMESTAMP column will get "stamped" with the current time.
There are several other differences then as well between these types, most of the are related to data/time functions. I suggest you dig into:
11.3.1. The DATE, DATETIME, and TIMESTAMP Types

You can do many more things in the database when using a timestamp instead of a plain number. Query by day of week, group by month, determine intervals, etc...

An int is only 4 bytes a datetime is 8 bytes so you'd have less possible values. In particular for php you are getting Unix timestamps which have a min date 1901-12-13, and max of 2038-01-19. This is essentially going back and making the same sort of decisions that lead to the Y2K problem. Assuming you can live with that you should be okay but what about non-Unix based hosts?

Because actual representation of data does not have to be exposed. Why?
flexibility (internal representation of data may change any time and user won't depend on it).
reliability (database may check data for consistency if it knows what the data is)
readability (there's no reason to treat a timestamp as integer, it shows the meaning of a record)

The reason there are different number types (such as timestamp), is to provide data integrity.
Data Integrity makes sure that we don't accidentally put in the number of waffles we had for breakfast :)
If we try to put in an invalid timestamp, MySQL will throw an error and prevent us from putting in bad data.

Related

MySql: saving date ranges VS saving single day

I am currently working on a simple booking system and I need to select some ranges and save them to a mysql database.
The problem I am facing is deciding if it's better to save a range, or to save each day separately.
There will be around 500 properties, and each will have from 2 to 5 months booked.
So the client will insert his property and will chose some dates that will be unavailable. The same will happen when someone books a property.
I was thinking of having a separate table for unavailable dates only, so if a property is booked from 10 may to 20 may, instead of having one record (2016-06-10 => 2016-06-20) I will have 10 records, one for each booked day.
I think this is easier to work with when searching between dates, but I am not sure.
Will the performance be noticeable worse ?
Should I save the ranges or single days ?
Thank you
I would advise that all "events" go into one table and they all have a start and end datetime. Use of indexes on these fields is of course recommended.
The reasons are that when you are looking for bookings and available events - you are not selecting from two different tables (or joining them). And storing a full range is much better for the code as you can easily perform the checks within a SQL query and all php code to handle events works as standard for both. If you only store one event type differently to another you'll find loads of "if's" in your code and find it harder to write the SQL.
I run many booking systems at present and have made mistakes in this area before so I know this is good advice - and also a good question.
This is too much for a comment,So I will leave this as an answer
So the table's primary key would be the property_id and the Date of a particular month.
I don't recommend it.Because think of a scenario when u going to apply this logic to 5 or 10 years system,the performance will be worse.You will get approximately 30*12*1= 360 raws for 1 year.Implement a logic to calculate the duration of a booking and add it to table against the user.

Are date calculations faster in PHP or MySQL?

A while back a database administrator mentioned to me that some server-side programmers don't utilize SQL as often as they should. For instance, when it comes making time-based calculations, he claims that SQL is better suited.
I didn't give that much consideration since it didn't really affect what I was doing. However, now I am making considerable time-based calculations. Typically, I have used PHP for this in the past. For the sake of performance, I am curious as to whether SQL would be more efficient.
For example, these are some of the tasks I have been doing:
$todaysDate = date("d-m-Y");
$todayStamp = strtotime($todaysDate); //Convert date to unix timestamp for comparison
$verifyStamp = strtotime($verifyDate); //Convert submitted date to unix timestamp for comparison
//The date comparison
if((strtotime($lbp) <= $verifyStamp) && ($verifyStamp <= $todayStamp)){
return true;
}
else {
$invalid = "$verifyDate is outside the valid date range: $lbp - $todaysDate.";
return $invalid;
}
The variables aren't that important - it's just to illustrate that I am making comparisons, adding time to current dates, etc.
Would it be beneficial if I were to translate some or all of these tasks to SQL? Note that my connection to my database is via PDO and that I usually have to create a new connection. Also, my date calculations typically will be inserted into a database. So when I say that I'm making comparisons or adding time to a current date, I mean that I'm making these calculation before adding whatever results from them to a query:
i.e. $result = something...INSERT INTO table VALUE = $result
The calculations could just as easily be INSERT INTO table VALUE = DATE_ADD(...
Any input is appreciated.
The overhead of talking to the database would negate any and all advantages it may or may not have. It's simple: if you're in PHP anyway, do the calculations in PHP. If the data you want to do calculations on is in the database, do it in the database. Don't transition between systems just because unless you can really proof that it saves you a ton of time to do so (most likely it doesn't). What you're showing is child's play in either system, it hardly gets any faster as it is.
Well when you consider SQL with any of the programming language, then using SQL is more preferable for calculations than any other language.
If you consider Php and SQL then I would like to tell you what I have realized from my analysis..
The PHP architecture is a client-server architecture, that is Client sends a HTTP-Request to the Server and the server responds back to the client with HTTP-Response
One the backside of the server, the server generates a simple HTML Format page which is static that page is generated using the dynamic codes of PHP on the server.
Now the total time is:
HTTP-Request + SQL-Query + Fetching data from SQL Query + Data Manipulation of SQL Data + Php-to-HTMLGeneration + HTTP-Response
But if in case you use the calculations to be done within the SQL Query itself then the time for Data Manipulation of SQL in php would be saved. As the Php would have to deal with the datas explicitly.
So the total time would be:
HTTP-Request + SQL-Query + Fetching data from SQL Query + Php-to-HTMLGeneration + HTTP-Response
This may look almost equal if you are dealing with less amount of data. But for an instance if you are dealing with 1000 of rows in one query then a loop in php which would run 1000 time would be more time consuming than running a single query which would calculate the complete 1000 row in just one command.
One thing to consider is how many date calculations you are performing and where in the query your conversion is taking place. If you are searching a DB of 10 million records and you are converting a DateTime field into a Unix Timestamp inside of a WHERE clause for every single record and only ending up with 100 records in the query result it would be less efficient to use SQL to perform that conversion on 10 million records than it would be to use PHP to convert the DateTime object into a Timestamp on only the resulting 100 records.
Granted, only the result of 100 records would be converted anyway if you put the conversion in the select statement so it would be pretty much the same.

Which is most suitable datatype for storing time and date

I have two choices of storing date and time in my database.
Generate the time & date from time function in php and then storing in database into int datatype which is of 4 bytes.
Generate the time & date during insertion in database into datetime datatype which is of 8 bytes.
My question is which type will make my SQL queries faster if I use date&time column for sorting.
I always hate it building queries on a DB that contains human unreadable date and time values in int format.
Maybe the query will be a nano second faster if you use int but is it really worth it? I say no!
Use a TIMESTAMP datatype. It's stored as a number, but returned formatted. So it's faster for sorting, and more human-readable.
You are better off using the native format of the database to store date times.
I can see almost no occasion where you would want to use another binary format for this purposes. That would make that component of the database essentially inoperable for other access methods.
As for human readability, you can solve that issue by having views access the tables (in other databases you can define a table with computed columns) that provide the dates in human readable format. Also, tools that know the database should produce the output in human readable format.
Unless you have a very large database or are in a very tightly constrained environment, then don't worry about storage. You are probably not thinking about the extra bits that are stored when you allow NULLs for a column, or the extra padding that might go between fields when they are no aligned on hardware word boundaries, or the empty space on data pages because the records don't align on page boundaries.
If space is such an important consideration, then you might want to develop your own date/time format to see if you can get it down to 2 or 3 bytes.

Can a variable be recognized as an int or float or time if its stored as a varchar

I am in need of storing a score in a mysql field but this score could be a time,integer or float. My first way of doing this was to identify the score type and then enter it into one of three fields but if the need arises to add a new score type I dont want to have to continually add a field to the database. I remember somewhere down the line someone told me that if you store somethign as a varchar then is wont be able to be read as an integer or float or even date. My question is, can I store all three of those as one specific type but read it any way I need when taking it from the database and using it in my php code?
In my opinion you could model the field as FLOAT except if you absolutely need to know about the type of variable stored. Time can be converted to an integer value by converting to timestamp. Integers are a subset of the real (floating point) numbers set actually so I guess that way you have everything covered. Floating point arithmetic can cause some issues with precision and equality testing though so be careful!
You can use CAST and CONVERT functions to convert the string datatype into another MySQL datatype such as INT, FLOAT, DECIMAL, DATE, DATETIME etc.
There are a few issues. How do you know what datatype is stored in a row? MySQL does have RegExp support but I do not recommend using it in your WHERE clauses. Store the datatype in another column.
Also, using cast functions in the where clause of your query will make them run slow. If you need to search upon/sort by the data you should use proper datatypes. Perhaps you should add one column for each datatype; and for each row, populate only the corresponding column.
mysql will happily convert text to numbers of the appropriate type if you perform a mathematical operation on it. However, it will also convert non-numeric text to zero and perform the same operation on it, so you need to check that you're only pulling fields of the appropriate type beforehand.
This forum post shows how to add a regular expression condition to your query to ensure that you're only pulling fields with numeric data in them. However, I think it's probably wiser to use a separate column to indicate what type of score each record is, and use that to retrieve the appropriate ones.
I don't know how to convert text to a date (putting it through date() doesn't work). However, note that the mysql date format (2012-05-08 11:20:23) has the date elements in order of descending significance. If you just want to find the highest / lowest date, or sort by date, treating them as strings will work fine.

DD-MM-YYYY date format and MySQL

I have a MySQL table:
dateStarted varchar(45)
dateEnded varchar(45)
Example:
alt text http://img8.imageshack.us/img8/765/dated.jpg
There is varchar (I don't know why the previous software engineer used this).
Can I search between two dates in MySQL with the varchar type?
Nope. You have to change the format to a proper one.
The previous software engineer used this because of ignorance. You have to correct his mistake.
Don't be afraid of some extra work. Actually it's part of every programmer's job. There is no code in the whole world, which is perfect forever. Constant code improving is called refactoring and take a big part of every software engineer's worktime.
SELECT
*
FROM test1
WHERE STR_TO_DATE(:date, '%d-%m-%Y') BETWEEN
STR_TO_DATE(dateStart,'%d-%m-%Y') AND
STR_TO_DATE(dateEnd,'%d-%m-%Y')
Just tried this on your dataset, and it works AFAICT.
But you should of course heed the advice given by the others here, and try to fix your predecessor's mistakes, if at all possible within time-constraints. This will become an issue at some point, due to the amount of casting going on.
You will need to determine the format that the two fields are in. Are they seconds from UNIX epoch? Are they YYYYMMDD format? Once you've done that, it would be fairly easy to convert it to a date and compare them.

Categories