Agregate functions in SQL
Aggregating functions is used to find values out of our data in SQL. Say for example if we have a books database we can group our data by authors then find out how many total books an author has written by aggregating that query. There are many different aggregating functions in SQL but the ones I am going to focus on today are COUNT, AVG, and MIN.
The COUNT function allows you to count the total number of data in a specific row after we group our data. For example in the screenshot I attached we are using the books table. We are gathering all the first names and last names from the table. Once we do that we group by author first name that way any authors that have the same first name in our table. Once we do that we call the function COUNT(*) to count the number of duplicates in that row. That would give us the total number of books that specific author has written based off our database.
The next function is AVG. This allows you to get the AVG of data that you group by. You would use it in a similar manner as I did in the COUNT function above however this would give you the average by adding up all of your data and dividing by the number of data that is grouped. I attached an example of a students table that I create that have been playing with. It is a bit complicated however we are going to focus just on the AVG(grade) part. We are calling for the columns first name, AVG(grade) and if it is null then it is automatically set to 0. Since we are grouping by the students first name all of the students grades will be grouped in that same row thus we can calculate the average of the grades.
The last aggregate function we are going to discuss is called MIN. Min allows us to get the row that has the minimum value of the row that we pass in the function. For example on or books table we have a column called pages. We can select the title column along with the MIN(pages) that will select the title that has the minimum amount of pages written in it. This is an extremely valuable function especially when we start to deal with data that is huge. In my books data I only have around 20 books total so it is not as big of a deal but when you start dealing with databases with millions of books like amazon then this tool would come in handy.
Comments
Post a Comment