Explanation of the use of GROUP BY in grouped queries and the SQL execution order

Explanation of the use of GROUP BY in grouped queries and the SQL execution order

In SQL, GROUP BY is used to group data in the results of SELECT. Before using GROUP BY, you need to know some important rules.

  • 1. The GROUP BY clause can contain any number of columns. This means that you can group data within groups, providing more detailed control over data grouping.
  • 2. If you specify multiple groups in the GROUP BY clause, the data will be aggregated on the last specified group.
  • 3. Each column listed in the GROUP BY clause must be a search column or a valid expression (but not an aggregate function). If an expression is used in the SELECT, the same expression must be specified in the GROUP BY clause. Aliases cannot be used.
  • 4. Except for the aggregate calculation statement, each column in the SELECT statement must be given in the GROUP BY clause.
  • 5. If there is a NULL value in the grouping column, NULL will be returned as a group. If there are multiple rows with NULL values, they will be grouped together.
  • 6. The GROUP BY clause must come after the WHERE clause and before the ORDER BY clause.

Filter Groups

Excessive use of the HAVING clause for grouping. The HAVING clause supports all WHERE operations. The difference between HAVING and WHERE is that WHERE filters rows, while HAVING is used to filter groups.

Another way to understand the difference between WHERE and HAVING is that WHERE filters before grouping, while HAVING filters on a per-group basis after grouping.

Grouping and Sorting

Generally, when you use the GROUP BY clause, you should also use the ORDER BY clause. This is the only way to guarantee that the data is sorted correctly.

The execution order of SQL SELECT statement is:

  • 1. The from clause assembles data from different data sources;
  • 2. The where clause filters the rows based on the specified conditions;
  • 3. The group by clause divides the data into multiple groups;
  • 4. Use aggregate functions for calculations;
  • 5. Use the having clause to filter groups;
  • 6. Calculate all expressions;
  • 7. Use order by to sort the result set;
  • 8. Select the collection output.

Let me give you an example.

select candidate name, max(total score) as max total score from tb_Grade
where candidate name is not null
group by candidate name having max(total score) > 600
order by max total score

In the above example, the SQL statements are executed in the following order:

  • 1. First, execute the FROM clause to assemble the data source data from the tb_Grade table
  • 2. Execute the WHERE clause to filter all data in the tb_Grade table that is not NULL
  • 3. Execute the GROUP BY clause to group the tb_Grade table by the "Student Name" column
  • 4. Calculate the max() aggregate function and find the largest values ​​in the total score according to the "total score"
  • 5. Execute the HAVING clause to filter courses with a total score greater than 600 points.
  • 6. Execute the ORDER BY clause and sort the final results by "Max Score".

Note: If join and on are used, on will be executed before where, then join will be executed, and then where will be executed.

Attachment:

Aggregate functions in MySQL:

  • 1. count() returns the number of rows in a column
  • 2. avg() returns the average value of a column
  • 3. max() returns the maximum value of a column
  • 4. min() returns the minimum value of a column
  • 5. sum() returns the sum of a column
  • 6. distinct removes duplicate values

Note: avg() ignores rows with null values, count(*) counts all rows, and count(column) ignores rows with null values

Summarize

The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. Thank you for your support of 123WORDPRESS.COM. If you want to learn more about this, please check out the following links

You may also be interested in:
  • Detailed tutorial on using Group By in SQL
  • Laravel implements Eloquent model group query and returns the number of each group groupBy()
  • Django ORM aggregate query and group query implementation details
  • Detailed explanation of the implementation principle of MySQL group query Group By
  • Detailed explanation of group query and join query statements in MySQL
  • SQL group query problem
  • Detailed explanation of the usage rules of group by in Oracle group query

<<:  Detailed graphic explanation of installing MySQL database and configuring Java project on Linux

>>:  A brief discussion on the lazy loading attribute pattern in JavaScript

Recommend

Example code of CSS layout at both ends (using parent's negative margin)

Recently, during the development process, I encou...

Solution to nginx-ingress-controller log persistence solution

Recently I saw an article on a public account tha...

Seven Principles of a Skilled Designer (1): Font Design

Well, you may be a design guru, or maybe that'...

MySQL query optimization: a table optimization solution for 1 million data

1. Query speed of two query engines (myIsam engin...

Detailed explanation of MySQL transactions and MySQL logs

Transactional Characteristics 1. Atomicity: After...

Introducing icons by implementing custom components based on Vue

Preface In project development, there are many wa...

MySQL 8.0.11 installation and configuration method graphic tutorial (win10)

This article records the installation and configu...

One sql statement completes MySQL deduplication and keeps one

A few days ago, when I was working on a requireme...

Detailed explanation of MySQL three-value logic and NULL

Table of contents What is NULL Two kinds of NULL ...

MySQL 5.7.17 compressed package installation-free configuration process diagram

There are two versions of MySQL database manageme...

Specific usage of fullpage.js full screen scrolling

1.fullpage.js Download address https://github.com...

Free tool to verify that HTML, CSS and RSS feeds are correct

One trick for dealing with this type of error is t...