Lecture 7
Lecture 7
Block3
Lectures (7, 8, 9 and 10)
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.
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;
The DISTINCT operator in a SELECT clause is used to prevent any duplicate rows occurring
in the final table. ﻟﻤﻨﻊ ﺗﻜﺮار اﻟﺒﯿﺎﻧﺎت
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
denes 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 identier 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
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.
Write a query that lists the identiers 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 داﻟﺔ
Page 3
M359 Block3 - Lecture7 Eng/ Waleed Omar
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.
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?
Find the average height-to-weight ratio of the patients in the patient table, in inches
per pound?
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;
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.
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
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';
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';
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 ?
١٠٠ و٥٠ ﻋﺮض رﻗﻢ اﻟﻮﺻﻔﺔ اﻟﻄﺒﯿﺔ اﻟﻠﻰ ﻛﻤﯿﺘﮭﺎ ﺑﯿﻦ
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 اﻋﺮض اﻟﻤﺮﺿﻰ اﻟﻠﻰ أرﻗﺎﻣﮭﻢ
The operator IN is used when a value in the column being compared is equal to one of the
values given in the list.
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'
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%';
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%'
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.
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.
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
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. اﻟﺤﻘﻮل اﻟﺘﻲ ﻧﻌﺮﺿﮭﺎ
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).
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.
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.
Not well formed because the WHERE clause contains an aggregate function.
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
(c) One way is to amend the following clause after the FROM clause:
WHERE patient_id <> 'p39'
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
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’.
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).
Page 14
M359 Block3 - Lecture7 Eng/ Waleed Omar
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.
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