COUNT() in SQL
Counts the number of rows or non-null values in a specified column. COUNT(*) counts all rows including nulls, while COUNT(column) counts non-null values in the specified column.
Syntax
Return type
COUNT() Function Example
What is COUNT() in SQL?
The COUNT()
function in SQL is used to count the number of rows or non-null values in a specified column. It is commonly used for aggregating data, performing statistical analysis, and generating summary reports.
This function is supported in SQL Server, MySQL, PostgreSQL, and Oracle.
The COUNT()
function is widely used in data aggregation, reporting, and business intelligence.
Parameters:
(asterisk): Count all rows
column: Column name to count non-null values
DISTINCT column: Column name to count unique values
Example Use Cases:
-- Count total employees
-- Count filled positions
-- Count unique product categories
Notes:
Behavior: COUNT(*) includes NULL values, COUNT(column) excludes NULLs
Performance Considerations: COUNT(*) often optimized for better performance
Version Info: Core aggregation function available in all major DBMS
Deprecated/Recommended Alternatives: None
Error Handling:
Error: Returns 0 for empty result sets
Recommendation: Use COALESCE when combining with other operations
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
COUNT()
COUNT(*)
Includes in *, excludes in column
PostgreSQL
COUNT()
COUNT(*)
Includes in *, excludes in column
SQL Server
COUNT()
COUNT(*)
Includes in *, excludes in column
SQLite
COUNT()
COUNT(*)
Includes in *, excludes in column
BigQuery
COUNT()
COUNT(*)
Includes in *, excludes in column
Snowflake
COUNT()
COUNT(*)
Includes in *, excludes in column
Athena
COUNT()
COUNT(*)
Includes in *, excludes in column
Related Functions:
SUM()
Calculates the total sum of all values in a specified column or expression, ignoring NULL values.
AVG()
Calculates the arithmetic mean (average) of all non-null values in a specified column or expression.
MIN()
Returns the smallest value from a specified column or expression, ignoring NULL values.
MAX()
Returns the largest value from a specified column or expression, ignoring NULL values.