64
School of Computer Science Introduction to SQL Using Oracle Example Queries and Exercises 2014/2015-CS

SQL booklet 2014-15.docx

Embed Size (px)

Citation preview

Page 1: SQL booklet 2014-15.docx

School of Computer Science

Introduction to SQL Using OracleExample Queries and Exercises

2014/2015-CS

Page 2: SQL booklet 2014-15.docx

Relational Database Management Systems

Hatfield Hospital Database..........................................................................................2

Using SQL to Manipulate the Data................................................................................4Data Manipulation Language – DML........................................................................4

Retrieving Data from the Database................................................................................5Queries which use only one table...............................................................................5Queries involving more than one table (Joins and Nested Select Statements)..........6Aggregate Functions..................................................................................................9Modifying the Database : Inserting & Updating......................................................11Modifying the Database : Deleting..........................................................................12Queries with Dates...................................................................................................12Pattern Matching......................................................................................................14Joining a Table with itself........................................................................................15Further SQL Examples.............................................................................................16Using NULL values.................................................................................................18Calculations..............................................................................................................18

Data Independence.......................................................................................................19Logical Data Independence......................................................................................19Physical Data Independence.....................................................................................19Views........................................................................................................................19Updating Views........................................................................................................22Advantage of Views.................................................................................................24

Data Definition Language (DDL)................................................................................24Creating Tables........................................................................................................25Oracle Data Types....................................................................................................25Creating an Index.....................................................................................................26

Appendix A – SQL PRACTICE..................................................................................27SECTION A.............................................................................................................27SECTION B.............................................................................................................29SECTION C.............................................................................................................30SECTION D.............................................................................................................31SECTION E..............................................................................................................31SECTION F..............................................................................................................32

Appendix B – SQL PRACTICE – Answers.................................................................33SECTION A.............................................................................................................33SECTION B.............................................................................................................34SECTION C.............................................................................................................35SECTION D.............................................................................................................36SECTION E..............................................................................................................37SECTION F..............................................................................................................38

Appendix C – Retrieval with SQL – Reference...........................................................40

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

SQL Booklet 2014-15 1

Page 3: SQL booklet 2014-15.docx

Hatfield Hospital DatabaseThe database consists of three tables, populated as follows:

PATIENT (SELECT * FROM patient;)

DRUG (SELECT * FROM drug;)

DOSE (SELECT * FROM dose;)

SQL Booklet 2014-15 2

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 dd-mmm-yyyy.

Page 4: SQL booklet 2014-15.docx

PATIENT – lists all the patients at the HATFIELD hospital.

The attributes have the following meanings:

PNO an identifying number unique to each patientPNAME the family name of the patientTITLE the style of address for each patient ( this is limited to mr,

mrs, miss, ms)DOB the date of birth of the patientCHILDREN the number of children the patient hasGP the name of the patient’s general practitioner (local

medical doctor)

DRUG – lists all the drugs used by the HATFIELD hospital

The attributes have the following meanings:

DNO an identifying number unique to each drugDNAME the commonly used name for the drugUNIT the unit of measure for dispensing the drugs

( tab=available in tablet form, mg=millegrammes, gm = grammes)

DOI date the drug was introducedCOST 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 identifies the patientDNO identifies the drugDOSEDATE the date on which the drug was given to the patientQTY the quantity of the drug (in dispensed units) given to the

patient

SQL Booklet 2014-15 3

Page 5: SQL booklet 2014-15.docx

Using SQL to Manipulate the Data

Data Manipulation Language – DML

SQL Booklet 2014-15 4

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 a1,a2,…. [attribute(s)]FROM r1,r2,…. [relation(s)]WHERE p; [predicate]

Page 6: SQL booklet 2014-15.docx

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 dname, dnofrom 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 dnamefrom drugwhere 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 dnofrom drugwhere 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 5

Page 7: SQL booklet 2014-15.docx

select pnofrom patientwhere gp = 'Dr.Spock' or gp = 'Dr.Taylor' or gp = 'Dr.Thatcher' ;

Alternatively:

select pnofrom patientwhere gp in

( 'Dr.Spock', 'Dr.Taylor', 'Dr.Thatcher');

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

select pnofrom patientwhere gp not in

( 'Dr.Spock', ‘Dr.Taylor', 'Dr.Thatcher');

Queries involving more than one table (Joins and Nested Select Statements).

SQL Booklet 2014-15 6

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

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.

Page 8: SQL booklet 2014-15.docx

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 patient’s 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.pnamefrom patient p JOIN dose d

ON p.pno = d.pnowhere d.dno = 'd7' ;

OR

select p.pnamefrom patient p, dose dwhere p.pno = d.pnoand 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

SQL Booklet 2014-15 7

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.

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_bFROM table1 t1, table2 t2WHERE 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.

Page 9: SQL booklet 2014-15.docx

the IN keyword captures the potential for more than one row returned from the inner query.

select pnamefrom patientwhere pno in

(select pno from dose where dno = '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 p.pnamefrom patient p JOIN dose d

ON p.pno = d.pnowhere d.dno = 'd7'and p.gp = 'Dr.Spock' ;

OR

select p.pnamefrom patient p, dose dwhere p.pno = d.pnoand d.dno = 'd7'and p.gp = 'Dr.Spock' ;

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 patient’s name, drug as that contains the cost of the drug, and dose as that records which patients have been given each drug.

select pnamefrom patient p JOIN dose d

ON p.pno = d.pnoJOIN drug drON d.dno = dr.dno

where dr.cost > 1.75 ;

OR

select pnamefrom patient p, dose d, drug drwhere p.pno = d.pnoand d.dno = dr.dno

SQL Booklet 2014-15 8

Page 10: SQL booklet 2014-15.docx

and dr.cost > 1.75 ;

Alternatively,

select pnamefrom patientwhere pno in

( select pno from dose where dno in

( select dno from drug where cost > 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.

Aggregate Functions(sometimes called set functions)

Common aggregate functions can be used in SQL

SQL Booklet 2014-15 9The ones supported in most systems are:

COUNT = return a count of the number of rowsSUM = return the sum of all values in a columnAVG = return the average of values in a columnMAX = return the maximum value in a column

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

Page 11: SQL booklet 2014-15.docx

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 avg(cost) as "Mean Tablet Cost" from drugwhere unit = 'tab' ;

12. How many GPs have patients at the hospital?

select count(distinct gp)from patient ;

13. What is the total quantity of d7 prescribed?

select sum (qty) as "d7 total"from dosewhere dno = 'd7' ;

14. What is the maximum dose of d7 ever given?

select max (qty) as "d7 max"from dosewhere dno = 'd7' ;

15. Please get the total quantities of each of the drugs that we have prescribed.

select dno, sum(qty) as "Total"from dose

SQL Booklet 2014-15 10

The ones supported in most systems are:

COUNT = return a count of the number of rowsSUM = return the sum of all values in a columnAVG = return the average of values in a columnMAX = return the maximum value in a column

Page 12: SQL booklet 2014-15.docx

group by dno;

16. Thank you, but I really only wanted those drugs with 10 or more units used.

select dno, sum(qty) as "Total"from dosegroup by dnohaving sum(qty) >= 10;

Thank you, but I would like the output in descending order of the total column.

select dno, sum(qty) as "Total"from dosegroup by dnohaving sum(qty) >= 10order by "Total" desc;

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

select dno, sum(qty) as "Total"from dosewhere pno != 'p7'group by dnohaving sum(qty) >= 10order by "Total" desc;

SQL Booklet 2014-15 11

Page 13: SQL booklet 2014-15.docx

Modifying the Database : Inserting & Updating

18. I want to add a new drug to the database.

insert into drug values('d3','zonk','tab','19-Jun-11', 1.11);

19. I want to add several new drugs to the database.

insert into drug values('&dno','&dname','&unit','&doi','&cost’);

SQL Booklet 2014-15 12

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

Page 14: SQL booklet 2014-15.docx

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.

insert into patient (pname, pno)values ('major', 'p9') ;

21. I now have some further data on this patient that I want to put in the table.

update patientset title = 'mr', dob = '3-Nov-1981'where pno = 'p9' ;

22. For some reason all of Dr Williams' patients have had their dose quantities recorded wrongly!

update doseset qty = qty – 1where pno in

(select pno from patient where gp = 'Dr.Williams');

Modifying the Database : Deleting

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

deletefrom dosewhere pno = 'p2' ;

24. I want to empty the dose table.

deletefrom dose;

NB Very dangerous – be careful !

SQL Booklet 2014-15 13

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.

Page 15: SQL booklet 2014-15.docx

SQL Booklet 2014-15 14

Page 16: SQL booklet 2014-15.docx

Queries with Dates

25. List drug names of drugs introduced from 2009 onwards.

select dnamefrom drugwhere doi > '31-Dec-2008' ;

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

select dname, trunc(sysdate – doi) as "Age in days"

from drugwhere months_between (sysdate, doi) > 24 ;

Note: values will vary from those shown dependant on current date

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

select pnofrom drug dr JOIN dose ds

ON dr.dno = ds.dnowhere months_between(dosedate,doi) <= 6 ;

OR

select pnofrom drug dr, dose dswhere dr.dno = ds.dnoand months_between(dosedate,doi) <= 6 ;

28. How old is each patient?

SQL Booklet 2014-15 15

Page 17: SQL booklet 2014-15.docx

select pname, trunc((sysdate - dob)/365.25) as "Age"

from patient;

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 patientwhere gp like '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 drugwhere dname like '%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 patientwhere pname like '%nog%'and dob > '1-jan-1970' ;

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

SQL Booklet 2014-15 16

Page 18: SQL booklet 2014-15.docx

select *from drugwhere dname not like 'slow%' ;

33. 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 patientwhere 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 e.namefrom employee e JOIN employee b

ON e.boss = b.namewhere e.salary > b.salary ;

OR

select e.namefrom employee e, employee bwhere e.boss = b.nameand e.salary > b.salary ;

Intermediate Table

SQL Booklet 2014-15 17

Page 19: SQL booklet 2014-15.docx

Result:

SQL Booklet 2014-15 18

Page 20: SQL booklet 2014-15.docx

Further SQL Examples

35. Give names and patient identifiers of 'married' couples.

select pa.pname as "Mr", pa.pno,pb.pname as "Mrs", pb.pno

from patient pa, patient pbwhere pa.pname = pb.pnameand pa.title = 'mr'and pb.title = 'mrs' ;

OR

select pa.pname as "Mr", pa.pno,pb.pname as "Mrs", pb.pno

from patient pa, patient pbwhere pa.pname = pb.pnameand pa.title = 'mr'and pb.title = 'mrs' ;

36. Get patient names if given drug d7.

(alternative to using IN)

select pnamefrom patient pwhere exists

( select * from dose d where p.pno = d.pno and d.dno = 'd7') ;

37. What about patients who have not been given d7 ?

(alternative to using NOT IN)

select pnamefrom patient pwhere not exists

( select * from dose d where p.pno = d.pno and d.dno = 'd7') ;

SQL Booklet 2014-15 19

Page 21: SQL booklet 2014-15.docx

38. Which patients have been given all the drugs?

select pnamefrom patient pwhere not exists (

select * from drug dr

where not exists (select *

from dose ds where ds.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 pno,dnofrom dose

union

select pno,'none'from patient pwhere not exists

( select * from dose d where p.pno=pno) ;

(NB You can achieve the same thing with an OUTER JOIN)

SQL Booklet 2014-15 20

Page 22: SQL booklet 2014-15.docx

Using NULL values

40. Say incomplete details of a drug are entered:

insert into drug (dno, cost)values ('d10',2.99);

41. Then if we want to know which drugs have not had a name entered for them:

select dnofrom drugwhere dname is null;

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

select dnofrom drugwhere dname is not null;

Calculations

43. What is the total cost of each drug used?

select dr.dno, sum (qty * cost) as "total cost"from drug dr, dose dswhere dr.dno = ds.dnogroup by dr.dno;

44. For each drug how much is the maximum quantity given above the average quantity?

select dno, max(qty) - avg(qty) as "above mean"from dosegroup by dno;

SQL Booklet 2014-15 21

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

Page 23: SQL booklet 2014-15.docx

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 deardrugswhere doi > '1-Jan-2010';

What the DBMS does behind the scenes:

= select dno, unit, doi, costfrom drugwhere doi > '1-Jan-2010'and cost > 1.00;

SQL Booklet 2014-15 22

Page 24: SQL booklet 2014-15.docx

46. 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;

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;

SQL Booklet 2014-15 23

Page 25: SQL booklet 2014-15.docx

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;

orcreate view patdrug (patname, drug, qty)as select pname, dname,qty from patient p join dose ds

on p.pno = ds.pnojoin drug dr

on ds.dno = dr.dno;

SQL Booklet 2014-15 24

Page 26: SQL booklet 2014-15.docx

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 andthe 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

- attempting to update a column in conflict with the view's qualification and the WITH CHECK OPTION is specified

50. create view drugcost ( dno, cost)as select dno, cost

from drug;

SQL Booklet 2014-15 25

Page 27: SQL booklet 2014-15.docx

OK to modify this view because

a) it is drawn from only one base tableb) 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;

thenupdate deardrugsset cost = 0.50where 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 26

Page 28: SQL booklet 2014-15.docx

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 viewselect dnamefrom patient p join dose ds

on p.pno = ds.pnojoin drug dron ds.dno = dr.dno

where pname= 'minogue' ;

ii) with a viewselect dnamefrom patdrugwhere patname = 'minogue';

d) Provide some degree of security

SQL Booklet 2014-15 27

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

Page 29: SQL booklet 2014-15.docx

Data Definition Language (DDL)

Creating Tables

Basic format

CREATE TABLE table_name (column_name format

{, column_name format }{, primary key/foreign key format } );

eg:

CREATE TABLE Patient( Pno VARCHAR2(4) NOT NULL,

Pname VARCHAR2(15) NOT NULL, Title VARCHAR2(4), Dob DATE, Children NUMBER(2), GP VARCHAR2(15),

PRIMARY KEY (Pno) );

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) fixed length character string of n charactersVARCHAR2(n) variable length character string having maximum length nNUMBER(n,d) number made up of n digits with d decimal places.NUMBER(n) whole number made up of n digitsDATE date and time

SQL Booklet 2014-15 28

Page 30: SQL booklet 2014-15.docx

Creating an Index

Basic format:

CREATE [UNIQUE] INDEX indexnameON 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 29

Page 31: SQL booklet 2014-15.docx

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 30

Page 32: SQL booklet 2014-15.docx

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 31

Page 33: SQL booklet 2014-15.docx

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 32

Page 34: SQL booklet 2014-15.docx

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 33

Page 35: SQL booklet 2014-15.docx

26. Put in a new patient, Mrs. Lee who has 2 children and was born on 23-May-50. ( 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 34

Page 36: SQL booklet 2014-15.docx

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 35

Page 37: SQL booklet 2014-15.docx

Appendix B – SQL PRACTICE – Answers

SECTION A

1. select *from drug;

2. select title, pnamefrom patient;

3. select qty, dosedatefrom dosewhere pno = 'p4';

4. select *from patientwhere title in ('mrs', 'miss', 'ms');

5. select pnamefrom patientwhere GP != 'Dr.Spock';

6. select dobfrom patientwhere pname = 'gooch'and title = 'mr';

7. select dnamefrom drugwhere cost < 1.00;

8. select dname, doifrom drugwhere unit = 'mg'or unit = 'gm' ;

9. select pno or select pnofrom patient from patientwhere children between 1 and 3; where children >= 1

and children <= 3;

10. select pno, dob or select pno, dobfrom patient from patientwhere children between 1 and 3 where children >= 1and gp = 'Dr.Williams'; and children <= 3

and gp = 'Dr.Williams';

SQL Booklet 2014-15 36

Page 38: SQL booklet 2014-15.docx

SECTION B

11. select p.pname or select pnamefrom patient p join dose d from patient p, dose d on p.pno = d.pno where p.pno = d.pnowhere dno = 'd1' ; and dno = 'd1' ;

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

12. select dr.dname or select dr.dnamefrom drug dr join dose d from drug dr, dose d on dr.dno = d.dno where dr.dno = d.dnowhere d.pno = 'p1' ; and d.pno = 'p1' ;

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

13. select pname, dno, qty or select pname, dno, qtyfrom patient p join dose d from patient p, dose d

on p.pno = d.pno where p.pno = d.dnowhere gp = 'Dr.Williams' and gp = 'Dr.Williams' and qty >= 5 ; and qy >= 5 ;

14. select distinct d.pno or select distinct d.dno

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

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

15. select distinct d.pname or select distinct d.dnamefrom patient p join dose d from patient p, dose d, on p.pno = d.pno drug d

join drug dr where p.pno = d.pno on d.dno = dr.dno and d.dno = dr.dno

where dr.unit = 'tab' ; and dr.unit = ‘tab’ ;

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

SQL Booklet 2014-15 37

Page 39: SQL booklet 2014-15.docx

16. select distinct p.gp or select distinct p.gpfrom patient p join dose d from patient p, dose d, on p.pno = d.pno drug d

join drug dr where p.pno = d.pno on d.dno = dr.dno and d.dno = dr.dno

where dr.dname = 'bliss' ; and dr.drname = ‘bliss’ ;

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

17. select p.pname, dr.dname, d.dosedatefrom 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.dosedatefrom patient p, dose d, drug drwhere p.pno = d.pnoand d.dno = dr.dnoand dr.cost > 1.00and d.qty <= 5and 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 patientwhere gp = 'Dr.Williams';

20. select min(cost) as "Cheapest Tablet"from drugwhere unit = 'tab';

21. select count(*) as "Mrs Goochs Prescriptions"from patient p,dose dwhere p.pno = d.pnoand pname = 'gooch'and title = 'mrs';

22. select sum(qty) as "Total 'Split' Prescribed"from dose d,drug drwhere d.dno = dr.dno

SQL Booklet 2014-15 38

Page 40: SQL booklet 2014-15.docx

and dname = 'split';

23. select pno as "Most d7"from dosewhere dno = 'd7'and qty in

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

24. select gp as”gp”,count(*) as "Patient Total"from patientgroup by gp;

25. select dno,sum(qty) as "Total Prescribed to p4"from dosewhere pno = 'p4'group by dnohaving sum(qty) >= 5order 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 patientset 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;

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

deletefrom patientwhere pname = 'currie'and title = 'mrs' ;

commit;

set autocommit on;

SQL Booklet 2014-15 39

Page 41: SQL booklet 2014-15.docx

SECTION E

29. select *from patientwhere pname like 'gooc%' ;

30. select *from dosewhere 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 patientwhere trunc (( sysdate – dob ) / 365.25) < 30 ;

32. select title || ' ' || pname as "Name"from drug dr, dose d, patient pwhere dr.dno = d.dnoand d.pno = p.pnoand dr.unit = 'tab'and trunc ((dosedate – dob) / 365.25) >= 25 ;

33. select *from patientwhere 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 pwhere dr.dno = d.dno and d.pno = p.pno and gp = 'Dr.Williams' ;

35. select dname,sum(qty)from drug dr, dose d, patient pwhere dr.dno = d.dno and d.pno = p.pno and gp != 'Dr.Spock'group by dname

UNION

select dname, 0from drug drwhere dno not in ( select dno from dose d, patient p where p.pno = d.pno and gp!= 'Dr.Spock') ;

SQL Booklet 2014-15 40

Page 42: SQL booklet 2014-15.docx

36. select pname || ', ' || title as "Name"from patientwhere gp in ( select gp from patient where pname = 'mansell'

and title = 'mr')and not ( pname = 'mansell' and title = 'mr' );

37. select dnamefrom drugwhere doi > ( select doi from drug where dname = 'slow down');

SECTION F

38. create view patientdose (PatientName,DrugNo,DateGiven,Qty)asselect pname,dno,dosedate,qtyfrom dose d, patient pwhere p.pno = d.pno ;

39. create view drugdose (DrugName,DateGiven,Qty,DoseCost)asselect dname,dosedate,qty,(qty*cost)from drug dr, dose dwhere dr.dno = d.dnoand dosedate > '1-jan-2004';

40. create view drugsummary (Drugname,TotalQty,TotalCost)asselect drugname,sum(qty),sum(dosecost)from drugdosegroup by drugname ;

41. select patnamefrom patientdosewhere drugno = 'd1'

42. select dategiven,dosecostfrom drugdosewhere drugname = 'split'and dosecost in

(select max(dosecost)from drugdose

SQL Booklet 2014-15 41

Page 43: SQL booklet 2014-15.docx

where drugname = 'split')

43. select drugname,totalqty,totalcostfrom drugsummary ds,drug drwhere ds.drugname = dr.dnameand unit = 'tab';

44. select drugnamefrom drugdosegroup by drugnamehaving sum(dosecost) in (select max(sum(dosecost)) from drugdose group by drugname);

SQL Booklet 2014-15 42

Page 44: SQL booklet 2014-15.docx

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{unionSubselect}

[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 expressionexpression comparison-operator any|all (subquery)expression is [not] nullexpression [not] like 'pattern'

pattern may contain-and/or % as wild card charactersExpression [not] between expression and expressionExpression [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:

countsumavgmaxmin

SQL Booklet 2014-15 43

Page 45: SQL booklet 2014-15.docx

OTHER USEFUL COMMANDS:

CREATE VIEWcreate view viewname [columnname{,columnname}}as select ….

DROP VIEWdrop view viewname {,viewname}

(Similarly with create/drop table, create/drop index etc.)

ALTER TABLEUse 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 DATABASEselect * from tabs

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

SQL Booklet 2014-15 44

Page 46: SQL booklet 2014-15.docx

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 LRC’s, 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 45

Page 47: SQL booklet 2014-15.docx

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 asUsername: The username you were provided with, likely to be the same as

your standard university account namePassword: The password for your account

SQL Booklet 2014-15 46

Page 48: SQL booklet 2014-15.docx

Hostname: vclsaorateach.herts.ac.uk, this is the server on which the OracleDatabase Instance is installed

Port: Replace with 1523SID: 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 47

Page 49: SQL booklet 2014-15.docx

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 48

Page 50: SQL booklet 2014-15.docx

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 49