0% found this document useful (0 votes)
14 views

Lecture 7

Uploaded by

Marnie Omar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lecture 7

Uploaded by

Marnie Omar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

M359 Tutorials

Block3
Lectures (7, 8, 9 and 10)

By/ Waleed Omar (Private Tutor)


Mobile: 0509114811
E-mail:[email protected]
Courses: MT262 + M359 + M255 + M150 + M257
M359 Block3 - Lecture7 Eng/ Waleed Omar

Introduction:
SQL (Structured Query Language) is a language that is designed to carry out these tasks for
relational databases; it has become the standard relational database language. SQL has DDL
and DML components and so provides a single interface to the database. It can be used both as
an embedded language for application processes and interactively as a query language. It is
also intended to be relatively easy to learn and use.

The first name: Structured English Query Language (SEQUEL)


Now changed to Structured Query Language (SQL)

Non-SQL DBMS functions:


SQL is not intended to support all the functions of a DBMS and may be implemented in a
DBMS. For example, there is no storage DDL specified in any SQL Standard, so a variety of
file storage and access methods can be found in different implementations

Retrieval using simple queries: ‫اﻟﺒﺤﺚ ﻋﻦ ﺑﯿﺎﻧﺎت‬


A query specification consists of (at most) the following five clauses:

SELECT <column list> ‫ﺗﺤﺪﯾﺪ اﻟﺤﻘﻮل‬


FROM <table list> ‫اﻟﺠﺪاول‬
WHERE <search condition> ‫ﺷﺮوط اﻟﺒﺤﺚ‬
GROUP BY <grouping column list> ‫ﻋﻤﻞ ﻣﺠﻤﻮﻋﺎت‬
HAVING <search condition> ‫ﺷﺮط ﻟﻠﻤﺠﻤﻮﻋﺎت‬
Order By < column list> ‫ﺗﺮﺗﯿﺐ ﻟﻠﺒﯿﺎﻧﺎت ﺣﺴﺐ ﺣﻘﻮل ﻣﻌﯿﻨﺔ‬

Keywords appear capitalized in this text. The individual parts are clauses.
Every query must contain at least a SELECT clause and a FROM clause. SQL is not case
sensitive for keywords and table names.

The asterisk, *, in the SELECT clause is referring to all the columns in the table.
SELECT * ‫اﻋﺮض ﻛﻞ ﺣﻘﻮل اﻟﺠﺪول‬
FROM treatment;

SELECT DISTINCT patient_id ‫ﻋﺮض أرﻗﺎم اﻟﻤﺮﺿﻰ اﻟﻐﯿﺮ ﻣﺘﻜﺮرة‬


FROM treatment;

The DISTINCT operator in a SELECT clause is used to prevent any duplicate rows occurring
in the final table. ‫ﻟﻤﻨﻊ ﺗﻜﺮار اﻟﺒﯿﺎﻧﺎت‬

The logical processing model:


Processing model can help you understand the effect of different forms of SQL statement. The
output of the processing model is logically equivalent to processing by a DBMS.

The logical processing of a query statement always begins with the FROM clause. The logical
processing ignores details of how to retrieve any stored data required by the query. The model
denes a clause by clause process for obtaining the nal table returned by the query.

Page 1
M359 Block3 - Lecture7 Eng/ Waleed Omar

EXERCISE 2.2
(a) Display the whole of the staff table. ‫اﻋﺮض ﻛﻞ ﺟﺪول اﻟﻤﺪرﺳﯿﻦ‬
(b) List the name and staff number of every member of staff represented in the staff table.
‫اﻋﺮض أرﻗﺎم وأﺳﻤﺎء اﻟﻤﺪرﺳﯿﻦ ﻓﻘﻂ‬
(c) List, without duplication, the staff numbers of every staff member who tutors some
students as represented in the tutors table, together with the student identier of each student
they tutor. ‫اﻋﺮض أرﻗﺎم وأﺳﻤﺎء اﻟﻤﺪرﺳﯿﻦ ﻓﻘﻂ ﻣﻊ ﻣﻨﻊ اﻟﺘﻜﺮار‬
Describe the logical processing, clause by clause, of the query given in the solution to part (c),
and explain your SELECT clause.

Solution:
(a) SELECT *
FROM staff
(b) SELECT name, staff_number
FROM staff

(c) SELECT DISTINCT staff_number, student_id


FROM tutors
For the logical processing model:
1- Processing the FROM clause results in an intermediate table which is the same as the tutors
table.
2- Processing the SELECT DISTINCT clause copies the values from staff_number and
student_id from each row in the intermediate table into a final table, excluding those rows that
contain duplicate values.

Value expressions:- ‫ﻋﻤﻠﯿﺔ ﺣﺴﺎﺑﯿﺔ ﻣﻌﺘﻤﺪة ﻋﻠﻰ ﺑﻌﺾ اﻟﺤﻘﻮل ﻓﻲ اﻟﺠﺪول‬


A value expression is an expression that involves operations on the data that is contained in a
column or columns. a value expression involves some operation or function that is applied to
the values in the required columns of each row to produce the nal column of results.

SELECT price + 0.05 AS increased_price ‫اﺳﻢ ﻣﺴﺘﻌﺎر ﻟﻠﻌﻤﻠﯿﺔ اﻟﺤﺴﺎﺑﯿﺔ‬


FROM drug;

SELECT height/weight AS hw_ratio


FROM patient;

Numeric and string operators:- ‫اﻟﻤﻌﺎﻣﻼت‬


A numeric operator is one of the arithmetic operators +, -, *, /. The columns used in a numeric
expression must be of numeric data type.

The main string operation is concatenation, symbolized by ||. String operations involve
columns of data type character string (i.e. CHAR or VARCHAR), and may include constant
character strings (enclosed in single quotes) with a character string operator.

SELECT patient_id, patient_name, (height/weight)*0.179 AS hw_ratio_in_per_lb


FROM patient;

Write a query that lists the identiers of all patients, their height in inches (1 in = 2.54 cm),
and their weight in stones (1 stone = 6.35 kg). Make sure that your query returns a table that
has columns with unique and meaningful names. ‫ﻋﺮض اﻟﻄﻮل ﺑﺎﻟﺒﻮﺻﺔ واﻟﻮزن ﺑﻮﺣﺪة اﺳﺘﻮن‬
Solution:
SELECT patient_id , height/2.54 AS height_in, weight/6.35 AS weight_stone
FROM patient;
Page 2
M359 Block3 - Lecture7 Eng/ Waleed Omar

Functions:-
A function takes a number of input values, known as its arguments, and returns a single value
SELECT patient_name, LENGTH(patient_name) AS name_length
FROM patient;

The function LENGTH gives you the number of characters in each value of the column
(‫ ﺗﻌﻄﻲ ﻋﺪد ﺣﺮوف اﻟﻨﺺ )اﻟﺤﻘﻞ اﻟﻨﺼﻲ‬Length ‫داﻟﺔ‬

SELECT patient_name, SUBSTR(patient_name, 1, 3) AS substring


FROM patient;

‫ ﺗﻘﺺ ﺟﺰء ﻣﻦ اﻟﻨﺺ وﻧﺤﺪد اﻟﺒﺪاﯾﺔ وﻋﺪد اﻟﺤﺮوف‬SUBSTR

Page 3
M359 Block3 - Lecture7 Eng/ Waleed Omar

Casts ‫ﻟﻠﺘﺤﻮﯾﻞ ﻣﻦ ﻧﻮع ﺑﯿﺎﻧﺎت اﻟﻰ ﻧﻮع اﺧﺮ‬


SQL provides a capability known as a cast, which converts data from one data type to another

SELECT CAST(staff_no AS INT)*2 AS twice_staff_no


FROM nurse;
.‫ﺣﻮﻟﻨﺎ رﻗﻢ اﻟﻤﻤﺮﺿﺔ ﻣﻦ ﻧﺺ اﻟﻰ رﻗﻢ ﻋﺸﺎن ﻧﻘﺪر ﻧﻌﻤﻞ ﻋﻠﯿﮫ ﻋﻤﻠﯿﺔ ﺣﺴﺎﺑﯿﺔ‬

SELECT drug_code, 'GBP'|| CAST(price AS CHAR(4)) AS new_price


FROM drug;
GBP ‫ ﺣﻮﻟﻨﺎ اﻟﺴﻌﺮ ﻟﻨﺺ ﺣﺘﻰ ﻧﺪﻣﺠﺔ ﻣﻊ ﻛﻠﻤﺔ‬CAST(price AS CHAR(4))
Notes about casting:
1- Any numerical value, date–time value or string value can be converted into a character
string value. If the character string is too short to hold the converted value, then the value will
be truncated. So the result of the expression CAST (4.9938 AS CHAR(4)) is ‘4.99’.

2- Any numerical value can be converted to any other numerical value. If the value being
converted does not t into the new data type (such as trying to cast a FLOAT of
value 4 000 000 into a SMALLINT), then an error is generated.

If you try to convert a numerical value to a type with less fractional precision, then the value
will be truncated. So the result of the expression CAST(4.9 AS INTEGER) is 4.

3- Any character string can be converted to any other data type.


The string ‘23.45’ can be cast into a FLOAT or a DECIMAL(5, 3), but not into a DATE. The
string ‘2005-03-02’ can be cast into a DATE, but not a FLOAT or an INTEGER.

Aggregate functions:- ‫دوال اﻟﺘﺠﻤﯿﻊ‬


Aggregate functions produce tables that consist of only a single row of data.

AVG (column): The argument for the aggregate function AVG is a collection of
values defined by an expression which returns a value of numeric data type. AVG
returns the average of the values in the collection. If DISTINCT is included in the
argument, all duplicate values are ignored in the calculation. ‫ﻟﺤﺴﺎب اﻟﻤﺘﻮﺳﻂ ﻟﻌﻤﻮد ﻣﻌﯿﻦ‬

Find the average number of beds of all wards represented in the ward table?
SELECT AVG(number_of_beds) AS average_beds ‫ﻣﺘﻮﺳﻂ ﻋﺪد اﻷﺳِﺮة ﺑﺄﻗﺴﺎم اﻟﻤﺴﺘﺸﻔﻰ‬
FROM ward;

Find the average height of all the patients represented in the patient table?

SELECT AVG(height) AS average_height, ‫ﻣﺘﻮﺳﻂ أوزان وأﻃﻮال اﻟﻤﺮﺿﻰ‬


AVG(weight) AS average_weight
FROM patient;

Find the average height-to-weight ratio of the patients in the patient table, in inches
per pound?

SELECT AVG((height/weight)*0.179) AS avg_hw_ratio_in_per_lb


FROM patient;

Page 4
M359 Block3 - Lecture7 Eng/ Waleed Omar

The COUNT function is used to find the number of rows in a table or the number of values in
a column. COUNT. If DISTINCT is included in the argument, all duplicate values are ignored.
If the collection is empty, then the function results in zero. ‫داﻟﺔ ﺗﺮﺟﻊ ﻋﺪد اﻟﺼﻔﻮف أو اﻟﻘﯿﻢ ﻓﻲ ﻋﻤﻮد‬

How many rows are there in the nurse table? ‫ﻛﻢ ﻋﺪد اﻟﻤﻤﺮﺿﺎت‬
SELECT COUNT(*) AS number_of_nurses
FROM nurse;

SELECT COUNT(patient_name) AS num_patient_names


FROM patient;

SELECT COUNT( DISTINCT patient_name) AS num_distinct_names


FROM patient

The two queries give different results Because the second query applied only on the of
distinct values.

SUM: SUM results in the sum of all values in the collection (numeric data type). If
DISTINCT is included in the argument, all duplicate values are ignored in the calculation.

MAX: results in the maximum value in the collection. In the case of character string data
types, DISTINCT can be included in the argument, but it does not have any effect.

MIN: This aggregate function operates in exactly the same way as MAX, except that it
selects the minimum value in the collection.

SELECT MAX(price) ‫ﻋﺮض أﻛﺒﺮ ﺳﻌﺮ‬


FROM drug

The WHERE clause


WHERE clause which specifies a search condition. Only those rows which satisfy the
condition given in the WHERE clause of a query contribute to its result
The SQL comparison operators are =, <, >, <=, >= and <> (not equal to).

What are the staff numbers of all staff members who are called Jennings?

SELECT staff_number
FROM staff
WHERE name = 'Jennings';

EXERCISE 2.9
Explain why it is necessary for the logical processing of the WHERE clause in the previous
query to be before the SELECT clause?
select ‫ ﻗﺒﻞ‬where ‫ﯾﺘﻢ ﺗﻨﻔﯿﺬ‬
Solution:
If the SELECT clause were processed before the WHERE clause, the column needed to
determine which rows are required would not be available in the intermediate table. The data
required by the condition in the WHERE clause would not then be available.

Q- List the patient identifier and height-to-weight ratio (in in/lb) of every patient represented
in the patient table who has a height-to-weight ratio of less than 0.45 in/lb?
Page 5
M359 Block3 - Lecture7 Eng/ Waleed Omar

SELECT patient_id, (height/weight)*0.179 AS hw_ratio


FROM patient
WHERE (height/weight)*0.179 < 0.45;

Q- What is the average price of the drugs in the drug table that have the type ‘Painkiller’?
‫؟‬Painkiller’ ‫ﻋﺮض ﻣﺘﻮﺳﻂ أﺳﻌﺎر اﻷدوﯾﺔ اﻟﻠﻰ ﻧﻮﻋﮭﺎ‬
SELECT AVG(price) AS average_price
FROM drug
WHERE type = 'Painkiller';

EXERCISE 2.11
What is the average height-to-weight ratio (in cm/kg) of the male patients in the hospital?
Solution:
SELECT AVG(height/weight) AS avg_hw_ratio
FROM patient
WHERE gender = 'M';

The AND, OR and NOT operators:-

List the patient identifier and name of every female patient represented in the patient table
who has either height less than 160 cm or weight more than 60 kg, except for the patient
whose name is ‘Maher’.?

Solution:-
SELECT patient_id, patient_name
FROM patient
WHERE gender = 'F'
AND (height < 160 OR weight > 60)
AND NOT patient_name = 'Maher'

EXERCISE 2.13
(a) Give the details from the student table, except student identification numbers, of all the
students named Ellis or Reeves.
Reeves ‫ أو‬Ellis ‫ﻋﺮض ﻛﻞ ﺗﻔﺎﺻﯿﻞ اﻟﻄﻠﺒﺔ إﻻ رﻗﻢ اﻟﻄﺎﻟﺐ ﻟﻠﻄﻠﺒﺔ اﻟﻠﻰ اﺳﻤﮭﻢ‬

(b) From the table assignment, list the student identification numbers of all the students who
have been awarded a mark of 70 or over on any assignment for a course that does not have
course code c4, together with the course codes of the courses on which they obtained these
marks.
c2 ‫ أوأﻛﺜﺮ وﻟﻢ ﯾﺴﺠﻠﻮا ﻓﻲ اﻟﻜﻮرس‬٧٠ ‫ﻋﺮض رﻗﻢ اﻟﻄﺎﻟﺐ ورﻗﻢ اﻟﻜﻮرس ﻟﻠﻄﻠﺒﺔ اﻟﻠﻰ ﺟﺎﺑﻮا‬
SOLUTION
(a) SELECT name, address, email_address, registration_date, region_number
FROM student
WHERE name = 'ellis' OR name = 'reeves';

(b) SELECT DISTINCT student_id, course_code


FROM assignment
WHERE mark >= 70 AND course_code <> 'c4'

The BETWEEN and IN operators


Page 6
M359 Block3 - Lecture7 Eng/ Waleed Omar

Q- List the prescription number and the quantity of the prescription, as represented in the
prescription table, for which the quantity in the prescription falls within the range 50 to 100 ?
١٠٠‫ و‬٥٠ ‫ﻋﺮض رﻗﻢ اﻟﻮﺻﻔﺔ اﻟﻄﺒﯿﺔ اﻟﻠﻰ ﻛﻤﯿﺘﮭﺎ ﺑﯿﻦ‬

SELECT prescription_no , quantity


FROM prescription
WHERE quantity BETWEEN 50 AND 100

The BETWEEN operator is inclusive. The expression quantity BETWEEN 50 AND 100
means that any value for quantity equal to or between 50 and 100 satisfies the condition.

List the patient identifiers and names of all the patients represented in the patient table whose
patient identifiers are p37, p78 or p87?
p37, p78 or p87 ‫اﻋﺮض اﻟﻤﺮﺿﻰ اﻟﻠﻰ أرﻗﺎﻣﮭﻢ‬

SELECT patient_id, patient_name


FROM patient
WHERE patient_id IN ('p37', 'p78', 'p87')

The operator IN is used when a value in the column being compared is equal to one of the
values given in the list.

Both BETWEEN and IN can be used with NOT


WHERE a NOT BETWEEN b AND c
WHERE NOT (a BETWEEN b AND c)
WHERE credit NOT IN (30, 60)

EXERCISE 2.14
(a)Formulate a query to find from the nurse table the staff numbers and names of all the nurses
whose names lie alphabetically between ‘Descartes’ and ‘Sesonske’ inclusive.
(b) Using the University database, write a query that uses the IN operator to find the student
identification numbers and course codes of all those students who sat the examinations in
Bedford, Taunton or Bath, according to the examination table.

(c) Rewrite the WHERE clause of your solution to part (b) so that the query does not use the
IN operator.
SOLUTION
(a) SELECT staff_no, nurse_name
FROM nurse
WHERE nurse_name BETWEEN 'Descartes' AND 'Sesonske'

(b) SELECT student_id, course_code


FROM examination
WHERE examination_location IN ('Bedford', 'Taunton', 'Bath')

(c) The most directly comparable form of the clause is:


WHERE examination_location = 'Bedford'
OR examination_location = 'Taunton'
OR examination_location = 'Bath'
The LIKE operator:- ‫ﻟﻠﺒﺤﺚ ﻋﻦ ﺟﺰء ﻣﻦ اﻟﺤﻘﻞ‬
Page 7
M359 Block3 - Lecture7 Eng/ Waleed Omar

Which is used to match a value from a column (of some string type) with a known string or
part of a string. NOT can also be used, as NOT LIKE.

List all the drug names in the drug table which begin with a ‘c’?
‫ ؟‬c ‫اﻋﺮض اﻟﺪواء اﻟﻠﻰ اﺳﻤﮫ ﯾﺒﺪأ ﺑﺤﺮف‬
SELECT drug_code, drug_name
FROM drug
WHERE drug_name LIKE 'c%';

è underscore character, _, stands for any single character,


While the percentage symbol,%, stands for any sequence of zero or more characters.

EXERCISE 2.16
(a) Notice that all painkillers in the drug table have a code beginning with a ‘P’. Write a query
to list the names of all the drugs in the drug table that are painkillers, by using a LIKE query to
find values in the drug_code column which begin with ‘P’.
(b) Write and run a query that finds the ward number and ward name of every ward in the
ward table whose name includes the letter ‘a’.
SOLUTION 2.16
(a) SELECT drug_name
FROM drug
WHERE drug_code LIKE 'P%'

(b) SELECT ward_no, ward_name


FROM ward
WHERE ward_name LIKE '%a%'

Using joins:- ‫رﺑﻂ اﻟﺠﺪاول‬


The Cartesian product of two tables is another table, which consists of all possible pairs of
rows from the two tables.

SELECT *
FROM small_occupied_by, small_ward

The process of forming pairs of rows by matching the contents of two related columns, taking
data from each of the original tables, is called a join of the tables.

SELECT patient_id, small_ward.ward_no, ward_name


FROM small_occupied_by, small_ward
WHERE small_occupied_by.ward_no = small_ward.ward_no;

EXERCISE 2.18

Page 8
M359 Block3 - Lecture7 Eng/ Waleed Omar

(a) Using the University database, write a query that uses the tutors table to list the
identification number of each student who is tutored by a member of staff whose staff number
is either 3158 or 8431, together with the code of the course for which they are tutored.
3158 or 8431 ‫ﻋﺮض رﻗﻢ اﻟﻄﺎﻟﺐ ورﻗﻢ اﻟﻜﻮرس ﻟﻠﻄﻠﺒﺔ اﻟﻠﻰ ﯾﺪرﺳﮭﻢ أي ﻣﺪرس رﻗﻤﮫ‬
(b) Modify your answer to part (a), using a join, so that the final result also includes the names
of the students. Identify the join condition.
(‫ﻋﺪل اﻻﺳﺘﻌﻼم وﺿﯿﻒ اﺳﻢ اﻟﻄﺎﻟﺐ ) ﻣﻮﺟﻮد ﻓﻲ ﺟﺪول اﻟﻄﻠﺒﺔ‬

SOLUTION
(a)
SELECT student_id, course_code
FROM tutors
WHERE staff_number IN ('3158', '8431')

(b)
SELECT student.student_id, name, course_code
FROM student, tutors
WHERE student.student_id = tutors.student_id
AND staff_number IN ('3158', '8431')

EXERCISE 2.19
(a) If a FROM clause refers to two tables, one consisting of 10 rows and the other 20 rows,
how many rows will be contained in the intermediate table resulting from the logical
processing of this clause?
(b) What does a join condition do?

SOLUTION 2.19
(a) 10*20 = 200.
(b) A join condition imposes a condition on those columns which represent a
relationship between the tables being joined so that only those rows satisfying the
condition appear in the final table.

Aliases and self joins


SQL allows you to provide an alternative name for each reference to a particular table in a
query. This alternative name is called a table alias. There are two advantages of using aliases.
· Some queries can be made more readable by renaming the tables in the FROM clause
with an alias.
· Queries which involve joining a table to itself (called self joins or recursive) are only
possible with the use of aliases.

EXERCISE 2.20
(a) and run a query that does not use aliases to list the name and address for each student and
their tutor. ‫ﻋﺮض اﺳﻢ وﻋﻨﻮان اﻟﻄﻠﺒﺔ واﻟﻤﺪرﺳﯿﻦ‬
(b) Write and run a second query which does use aliases which gives the same result as your
solution to part (a).
SOLUTION
(a) SELECT student.name, student.address, staff.name, staff.address
FROM student, staff, tutors
WHERE student.student_id = tutors.student_id
AND staff.staff_number = tutors.staff_number
(b)
Page 9
M359 Block3 - Lecture7 Eng/ Waleed Omar

SELECT s1.name, s1.address, s2.name, s2.address


FROM student s1, staff s2, tutors t
WHERE s1.student_id = t.student_id
AND s2.staff_number = t.staff_number

EXERCISE 2.22
A supermarket database contains a table called floor_staff with columns staff_no, name and
supervisor_no .write a query to find the name of the supervisor of the member of the floor
staff who has staff number 345. ٣٤٥ ‫ﻣﻄﻠﻮب ﻋﺮض ﻣﺪﯾﺮ اﻟﻤﻮﻇﻒ اﻟﻠﻰ رﻗﻤﮫ‬

SOLUTION
SELECT f2.name
FROM floor_staff f1, floor_staff f2
WHERE f2.staff_no = f1.supervisor_no
AND f1.staff_no = '345'

Inner joins
The SQL join operation combines rows from two tables by taking related pairs of rows, one
from each table. The rows that make up the joined table are those where the data in the
matching columns in each of the two tables satisfies the join condition.

The type of join we have considered so far is known as an inner join. SQL has an alternative
syntax for inner joins that makes this explicit using the keywords INNER JOIN and ON as part
of the FROM clause. In this syntax there is no WHERE clause.

EXERCISE 2.23
Rewrite the solution to Exercise 2.22 using the INNER JOIN syntax
SOLUTION
SELECT f2.name
FROM floor_staff f1 INNER JOIN floor_staff f2
ON f2.staff_no = f1.supervisor_no
WHERE f1.staff_no = '345'

Natural joins ‫ﯾﺘﻢ اﻟﺮﺑﻂ اﺗﻮﻣﺎﺗﯿﻚ ﺑﺎﻟﺤﻘﻮل اﻟﻤﺘﻄﺎﺑﻘﺔ ﻓﻲ اﻻﺳﻢ ﺑﯿﻦ اﻟﺠﺪوﻟﯿﻦ‬
SQL provides the syntax for natural joins on tables.
SELECT *
FROM course c, quota q
WHERE c.course_code = q.course_code;

Where a join is required on tables by making identical column names equal, is very common.
SQL allows the use of the keyword NATURAL JOIN to provide shorthand under such
circumstances.

EXERCISE 2.24
We wish to know which prescription numbers were used to treat the relevant symptoms. Using
the Hospital database, write a query using NATURAL JOIN which gives, for each prescription
number in the prescription table, the reasons for a particular prescription to be made.
SOLUTION
SELECT prescription_no , reason
FROM treatment NATURAL JOIN prescription
The GROUP BY clause:-
Page 10
M359 Block3 - Lecture7 Eng/ Waleed Omar

EXERCISE 2.25
How you would find out how many students are registered in each region from the University
database. (Hint: you will need more than one query.) ‫اﻋﺮض ﻋﺪد ﻃﻼب ﻛﻞ ﻣﻨﻄﻘﺔ‬
Solution:-
SELECT region_number, COUNT(*) AS number_of_students
FROM student
GROUP BY region_number;

The columns that appear in a SELECT clause in such a query must be: either
(a) A grouping column – that is a column specified in the GROUP BY clause with the same
value in every row of each group (e.g. region_number) ‫اﻟﺤﻘﻞ اﻟﻠﻰ ﺑﻨﻘﺴﻢ اﻟﺠﺪول ﺣﺴﺐ ﺗﻜﺮار ﻗﯿﻤﮫ‬
(b) A column contained within an aggregate function which results in one value for every
group. ‫اﻟﺤﻘﻮل اﻟﺘﻲ ﻧﻌﺮﺿﮭﺎ‬

SELECT drug_name, MAX(price) AS max_price


FROM drug
GROUP BY type

This query not well formed because a column, drug_name, appears in the SELECT
clause which neither has an aggregate function applied to it nor appears in the
GROUP BY clause.

For the courses with codes c2 and c4, list the course code and the number of students enrolled
on that course according to the enrolment table.
c2 or c4 ‫ﻋﺮض ﻋﺪد اﻟﻄﻼب اﻟﻤﺴﺠﻠﯿﻦ ﻓﻲ اﻟﻜﻮرس‬
SELECT course_code, COUNT(student_id) AS number
FROM enrolment
WHERE course_code IN ('c2', 'c4')
GROUP BY course_code

All the columns in the SELECT clause must appear in the grouping clause (but not necessarily
the other way around).

-:‫اﺳﺘﻌﻼم ﻟﻌﺮض ﻋﺪد اﻟﻮاﺟﺒﺎت ﻟﻜﻞ ﻃﺎﻟﺐ ﻓﻲ ﻛﻞ ﻛﻮرس‬


SELECT student_id, course_code, COUNT(*) AS number
FROM assignment
GROUP BY student_id, course_code;

Use the Hospital database to write a query that uses the table patient to list, for each ward
number except wards w5 and w7, the number of patients who occupy that ward.
SOLUTION
SELECT ward_no, COUNT(patient_id) AS occupying
FROM patient
WHERE ward_no NOT IN ('w5', 'w7')
GROUP BY ward_no
The HAVING clause:-
Page 11
M359 Block3 - Lecture7 Eng/ Waleed Omar

HAVING operates on the results of aggregate functions. so whole groups must satisfy the
search condition in a HAVING clause in order to be processed further.
Any column referenced in an expression in the search condition of a HAVING clause must be
a grouping column or must have an aggregate function applied to it.

Q: For each type of drug represented in the drug table, list the number of drugs of that type
and the lowest price of any drug of that type, provided that the minimum price is at least 0.15.

SELECT type, COUNT(drug_name) AS number, MIN(price) AS lowest_price


FROM drug
GROUP BY type
HAVING MIN(price) > 0.15;

EXERCISE 2.29
For the courses with codes c2 and c4, list the course code and the number of students enrolled
on that course according to the enrolment table (by having clause)?

SOLUTION
SELECT course_code, COUNT(student_id) AS number
FROM enrolment
GROUP BY course_code
HAVING course_code IN ('c2', 'c4')

EXERCISE 2.31
Are the following three queries well formed? If not, why not?
(a)
SELECT type, COUNT(drug_name) AS number, MIN(price) AS lowest_price
FROM drug
GROUP BY type
HAVING MIN(price) > 0.15
AND drug_code NOT IN ('B23', 'B48')

Not well formed because the HAVING clause refers to a column, drug_code, which
neither has an aggregate function applied to it nor is a grouping column.

(b) SELECT type, COUNT(drug_code) AS number,


AVG(price) AS average_price
FROM drug
WHERE MAX(drug_name) >= 'G'
GROUP BY type
HAVING AVG(price) >= 0.30

Not well formed because the WHERE clause contains an aggregate function.

(c) SELECT type, SUM(price) AS total_price


FROM drug
GROUP BY type
WHERE drug_name >= 'G'
HAVING SUM(price) > 1.00
OR type IN ('Placebo', 'Painkiller')

Page 12
M359 Block3 - Lecture7 Eng/ Waleed Omar

Not well formed because the WHERE and GROUP BY clauses have been written in
the wrong order.

EXERCISE 2.32
(a) For each patient for whom more than one prescription has been written, list the patient
identifier for that patient, the number of prescriptions that have been written for him or her,
and the date of the earliest of those prescriptions
(b) How would you modify the query you wrote in part (a) to exclude treatments administered
by the member of staff whose staff number is 462?
(c) How would you modify the query of part (b) to exclude the patient whose patient identifier
is p39?

SOLUTION
(a)
SELECT patient_id, COUNT(prescription_no) AS prescription_count,
MIN(start_date) AS earliest_prescription
FROM prescription
GROUP BY patient_id
HAVING COUNT(prescription_no) > 1

(b) Add the following clause after the FROM clause


WHERE staff_no <> '462'

(c) One way is to amend the following clause after the FROM clause:
WHERE patient_id <> 'p39'

Another way is to amend the HAVING clause to:


HAVING COUNT(prescription_no) > 1
AND patient_id <> 'p39'
This is possible because patient_id is a grouping column.

The ORDER BY clause:-


A query can be augmented with an ORDER BY clause within a query statement to provide
control over the sequencing of the rows in an output table. It simply controls the presentation
of that table. The clause is the last step in the logical processing of the query

List all the information in the staff table, ordered so that the values in the name column are
sorted into alphabetical order?

SELECT *
FROM staff
ORDER BY name;

By default, the ORDER BY clause assumes that the rows are to be sorted in ascending order.
ORDER BY name ASC ‫ﺗﺮﺗﯿﺐ ﺗﺼﺎﻋﺪي‬
ORDER BY name DESC ‫ﺗﺮﺗﯿﺐ ﺗﻨﺎزﻟﻲ‬

SELECT *
FROM drug
WHERE type <> 'Placebo'
ORDER BY type, price DESC

Page 13
M359 Block3 - Lecture7 Eng/ Waleed Omar

EXERCISE 2.43
Write and run a query to answer the following request:
For the staff members, whose identifiers are 5324 and 8431, list those courses for which they
tutor more than one student, and give the number of students that they tutor on those courses.

SOLUTION
SELECT course_code, staff_number,COUNT(student_id) AS number_tutored
FROM tutors
WHERE staff_number IN ('5324', '8431')
GROUP BY course_code, staff_number
HAVING COUNT(student_id) >= 2

Retrieval using composite queries:-


The UNION operator:- (‫اﺗﺤﺎد اﺳﺘﻌﻼﻣﯿﻦ)ﻋﺪد وﻧﻮع اﻟﺤﻘﻮل ﻻﺑﺪ ﯾﻜﻮن ﻣﺘﻄﺎﺑﻖ‬
The UNION operator constitutes a way of combining the results of separate, compatible
queries.

Provide a table which contains the staff number, name and position of each doctor and nurse
working in the hospital. The table should represent a nurse’s position as ‘Nurse’.

SELECT staff_no, doctor_name As staff_name, position


FROM doctor
UNION
SELECT staff_no, nurse_name, 'Nurse'
FROM nurse;

Note that the third column of the table resulting from second query contains the constant
‘Nurse’. This is simply a value expression. It yields the same constant value no matter what
other values there might be in each row.
Notes:
· UNION is unusual in SQL processing in that it automatically removes duplicate rows.
If you particularly do not want duplicate rows to be removed, then you can use the
operator UNION ALL.

· The final column names are defined by the first query of those composed with UNION.

· Each query specification results in a final table. These tables must be union compatible,
that is, they must have the same number of columns and corresponding columns must
have the same data types.

We require a table that contains, in the first column, the name of each patient in the patient
table and the name of each nurse in the nurse table, and in the second column, the height of
each patient and the string ‘Unknown’ for each nurse (as the database does not contain the
nurses’ heights).

SELECT patient_name, CAST(height AS VARCHAR(4))


FROM patient
UNION
SELECT nurse_name, 'Unknown'
FROM nurse

Page 14
M359 Block3 - Lecture7 Eng/ Waleed Omar

Using EXCEPT and INTERSECT:-


This query shows the EXCEPT operation, which lists the difference between two result sets.

What are the student identifier and course code of each enrolment that has been made, for
which no assignment has been submitted?
‫ﻋﺮض اﻟﻄﻠﺒﺔ اﻟﻠﻰ ﺳﺠﻠﻮا ﻓﻲ ﻣﻮاد وﻟﻢ ﯾﺴﻠﻤﻮا أي واﺟﺒﺎت‬
SELECT student_id, course_code
FROM enrolment
EXCEPT
SELECT student_id, course_code
FROM assignment

What are the student identifier and course code of each enrolment where the student has both
submitted an assignment and taken an examination?
‫ﻋﺮض اﻟﻄﻠﺒﺔ اﻟﻠﻰ ﺳﺠﻠﻮا ﻓﻲ ﻣﻮاد واﺧﺘﺒﺮوا ﻓﯿﮭﺎ ؟‬
SELECT student_id, course_code
FROM assignment
INTERSECT
SELECT student_id, course_code
FROM examination
.
What are the staff numbers of the nurses who do not supervise other nurses in the
hospital?
‫ﻋﺮض اﻟﻤﻤﺮﺿﺎت اﻟﺘﻲ ﻻ ﺗﺸﺮف ﻋﻠﻰ ﻣﻤﺮﺿﺎت أﺧﺮى؟‬
SELECT staff_no
FROM nurse
EXCEPT
SELECT supervisor
FROM supervises

Write an alternative to the following filed statement which does not use the UNION operator.
SELECT *
FROM drug
WHERE type = 'Painkiller'
UNION
SELECT *
FROM drug
WHERE type = 'Antibiotic'
UNION
SELECT *
FROM drug
WHERE type = 'Sedative'

Solution:-
SELECT *
FROM drug
WHERE type IN ('Painkiller', 'Antibiotic', 'Sedative')

Page 15
M359 Block3 - Lecture7 Eng/ Waleed Omar

Using the University database, write and run a query which lists, for the course with code c4,
the student identifier of each student who has submitted some assessed material for that
course, and the mark received for that assessed material.

The table generated by the query should also contain a third column named
assessment_number, which contains the number 99 if the row represents an examination, or
the assignment number if the row represents an assignment.

SELECT student_id, assignment_number AS assessment_number, mark


FROM assignment
WHERE course_code = 'c4'
UNION
SELECT student_id, '99' , mark
FROM examination
WHERE course_code = 'c4'

List the names of the students as well as their identification numbers?


(Hint: you will need to use a join.)

SELECT a.student_id, name,


assignment_number AS assessment_number, mark
FROM assignment a, student s
WHERE a.student_id = s.student_id
AND course_code = 'c4'
UNION
SELECT e.student_id, name, '99', mark
FROM examination e, student s
WHERE e.student_id = s.student_id
AND course_code = 'c4'

EXERCISE 3.3
The UNION operator is said to be commutative because if A and B are two union compatible
tables, then A UNION B and B UNION A give tables with the same rows. Are INTERSECT
and EXCEPT commutative?

SOLUTION 3.3
INTERSECT is commutative. Because the table generated by INTERSECT contains the rows
that are common to both tables, the order in which the tables are presented to INTERSECT
does not matter.
EXCEPT is not commutative.

Page 16

You might also like