0

Why does Django's count() result in a SQL query like

SELECT COUNT(*)

and is there a way to just count on a single column?

For instance, having a model with the following rows: - id - first_name - last_name Instead of having the count run on * which is similar to SELECT COUNT(id, first_name, last_name) I would like to only run

SELECT COUNT(id)

Or best to do SELECT COUNT(1). I want to do this because I once heard that this would be faster for huge tables.

NOTE: If it's faster or not is not the question, it's how to do the query with Django. So please don't mark it as duplicated with Count(*) vs Count(1) - SQL Server

5
  • what do you mean "count on a single row"? What exactly do you want to count? Please be specific. Commented Sep 3, 2019 at 10:19
  • @dirkgroten I updated the question. Hope that makes it clearer. Commented Sep 3, 2019 at 10:36
  • stackoverflow.com/questions/1221559/count-vs-count1-sql-server Commented Sep 3, 2019 at 10:37
  • Possible duplicate of Count(*) vs Count(1) - SQL Server Commented Sep 3, 2019 at 10:41
  • Note also that if you do COUNT(id) on column that may contain NULL values, you will receive a different result, as row with null values will not be counted. Use Django's aggregate if you actually want that. Commented Sep 3, 2019 at 10:42

2 Answers 2

1

If the purpose is to count rows that do not have a NULL value in column x, you should use Django's aggregate:

MyModel.objects.aggregate(Count('x'))

But if your purpose is to speed up your query, than this is pointless as SELECT COUNT(*) or SELECT COUNT(x) have the exact same speed as explained here.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

Entry.objects.values_list('field_name', flat=True).count()

Comments

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.