ByteBoard Notes Notes

Display classes whose average marks are above 70 using GROUP BY and HAVING

Informatics Practices XII · Experiment 36 of 38 · SQL

12-IPSQL queries
Expt. No.36
Page No.72

GROUP BY with HAVING

Aim

To display each class with its average marks, and then only the classes whose average is above 70.

Concepts used

Queries

USE school;SELECT class, COUNT(*), AVG(marks) FROM result GROUP BY class;SELECT class, AVG(marks) FROM result GROUP BY class HAVING AVG(marks) > 70;SELECT class, MAX(marks) FROM result GROUP BY class ORDER BY MAX(marks) DESC;

A marked line continues the line above it. In your file, write it on the same line.

Table used

Table: result
+-----+-------+-------+-------+
| sid | name  | class | marks |
+-----+-------+-------+-------+
|   1 | Asha  | XII-A |    82 |
|   2 | Rohan | XII-B |    64 |
|   3 | Ira   | XII-A |    88 |
|   4 | Kabir | XII-C |    71 |
|   5 | Diya  | XII-B |    69 |
|   6 | Neel  | XII-C |    77 |
|   7 | Sara  | XII-A |    59 |
+-----+-------+-------+-------+

Output

mysql> USE school; Database changed
mysql> SELECT class, COUNT(*), AVG(marks) FROM result GROUP BY class; +-------+----------+------------+ | class | COUNT(*) | AVG(marks) | +-------+----------+------------+ | XII-A | 3 | 76.3333 | | XII-B | 2 | 66.5000 | | XII-C | 2 | 74.0000 | +-------+----------+------------+ 3 rows in set
mysql> SELECT class, AVG(marks) FROM result GROUP BY class HAVING AVG(marks) > 70; +-------+------------+ | class | AVG(marks) | +-------+------------+ | XII-A | 76.3333 | | XII-C | 74.0000 | +-------+------------+ 2 rows in set
mysql> SELECT class, MAX(marks) FROM result GROUP BY class ORDER BY MAX(marks) DESC; +-------+------------+ | class | MAX(marks) | +-------+------------+ | XII-A | 88 | | XII-C | 77 | | XII-B | 69 | +-------+------------+ 3 rows in set

✓ Printed by running this query set, not typed by hand.

Result

The averages were XII-A 76.3333, XII-B 66.5000 and XII-C 74.0000, so HAVING kept XII-A and XII-C. The last query ordered the classes by their highest marks.

Viva voce: what the examiner may ask

01Where does HAVING go in a query?

After GROUP BY (and before ORDER BY).

02Why can't WHERE be used for AVG(marks) > 70?

WHERE works on single rows before grouping; averages exist only after grouping.

03Can ORDER BY use an aggregate function?

Yes, e.g. ORDER BY MAX(marks) DESC.

Variations for the lab test

  1. Display classes with more than 2 students.
  2. Display the total marks of each class in ascending order.
  3. Display classes whose lowest marks are above 60.
! Common mistake Writing HAVING before GROUP BY gives a syntax error.
Back to the 12-IP index