How to Check if Specific Number of Rows Exist Without COUNT(*) in PostgreSQL

postgresqlpostgresql-performance

I know we can check if at least one row of a table exists using EXISTS keyword, for example:

select * from A where exists(select from B where B.id = A.id)

What if I want to check if at least N rows exist, without using COUNT?

Performance matters to me. I don't want the whole table to be scanned to count matching rows. I just need my query to stop when N rows are found. I mean, the existence of at least N rows is what matters, and not the total count. That could save time if table is large.

Is there such feature in PostgreSQL?

Best Answer

You can add this in the EXISTS subquery:

LIMIT 1 OFFSET (N-1)

In other words, the subqery first tries to finds (N-1) rows, skip them and return the next (Nth) row. So, it will return something (one row) if and only if there are N+ rows.

You need appropriate indexes, i.e. an index on B(id) in this case, to make it as fast as possible, obviously.