COUNT
In SQL, the COUNT()
function is an aggregate function used to count the number of rows in a specified column or the number of non-NULL values in a set of rows. The COUNT()
function can be used with the SELECT
statement to retrieve the count of rows that match certain criteria.
Basic syntax
The basic syntax of the COUNT()
function is as follows:
SELECT COUNT(column_name)
FROM table_name
WHERE condition
COUNT(column_name)
: This counts the number of non-NULL values in the specifiedcolumn_name
. If no column name is provided inside the parentheses,COUNT(*)
counts the total number of rows in the table.table_name
: This is the name of the table from which you want to retrieve the data.condition
: This is an optional condition that specifies which rows to include in the count.
Examples
- Counting Total Number of Rows
To count the total number of rows in a table, you can use:
SELECT COUNT(*)
FROM employees
This query will return the total number of rows in the employees
table.
- Counting Number of Rows Based on a Condition
To count the number of employees who belong to the 'IT' department, you can use:
SELECT COUNT(*)
FROM employees
WHERE department = 'IT'
This query will return the count of rows where the department
column has the value 'IT'
.
- Counting Number of Non-NULL Values in a Column
To count the number of non-NULL values in the salary
column, you can use:
SELECT COUNT(salary)
FROM employees
This query will return the count of non-NULL values in the salary
column.