Re: count(*) vs count(id) - Mailing list pgsql-general

From Laurenz Albe
Subject Re: count(*) vs count(id)
Date
Msg-id fe5b3e56cf75094864ac0d05eadefacc42d572c0.camel@cybertec.at
Whole thread Raw
In response to Re: count(*) vs count(id)  (Matt Zagrabelny <mzagrabe@d.umn.edu>)
Responses Re: count(*) vs count(id)
List pgsql-general
On Mon, 2021-02-01 at 19:14 -0600, Matt Zagrabelny wrote:
> > > What is count(*) counting then? I thought it was rows.
> > 
> > Yeah, but count(id) only counts rows where id isn't null.
> 
> I guess I'm still not understanding it...
> 
> I don't have any rows where id is null:

Then the *result* of count(*) and count(id) will be the same.

The asterisk in count(*) is misleading.  Different from any other
programming language that I know, the SQL standard has decided that
you cannot have an aggregate function without arguments.  You have
to use the asterisk in that case.

So count(*) really is count(), that is, it counts one for every
row that it finds, no matter what the row contains.

But count(id) includes a check: if "id IS NULL", it is not counted.

If that condition is satisfied for all "id"s, you end up with
the same count.  But count(id) is more expensive, because it
will perform this unnecessary NULLness check for each row.

In short: use count(*) if you want to count rows, and use
count(x) if you want to count all rows where x IS NOT NULL.

Yours,
Laurenz Albe
-- 
Cybertec | https://www.cybertec-postgresql.com




pgsql-general by date:

Previous
From: Laurenz Albe
Date:
Subject: Re: vacuum is time consuming
Next
From: Andrus
Date:
Subject: Re: permission denied for large object 200936761