Mysql order items by the newest of 2 dates

 ORDER BY IF(UPDATEDATE > ADDDATE, UPDATEDATE, ADDDATE)

If you want to make your database scalable, the best approach will be to add a new column LATESTDATE along with an insert/update trigger which sets that to the latest of the two candidate fields using, for example, greatest.

Running per-row functions on your selects slows down very fast as the table gets bigger. If you want performance to stay workable as the table grows, this sort of trick is a common one.

It technically violates 3NF since it duplicates one of the dates but violation is okay for performance reasons and you still maintain the ACID properties because the triggers dictate that the columns stay consistent.

I don't know the MySQL trigger syntax off the top of my head but I would do something like:

  • Create the new column, setting it to a suitable default value.
  • Create the insert/update triggers to ensure changes will be reflected.
  • Touch all the rows with a query like update TBL set ADDDATE = ADDDATE so that the trigger fires for all current rows.

The advantage this solution has is that it moves the cost of calculation to the time when data changes, not every single time you query the database. This amortises the cost across all reads, making it more efficient (unless you're one of those very rare beasts where the table is written more often than read).

Keep in mind this may not be necessary if the size of your table is relatively small - I work in environments where the tables are truly huge.


Use GREATEST to find the newest date:

ORDER BY GREATEST(UPDATEDATE, ADDDATE)