Letting MySQL figure out date intervals vs. PHP - php

In a MySQL 5.1 InnoDB environment, what is the best way to SELECT data based on date intervals?
Letting MySQL do it via something like DATE_SUB(CURDATE(), INTERVAL 5 DAY) > created_at
Or have PHP prepare the date before submission via strtotime?

I would do it via the query to MySql. That way, you keep the logic of selecting dates out of the PHP. The PHP just handles the display, and you get the advantage of smaller chunks of data coming out of the database as well.

I don't think it matters from performance point of view in this case. Your expression (DATE_SUB) will be evaluated just once. Another point is that your webserver and mysql server can use different timezones, so you may have different results.

I would keep as much logic closest to the database - it has more ability to do any optimisations. Also gives the ability to do change tables easier, change the use of PHP (perhaps java/C# ...) in the future. It also differentiates beteen database (for the data), PHP (for HTML delivery), Javascript (for user enjoyment), CSS (to make things pretty)

You can select a date range using BETWEEN ... AND ...
SELECT * FROM table1 t1 WHERE now() BETWEEN t1.startdate AND t1.enddate
or
SELECT * FROM table1 t1
WHERE t1.somedate BETWEEN DATE_SUB(now(),INTERVAL 1 DAY) AND now()
I prefer this syntax because it's so close to my mental picture of ranges.

Related

SQL Subtract two rows from each other in same column to get a result

I am running many energy readers which collects data with intervals of 5min. To get power used between two time stamps, I need to subtract older data from the newer data.
I am new to SQl, so I would like to ask what SQL syntax do I need to use to get a total sum between two Values.
Database Structure example:
Thank you very much.
You would typically use window function lead() or lag() - if your database supports that.
The following query puts on each row the difference with the previous value of the same equipment:
select
t.*,
t_energy_a - lag(t_energy_a) over(partition by meter_id order by dod) diff
from mytable t

Default date filter in mysql php application

I am working on a PHP and MySQL based application in which I am processing mysql data tables for one week data at a time. All my PHP scripts will run in a particular sequence and process the data in all tables (upto 15 tables) for given week.
Presently I have written the date filter in WHERE clause and application is working fine.
IS there any way by which I can set the week's date range at one place and all the queries are fired in all the tables with given date range.
I want this bcoz my application processes are growing and its hard to manage 20+ pages and 50+ queries written in it.
I am using command line PHP.
Please suggest the technique if any.
Thanks
You could use $_SESSION...
$sql = $db->query("SELECT * FROM table WHERE date BETWEEN '". $_SESSION['range']['from'] ."' AND '". $_SESSION['range']['to'] ."'");
... which will persist for the browser session.
SELECT stuff from your_table
WHERE your_date_field > DATE_ADD(CURDATE(), INTERVAL - 7 DAY);
Run that once a week to get last 7 days, then hack it around to get the exact results you want.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

PHP MySQL hide rows more than 1 minute old

I am trying to make a PHP chat script and I want to make sure it doesn't display any entries older than 1 minute. The database contains a timestamp on each row called timestamp.
How can I do this?
SQL
SELECT *
FROM tablename
WHERE timestamp > TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MINUTE))
It's been a while since I've used that particular function, so I might be a bit off but it's close.
JavaScript
It sounds like you might want to actively hide old messages. In that case you need to include the timestamp meta-data so you can filter it using JavaScript.

Issue of PHP and MySql function

while fetching data from MySQL for today's date, what should be preferred why
1) "select * from table1 where created_dt Like CURDATE()";
2) "select * from table1 where created_dt Like ".date(Y-m-d H:i:s);
will it make any difference in execution time of the script, If i use MySql function instead of php function or vice versa
will it make any difference in execution time of the script
Definitely NO.
The difference would be pretty negligable, though generating the date in SQL would probably be marginally faster.
You should not be using 'like' though, since that is for partial string comparisons, and you are using a date field (which, internally, will be an integer). You are also missing two sets of quotes for your php date example.
But most importantly, if you are using a datetime format for created_dt, and then attempting to match by date using date(created_dt) or any kind of string comparison, you will not be taking advantage of indexing, and are likely to cause a full table scan. You'd be better using:
select * from table1 where created_dt between CURDATE() and date_add(CURDATE(), interval 1 day);
Which can take advantage of a btree index on created_dt to make your query perform considerably faster and more efficiently.
It would be best to use option 1 - date value computed on the database server because:
MySQL doesn't need to convert the string value from the query to a date, since CURDATE retrieves a DATE value
the PHP date function parses the parameter and formates the date and concatenates the result to the query string, which is surely a more complex task then the mysql CURDATE function which has no parameters and simply retrieves the date

MySQL cache and date functions

I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?
example:
$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';
vs
$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';
Any function containing CURDATE() will not be cached. Source
Hardcoding the date should still be cached as far as I can tell. Though you might want to consider using the prepare functionality instead of splicing strings into your query (for sanity and security sake).
It's quite simple actually. The MySQL server does not see your PHP code so it'll receive one of these:
SELECT id FROM table WHERE publish_date = '2010-01-18';
SELECT id FROM table WHERE publish_date = CURDATE();
It will not read your intentions either. For MySQL, '2010-01-18' is a string and is deterministic: its value is always '2010-01-18'. However, CURDATE() is not deterministic: its value varies depending on the date when you run it. Thus the first one is cacheable and the second one is not.
I personally preffer first way, because it give clear head about server time (time zone), my mysql server happend to be 10h earlier when promissed :)
localtime in your PHP script will apply in SQL

Categories