A certain kind of question comes up sometimes when building an application with a relational database:
What is the most recent item for each category?
It often happens with a one-to-many table relationship. You might have a departments table and an employees table, where a department has many employees, and you would like to know each department's most recently hired employee.
The general version of this question even has a name, Greatest N Per Group, and it's not limited to one-to-many relationships, nor to most recent items. Nevertheless, that example is broadly useful because it arises naturally when inserting records into a DB table over time. In this post I'll show the query using standard SQL and walk through integrating it into Rails. Read on for details!