[Feature Proposal] FETCH FIRST N ROWS ONLY (WITH TIES)

Postgres recently implemented a feature in version 13: instead of specifying LIMIT 10, you can now specify FIRST FIRST 10 ROWS WITH TIES. This basically lets you grab any rows that are “tied” for position according to the ORDER BY clause. This article explains more in-depth. SQL Server supports it as well, and it’s part of the SQL standard.

I think adding support for this feature would be useful in Rails, as it makes keyset pagination easier. Without getting into the weeds on what that is, it’s essentially a way to do pagination such that you exploit a database index to make every fetch super-fast. Having WITH TIES makes implementing proper keyset pagination much easier - without it, it’s quite hard to avoid skipping values.

As far as I can tell, this wouldn’t be too hard to add, either: you could add a include_ties: kwarg on .limit, and then modify Arel::Nodes::Limit to handle it. If this feature seems valuable, I could probably get a PR open for it fairly quickly.