*COUNT() in SQL: Guaranteed Results**
This article clarifies whether the SQL function COUNT(*)
always produces a result.
The Answer: Yes, COUNT(*)
always returns a numerical value.
Explanation:
COUNT(*)
calculates the total number of rows in a table or a selected subset. Unlike aggregate functions like SUM
or MAX
, which return NULL
if no rows match the query criteria, COUNT(*)
will always return a count—even if that count is zero (meaning no rows satisfied the WHERE clause). It's counting the number of rows within the defined scope, not just those matching a specific condition.
Important Note: GROUP BY Clause
The only exception is when COUNT(*)
is used with a GROUP BY
clause. If a group defined by GROUP BY
has no rows that meet the query's conditions, COUNT(*)
will return NULL
for that specific group. This is because COUNT(*)
operates on each group individually.
Practical Implications:
Understanding this behavior is vital for writing reliable SQL queries. Knowing that COUNT(*)
always yields a result helps prevent errors caused by unexpected NULL
values.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3