COUNT in SQL?

COUNT in SQL?

The COUNT function in SQL is used to return the number of rows in a result set. It can count all rows or only those that meet a specific condition.


Key Points

  1. Counts Rows:
    The COUNT function calculates the total number of rows in a table or result set, either including or excluding NULL values based on the usage.

  2. Flexible with Conditions:
    You can use COUNT with conditions in the WHERE clause or with specific columns to get targeted counts.

SELECT COUNT(column_name) 
FROM table_name 
WHERE condition;

Example

Counting All Rows

SELECT COUNT(*) 
FROM employees;
  • This query returns the total number of rows in the employees table, including rows with NULL values.

Counting Non-NULL Values in a Column

SELECT COUNT(salary) 
FROM employees;
  • This query returns the number of rows where the salary column is not NULL.

Counting Rows with a Condition

SELECT COUNT(*) 
FROM employees 
WHERE department = 'HR';
  • This query counts rows where the department is 'HR'.

When to Use COUNT

  • To determine the total number of rows in a table or a filtered subset.

  • To measure data completeness by checking for NULL values in a column.