I have a table with 2 dates - the ADDDATE and UPDATEDATE.
When an item is added, the ADDDATE is the current date and the UPDATEDATE is 0000-00-00.
I need to
Use GREATEST to find the newest date:
ORDER BY GREATEST(UPDATEDATE, ADDDATE)
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:
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.