Skip to content

Conversation

@somitmittal
Copy link

@somitmittal somitmittal commented Aug 2, 2021

Sorry this is my first time contributing to open source,

In this PR, I have made the changes related to how count of queryset is evaluated.
SO currently, what we do is :
list_length = iterable.count()
This leads to a SQL query of the form : SELECT COUNT(*) as __count which is time consuming at SQL level because it does a count on the all records,

Solution:
Since we are only interested in the queryset count or number of records for pagination purposes, I feel the optimized or faster way to do this would be to run a SQL Query like : SELECT COUNT('pk') as pk__count where pk refers to the primary key in the db table. This query would definitely consume lesser time than SELECT COUNT(*) as it will do a count on primary key.
TO do that we can change the line of code from
list_length = iterable.count()
TO :
list_length = iterable.aggregate(Count('pk'))['pk__count'] // this will run a query like SELECT COUNT('pk') as pk__count

I feel this change can bring some speedup in graphql queries as we are now only fetching count of primary key rather than count(*) which can give some speed advantages.

Please correct me if I am wrong. Thanks :)

@ulgens
Copy link
Collaborator

ulgens commented Sep 7, 2021

Do we have any documentation or benchmark about the performance increase provided by this change?

@keithhackbarth
Copy link
Collaborator

https://dba.stackexchange.com/questions/41090/postgres-count-vs-countid
https://stackoverflow.com/questions/2710621/count-vs-count1-vs-countpk-which-is-better

I'm pretty sure COUNT(*) is as fast if not faster than COUNT(id) on most databases. And even if it wasn't I think it would have to be significantly faster to warrant the non-standard syntax. I would suggest closing this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants