The COUNT function in SQL is used to count the number of rows with a specific condition. It can count all rows in a table or subset of rows based on specific conditions.
SQL Count Syntax
SQL
x
1
SELECT COUNT(column_name)
2
FROM table_name
3
WHERE condition;
SQL Count Example
This query count all rows in the Patients table, including those with NULL values in any column.
SQL
1
1
SELECT COUNT(*)
2
FROM Patients;

SQL Count Specify Column Example
This query counts only the rows where the contact_number is not NULL in the Patients table.
SQL
1
1
SELECT COUNT(contact_number)
2
FROM Patients;

SQL Count Adding a WHERE Clause Example
This query counts the number of rows where the gender column has the value ‘F’, i.e., the number of female patients.
SQL
1
1
SELECT COUNT(*)
2
FROM Patients
3
WHERE gender = 'F';

SQL Count Ignore Duplicates Example
This query counts the number of unique values in the specialty column in the Doctors table, ignoring any dupicate specialties.
SQL
1
1
SELECT COUNT(DISTINCT specialty)
2
FROM Doctors;

SQL Count Using an Alias Example
This query counts all rows in the Patients table and uses an alias total_patients to give a meaningful name to the result.
SQL
1
1
SELECT COUNT(*) AS total_patients
2
FROM Patients;
3

SQL Count Visual Diagram
