Aggregating data v16
Like most other relational database products, EDB Postgres Advanced Server supports aggregate functions. An aggregate function computes a single result from multiple input rows. For example, some aggregates compute the COUNT
, SUM
, AVG
(average), MAX
(maximum), and MIN
(minimum) over a set of rows.
As an example, you can find the highest and lowest salaries with the following query:
If you want to find the employee with the largest salary, you might be tempted to try:
This approach doesn't work because you can't use the aggregate function MAX
in the WHERE
clause. This restriction exists because the WHERE
clause determines the rows that go into the aggregation stage. Hence, it has to be evaluated before aggregate functions are computed. However, you can restart the query to accomplish the intended result by using a subquery. The subquery is an independent computation that obtains its own result separately from the outer query.
Aggregates are also useful in combination with the GROUP BY
clause. For example, the following query gets the highest salary in each department.