SQL AVG Tutorial šŸŽÆ

beginner
18 min

SQL AVG Tutorial šŸŽÆ

Welcome to the SQL AVG Tutorial for beginners and intermediates! In this lesson, we'll learn about the AVG function in SQL, which helps us calculate the average of numerical values in a table. šŸ“

What is SQL AVG? šŸ’”

The AVG function in SQL returns the average of the numerical values in a specified column or expression. It's a great tool for analyzing data and understanding central tendencies.

Syntax šŸ“

Here's the basic syntax of the AVG function:

sql
AVG(column_name)
  • column_name: Specify the column containing numerical values for which you want to calculate the average.

Example šŸ’”

Let's consider a simple table named students with the following data:

| StudentID | Marks | |-----------|-------| | 1 | 85 | | 2 | 78 | | 3 | 82 | | 4 | 90 | | 5 | 76 |

To find the average marks of the students, we'll use the AVG function as follows:

sql
SELECT AVG(Marks) AS AverageMarks FROM students;

The output would be:

AverageMarks ------------ 80.00

Advanced Examples šŸ’”

Calculating Average of Multiple Columns

If you have multiple columns containing numerical data and want to find the average of all of them, use multiple column names separated by commas:

sql
SELECT AVG(Marks), AVG(Age) FROM students;

Using WHERE Clause with AVG

You can use the WHERE clause to filter rows before calculating the average:

sql
SELECT AVG(Marks) AS AverageMarks FROM students WHERE StudentID > 2;

Quiz šŸ’”

Quick Quiz
Question 1 of 1

Which SQL function returns the average of numerical values in a specified column or expression?

Wrapping Up šŸ’”

In this tutorial, we learned about the AVG function in SQL, its syntax, and how to use it in practice. By the end of this lesson, you should be able to calculate averages for various scenarios. Keep practicing and happy coding! šŸ’»

šŸ“ Remember, the AVG function is a powerful tool for analyzing data in SQL, and mastering it will help you better understand your data in real-world projects. šŸ’”

Happy learning! šŸŽ“šŸ’»šŸš€