Mysql date_add returns wrong row in python, right row in phpmyadmin I am trying to get the first and last record from a month.  In phpmyadmin I ge the correct result.  In python I don't.  In fact python returns the same row for both of these queries.  First number is the table primary key for the rows.

SELECT * 
FROM mcs 
WHERE time_stamp &lt; DATE_ADD( DATE_ADD( LAST_DAY( NOW( ) ) , 
                                       INTERVAL 25 HOUR ) , 
                             INTERVAL -2 MONTH) 
  AND wot_id = 1010965979
LIMIT 1

838831, '1010965979', datetime.datetime(2015, 3, 6, 22, 0), Decimal('444.88'), Decimal('0.00')

SELECT * 
FROM mcs 
WHERE time_stamp &lt; DATE_ADD( DATE_ADD( LAST_DAY( NOW( ) ) , 
                                       INTERVAL 24 HOUR ) , 
                             INTERVAL -1 MONTH)
  AND wot_id = 1010965979 
LIMIT 1

838831, '1010965979', datetime.datetime(2015, 3, 6, 22, 0), Decimal('444.88'), Decimal('0.00')


phpmyadmin shows this row for the first query,  

839037 1010965979 2015-04-01 00:00:00 437.36 0.00

and this for the second:

953868 1010965979 2015-04-30 23:00:00 479.67 0.00

using MySQLdb and python 3

What is wrong?  is this a bug in MySQLdb?  I would not think so as it just passing a SQL string to mysql
First, a crucial mistake of the queries:


LIMIT without ORDER BY does not guarantee consistent results.
If you get correct results using LIMIT without ORDER BY, it's only by accident.


The results you got from running the queries in PHPMyAdmin was only accidental. There is no guarantee that you'll get the same results if you run the same queries tomorrow. 

Adding ORDER BY (either ASC or DESC) will solve the issue.

There is also another problem with the 1st query. Adding 25 hours instead of 24 might be a nice hack - if it worked. It might work with the current data but it will stop, if there are ever rows that are not limited to full hours or there are no rows for the first hour of a month. You need to use 24 hours (or 1 day) and timestamp &gt;= ... and ORDER BY .. ASC to get the first row from a period.

Queries rewritten (I used date arithmetic instead of your DATE_ADD(), this is entirely personal preference, the DATE_ADD() is fine in your queries):

-- First row in previous month (or later)
SELECT * 
FROM mcs 
WHERE time_stamp &gt;= LAST_DAY(NOW()) + INTERVAL 1 DAY + INTERVAL -2 MONTH 
  AND wot_id = 1010965979
ORDER BY time_stamp ASC
LIMIT 1 ;

-- Last row in previous month (or earlier)
SELECT * 
FROM mcs 
WHERE time_stamp &lt;  LAST_DAY(NOW()) + INTERVAL 1 DAY + INTERVAL -1 MONTH 
  AND wot_id = 1010965979
ORDER BY time_stamp DESC 
LIMIT 1 ;