SQL COUNT()
The SQL COUNT() function is an aggregate function used to count the number of rows in a table that meet a specified condition. It is often used in conjunction with the SELECT statement to retrieve the number of rows that satisfy a given condition or to count all the rows in a table.
Here is the basic syntax of the COUNT() function:
1 |
SELECT COUNT(column_name) FROM table_name WHERE condition; |
column_name
: The name of the column for which you want to count the number of non-null values. You can also use the wildcard (*) to count all rows regardless of a specific column.table_name
: The name of the table from which you want to count the rows.condition
: Optional. It specifies the condition that must be met for a row to be included in the count.
Examples:
1. Count all rows in a table:
1 |
SELECT COUNT(*) FROM employees; |
2. Count the number of employees with a salary greater than 50000:
1 |
SELECT COUNT(*) FROM employees WHERE salary > 50000; |
3. Count the number of distinct values in a column (e.g., count the number of unique job titles in the employees table):
1 |
SELECT COUNT(DISTINCT job_title) FROM employees; |
It’s important to note that the COUNT() function doesn’t consider NULL values unless you specifically include them in the count using the COUNT(*) syntax.
1 |
SELECT COUNT(*) FROM employees WHERE column_name IS NULL; |
This will count the number of rows where the specified column has NULL values.