Should I COUNT(*) or not?

前端 未结 14 1346
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 15:49

I know it\'s generally a bad idea to do queries like this:

SELECT * FROM `group_relations`

But when I just want the count, should I go for this

14条回答
  •  遥遥无期
    2021-01-30 16:30

    If the column in question is NOT NULL, both of your queries are equivalent. When group_id contains null values,

    select count(*)
    

    will count all rows, whereas

    select count(group_id)
    

    will only count the rows where group_id is not null.

    Also, some database systems, like MySQL employ an optimization when you ask for count(*) which makes such queries a bit faster than the specific one.

    Personally, when just counting, I'm doing count(*) to be on the safe side with the nulls.

提交回复
热议问题