M358 - The GROUP BY clause
fellstrider.com - the logo!
Home| OU Study Rooms | M358 Index | Block 1 - Information Systems | Block 2 - Relational Theory | Block 3 - SQL
 
The GROUP BY clause

Allows the query to return values from a query to a specific column in a table:

SELECT region, COUNT(*)
FROM student
GROUP BY region;

The SELECT clause in a GROUP BY query can only contain value expressions consisting of the GROUP BY columns or aggregate functions.

Result of the GROUP BY query!

If the GROUP BY facility was not there, each individual region would have to be counted, one by one:

SELECT COUNT(*)
FROM student
WHERE region = '1';   //repeated for each region resulting in numerous queries

Logical processing

Group search conditions

The HAVING clause

Groups from a GROUP BY clause have to satisfy the HAVING clause (where specified) to be processed further. Similar to a WHERE clause but applied to a group of rows instead of individual rows.

SELECT country, COUNT(product), SUM(quantity)
FROM production
GROUP BY country
HAVING SUM(quantity) > 15000;
Result of the HAVING SUM query!

Logical processing

Any column referenced in a predicate in the search condition of a HAVING clause must be a grouping column or have an aggregate function applied.

The ORDER BY clause

Final tables are ordered as per the implementation related to how data is stored. Control over ordering can be specified by an ORDER BY clause in a query statement. There is no influence on table content, only presentation.

SELECT *
FROM staff;                      //No apparent ordering
Result of the no order query!
SELECT *
FROM staff
ORDER BY name;                   //Ordering is ascending by default
Result of the ORDER BY name query!
SELECT *
FROM staff
ORDER BY name ASC;               //Including ASC ketword has no effect
                                   Compare the images above and below
Result of the ORDER BY ASC name query!
SELECT *
FROM staff
ORDER BY name DESC;              //Keyword DESC reverses default ordering
Result of the ORDER BY DESC name query!

Assigning names to expression results is the only way in which ordering can be achieved where the results of value expressions need ordering.

SELECT name, population/area AS pop_density
FROM country
ORDER BY pop_density;
Result of using AS in the query!

Ordering can be specified using more than one column.

SELECT *
FROM enrolment
WHERE student_id NOT IN ('s01', 's04')
ORDER BY student_id, course_code DESC;
Ordering using more than one column!
Home| OU Study Rooms | M358 Index | Block 1 - Information Systems | Block 2 - Relational Theory | Block 3 - SQL
Move on to updating.

Valid CSS! Valid XHTML 1.0!

Comments, suggestions, ideas to
Stuart Banner