SQL COUNT() Function
The SQL COUNT() function is used to count the number of rows in a result set or the number of occurrences of a particular condition in a table. It is often used in conjunction with the SELECT statement to retrieve information about the number of rows that meet a specified condition.
The basic syntax of the COUNT() function is as follows:
1 |
SELECT COUNT(column_name) FROM table_name WHERE condition; |
column_name
: The column for which you want to count the number of non-null values. You can also use*
to count all rows regardless of a specific column.table_name
: The name of the table from which you want to retrieve the data.condition
: An optional condition that specifies which rows to count. If omitted, COUNT() will count all rows.
Here are a couple of examples:
Counting all rows in a table:
1 |
SELECT COUNT(*) FROM employees; |
Counting the number of employees with a specific job title:
1 |
SELECT COUNT(*) FROM employees WHERE job_title = 'Manager'; |
Counting Distinct Values:
1 |
SELECT COUNT(DISTINCT department) FROM employees; |
This query counts the number of distinct departments in the “employees” table.
Counting Rows Grouped by a Column:
1 |
SELECT department, COUNT(*) FROM employees GROUP BY department; |
This query counts the number of employees in each department.
Counting Rows Using Aliases:
1 |
SELECT COUNT(*) AS total_employees FROM employees; |
This query uses an alias (total_employees
) for the result of the COUNT() function.