Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when are aggregate functions executed in sql (like sum(),max().. etc)

As per my knowledge group by clause is executed before the select statement.

So if we have a sum() function in a select statement,when is that function exactly executed?

for eg in the below query

select c1,sum(c2)
from table
group by c1;

is sum(c2) executed when the grouping takes place?If yes,then how does it know that it has to perform sum() and not anything else ,because group by happens before the select clause. Or is it something else?

Thank You!

like image 878
SuperAadi Avatar asked Sep 03 '25 15:09

SuperAadi


2 Answers

As per my knowledge group by clause is executed before the select statement.

This is incorrect. The only "ordering" implicit in an SQL statement is the logical order of interpretation of the query. This specifies that identifiers are first interpreted based on the FROM clause, then the WHERE clause, and so on.

A SELECT statement describes the result set. The SQL engine is free to produce the result set in whatever ways it sees fit. This usually consists of two phases, the compilation phase and the optimization phase. The interpretation of identifiers is in the compilation phase.

What actually gets executed is typically a directed-acyclic graph (DAG) of operations. The query gets compiled into this structure. Most databases support a method of seeing what actually gets executed, typically via an explain method. The DAG can rearrange operations and even eliminate some (if they are not needed).

like image 125
Gordon Linoff Avatar answered Sep 05 '25 04:09

Gordon Linoff


Aggregate functions in SQL is executed after GROUP BY clause.

like image 27
B.LeeN Avatar answered Sep 05 '25 04:09

B.LeeN