SQL (Structured Query Language) provides a range of mathematical functions that can be used to summarize data efficiently.
The COUNT()
function returns the number of rows that match a requirement specified in the query.
SELECT COUNT(columnName)FROM tableNameWHERE condition;
Let’s create a demo table called Student
.
CREATE TABLE Student (s_ID int,s_name varchar(255),s_major varchar(255),s_age int);INSERT INTO StudentVALUES (78391,'Brad','CS',20);INSERT INTO StudentVALUES (93742,'Allie','Econ',17);INSERT INTO StudentVALUES (31289,'Sally','CS',18);INSERT INTO StudentVALUES (21328,'Chris','Psych', 20);INSERT INTO StudentVALUES (32891,'Betty','Arch', 19);
Student
s_ID | s_name | s_major | s_age |
78391 | Brad | CS | 20 |
93742 | Allie | Econ | 17 |
31289 | Sally | CS | 18 |
21328 | Chris | Psych | 20 |
32891 | Betty | Arch | 19 |
We can use the COUNT()
function to get the total number of students without going through the entire database ourselves.
This returns the total number of rows in the Student
table.
SELECT COUNT(*) As "Number of Students"FROM Student;
COUNT()
with WHERE
clauseThe WHERE
clause is added with the function to get rows that fulfill a specific condition.
For example, if we wish to see the number of students above 18, we use the COUNT()
function and specify the condition as above 18 in the WHERE
clause.
SELECT COUNT(*) As "Students above 18"FROM StudentWHERE s_age > 18;