How do I use aggregate functions like COUNT, SUM, AVG

In MySQL, aggregate functions are used to perform calculations on multiple rows of a dataset and return a single value. Common aggregate functions include COUNT, SUM, and AVG. Here's how to use each one:

COUNT

The COUNT function counts the number of rows that match a specified condition. It can be used on columns or as a wildcard.

SUM

The SUM function calculates the total of a numeric column.

AVG

The AVG function computes the average value of a numeric column.

Example:

<?php $conn = new mysqli("localhost", "username", "password", "database"); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // COUNT Example $count_query = "SELECT COUNT(*) as total FROM users WHERE active = 1"; $result = $conn->query($count_query); $count = $result->fetch_assoc(); echo "Active users: " . $count['total']; // SUM Example $sum_query = "SELECT SUM(salary) as total_salary FROM employees"; $result = $conn->query($sum_query); $sum = $result->fetch_assoc(); echo "Total Salary: " . $sum['total_salary']; // AVG Example $avg_query = "SELECT AVG(age) as average_age FROM customers"; $result = $conn->query($avg_query); $avg = $result->fetch_assoc(); echo "Average Age: " . $avg['average_age']; $conn->close(); ?>

mysql aggregate functions COUNT SUM AVG SQL queries database queries