Aggregations (ORDER BY, GROUP BY, HAVING, SUM, COUNT, AVG, etc)

ORDER BY

The ORDER BY keyword sorts the records in ascending order by default.

Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Example

SELECT * FROM Customers
ORDER BY Country;

GROUP BY

It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.

Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Example

GROUP BY ROLLUP

Creates a group for each combination of column expressions. In addition, it "rolls up" the results into subtotals and grand totals.

For example, GROUP BY ROLLUP (col1, col2, col3, col4) creates groups for each combination of column expressions in the following lists.

  • col1, col2, col3, col4

  • col1, col2, col3, NULL

  • col1, col2, NULL, NULL

  • col1, NULL, NULL, NULL

  • NULL, NULL, NULL, NULL --This is the grand total

GROUP BY CUBE

GROUP BY CUBE creates groups for all possible combinations of columns.

For GROUP BY CUBE (a, b) the results has groups for unique values of (a, b), (NULL, b), (a, NULL), and (NULL, NULL).

HAVING

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

Syntax

Example

SUM

SUM can be used with numeric columns only. Null values are ignored.

Syntax

Example

COUNT

COUNT is a deterministic function when used without the OVER and ORDER BY clauses.

Syntax

Example

AVG

Syntax

Example

Last updated