I’m looking to sort multiple tables that are in a database based on the last time the table was updated. The tables all have a column called Update_Time
that updates the timestamp when that row is updated in the table. I have tried with the UPDATE_TIME
from the TABLE_SCHEMA, but that updates when any of the tables on my webpage gets updated. Below is what I have tried that doesn’t work. Any help would be greatly appreciated.
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'myDatabase'
ORDER BY (
SELECT MAX(`Update_Time`) AS "Last Updated" FROM `myTable`
);
2
Answers
First, your
order by
clause is using a date, not a column, to perform the sort, so every row is sorted with the same value which has no effect. For example, if the most recent update date is2024-01-06
your query becomes:Second, the schema information held by the database server is not the data it’s meta data about the tables. You would have to use some dynamic SQL to get the list of tables from the schema info then run queries to get the most recent update in each table, then rank the tables by that date.
What do you actully need the most recent update for? There might be an easier way to do this if you tell us more about the problem you are actully trying to solve.
In response to your comment about getting this working with the table design you have, you can use a
union
query if the number of tables (competition classes) is fixed.Is this what you are looking for? Try to run this and in the output youll get the dynamic SQL for all the tables in union just add order by update_time at all and little bit syntax adjustment of the output sqls