Wednesday, December 2, 2009

Find the last updated row from MySql database

1. The Engine of the required tables must be MYISAM. If it is INNODB change it to MYISAM.


2. Now add an additional column in all required tables for timestamp.
MySQL query for this is:
ALTER TABLE table_name ADD COLUMN column_name ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP;


3. Now select the last modified table from all the tables:

SELECT TABLE_NAME FROM information_schema.TABLES WHERE table_schema =? AND TABLE_ROWS>0 ORDER BY UPDATE_TIME DESC LIMIT 1.
Note that you have to write only name of your database in place of question mark.

4. And finally select the latest modified row from that table:

SELECT MAX(time_stamp_column_name), row_id FROM table name GROUP BY row_id DESC LIMIT 1.