MySQL COUNT, AVG, SUM

MySQL Aggregate Functions: COUNT(), AVG(), and SUM()

MySQL provides powerful aggregate functions to perform calculations on data.


Demo Database

Below is a selection from the "Students" table in the school_db database:


student_id

name 

gender

city

age

score

course_id

email

phone_number

1

Alice

Female

Delhi

20

85

101

NULL

1234567890

2

Bob

Male

Mumbai

22

75

NULL

bob@email.com

NULL

3

Charlie

Male

Delhi

21

95

102

NULL

NULL

4

David

Male

Bangalore

23

65

101

david@email.com

NULL

5

Eve

Female

Mumbai

20

80

103

NULL

NULL

6

Frank

Male

Delhi

22

90

103

NULL

NULL

7

Alice

Female

Mumbai

19

60

102

NULL

NULL

1. COUNT() – Count Rows

The COUNT() function returns the total number of rows that match a condition.


Syntax:


SELECT COUNT(column_name)
FROM table_name
WHERE condition;


The following SQL statement finds the number of students:

Example
SELECT COUNT(*) AS total_students FROM students;

Try it yourself

Note

NULL values are ingnored.


2. AVG() – Calculate Average Value

The AVG() function returns the average (mean) value of a numeric column.


Syntax:


SELECT AVG(column_name)
FROM table_name
WHERE condition;

The following SQL statement finds the average score of all students:

Example
SELECT AVG(score) AS avg_score FROM students;

Try it yourself


3. SUM() – Calculate Total Value

The SUM() function returns the sum (total) of a numeric column.


Syntax:


SELECT SUM(column_name)
FROM table_name
WHERE condition;

The following SQL statement finds the sum of the "score" fields in the "Students" table:

Example
SELECT SUM(score) AS total_score FROM students;

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.