Count Function In Sql in SQL
? COUNT Function in SQL
The COUNT() function returns the number of rows that match a specified condition. It's commonly used to count rows in a table or count non-null values in a column.
? Syntax
COUNT(*)COUNT(column_name)COUNT(DISTINCT column_name)? Usage Variants
| Usage | Description | Example |
|---|---|---|
COUNT(*) | Counts all rows including duplicates and NULLs | SELECT COUNT(*) FROM employees; |
COUNT(column_name) | Counts non-null values in a specific column | SELECT COUNT(email) FROM employees; |
COUNT(DISTINCT column_name) | Counts distinct non-null values | SELECT COUNT(DISTINCT department_id) FROM employees; |
? Examples
Count all rows
SELECT COUNT(*) AS total_employees FROM employees;Count non-null values in a column
SELECT COUNT(phone_number) AS phones_provided FROM employees;Count distinct values in a column
SELECT COUNT(DISTINCT department_id) AS unique_departments FROM employees;? Notes
COUNT(*)is usually fastest because it just counts rows.COUNT(column_name)ignores NULL values.COUNT(DISTINCT column_name)counts unique values only.
Want me to show how COUNT() works with GROUP BY or with conditions?