Things I didn’t know about MySQL #1: GREATEST

Somehow I have used SQL for nearly 30 years without knowing about the GREATEST function. It’s only when you need to do something that looks impossible that you delve into the online manual and find gems like this.

In this case, I had a query that needed to return, and order the rows by, the latest date from three different date columns in three different tables. Impossible I thought — I’ll have to muck about with MAX for each column, and then do the comparison in PHP. Not at all!

SELECT R.requestid, C.cliid, clifname, clilname,requestdate, GREATEST(emaildate,climoddate,requestlastmodified) AS lastmoddate
FROM ClientRequests R
INNER JOIN Clients C ON C.cliid = R.cliid
LEFT OUTER JOIN Emails E ON R.requestid = E.requestid
GROUP BY R.requestid
ORDER BY GREATEST(emaildate,climoddate,requestlastmodified)

If one or more of the columns might include null values, you need to do a little more work with COALESCE:
SELECT R.requestid, C.cliid, clifname, clilname,requestdate, GREATEST(COALESCE(emaildate,0),climoddate,requestlastmodified) AS lastmoddate
FROM ClientRequests R
INNER JOIN Clients C ON C.cliid = R.cliid
LEFT OUTER JOIN Emails E ON R.requestid = E.requestid
GROUP BY R.requestid
ORDER BY GREATEST(COALESCE(emaildate,0),climoddate,requestlastmodified)

This entry was posted in Databases. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>