Retrieving the top N records with ties on Postgres
A customer asked for a top absentees report, and we immediately created a query, but an unexpected behavior happened.
Photo by Possessed Photography on Unsplash
But there’s an issue with that report that is not entirely obvious:
That’s called a tie: Richard Doe and Robert Doe have the same number of absences.
In other words, we might have more than 3 rows to describe the top 3 absentees.
For that scenario, we have a FETCH FIRST … ROWS WITH TIES clause on Postgres 13+:
If there are no ties, it will behave pretty much the same as LIMIT
.
Now we are good to deploy that to production!