
For an instructor lead, in-depth look at learning SQL click below.
SQL or Structured Query Language is a powerful tool used to communicate and manipulate databases. In today’s data-driven world, understanding how to use SQL to extract useful information from raw data stored in databases is critically important. One commonly used operation in SQL is averaging. This blog post will walk you through how to calculate the average of a column in SQL.
What is the AVG function?
SQL provides a built-in function called AVG that can be used to find the average value of a specific column. The AVG function calculates the average by adding up all numbers in the specified column and then dividing by the count of numbers.
Basic Syntax of AVG function
|
1 2 3 4 |
SELECT AVG(column_name) FROM table_name; |
Here, ‘column_name’ represents the column in the table over which you wish to find the average and ‘table_name’ represents the name of the table where this column is located.
Example of using the AVG function
Suppose we have a table named ‘Employees’ with the following columns: EmployeeID, Name, Age, and Salary. If we want to find the average age of all employees, the SQL query would look like this:
|
1 2 3 4 |
SELECT AVG(Age) FROM Employees; |
This will return the average age of all employees in the ‘Employees’ table.
What if I want to group the average calculation?
In some scenarios, you might want to calculate average for each group in a column, not the whole column. In such cases, you can use the AVG function along with the GROUP BY statement.
For instance, let’s assume that our ‘Employees’ table also includes a ‘Department’ column and we want to find the average salary in each department. The SQL query would be:
|
1 2 3 4 5 |
SELECT Department, AVG(Salary) FROM Employees GROUP BY Department; |
Conclusion
Getting well versed in SQL would require consistent practice. Try out different functions like AVG and commands like GROUP BY on various tables. Understand what each function does and when to use them. The more you practice, the more you learn!
