Stephen Karger

Recent Posts

Finding the most recent item by group in Rails

By Stephen Karger on Jun 21, 2019 9:09:03 AM
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!

Read More →

Recent Posts