I’m currently working on optimizing a MySQL query, and I’m wondering if there’s a way to retrieve both the count of the results and the actual result set in a single query. I’m aware that I can achieve this using separate queries, one for the count and one for fetching the results, but I’m curious if there’s a more efficient way to accomplish this within a single query.
2
Answers
Yes, you can use a subquery in SELECT :
Select *, (SELECT COUNT(id) FROM city) as total FROM city;
And here is the result :
enter image description here
or in join case you can use this method :
and here is the result :
Do it in the other order.
Rather than count the QuerySet size, then fetch it, you should instead fetch it and then determine length.
You can convert a QuerySet to a list. This fetches the query.
Then
len()
on that list can be found without a query to the database.