Specify sorting order for a GROUP BY query to retrieve oldest or newest record for each group

Posted by Beau Simensen on Stack Overflow See other posts from Stack Overflow or by Beau Simensen
Published on 2010-04-27T15:08:57Z Indexed on 2010/04/27 15:23 UTC
Read the original article Hit count: 184

Filed under:
|

I need to get the most recent record for each device from an upgrade request log table. A device is unique based on a combination of its hardware ID and its MAC address. I have been attempting to do this with GROUP BY but I am not convinced this is safe since it looks like it may be simply returning the "top record" (whatever SQLite or MySQL thinks that is).

I had hoped that this "top record" could be hinted at by way of ORDER BY but that does not seem to be having any impact as both of the following queries returns the same records for each device, just in opposite order:

SELECT extHwId,
       mac,
       created
  FROM upgradeRequest
 GROUP BY extHwId, mac
 ORDER BY created DESC

SELECT extHwId,
       mac,
       created
  FROM upgradeRequest
 GROUP BY extHwId, mac
 ORDER BY created ASC

Is there another way to accomplish this? I've seen several somewhat related posts that have all involved sub selects. If possible, I would like to do this without subselects as I would like to learn how to do this without that.

© Stack Overflow or respective owner

Related posts about sql

Related posts about group-by