I want to select a limited number of items but only keeping ones with a distinct value for a specific field. I have tried using `SELECT DISTINCT ON(field)` as well as `GROUP BY` but they are both extremely slow because the table is very large. I assume this is because using DISTINCT will actually sort the table into distinct values before selecting at all.

```
SELECT DISTINCT ON(parent) id FROM posts WHERE sub = ? LIMIT 25

```

For my purposes this is unnecessary because I am using a LIMIT and can guarantee the limit will be met without scanning much of the table at all. Similar to selecting a value with a condition, which (without an index) will scan each row and check if it meets the condition before continuing, how can I use not having duplicate fields as a condition?

Another way to think about it is how do I do this:

```
SELECT DISTINCT ON (parent) post.id FROM
(SELECT id FROM posts WHERE sub = ? ORDER BY id LIMIT 25) AS post

```

While guaranteeing that there are 25 results. Here the result is very fast but it will usually have less results than required because multiple rows can have the same `parent`.