Hacker News new | ask | show | jobs
by davidhyde 1986 days ago
I find window functions to be an excellent way to find the max version of a set of things. The trick is to partition by some columns (similar to how you would use a group by), order by descending on your version number field, and use the row_number() function which is very lightweight. Then you filter for all entries where rownumber = 1 and voila you have the max version without having to link back on yourself!
3 comments

Sadly, I've worked on a lot of codebases where even the "link back on yourself" trick was unknown to the developers, generally leading to devs dumping the entire dataset into an array and then manually iterating over it to find the max values. I wish developers would learn more SQL at the start of their careers...
Is this different than something like the following?

SELECT app_name, MAX_BY(version_number, updated_at) as version_number FROM table GROUP BY 1

Yes! I use this daily.