The difference between COUNT(*) and COUNT(1) is none. They are exactly the same. They do the same thing with the same amount of work to the Database.
However, there is a difference between COUNT(*) and COUNT(column). COUNT(*) counts the number of records in a table while COUNT(column) counts all the data in that given column, except null values.
Example:
Suppose we have a table called CUSTOMER and to show it, we run the following query,
Notice the homephone column has two values as null.
We will be able to see this result,
In Oracle PL/SQL, the COUNT()
function is used to count the number of rows in a result set that match a specified condition. There is a common misunderstanding about the differences between using COUNT(*)
, COUNT(1)
, and COUNT(column_name)
. Let's clarify these differences with examples:
- COUNT(*):
COUNT(*)
counts the total number of rows, regardless of whether there are NULL values in any columns.- It's usually used when you want to count the number of rows without regard to any specific column.
Example:
sqlSELECT COUNT(*) FROM employees;
- COUNT(1):
COUNT(1)
is functionally the same asCOUNT(*)
.- It's used to indicate that you're counting rows without any reference to columns.
Example:
sqlSELECT COUNT(1) FROM employees;
- COUNT(column_name):
COUNT(column_name)
counts the number of rows where the specified column has non-NULL values.- It's often used when you want to count non-NULL values in a specific column.
Example:
sqlSELECT COUNT(salary) FROM employees;
In all these cases, the result will be the same: the number of rows in the employees
table.
When choosing between COUNT(*)
and COUNT(1)
, there's generally no significant performance difference, as modern database optimizers often treat them interchangeably.
However, if you're concerned about performance and you want to count non-NULL values in a specific column, using COUNT(column_name)
is more meaningful and efficient. It also gives you a clearer indication of what you're actually counting.
To summarize:
- Use
COUNT(*)
orCOUNT(1)
when you want to count all rows. - Use
COUNT(column_name)
when you want to count non-NULL values in a specific column.
Remember that the exact performance characteristics might vary depending on the database system you're using, but the differences are usually negligible.
Hope you all have a wonderful day!! Above all, do not stress.