The COUNT function in MySQL is an aggregate function that returns the number of rows matching a specified condition. It's particularly useful when you need to know the number of records that match certain criteria.
Syntax
Here is the basic syntax for the COUNT function in MySQL:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
In this syntax:
column_name: This is the name of the column for which you want to count the number of non-NULL values.
table_name: This is the name of the table from which you want to count.
condition: This is an optional part of the syntax. It specifies the condition that the rows must meet to be counted.
Demo Database
Examples
Now, let's go through some practical examples of using the COUNT function:
Counting All Rows
To count all students in the Students table:
SELECT COUNT(*) FROM Students;
This command will return the total number of rows in the Students table.
Counting with a Condition
To count all students who are in grade_level 10:
SELECT COUNT(*) FROM Students WHERE grade_level = 10;
Counting Distinct Values
SELECT COUNT(DISTINCT major_subject) FROM Students;
Comments
Post a Comment