What are the best practices for structuring SQL queries to efficiently calculate averages and ratios in PHP?

When calculating averages and ratios in SQL queries in PHP, it is important to structure the queries efficiently to minimize the amount of data being processed. One way to do this is by using aggregate functions like AVG() for calculating averages and SUM() for calculating ratios. Additionally, using proper indexing on the relevant columns can improve query performance.

// Example of calculating average using SQL query in PHP
$query = "SELECT AVG(column_name) AS average_value FROM table_name";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$average = $row['average_value'];

// Example of calculating ratio using SQL query in PHP
$query = "SELECT (SUM(column1) / SUM(column2)) AS ratio_value FROM table_name";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$ratio = $row['ratio_value'];