CS232L-Lab#03
CS232L-Lab#03
LAB 03
SQL CLAUSES-
ORDER BY, GROUP BY, HAVING
Objective
The objective of this session is to get deeper insight of different clauses used along with going
over examples on how to put them to use with select DQL command.
Instructions
• Open the handout/lab manual in front of a computer in the lab during the session.
• Practice each new command by completing the examples and exercise.
• Turn-in the answers for all the exercise problems as your lab report.
• When answering problems, indicate the commands you entered, and the output displayed.
• Try to practice and revise all the concepts covered in all previous session before coming
to the lab to avoid un-necessary ambiguities.
1
CS232-L – LAB 3
After Grouping the data, you can filter the grouped record using HAVING Clause. HAVING
Clause returns the grouped records which match the given condition. You can also sort the
grouped records using ORDER BY. ORDER BY used after GROUP BY on aggregated
column. Clauses help us filter and analyze data quickly. When we have large amounts of data
stored in the database, we use Clauses to query and get data required by the user.
The GROUP BY clause divides the rows returned from the SELECT statement into groups.
For each group, you can apply an aggregate function e.g., SUM() to calculate the sum of
items or COUNT() to get the number of items in the groups. The following statement
illustrates the basic syntax of the GROUP BY clause:
SELECT
column_1,
column_2,
...,
aggregate_function(column_3)
FROM
table_name
GROUP BY
column_1,
column_2,
...;
In this syntax:
• First, select the columns that you want to group e.g., column1 and column2, and
column that you want to apply an aggregate function (column3).
• Second, list the columns that you want to group in the GROUP BY clause.
3.2.1 GROUP BY clause examples
Let’s take a look at the payment table in the sample database of PostgreSQL i.e. dvdrental
2
CS232-L – LAB 3
You can use the GROUP BY clause without applying an aggregate function. The following
query gets data from the payment table and groups the result by customer id.
SELECT
customer_id
FROM
payment
GROUP BY
customer_id;
In this case, the GROUP BY works like the DISTINCT clause that removes duplicate rows
from the result set.
The GROUP BY clause is useful when it is used in conjunction with an aggregate function.
For example, to select the total amount that each customer has been paid, you use the GROUP
BY clause to divide the rows in the payment table into groups grouped by customer id. For
each group, you calculate the total amounts using the SUM() function.
The following query uses the GROUP BY clause to get the total amount that each customer
has been paid:
SELECT
customer_id,
SUM (amount)
FROM
payment
GROUP BY
customer_id;
3
CS232-L – LAB 3
The GROUP BY clause sorts the result set by customer id and adds up the amount that
belongs to the same customer. Whenever the customer_id changes, it adds the row to the
returned result set.
To find the number of payment transactions that each staff has processed, you group the rows
in the payment table by the values in the staff_id column and use the COUNT() function to
get the number of transactions:
SELECT
staff_id,
COUNT (payment_id)
FROM
payment
GROUP BY
staff_id;
The GROUP BY clause divides the rows in the payment into groups and groups them by
value in the staff_id column. For each group, it returns the number of rows by using
the COUNT() function.
4
CS232-L – LAB 3
SELECT
customer_id,
staff_id,
SUM(amount)
FROM
payment
GROUP BY
staff_id,
customer_id
ORDER BY
customer_id;
In this example, the GROUP BY clause divides the rows in the payment table by the values in
the customer_id and staff_id columns. For each group of (customer_id, staff_id),
the SUM() calculates the total amount.
SELECT
DATE(payment_date) paid_date,
SUM(amount) sum
FROM
payment
GROUP BY
DATE(payment_date);
Code language: SQL (Structured Query Language) (sql)
5
CS232-L – LAB 3
The HAVING clause is often used with the GROUP BY clause to filter groups or aggregates
based on a specified condition. The following statement illustrates the basic syntax of
the HAVING clause:
SELECT
column1,
aggregate_function (column2)
FROM
table_name
GROUP BY
column1
HAVING
condition;
In this syntax, the group by clause returns rows grouped by the column1.The HAVING clause
specifies a condition to filter the groups. PostgreSQL evaluates the HAVING clause after
the FROM, WHERE, GROUP BY, and before the SELECT, DISTINCT, ORDER
BY and LIMIT clauses. Since the HAVING clause is evaluated before the SELECT clause,
you cannot use column aliases in the HAVING clause. Because at the time of evaluating
the HAVING clause, the column aliases specified in the SELECT clause are not available.
6
CS232-L – LAB 3
The following query uses the GROUP BY clause with the SUM() function to find the total
amount of each customer:
SELECT
customer_id,
SUM (amount)
FROM
payment
GROUP BY
customer_id;
The following statement adds the HAVING clause to select the only customers who have
been spending more than 200:
SELECT
customer_id,
SUM (amount)
FROM
payment
GROUP BY
customer_id
HAVING
7
CS232-L – LAB 3
The following table shows the comparisons between these two clauses, but the main
difference is that the WHERE clause uses condition for filtering records before any groupings
are made, while HAVING clause uses condition for filtering values from a group.
HAVING WHERE
1. The HAVING clause is used in database 1. The WHERE clause is used in database
systems to fetch the data/values from the groups systems to fetch the data/values from the tables
according to the given condition. according to the given condition.
2. The HAVING clause is always executed with 2. The WHERE clause can be executed without
the GROUP BY clause. the GROUP BY clause.
3. The HAVING clause can include SQL 3. We cannot use the SQL aggregate function
aggregate functions in a query or statement. with WHERE clause in statements.
4. We can only use SELECT statement with 4. Whereas, we can easily use WHERE clause
HAVING clause for filtering the records. with UPDATE, DELETE, and SELECT
statements.
5. The HAVING clause is used in SQL queries 5. The WHERE clause is always used before the
after the GROUP BY clause. GROUP BY clause in SQL queries.
6. It is a post-filter. 6. It is a pre-filter.
When you query data from a table, the SELECT statement returns rows in an unspecified
order. To sort the rows of the result set, you use the ORDER BY clause in
the SELECT statement.
The ORDER BY clause allows you to sort rows returned by a SELECT clause in ascending or
descending order based on a sort expression.The following illustrates the syntax of
the ORDER BY clause:
8
CS232-L – LAB 3
SELECT
select_list
FROM
table_name
ORDER BY
sort_expression1 [ASC | DESC],
...
sort_expressionN [ASC | DESC];
In this syntax:
• First, specify a sort expression, which can be a column or an expression, that you want
to sort after the ORDER BY keywords. If you want to sort the result set based on
multiple columns or expressions, you need to place a comma (,) between two columns
or expressions to separate them.
• Second, you use the ASC option to sort rows in ascending order and the DESC option
to sort rows in descending order. If you omit the ASC or DESC option, the ORDER
BY uses ASC by default.
Due to the order of evaluation, if you have a column alias in the SELECT clause, you can use
it in the ORDER BY clause.
We will use the customer table in the sample database for the demonstration.
The following query uses the ORDER BY clause to sort customers by their first names in
ascending order:
9
CS232-L – LAB 3
SELECT
first_name,
last_name
FROM
customer
ORDER BY
first_name ASC;
Code language: SQL (Structured Query Language) (sql)
Since the ASC option is the default, you can omit it in the ORDER BY.
SELECT
first_name,
last_name
FROM
customer
ORDER BY
last_name DESC;
Code language: SQL (Structured Query Language) (sql)
10
CS232-L – LAB 3
The following statement selects the first name and last name from the customer table and
sorts the rows by the first name in ascending order and last name in descending order:
SELECT
first_name,
last_name
FROM
customer
ORDER BY
first_name ASC,
last_name DESC;
Code language: SQL (Structured Query Language) (sql)
11
CS232-L – LAB 3
In this example, the ORDER BY clause sorts rows by values in the first name column first.
And then it sorts the sorted rows by values in the last name column. As you can see clearly
from the output, two customers with the same first name Kelly have the last name sorted in
descending order.
Practice Problem:
Dane country Airport officials decided that all the information related to the airline
flight should be organized using a DBMS, and you are hired to design the database.
Your first task is to organize the information about all the airplanes stationed and
maintained at the airport. The following relations keep track of airline flight
information:
Flights (flno, from_loc, to_loc, distance, price) //details about all the flights
Aircraft (aid, aname, cruisingrange) //details of the aircraft including the registration
number assigned, model of the craft and the maximum capacity of the craft in terms of
distance it can travel.
Certified (eid, aid) //Certification details of the pilots for specific crafts.
Employees (eid, ename, salary) //details of employees
12
CS232-L – LAB 3
Part A:
1. Create the above-mentioned tables and insert data in tables as given below.
create table flight , (444,'Dallas','Sydeny',10000,52000)
( , (555, 'LA','Singapore',11000,55000)
flight_no number, , (666, 'UK','Atlanta',15000,60000);
from_loc varchar(20), insert all
to_loc varchar(20), into aircraft values (111, 'AD Scout',1000)
distance number, into aircraft values (112, 'Airco', 15000)
price number into aircraft values (113, 'Avis', 9000)
); into aircraft values (114, 'Bernard', 8000)
into aircraft values (115, 'Comte', 20000)
create table aircraft select * from dual;
( insert all
aid number, into employee values (100, 'Oliver', 85000)
aname varchar(20), into employee values (101, 'Jack', 50000)
cruisingrange number into employee values (102, 'Thomas',
); 89000)
into employee values (103, 'George', 10000)
create table certified into employee values (105, 'James', 90000)
( into employee values (106, 'Daneil', 100000)
eid number, into employee values (107, 'Noah', 50000)
aid number into employee values (108, 'Joe', 25000)
); into employee values (109, 'Pheebs', 90000)
into employee values (110, 'Ross', 5000)
create table employee select * from dual;
(
eid number, insert all
ename varchar(20), into certified values (100,114)
salary number into certified values (102,113)
); into certified values (105,112)
insert all into certified values (106,115)
into flight values into certified values (107,111)
(222,'Perth','London',9000,50000) into certified values (108,112)
, (333,'Auckland','Dubai',7000,40000) select * from dual;
Part B:
1. Calculate total tickets price sold for all flights.
4. For each bonus value, check number of employees given same bonus.
SELECT COUNT(EID) AS NO_OF_EMPLOYEES,BONUS FROM
EMPLOYEE GROUP BY BONUS;
13
CS232-L – LAB 3
7. Display sum of salaries of all employees having name starting with ‘J’ and sum of
salaries is above 20000.
SELECT SUM(SALARY) FROM EMPLOYEE WHERE ENAME LIKE 'J%' AND
SALARY>20000;
8. Display aircraft data in descending order based upon their cruising range.
SELECT * FROM AIRCRAFT ORDER BY CRUISINGRANGE DESC;