Finding the Second Highest Value with SQL
February 12th, 2007
For a project I'm currently working on, subscribed users get up to the minute most current information (as outlined by a date field in MySQL). Unsubscribed users get the information still, only it is a day behind.
Due to the way the information is going into the system, there could be multiple entries for one date, and then no entries for a few days, then new, etc. Basically, the information cannot be predicted by the application. Retrieving the most recent date is trivially easy with a MAX command, but there is no "almostMAX" command, so I found myself staring at the screen wondering what the most efficient way to approach this was. Here's my solution:
SELECT * FROM table GROUP BY dateIssued ORDER BY dateIssued DESC LIMIT 1,1
Fortunately for me, LIMIT accepts offsets, and I can specific to grab only the second entry. If you can think of a more elegant way to do this (or heck, if you just want to comment), please leave a note below.
This entry was made on February 12th, 2007 @ 9:10 and filed into How-To, PHP.

Shadowhand wrote on February 14th, 2007 @ 8:39
Nice entry Derek. I don’t have any recommendations for you, however, I do have a comment: DON’T USE DATE FIELDS! They are silly and MySQL only. Use an unsigned int(11) field, and use Unix timestamps. It’s faster with large amounts of records and allows for finer-tuned searches by date. The date type is also not standard SQL, particularly MySQL’s date field, so it’s not compatible with other database types.