﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35865	Queryset aggregation keeps unnecessary SQL joins	Ruslan	Rudraksha Dwivedi	"**Problem:**
`Query.count()` results sub optimal SQL query. Though, the impact might be minimal and highly depend on SQL engine implementation. But cleaner and less controversial SQL is always better

**Observed behavior:**
When using `.count()` method (through QuerySet or Query — doesn't matter) it still keeps all joins, even if they are not required for the query.

**Expected behavior:**
Calling `.count()` (`Query.get_count()`) should setup only necessary joins and ignore any other joins that were added due to custom `QuerySet.values` or any other method that modifies SELECT.

**Some context:**
Version: 4.x, 5.x, dev
The code (django/django/db/models/sql/query.py:635):
{{{
def get_count(self, using):
    """"""
    Perform a COUNT() query using the current filter constraints.
    """"""
    obj = self.clone()
    return obj.get_aggregation(using, {""__count"": Count(""*"")})[""__count""]
}}}

I tried to call `obj.clear_select_clause()` but it didn't affect any joins, because they are apparently somewhere in `Query.alias_map` and I am not yet that familiar with how it actually works. But I will appreciate any hints, even if it is a non-issue for a Django project itself."	Cleanup/optimization	assigned	Database layer (models, ORM)		Normal			Simon Charette Stephen	Accepted	0	0	0	0	0	0
