Overview
The COUNT function in SQL is used to count the number of rows in a table or the number of non-null values in a column. It's a fundamental aggregate function that returns a single value representing the count.
Syntax
COUNT(expression)
COUNT(*)
COUNT(column_name)
Arguments
expression
: An expression that is evaluated for each row. Only rows where the expression evaluates to non-NULL are counted.*
: Counts all rows, regardless of NULL values.column_name
: Counts the number of non-NULL values in a specific column.
Examples
Counting All Rows
SELECT COUNT(*) FROM Customers;
// Returns the total number of customers in the Customers table.
Counting Non-NULL Values in a Column
SELECT COUNT(Email) FROM Customers;
// Returns the number of customers who have an email address.
Counting Distinct Values in a Column (requires a subquery)
SELECT COUNT(DISTINCT City) FROM Customers;
// Returns the number of different cities where customers reside.