4

Given this table

| id | name  | created_at                 |
| 1  | test  | 2015-02-24 11:13:28.605968 |
| 2  | other | 2015-02-24 13:04:56.968004 |
| 3  | test  | 2015-02-24 11:14:24.670765 |
| 4  | test  | 2015-02-24 11:15:05.293904 |

And this query which returns only the rows id 2 and id 4.

SELECT DISTINCT ON (documents.name) documents.*
FROM "documents"  
ORDER BY documents.name, documents.created_at DESC

How can i return the number of rows affected? Something like

SELECT COUNT(DISTINCT ON (documents.name) documents.*) FROM "documents"

1 Answer 1

5

You can use an outer query:

SELECT COUNT(1)
FROM (
    SELECT DISTINCT ON (name) *
    FROM documents
    ORDER BY name, created_at DESC
    ) alias
Sign up to request clarification or add additional context in comments.

1 Comment

As soon as you start adding more columns than "name" it doesn't work, FYI. Distinct ON will take each individual column for uniqueness, where distinct col1,col2,col3 checks the entire combination.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.