Vous êtes sur la page 1sur 53

School of Computer Science

Introduction to SQL Using Oracle

2014/2015-CS

Example Queries and ExercisesRelational Database


Management Systems
Hatfield Hospital Database..........................................................................................2
Using SQL to Manipulate the Data................................................................................4
Data Manipulation Language DML........................................................................4
Retrieving Data from the Database................................................................................5
Queries which use only one table...............................................................................5
Queries involving more than one table (Joins and Nested Select Statements)..........6
Aggregate Functions..................................................................................................9
Modifying the Database : Inserting & Updating......................................................11
Modifying the Database : Deleting..........................................................................12
Queries with Dates...................................................................................................12
Pattern Matching......................................................................................................14
Joining a Table with itself........................................................................................15
Further SQL Examples.............................................................................................16
Using NULL values..................................................................................................18
Calculations..............................................................................................................18
Data Independence.......................................................................................................19
Logical Data Independence......................................................................................19
Physical Data Independence.....................................................................................19
Views........................................................................................................................19
Updating Views........................................................................................................22
Advantage of Views.................................................................................................24
Data Definition Language (DDL)................................................................................24
Creating Tables.........................................................................................................25
Oracle Data Types....................................................................................................25
Creating an Index.....................................................................................................26
Appendix A SQL PRACTICE...................................................................................27
SECTION A.............................................................................................................27
SECTION B.............................................................................................................29
SECTION C.............................................................................................................30
SECTION D.............................................................................................................31
SECTION E..............................................................................................................31
SECTION F..............................................................................................................32
Appendix B SQL PRACTICE Answers.................................................................33
SECTION A.............................................................................................................33
SECTION B.............................................................................................................34
SECTION C.............................................................................................................35
SECTION D.............................................................................................................36
SECTION E..............................................................................................................37
SECTION F..............................................................................................................38
Appendix C Retrieval with SQL Reference...........................................................40
SQL Booklet 2014-15

Appendix D Using SQL Developer...........................................................................42

SQL Booklet 2014-15

Hatfield Hospital Database


The database consists of three tables, populated as follows:
PATIENT (SELECT * FROM patient;)

DRUG (SELECT * FROM drug;)

DOSE (SELECT * FROM dose;)

An IMPORTANT NOTE about DATES.


Note: Although the years are abbreviated to their 2 digit format in this
display, they are in fact held in full within the database. Thus the dates in
Patient and Drug (DOI and DOB) precede those in Dose.
If you use the 2 digit format to enter new data Oracle will assume that you
are referring to the current century. So, for example, if you add, a new
patient actually born in 1985 using the dd-mmm-yy format, the date of
birth stored will be some time in 2085! To avoid this use the format ddmmm-yyyy.
SQL Booklet 2014-15

PATIENT lists all the patients at the HATFIELD hospital.


The attributes have the following meanings:
PNO
PNAME
TITLE
DOB
CHILDREN
GP

an identifying number unique to each patient


the family name of the patient
the style of address for each patient ( this is limited to mr,
mrs, miss, ms)
the date of birth of the patient
the number of children the patient has
the name of the patients general practitioner (local
medical doctor)

DRUG lists all the drugs used by the HATFIELD hospital


The attributes have the following meanings:
DNO
DNAME
UNIT
DOI
COST

an identifying number unique to each drug


the commonly used name for the drug
the unit of measure for dispensing the drugs
( tab=available in tablet form, mg=millegrammes, gm =
grammes)
date the drug was introduced
the cost of the drug per unit dispensed. The cost is in
pounds sterling, there are 100 pence to the pound.

DOSE lists which drugs were given to which patients on which dates and in
what quantity.
The attributes have the following meanings:
PNO
DNO
DOSEDATE
QTY

SQL Booklet 2014-15

identifies the patient


identifies the drug
the date on which the drug was given to the patient
the quantity of the drug (in dispensed units) given to the
patient

Using SQL to Manipulate the Data


Data Manipulation Language DML

Required manipulation

SQL keyword

Add data to the database

INSERT

Change data already in the database

UPDATE

Delete data from the database

DELETE

Get data out of the database

SELECT

BASIC FORMAT of select statement:


SELECT
FROM
WHERE

SQL Booklet 2014-15

a1,a2,.
r1,r2,.
p;

[attribute(s)]
[relation(s)]
[predicate]

Retrieving Data from the Database


Queries which use only one table
1.

List all the details of all the drugs in the database.


select
from

*
drug ;

Result is output of the complete drug table (as on page 2)


Note: the use of * to mean all the attributes
2.

Get the drug names of all drugs in the database together with their code
numbers ( Projection ).
select
from

dname, dno
drug ;

The result contains all the rows in drug table but just showing the two
named columns in the order specified:

3.

Retrieve the names of all drugs in tablet form ( Selection ) :


select
from
where

dname
drug
unit = 'tab' ;

Notice that just the rows meeting the condition are selected.
4.

Retrieve the identifiers of drugs in tablet form which cost more than 50
pence each.
select
dno
from
drug
where
unit='tab'
and
cost>0.50;

5.

List patient identifiers of patients who have Dr. Spock, Dr. Taylor, or Dr.
Thatcher as their GP.

SQL Booklet 2014-15

select
from
where
or
or

pno
patient
gp='Dr.Spock'
gp='Dr.Taylor'
gp='Dr.Thatcher';

Alternatively:
select
pno
from
patient
where
gpin
('Dr.Spock','Dr.Taylor',
'Dr.Thatcher');

6.

Get the patient identifiers of all patients except those of Drs Spock, Taylor
and Thatcher.

select
pno
from
patient
where
gpnotin
('Dr.Spock',Dr.Taylor',
'Dr.Thatcher');

You should now try SQL Practice SECTION A (answers are also included).
You might need to refer to the section: Retrieval with SQL Reference.

SQL Booklet 2014-15

Queries involving more than one table (Joins and Nested Select Statements).
An NOTE about JOINS.
Those who took Data Driven Systems last year, will have been taught the
JOIN syntax based in the FROM clause:
i.e.
SELECT t1.col_a, table2.col_b
FROM table1 t1 JOIN table2 t2
ON t1.col_pk = t2.col_fk;
This workbook will also introduce another method for joining tables
which you may have met in other learning environments. This utilises a
list of tables to be joined in the FROM clause and then join condition (s)
in the WHERE clause (alongside standard SELECTION conditions)
i.e.
SELECT t1.col_a, table2.col_b
FROM table1 t1, table2 t2
WHERE t1.col_pk = t2.col_fk;
It is advisable that you stick to one method or the other, the choice
you make will not affect any marks awarded for assessments
undertaken during this course.

7.

I want the patient names of patients who have been given drug d7.
Here we need information from two tables; patient because that contains
the patients name, and dose because that records which patients have
taken which drugs. Therefore I can join the tables to produce a temporary
table which includes all the columns I need to report on:

select
p.pname
from
patientpJOINdosed
ONp.pno=d.pno
where
d.dno='d7';
OR
select
from
where
and

SQL Booklet 2014-15

p.pname
patientp,dosed
p.pno=d.pno
d.dno='d7';

8.

Alternatively, one query can be nested inside another, note that there can
be only one attribute in the where clause of the outer query, and the use of
the IN keyword captures the potential for more than one row returned from
the inner query.
select
from
where

pname
patient
pnoin
(selectpno

fromdose

wheredno='d7');

Try to evaluate this query by hand, looking at the given data values. What
strategy did you use?
9.

Get the patient names of Dr. Spock's patients who have been given drug
d7.
select
from
where
and

p.pname
patientpJOINdosed
ONp.pno=d.pno
d.dno='d7'
p.gp='Dr.Spock';

select
from
where
and
and

p.pname
patientp,dosed
p.pno=d.pno
d.dno='d7'
p.gp='Dr.Spock';

OR

10.

Find the patient names of patients who have been given drugs costing
more than 1.75 per unit.
This query involves all three tables; patient as that contains the patients
name, drug as that contains the cost of the drug, and dose as that records
which patients have been given each drug.
select
from

where
OR
SQL Booklet 2014-15

pname
patientpJOINdosed
ONp.pno=d.pno
JOINdrugdr
ONd.dno=dr.dno
dr.cost>1.75;

select
from
where
and
and

pname
patientp,dosed,drugdr
p.pno=d.pno
d.dno=dr.dno
dr.cost>1.75;

Alternatively,
select
from
where

pname
patient
pnoin
( selectpno

fromdose

wherednoin
(selectdno

fromdrug

wherecost>1.75));

Nested queries tend to take longer to execute than non-nested ones,


however some queries can be much more easily expressed using nested
queries.

You should now try SQL Practice SECTION B (answers are also included).
You might need to refer to the section: Retrieval with SQL Reference.

SQL Booklet 2014-15

Aggregate Functions
(sometimes called set functions)
Common aggregate functions can be used in SQL
The ones supported in most systems are:
COUNT
SUM
AVG
MAX
MIN

= return a count of the number of rows


= return the sum of all values in a column
= return the average of values in a column
= return the maximum value in a column
= return the minimum value in a column

NB These functions cannot be used in the 'WHERE' clause of a SQL statement.


11.

Calculate the average unit cost of drugs in tablet form.


select
from
where

12.

How many GPs have patients at the hospital?


select
from

13.

avg(cost)as"MeanTabletCost"
drug
unit='tab';

count(distinctgp)
patient;

What is the total quantity of d7 prescribed?


selectsum(qty)as"d7total"
from
dose
where
dno='d7';

14.

What is the maximum dose of d7 ever given?


selectmax(qty)as"d7max"
from
dose
where
dno='d7';

SQL Booklet 2014-15

15.

Please get the total quantities of each of the drugs that we have prescribed.
select
dno,sum(qty)as"Total"
from dose
groupby dno;

16.

Thank you, but I really only wanted those drugs with 10 or more units
used.
select
dno,sum(qty)as"Total"
from dose
groupby dno
havingsum(qty)>=10;

Thank you, but I would like the output in descending order of the total
column.
select
from
groupby
having
orderby

17.

dno,sum(qty)as"Total"
dose
dno
sum(qty)>=10
"Total"desc;

I do not want any drugs that have been given to patient p7 to be included
in the totals.
select
from

SQL Booklet 2014-15

dno,sum(qty)as"Total"
dose

where
groupby
having
orderby

pno!='p7'
dno
sum(qty)>=10
"Total"desc;

You should now try SQL Practice SECTION C (answers are also included).
You might need to refer to the section: Retrieval with SQL Reference.

SQL Booklet 2014-15

Modifying the Database : Inserting & Updating


18.

I want to add a new drug to the database.


insertintodrugvalues
('d3','zonk','tab','19Jun11',1.11);

19.

I want to add several new drugs to the database.


insertintodrugvalues
('&dno','&dname','&unit','&doi','&cost);
SQL Developer will prompt for input values, via popup boxes. Strings
should not be quoted. Dates should be of the form 12/Jan/04 meaning 12th
of January 2004 as this is the standard date format.

20.

I want to add a new patient but all I have is his pno and name.
insertintopatient(pname,pno)
values('major','p9');

21.

I now have some further data on this patient that I want to put in the table.
updatepatient
settitle='mr',dob='3Nov1981'
wherepno='p9';

22.

For some reason all of Dr Williams' patients have had their dose quantities
recorded wrongly!
updatedose
setqty=qty1
wherepnoin
(selectpno
frompatient
wheregp='Dr.Williams');

Modifying the Database : Deleting


23.

I want to delete all the data on patient p2 from the dose table
delete
from
where

24.

dose
pno='p2';

I want to empty the dose table.


delete
from

dose;

NB Very dangerous be careful !


SQL Booklet 2014-15

Note if necessary:
DROP TABLE tablename
will completely remove
the table.

You should now try SQL Practice SECTION D (answers are also included).
You might need to refer to the section: Retrieval with SQL Reference.

SQL Booklet 2014-15

SQL Booklet 2014-15

Queries with Dates


25.

List drug names of drugs introduced from 2009 onwards.


select
from
where

26.

dname
drug
doi>'31Dec2008';

List drug names of drugs more than 2 years old together with their age in
days.

select dname,
trunc(sysdatedoi)as"Ageindays"
from
drug
where months_between(sysdate,doi)>24;

Note:valueswillvaryfromthoseshowndependantoncurrentdate

27.

List patient identifiers of patients who were given drugs within 6 months
of their introduction

select pno
from
drugdrJOINdoseds
ONdr.dno=ds.dno
where months_between(dosedate,doi)<=6;
OR
select
from
where
and

SQL Booklet 2014-15

pno
drugdr,doseds
dr.dno=ds.dno
months_between(dosedate,doi)<=6;

28.

How old is each patient?

selectpname,
trunc((sysdatedob)/365.25)as"Age"
frompatient;

There are many other functions on dates which you can find out about,
e.g. To_Date returns a date formatted based on a given suitable string.
Pattern Matching
29.

List patients of Dr. Tailor or is it Dr. Taylor


select *
from
patient
where gplike'Dr.Ta_lor%';

note the necessary trailing %


note also the strings within quotes are caSe seNsiTive
30.

List the data we have on drugs with the word 'dreams' in their name.
select *
from
drug
where dnamelike'%dreams%';

31.

All we know about this patient was they were born after Jan 1st 1970 and
they have the letters 'nog' somewhere in their name;
select
from
where
and

SQL Booklet 2014-15

*
patient
pnamelike'%nog%'
dob>'1jan1970';

32.

I'm not interested in the drugs that have names starting with 'slow', but I
want data on the others.
select
from
where

33.

*
drug
dnamenotlike'slow%';

I want information on Dr. William's patients but I'm not sure how the
names of GPs are stored in the database
select
from
where

*
patient
upper(gp)like'%WILLIAMS%';

Joining a Table with itself


Sometimes it is necessary to join a table with itself. To do this you must create two
different names (table aliases) for the table, as shown:

34.

List of names of employees who earn more than their boss.


select
from
where

e.name
employeeeJOINemployeeb
ONe.boss=b.name
e.salary>b.salary;

select
from
where
and

e.name
employeee,employeeb
e.boss=b.name
e.salary>b.salary;

OR

SQL Booklet 2014-15

Intermediate Table

Result:

SQL Booklet 2014-15

Further SQL Examples


35.

Give names and patient identifiers of 'married' couples.


select pa.pnameas"Mr",pa.pno,
pb.pnameas"Mrs",pb.pno
from
patientpa,patientpb
where pa.pname=pb.pname
and
pa.title='mr'
and
pb.title='mrs';

OR
select pa.pnameas"Mr",pa.pno,
pb.pnameas"Mrs",pb.pno
from
patientpa,patientpb
where pa.pname=pb.pname
and
pa.title='mr'
and
pb.title='mrs';

36.

Get patient names if given drug d7.


(alternative to using IN)
select
from
where

37.

pname
patientp
exists
(
select

from

where

and

*
dosed
p.pno=d.pno
d.dno='d7');

What about patients who have not been given d7 ?


(alternative to using NOT IN)
select
from
where

SQL Booklet 2014-15

pname
patientp
notexists
(
select

from

where

*
dosed
p.pno=d.pno

d.dno='d7');

and

38.

Which patients have been given all the drugs?


select pname
from
patientp
where notexists(
select*

fromdrugdr

wherenotexists(
select*

fromdoseds

whereds.pno=p.pno

and ds.dno=dr.dno));

39.

A list is wanted of all patient numbers together with the drugs they have
been given (include those who have not been given any drugs).
select
from

pno,dno
dose

union
select
from
where

SQL Booklet 2014-15

pno,'none'
patientp
notexists
(
select

from

where

*
dosed
p.pno=pno);

(NB You can achieve the same thing with an OUTER JOIN)
Using NULL values
40.

Say incomplete details of a drug are entered:


insert
values

41.

Then if we want to know which drugs have not had a name entered for
them:
select
from
where

42.

intodrug(dno,cost)
('d10',2.99);

dno
drug
dnameisnull;

Or if only want data on drugs which have names entered:


select
from
where

dno
drug
dnameisnotnull;

Calculations
43.

What is the total cost of each drug used?


select
from
where
group

44.

dr.dno, sum (qty * cost) as "total cost"


drug dr, dose ds
dr.dno = ds.dno
by dr.dno;

For each drug how much is the maximum quantity given above the
average quantity?
select
from
group

SQL Booklet 2014-15

dno, max(qty) - avg(qty) as "above mean"


dose
by dno;

You should now try SQL Practice SECTION E (answers are also included).
You might need to refer to the section: Retrieval with SQL Reference.

Data Independence
Logical Data Independence
a change to the logical structure of the data should not result in a need to
change the logic of existing uses of the data.
Physical Data Independence
a change to the mechanisms for accessing and storing data should not
result in a need to change the logic of existing uses of the data.
Views
A view is a virtual table:
i.e. a table that does not exist in its own right but looks to the user as if it did.
A view is a way to let each user see the parts of the database that they need, in the
format that is most easily understood by them.
45.

Joan is only ever interested in drugs costing more that 1 per unit.
a) Create a suitable view:
create view deardrugs (dno, unit, doi, cost)
as
select dno, unit, doi, cost
from
drug
where
cost > 1.00 ;

b) Use the view as if it were a table


select
from
where
SQL Booklet 2014-15

*
deardrugs
doi > '1-Jan-2010';

What the DBMS does behind the scenes:


=

46.

select
from
where
and

dno, unit, doi, cost


drug
doi > '1-Jan-2010'
cost > 1.00;

Jane is only interested in prescriptions of 5 or more units and wants to use


her own names for the columns and wants them in a different order.
create view bigdose ( drug, qty,
patient, dategiven )
as
select dno, qty, pno, dosedate
from
dose
where
qty >= 5;

47.

Jim also is only interested in what is in Jane's view but doesn't need patient
data and also wants to use his own terms
create view newbigdose ( drugno, dose, cdate )
as
select drug, qty, dategiven
from
bigdose
where
dategiven > '01-Jul-2010' ;

48.

Jack wants all the data in the dose table but frequently needs the patients'
names as well

create view patdose ( pno, pname, dno,


dosedate, qty )
as
select p.pno, pname, dno, dosedate, qty
from
patient p join dose d
on p.pno = d.pno;
SQL Booklet 2014-15

or
create view patdose ( pno, pname, dno,
dosedate, qty )
as
select p.pno, pname, dno, dosedate, qty
from
patient p, dose d
where
p.pno = d.pno;

Note: in this case, as the attributes in the view have the same names as
those in the defining query, you could omit the attribute names shown in
italics.
49.

Jo doesn't deal in codes and often wants the names of patients, which drugs
they have been given and how much.
create view patdrug (patname, drug, qty)
as
select pname, dname,qty
from
patient p, drug dr, dose ds
where
p.pno = ds.pno
and
ds.dno = dr.dno;
or
create view patdrug (patname, drug, qty)
as
select pname, dname,qty
from
patient p join dose ds
on p.pno = ds.pno
join drug dr
on ds.dno = dr.dno;

SQL Booklet 2014-15

Updating Views
Most Relational DBMS do not allow modification of views if:
-

view has more than one base table

any columns in the view are derived from an expression or aggregate (set)
function

In addition Inserts are not allowed if


-

the insert is in conflict with the where condition of the view and
the WITH CHECK OPTION is specified

there is a column in the underlying base table defined as NOT NULL which is
not in the view

and Updates are not allowed if


50.

attempting to update a column in conflict with the view's qualification and the
WITH CHECK OPTION is specified
create view drugcost ( dno, cost)
as
select dno, cost
from drug;

SQL Booklet 2014-15

OK to modify this view because


a) it is drawn from only one base table
b) none of the missing columns is NOT NULL
51.

create view agecost ( doi, cost)


as
select doi, cost
from drug;

Here we can
- update e.g. update agecost set cost = 1.15 where cost = 0.15;
- delete e.g. delete from agecost where cost = 5.00;
- but we CANNOT insert ( because the key, which is not included in the
view is NOT NULL)
52.

There are potential problems if the view has a restriction on the values in a
column. Updating that value might mean the whole row disappears from the
view and cannot be retrieved. Putting 'with check option' into the definition of
the view prevents this.
create view deardrugs (dno, unit, doi, cost)
as
select dno, unit, doi, cost
from
drug
where
cost > 1.00
with check option;

then
update
set
where

deardrugs
cost = 0.50
dno = 'd2';

will not succeed.


Multitable views: in general multitable view such as patdose or patdrug cannot
be updated. You might find some installations of Oracle will make certain updates to
multitable views where it can map back unambiguously to base tables.
SQL Booklet 2014-15

Advantage of Views
a)

provide some logical independence

e.g. if the drug table is split in two for performance reasons eg.
drugbasics (dno, dname)
drugdetails (dno, unit, doi, cost)
then

create view drug (dno, dname, unit, doi, cost)


as
select db.dno, dname, unit, doi, cost
from
drugbasics db, drugdetails dd
where
db.dno = dd.dno;

This view will allow users to see the data as before.


b)

Allow the same data to be seen by different users in different ways

c)

Simplify users' perception and hence make data manipulation easier

e.g. Get names of drugs given to patient minogue.


i)

without a view
select
from

where
ii)

d)

with a view
select
from
where

dname
patient p join dose ds
on p.pno = ds.pno
join drug dr
on ds.dno = dr.dno
pname= 'minogue' ;
dname
patdrug
patname = 'minogue';

Provide some degree of security

SQL Booklet 2014-15

Data
Definition Language (DDL)
You should now try SQL Practice SECTION F (answers are also included).
You might need to refer to the section: Retrieval with SQL Reference.
Creating Tables
Basic format
CREATE TABLE table_name (
column_name
format
{, column_name
format }
{, primary key/foreign key format } );
eg:
CREATE TABLE Patient
(
Pno
Pname
Title
Dob
Children
GP
PRIMARY KEY (Pno) );

VARCHAR2(4) NOT NULL,


VARCHAR2(15) NOT NULL,
VARCHAR2(4),
DATE,
NUMBER(2),
VARCHAR2(15),

CREATE TABLE Drug


(
Dno
VARCHAR2(4) NOT NULL,
Dname
VARCHAR2(20),
Unit
VARCHAR2(3),
Doi
DATE,
Cost
NUMBER(6,2),
PRIMARY KEY (Dno) );
CREATE TABLE Dose
(
Pno
VARCHAR2(4) NOT NULL,
Dno
VARCHAR2(4) NOT NULL,
DoseDate
DATE NOT NULL,
Qty
NUMBER(4),
PRIMARY KEY (Pno,Dno,Dosedate),
PRIMARY KEY (Pno) REFERENCES Patient(Pno),
PRIMARY KEY (Dno) REFERENCES Drug(Dno) );
Oracle Data Types
When a table is created in Oracle it needs to know what type of data is to be stored in
each column (attribute).
The main data types recognised by Oracle are:
CHAR(n)
VARCHAR2(n)
NUMBER(n,d)
NUMBER(n)
DATE

SQL Booklet 2014-15

fixed length character string of n characters


variable length character string having maximum length n
number made up of n digits with d decimal places.
whole number made up of n digits
date and time

Creating an Index
Basic format:
CREATE [UNIQUE] INDEX indexname
ON tablename (columnname {,columname});
eg
CREATE INDEX gp_idx ON Patient (Gp);
Remember: that an index is always created on a primary key so does not require
specific definition.

SQL Booklet 2014-15

Appendix A SQL PRACTICE


(with Hatfield Hospital Database)
SECTION A
1.

List all the information in the drug table.

2.

List patient titles and names.

3.

List the quantity and date of drugs given to patient 'p4'

4.

List full details of female patients ( title is miss, ms, or mrs or just not mr).

5.

Get patient names of patients who are not patients of Dr.Spock.


(beware; data values are case sensitive and spaces count)

SQL Booklet 2014-15

6.

What was the date of birth of Mr. Gooch?

7.

List names of drugs which cost less than 1.00 per unit.

8.

List names of drugs that are in 'mg' or 'gm' units together with their date of
introduction.

9.

List patient nos of patients who have between 1 and 3 children.

10.

List patient nos and dates of birth of patients who have between 1 and 3
children and whose GP is Dr.Williams.

SQL Booklet 2014-15

SECTION B
11.

Get the names of patients who have been given drug d1.

12.

Drug names of drugs given to patient p1.

13.

Names of any of Dr. Williams' patients who have been given doses of 5 or
more units of a drug, together with drug no and quantity.

14.

List patient nos of patients who have been given drugs in tablet form.

15.

List names of patients who have been given drugs in tablet form.

16.

Who are the GPs who have patients who have been given bliss?

17.

Get patient name, drug name and dose date for doses given to patients with
two children or less, of drugs costing more than 1.00, in quantities of 5 or less.

SECTION C
SQL Booklet 2014-15

18.

How many drugs have we in the database?

19.

What is the average no of children of patients of Dr.Williams?

20.

What is the lowest cost of a tablet?

21.

How many prescriptions has patient Mrs Gooch been given?

22.

What is the total amount of the drug 'split' that has been prescribed?

23.

What is the patient no of the patient who has been given the highest dosage of
drug d7 (in one prescription)?

24.

What is the total number of patients that each GP has in the hospital?

25.

List the total dosage of each different drug given to patient p4 starting with the
highest and leaving out any totals less than 5.

SECTION D

SQL Booklet 2014-15

26.

Put in a new patient, Mrs. Lee who has 2 children and was born on 23-May50. ( i.e. 1950)

27.

Modify the database to reflect that all of Dr.Spock's patients have been taken
over by Dr.Owen.

28.

Modify the database to reflect that mrs currie has died and we wish to remove
any reference to her.

SECTION E
29.

Get full details of patients whose names start 'gooc'.

30.

List details of doses given in 2010.

31.

Get names of patients who were less than 30 years old at the start of this year.

32.

List names of patients given drugs in tablet form after their 25th birthday.

33.

List details of patients for whom we have incomplete information.

34.

What is the average cost of prescriptions given to Dr.Williams' patients?

(NB. 35-37 are more difficult)


35.

List all the drug names together with quantity prescribed to patients of all GPs
other than Dr. Spock.

SQL Booklet 2014-15

36.

List patient names of patients who have the same GP as mr. mansell.

37.

List names of drugs introduced after the drug 'slow down' was.

SECTION F
Set up views which will look like the following to the users:
38.

patdose ( PatientName, DrugNo, DateGiven, Qty)

39.

drugdose ( DrugName, DateGiven, Qty, DoseCost)


only include prescriptions since November 1st, 2010

40.

drugsummary (DrugName, TotalQty, TotalCost)


NB use drugdose view from 39 to construct this new view

Use these views in the following queries:


41.

Get the names of patients who have been given drug d1 (compare with q11)

42.

What was the date and the cost of the most expensive prescription for the drug
'split' since the beginning of 2004?

43.

Get the drug names, total qty and total cost for drugs in tablet form.

44.

Get the drug name of the drug that has cumulatively been the most costly drug
prescribed since the start of 2004.

45.

Which (if any) of the above views can be used for inserting, updating and
deleting?

SQL Booklet 2014-15

Appendix B SQL PRACTICE Answers


SECTION A
1.

select *
from drug;

2.

select title, pname


from patient;

3.

select qty, dosedate


from dose
where pno = 'p4';

4.

select *
from patient
where title in ('mrs', 'miss', 'ms');

5.

select pname
from patient
where GP != 'Dr.Spock';

6.

select dob
from patient
where pname = 'gooch'
and title = 'mr';

7.

select dname
from drug
where cost < 1.00;

8.

select dname, doi


from drug
where unit = 'mg'
or unit = 'gm' ;

9.

select pno
or
from patient
where children between 1 and 3;

select pno
from patient
where children >= 1
and children <= 3;

10.

select pno, dob


from patient
where children between 1 and 3
and gp = 'Dr.Williams';

select pno, dob


from patient
where children >= 1
and children <= 3
and gp = 'Dr.Williams';

SQL Booklet 2014-15

or

SECTION B
11.

select p.pname
from patient p join dose d
on p.pno = d.pno
where dno = 'd1' ;
or

12.

select pname
from patient p, dose d
where p.pno = d.pno
and dno = 'd1' ;

select pname
from patient
where pno in
(select pno
from dose
where dno = 'd1') ;

select dr.dname
from drug dr join dose d
on dr.dno = d.dno
where d.pno = 'p1' ;
or

or

or

select dr.dname
from drug dr, dose d
where dr.dno = d.dno
and d.pno = 'p1' ;

select dname
from drug
where dno in
(select dno
from dose
where pno = 'p1');

13.

select pname, dno, qty


from patient p join dose d
on p.pno = d.pno
where gp = 'Dr.Williams'
and qty >= 5 ;

or

select pname, dno, qty


from patient p, dose d
where p.pno = d.dno
and gp = 'Dr.Williams'
and qy >= 5 ;

14.

select distinct d.pno


from dose d join drug dr
on d.dno = dr.dno
where dr.unit = 'tab' ;

or

select distinct d.dno


from dose d, drug dr
where d.dno = dr.dno
and dr.unit = 'tab' ;

or

15.

select pno
from dose
where dno in
(select dno
from drug
where unit = 'tab');

select distinct d.pname


from patient p join dose d
on p.pno = d.pno
join drug dr
on d.dno = dr.dno
where dr.unit = 'tab' ;
or

SQL Booklet 2014-15

or

select distinct d.dname


from patient p, dose d,
drug d
where p.pno = d.pno
and d.dno = dr.dno
and dr.unit = tab ;

select pname
from patient
where pno in
( select pno
from dose
where dno in
( select dno
from drug
where unit = 'tab' ) ;

16.

select distinct p.gp


or
from patient p join dose d
on p.pno = d.pno
join drug dr
on d.dno = dr.dno
where dr.dname = 'bliss' ;
or

17.

select distinct p.gp


from patient p, dose d,
drug d
where p.pno = d.pno
and d.dno = dr.dno
and dr.drname = bliss ;

select gp
from patient
where pno in
( select pno
from dose
where dno in
( select dno
from drug
where dname = 'bliss' ) ;

select p.pname, dr.dname, d.dosedate


from patient p join dose d
on p.pno = d.pno
join drug dr
on d.dno = dr.dno
where dr.cost > 1.00
and d.qty <= 5
and p.children <= 2;

or
select p.pname, dr.dname, d.dosedate
from patient p, dose d, drug dr
where p.pno = d.pno
and d.dno = dr.dno
and dr.cost > 1.00
and d.qty <= 5
and p.children <= 2;

SECTION C
18.

select count(*) as "Number of Drugs"


from drug;

19.

select avg(children) as "Dr Williams patient kid avg"


from patient
where gp = 'Dr.Williams';

20.

select min(cost) as "Cheapest Tablet"


from drug
where unit = 'tab';

21.

select count(*) as "Mrs Goochs Prescriptions"


from patient p,dose d
where p.pno = d.pno
and pname = 'gooch'
and title = 'mrs';

22.

select sum(qty) as "Total 'Split' Prescribed"


from dose d,drug dr
where d.dno = dr.dno

SQL Booklet 2014-15

and dname = 'split';

23.

select pno as "Most d7"


from dose
where dno = 'd7'
and qty in
( select max(qty)
from dose
where dno = 'd7' );

24.

select gp asgp,count(*) as "Patient Total"


from patient
group by gp;

25.

select dno,sum(qty) as "Total Prescribed to p4"


from dose
where pno = 'p4'
group by dno
having sum(qty) >= 5
order by sum(qty) desc;

SECTION D
26.

insert into patient(pno,pname,title,dob,children)


values ('p10, 'lee', 'mrs', '23-May-1950', 2) ;

27.

update patient
set gp = 'Dr.Owen'
where gp = Dr.Spock' ;

28.

We have to remove rows from both the dose table and the patient table. One
way is to use a transaction to make sure that both these actions happen,
another way is to have declared a referential contraint with cascade delete
when the tables were created. Here we assume no cascade delete is in place:
set autocommit off;
delete
from dose
where
(

pno in
select pno
from patient
where pname = 'currie'
and title = 'mrs' ) ;

delete
from patient
where
pname = 'currie'
and
title = 'mrs' ;
commit;
set autocommit on;

SQL Booklet 2014-15

SECTION E
29.

select *
from patient
where pname like 'gooc%' ;

30.

select *
from dose
where dosedate >= TO_DATE ('01-jan-2010', 'dd-mon-yyyy')
and dosedate <= TO_DATE ('31-dec-2010', 'dd-mon-yyyy') ;

31.

select title || ' ' || pname as "Name"


from patient
where trunc (( sysdate dob ) / 365.25) < 30 ;

32.

select title || ' ' || pname as "Name"


from drug dr, dose d, patient p
where dr.dno = d.dno
and d.pno = p.pno
and dr.unit = 'tab'
and trunc ((dosedate dob) / 365.25) >= 25 ;

33.

select *
from patient
where title is null
or dob is null
or children is null
or gp is null ;

34.

select avg (qty * cost) as "Dr. William's average cost"


from drug dr, dose d, patient p
where dr.dno = d.dno
and d.pno = p.pno
and gp = 'Dr.Williams' ;

35.

select dname,sum(qty)
from drug dr, dose d, patient p
where dr.dno = d.dno
and d.pno = p.pno
and gp != 'Dr.Spock'
group by dname
UNION
select dname, 0
from drug dr
where dno not in
( select dno
from dose d, patient p
where p.pno = d.pno
and gp!= 'Dr.Spock') ;

SQL Booklet 2014-15

36.

select pname || ', ' || title as


from patient
where gp in
( select gp
from patient
where pname = 'mansell'
and title = 'mr')
and not ( pname = 'mansell'
and title = 'mr' );

37.

select dname
from drug
where doi >
( select doi
from drug
where dname = 'slow down');

"Name"

SECTION F
38.

create view patientdose (PatientName,DrugNo,DateGiven,Qty)


as
select pname,dno,dosedate,qty
from dose d, patient p
where p.pno = d.pno ;

39.

create view drugdose (DrugName,DateGiven,Qty,DoseCost)


as
select dname,dosedate,qty,(qty*cost)
from drug dr, dose d
where dr.dno = d.dno
and dosedate > '1-jan-2004';

40.

create view drugsummary (Drugname,TotalQty,TotalCost)


as
select drugname,sum(qty),sum(dosecost)
from drugdose
group by drugname ;

41.

select patname
from patientdose
where drugno = 'd1'

42.

select dategiven,dosecost
from drugdose
where drugname = 'split'
and dosecost in
(select max(dosecost)
from drugdose

SQL Booklet 2014-15

where drugname = 'split')


43.

select drugname,totalqty,totalcost
from drugsummary ds,drug dr
where ds.drugname = dr.dname
and unit = 'tab';

44.

select drugname
from drugdose
group by drugname
having sum(dosecost) in
(select max(sum(dosecost))
from drugdose
group by drugname);

SQL Booklet 2014-15

Appendix C Retrieval with SQL Reference


SUBSELECT STATEMENT:
select [distinct] expression [as result-columnname]
{,expression [as result-columnname]}
from tablename {,tablename}
[where predicate]
[group by columname {,columnname}
[having predicate]]

FULL SELECT STATEMENT:


Subselect
{union
Subselect}
[order by columnname [asc|desc]
{,columnname [asc|desc]}];
An expression is a column name, a calculation, a set function or a literal.
A predicate is
[not] search condition {and|or [not] search condition}
A search condition is one of the following:
expression comparison-operator expression
expression comparison-operator any|all (subquery)
expression is [not] null
expression [not] like 'pattern'
pattern may contain-and/or % as wild card characters
Expression [not] between expression and expression
Expression [not] in [subquery]
Expression [not] in (expression {,expression})
exists (subquery)
Comparison operators are:
Equal
=
not equal
!=
less than
<
greater than
>
less than or equal
greater than or equal

<=
>=

Set functions are: function ([distinct] expression)


where the functions are:
count
sum
avg
max
min

SQL Booklet 2014-15

OTHER USEFUL COMMANDS:


CREATE VIEW
create view viewname [columnname{,columnname}}
as select .
DROP VIEW
drop view viewname {,viewname}
(Similarly with create/drop table, create/drop index etc.)
ALTER TABLE
Use alter table if, for example, you want to add a column or an integrity constraint.
TO GET INFORMATION ON THE STRUCTURE OF A TABLE or VIEW;
describe tablename|viewname
TO GET INFORMATION ON WHAT TABLES YOU HAVE IN THE DATABASE
select * from tabs

Key:
{.} means optionally a further 1 or more
[.] means optional once
A|B means A or B

SQL Booklet 2014-15

Appendix D Using SQL Developer


These notes are to help you get used to creating and running queries using SQL Developer. If
you have used SQL Developer in the past, please note that the version has been upgraded
since the previous academic year.
1. Run SQL Developer from the Applications Folder in the STCA laboratories, and in the
LRCs, Click: Start > All Programs > SQL Developer > SQL Developer
2. You will see the following flash screen:

3. This will be followed by the SQL Developer application window:

4. If a Tips of the Day popup appears, disable it and continue


5. The version in use at UH is given by selecting Help>About

SQL Booklet 2014-15

This may be useful if you wish to install the same version on your own computer. SQL
Developer can be downloaded from the ORACLE website (www.oracle.com), free of
charge.
6. You first need to make a connection to the Oracle 11g Database Instance MORK
7. Click on the Green Plus

at the top of the left pane

8. By default the Oracle connection tab should be active. If not, click on the Oracle tab.
Fill in the fields indicated:
Connection Name: A short string you can identify this connection as
Username:
The username you were provided with, likely to be the same as
your standard university account name
Password:
The password for your account

SQL Booklet 2014-15

Hostname:
Port:
SID:

vclsaorateach.herts.ac.uk, this is the server on which the Oracle


Database Instance is installed
Replace with 1523
mork11, this is the instance we will use for DMA

Leave everything else as supplied by default

9. Click on Connect. If you get an error after status or as a popup window, recheck your
settings before asking for help.
10. If you have already created a connection, it will appear in the left pane. Double-Click on
it and you will simply be asked for your password

11. If the connection is successful, the connection string will appear in the left pane and will
be populated by a list of potential objects that your account supports. The right pane will
also change to an input screen for SQL queries.

SQL Booklet 2014-15

12. After entering a query, it can be executed using either the Run Statement or Run Script
options.
13. The output will appear in a window below the SQL input window

SQL Booklet 2014-15

14. A print of both output types can be obtained using the print icon

(Ctrl-P)

15. The SQL input can be saved to a file using File>Save (Ctrl-S).
16. Existing Tables can be viewed. Click on the + next to the your connections Tables folder,
then click in the table you wish to view. The structure of the table will appear in a new tab
in the right-pane.

17. Click on the Data tab to view the contents of the table

18. We have only scratched the surface of SQL Developers capability; please feel free to
explore what else it can do.

SQL Booklet 2014-15

SQL Booklet 2014-15

Vous aimerez peut-être aussi