Coding Ref

Calculating averages in SQL

Calculating averages in SQL

In SQL, the AVG function is used to calculate the average value of a set of numbers. It takes a column name or expression as an argument and returns the average value of all non-NULL values in that column.

Here is an example of how the AVG function is used:

SELECT AVG(TotalSales)
FROM SalesData

This query will return the average value of the TotalSales column in the SalesData table.

Here is another example that uses the AVG function to calculate the average number of purchases made by customers in the Customer table:

SELECT AVG(TotalPurchases)
FROM Customer

This query will return the average number of purchases made by all customers in the table.

You can also use the AVG function in combination with the WHERE clause to calculate the average of a specific set of values.

For example, the following query uses the AVG function to calculate the average number of purchases made by customers who live in a specific city:

SELECT AVG(TotalPurchases)
FROM Customer
WHERE City = 'New York'

This query will return the average number of purchases made by all customers who live in New York.

Conclusion

In SQL, the AVG function is used to calculate the average value of a set of numbers. It takes a column name or expression as an argument and returns the average value of all non-NULL values in that column.

You'll also like

Related tutorials curated for you

    How to combine two columns in SQL

    How to get the day of the week in SQL

    What is a blind SQL injection?

    Find column names in SQL

    Filtering in GraphQL

    What is SQL ALL?

    Pandas read SQL

    What is SQL ANY?

    How to use between inclusive in SQL?

    SQL aliases

    ABS function in SQL

    What is cardinality in SQL?