The SQL COUNT() Function
The SQL COUNT() function in SQL is used to determine how many rows or records are present in a given column or table. It is frequently used to do tasks like calculating the total number of records that satisfy a set of requirements or counting the unique values in a column.
Let’s explain SQL COUNT() function with some examples
Example 1: Count All Rows in a Table
Suppose you have a table called “Students” with information about students, and you want to find out how many records (rows) are in the table.
SQL> SELECT COUNT(*) AS TotalStudents FROM Students;
COUNT(*) counts all rows in the “Students” table.
AS TotalStudents provides an alias for the result column for clarity.
Example 2: Counting Rows Meeting a Condition
You can also use the COUNT function to count the number of rows that meet specific criteria.
SQL> SELECT COUNT(*) AS HighGPACount FROM Students
WHERE GPA >= 3.5;
COUNT(*) counts all rows that satisfy the condition (GPA >= 3.5) in the “Students” table.
Example 3: Count Distinct Values
The COUNT function can be used with the DISTINCT keyword to count the number of unique values in a column.
SQL> SELECT COUNT(DISTINCT CourseName) AS UniqueCourses
FROM Courses;
COUNT (DISTINCT CourseName) counts the number of unique course names in the “Courses” table.
Example 4: Counting Rows Grouped by a Column
You can also use COUNT with the GROUP BY clause to count the number of rows within groups.
SQL> SELECT Department, COUNT(*) AS StudentsPerDepartment FROM Students
GROUP BY Department;
GROUP BY Department: groups the students by their department.
COUNT(*) counts: the number of students in each department.
The above SQL COUNT() function examples show you how to count rows in a table, count rows that satisfy certain criteria, count different values, and count rows inside groups using the SQL COUNT function.
A potent tool for extracting important statistics and data from your database is the COUNT function.