IT-Hardware & Networking
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
In SQL, both
COUNT(*)andCOUNT(column)count rows, but they behave differently withNULLvalues.COUNT(*)Counts all rows in the result set, including rows where columns contain
NULL.Example:
If the table has 10 rows, result =
10.COUNT(column)Counts only rows where the specified column is NOT NULL.
Example:
If
emailhas:Then:
Key Difference
COUNT(*)COUNT(column)With
GROUP BYExample:
COUNT(*)→ total employees in each departmentCOUNT(manager_id)→ employees whosemanager_idis not NULLPerformance Notes
In modern databases (like PostgreSQL, MySQL, SQL Server, Oracle):
COUNT(*)is usually optimized and preferred for counting rows.COUNT(1)andCOUNT(*)are generally equivalent in performance.COUNT(column)may behave differently because it must check for NULLs.Quick Rule
Use:
COUNT(*)→ when you want total row countCOUNT(column)→ when you want count of non-null values in a specific column