Re: count(*) vs count(id)

Поиск
Список
Период
Сортировка
От Laurenz Albe
Тема Re: count(*) vs count(id)
Дата
Msg-id fe5b3e56cf75094864ac0d05eadefacc42d572c0.camel@cybertec.at
обсуждение исходный текст
Ответ на Re: count(*) vs count(id)  (Matt Zagrabelny <mzagrabe@d.umn.edu>)
Ответы Re: count(*) vs count(id)  (Hellmuth Vargas <hivs77@gmail.com>)
Список 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 по дате отправления:

Предыдущее
От: Laurenz Albe
Дата:
Сообщение: Re: vacuum is time consuming
Следующее
От: Andrus
Дата:
Сообщение: Re: permission denied for large object 200936761