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

ezdazuzena
  • 6,120
  • 6
  • 41
  • 71
  • what do you mean "count on a single row"? What exactly do you want to count? Please be specific. – dirkgroten Sep 03 '19 at 10:19
  • @dirkgroten I updated the question. Hope that makes it clearer. – ezdazuzena Sep 03 '19 at 10:36
  • https://stackoverflow.com/questions/1221559/count-vs-count1-sql-server – dirkgroten Sep 03 '19 at 10:37
  • Possible duplicate of [Count(\*) vs Count(1) - SQL Server](https://stackoverflow.com/questions/1221559/count-vs-count1-sql-server) – dirkgroten Sep 03 '19 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. – dirkgroten Sep 03 '19 at 10:42

2 Answers2

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.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
1

Try this

Entry.objects.values_list('field_name', flat=True).count()
ezdazuzena
  • 6,120
  • 6
  • 41
  • 71
Asad
  • 33
  • 7