Showing posts with label GROUP BY. Show all posts
Showing posts with label GROUP BY. Show all posts

Wednesday, August 1, 2012

Right use of GROUP BY in SQL-queries

This article is about the right use of grouping in SQL-queries. I wrote the article, because this subject is very important. More than that it is not too much complicated and suits to the format of short useful articles, that my blog is for.

Job interviews like questions concerning grouping (using GROUP BY in SQL-queries). If you don't use SQL-queries every day or don't know them well, refresh your memory before your interview.

Let's take an example. Figure 1 shows a table Persons, which stores information about persons. The table has four column headers: ID, name, dept_name, salary.

First of all we use GROUP BY with aggregation.

Aggregate functions are functions that take a collection of values as input and return a single value. SQL offers five built-in aggregate functions:
  • Average: avg
  • Minimum: min
  • Maximum: max
  • Total: sum
  • Count: count

Consider the query "Find the average salary of persons." Try to write the query by yourself before you look at the solution. We write query as follows: