Practical 7 - Aggregrate Functions - CSU357P - Shoolini U

Practical 7: Aggregrate Functions

7. Aggregate Functions in SQL

Aggregate functions are essential for summarizing data in SQL. They operate on a set of values and return a single value. Here, we cover key aggregate functions:

Aggregate functions compute results based on a column of numeric data returned by a SELECT statement. They summarize the results of a selected data column. These functions are integral to the GROUP BY clause but can also be used independently.

7.1. Usage Examples

The following examples demonstrate how to use aggregate functions in SQL:

7.1.1. Calculating Average Salary
SELECT AVG(salary) FROM employee;

This query returns the average salary of all employees.

7.1.2. Average Salary for Specific Job Title

SELECT AVG(salary)
FROM employee
WHERE title = 'Programmer';

This query returns the average salary for employees with the title 'Programmer'.

7.1.3. Counting Rows in a Table
SELECT COUNT(*) FROM employees;

This query returns the number of rows in the employees table.

7.2. Review Exercises

  1. Select the maximum price of any item ordered in the items_ordered table.
  2. Select the average price of all items ordered in December.
  3. Count the total number of rows in the items_ordered table.
  4. Find the lowest price of tents ordered in the items_ordered table.

7.3. Exercise Answers

7.3.1. Exercise #1
SELECT MAX(price) FROM items_ordered;
7.3.2. Exercise #2

SELECT AVG(price)
FROM items_ordered
WHERE order_date LIKE '%Dec%';
7.3.3. Exercise #3
SELECT COUNT(*) FROM items_ordered;
7.3.4. Exercise #4

SELECT MIN(price)
FROM items_ordered
WHERE item = 'Tent';