Universyty of Technology Sydney SQL - Exam Notes 2020

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Jyotsna Arora 97117461

SQL Exam Notes

SELECT: List the columns (and expressions) to be returned from


the query
FROM: Indicate the table(s) or view(s) from which data will be
obtained
WHERE: Indicate the conditions under which a row will be
included in the result
GROUP BY: Indicate categorization of results
HAVING: Indicate the conditions under which a category (group)
will be included
ORDER BY: Sorts the result according to specified criteria

 Distinct is used to eliminate duplicates


 Operators that are used in where clause: between, and/or, like, is not null, in
 The WHERE clause can contain several conditions linked by AND or OR.
 In a WHERE containing one or more ANDs all specified conditions must be
true.
 In a WHERE containing one or more ORs, at least one of the conditions must
be true.
 If you mix ANDs and ORs, the ANDs have precedence.
 The LIKE operator allows you to compare strings using wildcards.
 With parentheses, you can override normal precedence rules. In this case
parentheses make the OR take place before the AND.
 you CANNOT write either = NULL or <> NULL. Need to write is not null
 The IN operator in this example allows you to include rows whose
CustomerState value is either FL, TX, CA, or HI.
 Using group by: you can categorize your results into several groups,
 then analyse the data in each group based on your required information.
 Aggregate functions such as AVG, SUM, MIN, MAX and COUNT can be used to analyse the data in
each group
 select round(avg(productstandardprice), 2) from product_t;
 ‘*’ means “the whole row”. Count function to find the number of
rows. Nulls values in a column is not counted
 Select customerstate, count(customerstate) from customer_t group by customerstate Order by
customerstate;
 Scalar aggregate: single value returned from SQL query with aggregate function
 select avg(productstandardprice) from product_t;
 Vector aggregate: multiple values returned from SQL query with
aggregate function (via GROUP BY)
 Select column1, column2
 From Table1
 Where [Condition on rows]
 Group by column1, column2
 Having [Condition on groups]
 Order by column1
 Boolean operators (), NOT, AND, OR (in this order)
 Between operator counts the end points as well hence must use < and > to
get the right answer

 Join comes in after from clause and before where clause. Part of the from
clause
 INNER JOIN clause is an alternative to WHERE clause and is used to match primary and foreign keys.
 An INNER join will only return rows from each table that have matching rows in the other.
 Natural Join is automatic inner join though eliminates the duplicate columns in the result table.
 Cross join: first row in table a against all rows in table b.
 Left outer join produces a complete set of records from Table A , with the matching records (where
available) in Table B. If there is no match, the right side will contain null.
Jyotsna Arora 97117461

Subquery
 In a condition of the WHERE
clause
 As a “table” of the FROM clause
 Within the HAVING clause
 Subqueries (Nested queries) can
be:
o Non-correlated (Simple
or Type 1): executed
once for the entire outer
query
o Correlated: executed
once for each row
returned by the outer
query
 ALL operator to find min and max
 A correlated subquery always refers to an attribute from a table referenced in the outer query
 The EXISTS operator will return a TRUE value if the subquery resulted in a non-empty set, otherwise
it returns a FALSE.
 Noncorrelated subqueries:
o Do not depend on data from the outer query
o Execute once for the entire outer query
 Correlated subqueries:
o Make use of data from the outer query
o Execute once for each row of the outer query
Jyotsna Arora 97117461

o Can use the EXISTS operator

 Instead of SELECT *, identify the specific attributes in the SELECT clause; this helps reduce
network traffic of result set
 Limit the number of subqueries; try to make everything done in a single query if possible
 If data is to be used many times, make a separate query and store it as a view
 Understand how indexes are used in query processing
 Write simple queries
 Break complex queries into multiple simple parts
 Don’t nest one query inside another query
 Don’t combine a query with itself (if possible avoid self-joins)
 Retrieve only the data you need

Tut 1:
List all drugs ordered by price in descending order, and DrugName in ascending order; show all columns.
select * from drug order by drugprice desc, drugname;
List Drugs that cost between 10 and 20 dollars. select drugName from drug where drugPrice between 10 and
20;
Give the total number of rows in the drug table. select sum (drugprice) from drug where drugname in
('Panadol','Aspirin');
How many different drug methods are recorded in the Drug table? select count (distinct(drugmethod)) from
drug ;
Give the average price of drugs for each drug method; do not include drug methods with only one drug.
select DrugMethod, avg(DrugPrice) from Drug where DrugMethod is not null group by DrugMethod having
count(*) > 1; Give the average price of drugs for each DrugMethod. select DrugMethod, avg(DrugPrice) from
Drug where DrugMethod is not null group by DrugMethod;
Tut2:
Jyotsna Arora 97117461

List all the ward numbers that have staff members from Victoria state. Eliminate duplicate values.
Select distinct(wardno) from nurseward inner join staff on staff.staid=nurseward.nurid where stastate= 'VIC'
and statype='N';
List all the ward numbers where staff from New South Wales state have worked in. Organize the list
alphabetically descending and avoid duplicates in the result.
select distinct(wardno) from nurseward inner join staff on nurseward.nurid=staff.staid where stastate='NSW';
List all the ward numbers and the ward name that “Christopher Hanton” has worked in.
Select ward.wardno, wardname from ward inner join Nurseward on ward.wardno=nurseward.wardno inner join
staff on nurseward.nurid=staff.staid where stafname='Christopher' and stalname='Hanton';

List full name and salary of staff who get paid more than Christopher Hanton (S632).
select s1.stafname, s1.stalname from staff s1, staff s2 where s1.stacsalary>s2.stacsalary and s2.staid= 'S632';
List full name of the staff whose salary fall between the salary of Mikalya Vida (S837) and Natasha
Laboureyas (S673), not inclusive.
select s1.stafname, s1.stalname, s1.stacsalary from staff s1, staff s2, staff s3 where s1.stacsalary > s2.stacsalary
and s1.stacsalary < s3.stacsalary and s2.staid = 'S837' and s3.staid = 'S673';
List all ward numbers and staff ID of those who have worked in them. (Give two different ways of
constructing this query).
select ward.wardno, nurid from ward left outer join nurseward on ward.wardno = nurseward.wardno order by
ward.wardno;
Or
select ward.wardno, nurid from nurseward right outer join ward on nurseward.wardno = ward.wardno order by
ward.wardno;
Which staff members have not worked in any wards?
select staid from staff left outer join nurseward on staff.staid = nurseward.nurid where nurid is null;
List all the available wards in 2014 (ward2014) and the capacity of those that are still available.
Select w1.wardname, w2.wardcap from ward2014 w1 left outer join ward w2 on w1.wardno= w2.wardno;
Which wards used to be active in 2014, and are not provided anymore?
select w1.wardname from ward2014 w1 left outer join ward w2 on w1.wardno = w2.wardno where w2.wardno
is null;

List all the wards that were available in both the ward2014 and the current wards?
select w1.wardname, w2.wardname from ward2014 w1 full outer join ward w2 on w1.wardno = w2.wardno;

Tut3
List all admission dates and their symptoms for patient “Jane Adams”.
a) join: select PatAdmDate, PatSymp from PatMChart, Patient where PatFName= 'Jane' and PatLName=
'Adams' and PatMChart.PatID = Patient.PatID;
b) simple subquery: select PatAdmDate, PatSymp From PatMChart Where PatID in (select PatID From Patient
Where PatFName= 'Jane' and PatLName= 'Adams');

Give all patients that originate from the same state as “Mitchell Newell”.
a) join: select p1.PatFName, p1.PatLName from Patient p1, Patient p2 where p1.PatState = p2.PatState and
p2.PatFName = 'Mitchell' and p2.PatLName = 'Newell' and p1.PatFName <> 'Mitchell' and p1.PatLName <>
'Newell';
b) simple subquery: select PatFName, PatLName from Patient where PatFName <> 'Mitchell' and PatLName <>
'Newell' and PatState = (select PatState from Patient where PatFName = 'Mitchell' and PatLName = 'Newell');

Give drugs with prices that fall between the price of Nurofen and Morphine inclusively.
a) join: select d1.DrugName, d1.DrugPrice from Drug d1, Drug d2, Drug d3 where d1.DrugPrice between
d2.DrugPrice and d3.DrugPrice and d2.DrugName = 'Nurofen' and d3.DrugName = 'Morphine';
b) simple subquery: select d1.DrugName, d1.DrugPrice from Drug d1 where d1.DrugPrice >= (select DrugPrice
from Drug where DrugName='Nurofen') and d1.DrugPrice <= (select DrugPrice from Drug where
DrugName='Morphine');
Jyotsna Arora 97117461

Give the name and price of the most expensive drug.


select drugname, drugprice from drug where drugprice = (select max(drugprice) from drug);

List drugs costing less than the average price.


select drugname, drugprice from drug where drugprice < (select avg(drugprice) from drug);

Give drug names and prices for drugs that are less expensive than all drugs with dosage “As prescribed by
doctor” (Hint: use > all predicate).
select drugname, drugprice from drug where drugprice < (select min(drugprice) from drug where drugdosg =
'As prescribed by doctor');
OR
select DrugName, DrugPrice from Drug where DrugPrice < all (select DrugPrice from Drug where DrugDosg =
'As prescribed by doctor');

List all patient IDs and names who have been prescribed Panadol or Nurofen (Hint: use =any predicate)
select patid, patfname, patlname from patient where patid in (select distinct patid from prescribeddrug where
drugno in (select drugno from drug where drugname = 'Panadol' or drugname = 'Nurofen'));
OR
select distinct PatFName, PatLName from PrescribedDrug, Patient where Patient.PatID = PrescribedDrug.PatID
and DrugNo in (select DrugNo from drug where drugname = 'Panadol' or drugname = 'Nurofen'); OR select
distinct PatFName, PatLName from PrescribedDrug, Patient where Patient.PatID = PrescribedDrug.PatID and
DrugNo = any (select DrugNo from Drug where DrugName = 'Panadol' or DrugName = 'Nurofen') order by
PatFName;

Give the patient name which has been prescribed the highest amount of Panadol (D1486032).
select patfname, patlname from patient where patid = (select patID from prescribeddrug where drugamt = (select
max(drugamt) from prescribeddrug where drugno = 'D1486032') and drugno = 'D1486032');
OR
select patfname, patlname, drugno, drugamt from patient, prescribeddrug where patient.patId =
prescribeddrug.patId and drugamt = (select max(drugamt) from prescribeddrug where drugno = 'D1486032') and
drugno = 'D1486032';

List patient chart admission date and diagnostics for all patients which have been prescribed Vitamin C.
select patadmdate ,patdiag from patmchart, prescribeddrug where patmchart.patcid = prescribeddrug.patcid and
drugno = (select drugno from drug where drugname = 'Vitamin C');
OR
select patadmdate ,patdiag from patmchart where (patid, patcid) in (select patid, patcid from prescribeddrug
where drugno in (select drugno from drug where drugname = 'Vitamin C'));

Find the patient chart ID which uses the largest number of different drugs.
select PatCID, count(*) from PrescribedDrug group by PatCID having count(*) >= all (select count(*) from
PrescribedDrug group by PatCID);

Give the drug name and description used for the most recent patient chart. select drugname, drugdesc from drug
where drugno = (select drugno from prescribeddrug where patcid = (select patcid from patmchart where
patadmdate = (select max(patadmdate) from patmchart)));

Tut4
List all drugs with method “Oral use with water” and any patient charts that includes these drugs (Give two
different ways of constructing this query).
select Drug.DrugNo, Drug.DrugName, Drug.DrugMethod,PrescribedDrug.PatCID from Drug left outer join
PrescribedDrug on Drug.DrugNo = PrescribedDrug.DrugNo where Drug.DrugMethod = 'Oral use with water'
order by Drug.DrugNo;
OR
select Drug.DrugNo, Drug.DrugName, Drug.DrugMethod,PrescribedDrug.PatCID from PrescribedDrug right
outer join Drug on Drug.DrugNo = PrescribedDrug.DrugNo where Drug.DrugMethod = 'Oral use with water'
order by Drug.DrugNo;

List all drugs with method ‘Oral use with water’ and all patient charts (those patient charts that include oral use
with water drugs and those that do not)
Jyotsna Arora 97117461

select PC.patCID,TBL1.DrugNo, TBL1.DrugName, TBL1.DrugMethod from PatMChart PC full outer join


(select pdr.DrugNo, d.DrugName, d.DrugMethod, pdr.PatCID from Drug d left outer join PrescribedDrug pdr on
d.DrugNo = pdr.DrugNo where d.DrugMethod ='Oral use with water') TBL1 on PC.PatCID = TBL1.PatCID;

Which drugs are not used in any patient chart? (use uncorrelated/simple subquery operation)
select DrugNo, DrugName from Drug where DrugNo not in (select DrugNo from PrescribedDrug);

Which drugs are not used in any patient chart? (use correlated subquery operation)
select DrugNo, DrugName from Drug d where not exists (select * from PrescribedDrug pdr where pdr.DrugNo
= d.DrugNo); OR select DrugNo, DrugName from Drug d where not exists (select DrugNo from
PrescribedDrug pdr where d. DrugNo = pdr.DrugNo);

List each drugNo and the patient chart ID that have been prescribed with the largest amount of this drug(use
correlated subquery).
select DrugNo, PatCID, DrugAmt from PrescribedDrug pd where DrugAmt = (select max(DrugAmt)from
PrescribedDrug where DrugNo = pd.DrugNo);

List DrugNo that are used in more than one patient chart (use correlated subquery operation).
select distinct DrugNo from PrescribedDrug pdr where DrugNo in (select DrugNo from PrescribedDrug where
PatCID <> pdr.PatCID);
OR
select distinct DrugNo from PrescribedDrug pdr where DrugNo in (select DrugNo from PrescribedDrug group
by DrugNo having count(*)>1 and DrugNo = pdr. DrugNo);

Insert a row into the drug table with the following values: (‘D5011702’,‘Zyrtec’, ‘Zyrtec 10mg 70 Tablets’,
‘Every 8 hrs’, ‘Oral use with water’,29.99)
insert into Drug (DrugNo, DrugName, DrugDesc, DrugDosg, DrugMethod, DrugPrice) values
('D5011702','Zyrtec', 'Zyrtec 10mg 70 Tablets', 'Every 8 hrs', 'Oral use with water',29.99);

Increase the PRICE of the Aspirin Drug by 10%.


update Drug set DrugPrice = DrugPrice*1.1 where DrugName = 'Aspirin';

Delete the Zyrtec drug


delete from Drug where DrugName = 'Zyrtec';

Pizza
Find the pizza which uses the smallest number of ingredients.
Select pizza from recipe group by pizza having count(*) <= all (select count(*) from recipe group by pizza)

List the ingredients, and for each ingredient, also list the pizza that contains the largest amount of this
ingredient.
select ingredient, pizza, amount from recipe r where amount =(select max(amount) from recipe where
recipe.ingredient=r.ingredient)

List all 'meat' ingredients used in pizzas, also list the pizza names. Do not use a subquery.
Select recipe.ingredient, pizza from recipe, items where items.ingredient=recipe.ingredient and items.type=
'meat'

Give pizzas and prices for pizzas that are more expensive than all Italian pizzas. You must use a subquery.
select pizza, price from menu where price > (select max(price) from menu group by country having country
='italy')

Give cheapest price of pizzas from each country of origin, only list countries with cheapest price of less
than $7.00
select country, min(price) from menu where price < 7 group by country having country is not null
or
select country, min(price) from menu group by country having min(price)<7 and country is not null

Give the average price of pizzas from each country of origin, do not list countries with only one pizza.
select country, avg(price) from menu group by country having count(*) >1 and country is not null
Jyotsna Arora 97117461

List all pizzas that cost less than 'siciliano' pizza, also give their prices
select pizza, price from menu where price < (select price from menu where pizza ='siciliano') and
pizza<>'siciliano'

List all ingredients for the Italian pizza (i.e. country = 'italy'). You must use a subquery.
select distinct(ingredient) from recipe where pizza in (select pizza from menu where country ='italy')

List all ingredients for the Mexican pizza (i.e. country = ‘mexico’). You must use a subquery.

List all ingredients and their types for the ‘margarita’ pizza. Do not use a subquery.
select items.ingredient, type from items inner join recipe on recipe.ingredient = items.ingredient and pizza
='margarita';

List pizzas with at least one meat ingredient. You must use a subquery.
select distinct(pizza) from recipe where ingredient in (select ingredient from items where type ='meat');

Give all pizzas that originate from the same country as siciliano.
select pizza from menu where country = (select country from menu where pizza = 'siciliano') and pizza <>
'siciliano';

List all ‘fish’ ingredients used in pizzas, also list the pizza names. Do not use a subquery.
select recipe.ingredient, pizza from recipe inner join items on items.ingredient = recipe.ingredient and type
='fish';

List ingredients used in more than one pizza (use correlated subquery operation).
select distinct ingredientfrom recipe rwhere ingredient in (select ingredientfrom recipewhere pizza <> r.pizza);
OR
select distinct ingredient from recipe r where ingredient in (select ingredient from recipe group by ingredient
having count(*)>1 and ingredient=r.ingredient);

List ingredients that are not used in any pizzas.


select ingredient from items where ingredient not in (select ingredient from recipe);

List ingredients that are used in more than one pizza.


Select distinct(ingredient) from recipe group by ingredient having count(*)>1;

List al pizzas that cost more than ‘stagiony’ pizza. Also give their prices.
select pizza, price from menu where price > all(select price from menu where pizza ='stagiony');

List all pizzas that cost less than ‘siciliano’ pizza, also give their prices.
Select pizza, price from menu where price < all(select price form menu where pizza = ‘siciliano’)
Jyotsna Arora 97117461

You might also like