Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Lab Manual

CS130L – Database Systems Lab


Lab No: 07
Topic: Aggregate Functions

Class: BSAI
Semester: II-A
Session: Spring, 2024
Lab Instructor: Asra Masood

Lab Date: ----, 2024


Lab Time: 8:00 - 10:10

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

Instructions

Submission: Use proper naming convention for your submission file. Name the submission
file as Lab_NO_DEGREE_ROLLNUM (e.g. Lab_01_BSAI_00000). Submit the file on Google
Classroom within the deadline. Failure to submit according to the above format would result in
deduction of 10% marks. Submissions on the email will not be accepted.

Plagiarism: Plagiarism cases will be dealt with strictly. If found plagiarized, both the involved
parties will be awarded zero marks in the assignment, all of the remaining assignments, or even
an F grade in the course. Copying from the internet is the easiest way to get caught!

Deadline: The deadlines to submit the assignment are hard. Late submission with marks
deduction will be accepted according to the course policy shared by the instructor. Correct and
timely submission of the assignment is the responsibility of every student; hence no relaxation
will be given to anyone.

Comments: Comment your code properly. Write your name and roll number (as a block
comment) at the beginning of the solution to each problem.
Objectives
InTip
this: lab,
For you
timely
willcompletion
learn: of the assignment, start as early as possible. Furthermore, work
smartly - as some of the problems can be solved using smarter logic.
o1. About
Note: Structure
Follow theADT.
given instructions to the letter, failing to do so will result in a zero.
o How to define a Structure, initialize and refer to individual members of a Structure.

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

Objectives
In this lab, you will learn to:
• Study and implement Order By, Limit, Group By, and Having clause.
• Study and implement Aggregate Functions: COUNT, MAX, MIN, AVG, SUM, STD.

Concepts

Order By clause:
The order of rows returned in a query result is undefined. The ORDER BY clause can be used to sort the
rows. This clause comes last in the SELECT statement. ASC at the end of the ORDER BY clause specifies
ascending order where as DESC specifies descending order. ASC is the default order. The syntax for
an ORDER BY statement is as follows:

SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC];

The selected row will be ordered according to the values in columnA, in either ascending (ASC) (default)
or descending (DESC) order. If several rows have the same value in columnA, it will be ordered according
to columnB, and so on. For strings, the ordering could be case-sensitive or case-insensitive, depending
on the so-called character collating sequence used. For examples,
-- Order the results by price in descending order
SELECT * FROM products WHERE name LIKE 'Pen %' ORDER BY price DESC;

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

-- Order by price in descending order, followed by quantity in ascending (default) order


SELECT * FROM products WHERE name LIKE 'Pen %' ORDER BY price DESC, quantity;

You can randomize the returned records via function RAND(), e.g.,
SELECT * FROM products ORDER BY RAND();

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

LIMIT Clause:
A SELECT query on a large database may produce many rows. You could use the LIMIT clause to limit the
number of rows displayed, e.g.,
-- Display the first two rows
SELECT * FROM products ORDER BY price LIMIT 2;

To continue to the following records, you could specify the number of rows to be skipped, followed by
the number of rows to be displayed in the LIMIT clause, as follows:
-- Skip the first two rows and display the next 1 row
SELECT * FROM products ORDER BY price LIMIT 2, 1;

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

AS - Alias
You could use the keyword AS to define an alias for an identifier (such as column name, table name).
The alias will be used in displaying the name. It can also be used as reference. For example,
-- Define aliases to be used as display names
SELECT productID AS ID, productCode AS Code,
name AS Description, price AS `Unit Price`
FROM products
ORDER BY ID;
-- Use alias ID as reference
Take note that the identifier "Unit Price" contains a blank and must be back-quoted.

Function CONCAT()
You can also concatenate a few columns as one (e.g., joining the last name and first name) using
function CONCAT(). For example,
SELECT CONCAT(productCode, ' - ', name) AS `Product Description`, price FROM products;

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

GROUP BY Clause:
The GROUP BY clause allows you to collapse multiple records with a common value into groups. For
example,
SELECT productCode FROM products GROUP BY productCode;
-- Only first record in each group is shown

GROUP BY by itself is not meaningful. It is used together with GROUP BY aggregate functions (such as
COUNT(), AVG(), SUM()) to produce group summary.
GROUP BY Aggregate Functions: COUNT, MAX, MIN, AVG, SUM, STD
We can apply GROUP BY Aggregate functions to each group to produce group summary report.
The function COUNT(*) returns the rows selected; COUNT(columnName) counts only the non-NULL
values of the given column. For example,
-- Function COUNT(*) returns the number of rows selected
SELECT COUNT(*) AS `Count` FROM products;
-- All rows without GROUP BY clause

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

SELECT productCode, COUNT(*) FROM products GROUP BY productCode;

-- Order by COUNT - need to define an alias to be used as reference


SELECT productCode, COUNT(*) AS count
FROM products
GROUP BY productCode
ORDER BY count DESC;

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

Besides COUNT(), there are many other GROUP BY aggregate functions such as AVG(), MAX(), MIN() and
SUM(). For example,
SELECT MAX(price), MIN(price), AVG(price), STD(price), SUM(quantity)
FROM products;
-- Without GROUP BY - All rows

SELECT productCode, MAX(price) AS `Highest Price`, MIN(price) AS `Lowest Price`


FROM products
GROUP BY productCode;

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

SELECT productCode, MAX(price), MIN(price),


CAST(AVG(price) AS DECIMAL(7,2)) AS `Average`,
CAST(STD(price) AS DECIMAL(7,2)) AS `Std Dev`,
SUM(quantity)
FROM products
GROUP BY productCode;
-- Use CAST(... AS ...) function to format floating-point numbers

HAVING clause
HAVING is similar to WHERE, but it can operate on the GROUP BY aggregate functions; whereas WHERE
operates only on columns.
SELECT productCode AS `Product Code`, COUNT(*) AS `Count`,
CAST(AVG(price) AS DECIMAL(7,2)) AS `Average`
FROM products
GROUP BY productCode
HAVING Count >=3;
-- CANNOT use WHERE count >= 3

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

Lab Task:
Using Sakila Database:
Formulate SQL queries for the following needs and execute them on Sakila database.

1. List the last names of actors, as well as how many actors have that last name.
2. List last names of actors and the number of actors who have that last name, but only for names
that are shared by at least two actors.
3. Find all actors whose last names contain the letters `LI` order the rows by last name and
first name, in that order.
4. Which films have the highest replacement cost?
5. What is the average length of films in each rating category?
6. List the replacement costs for films whose lengths are at least 90 minutes.
7. Get the register date of the first customer.
8. For the customers who ever spent more than 10$ for a single payment, find their latest
payment date.
9. For each customer, list number of staff who served him/her. Show a sample of the first
10 customers.
10. Compute the average replacement cost for each unique value of the length variable.

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies

You might also like