MAX

MySQL Get row with greatest parent row

If you have a database of CDs, and artists, etc.

Say you want to get a list of artists with their most recent releases:

SELECT 
    artist.name, 
    album.title, 
    album.release_date
FROM artist
LEFT JOIN 
    album ON artist.artistID = album.artistID
WHERE album.albumID = (
    SELECT MAX(albumID) FROM album WHERE artist.artistID =  album.artistID
    )

Make sure you have indexed correctly, this could be a slow one.

Using MAX and DATE_FORMAT to get the latest date from a MySQL table

Don’t use DATE_FORMAT when trying to assertain the latest date in a table. It won’t work. DATE_FORMAT will convert the dates to a string, and then the MAX will compare the strings, not the dates.

SELECT MAX(DATE_FORMAT(date_field, '%d-%m-%Y')) AS latest_date 
FROM table;

Is NOT the same as;

SELECT MAX(date_field) AS latest_date 
FROM table;

The latter is the correct way of doing it.