SQL Queries
SQL Queries
SQL QUERIES
1
SQL TEXTBOOK
SELECTing Attributes Using ORDER BY SELECTing Rows Using AND Using OR Using Between
Chapter
INTRODUCTION TO SQL
Data management - uses a set of commands to enter, correct, delete, and update data within the database tables
Data query - uses a set of command to retrieve records from the database
SELECT FROM
PATIENT DATABASE
ER Diagram Relations: SQL: CREATE TABLE PHYSICIAN (PhysicianID char(3) PhysicianName varchar2(35) NOT NULL, AreaCode char(3), LocalNumber char(8) NOT NULL, CONSTRAINT PhysicianPKey PRIMARY KEY (PhysicianID)); CREATE TABLE PATIENT (AccountNumber char(5), Name varchar2(35) NOT NULL, Age number(2), Gender char(1), Balance number(7,2), DoctorID char(3) NOT NULL, CONSTRAINT PatientPKey PRIMARY KEY (AccountNumber), CONSTRAINT PatientFKey FOREIGN KEY (DoctorID) REFERENCES PHYSICIAN); PhysicianID Physician AreaCode LocalNumber Name V11 V12 V13 V14 Kalayta Roberts Nolte Gibson 312 773 847 333-3333 888-8888 666-6666 777-7777
Physician
treats
Patient
Foreign Key
PHYSICIAN (PhysicianID, PhysicianName, AreaCode, LocalNumber) PATIENT (AccountNumber, Name, Age, Gender, Balance, DoctorID)
INSERT INTO PHYSICIAN VALUES (V13 Nolte, null, 666-6666); Account Doctor Number Name Age Gender Balance ID 10001 10002 10003 10004 Tootsie 10 Female 100.00 V11 Rambo 7 Male 0.00 V14 Whitey 1 Male 550.00 V14 Trigger 20 Male 99.00 V12 4
Syntax:
SELECT <column(s)> FROM <table name>; SELECT Name, Age FROM PATIENT;
Name Age Tootsie 10 Rambo 7 Whitey 1 Trigger 20 5
Account Doctor Number Name Age Gender Balance ID 10001 10002 10003 10004 Tootsie 10 Female 100.00 V11 Rambo 7 Male 0.00 V14 Whitey 1 Male 550.00 V14 Trigger 20 Male 99.00 V12
Syntax:
SELECT <column(s)>
FROM <table name> WHERE <conditions>; SELECT Name, Age FROM PATIENT WHERE Gender = Male;
Name Age Rambo 7 Whitey 1 Trigger 20
MATHEMATICAL OPERATORS
SYMBOL MEANING
=
< <= > >= !=
Example:
List all physicians not in area code 312
Equal to
Less than Less than or equal to Greater than Greater than or equal to Not equal to
Records with a NULL area code are not selected. Single quotes required because AreaCode is a text field PhysicianID PhysicianName AreaCode LocalNumber V12 V14 Roberts Gibson 773 847 888-8888 777-7777 7
LOGICAL OPERATORS
SYMBOL MEANING
AND
OR NOT
Example:
SELECT * FROM PATIENTS WHERE Gender = Male AND Balance > 0.00;
Account Doctor Number Name Age Gender Balance ID 10003 Whitey 1 Male 10004 Trigger 20 Male 550.00 V14 99.00 V12
LOGICAL OPERATORS
SYMBOL MEANING
AND
OR NOT
Example:
SPECIAL OPERATORS
SYMBOL MEANING
BETWEEN
IS NULL LIKE IN
10
BETWEEN
The condition BETWEEN is used to define attribute limits.
Example:
A listing of all patient names who are between 1 and 15 years old.
SELECT Name FROM PATIENT WHERE Age BETWEEN 1 and 15; SELECT Name FROM PATIENT WHERE Age >= 1 AND Age <= 15;
11
IS NULL
Standard SQL allows the use of IS NULL to check for an attribute value that has never been entered.
Example:
SELECT PhysicianName FROM PHYSICIAN WHERE AreaCode IS NULL; SELECT PhysicianName FROM PHYSICIAN WHERE AreaCode = OR AreaCode = ;
PhysicianName Nolte
PhysicianName
12
LIKE
SQL allows the use wildcard characters percent (%) and underscore (_) to make matches when the entire string is not know; % means any and all following characters are eligible _ means any one character may be substituted for the under score The conditional LIKE must be used in conjunction with the wildcard characters.
Example:
A listing of all physician IDs whose patients name begin with the letter T. DoctorID V11 V12
A listing of all patient named Toots or Tootsy or any similar spelling. Name Tootsie Name Rambo Whitey Trigger
What is the output listing produced from SELECT Name FROM PATIENT WHERE NOT LIKE Toots%;
13
IN
Many queries that would require the use of the logical OR can be more easily handled with the help of the special operator IN.
Example:
A listing of all patient names whose doctor has DoctorID V14 or V12. Name Rambo Whitey Trigger
14
An advantage of SQL is its ability to let the user produce complex free-form queries SQL provides useful functions
Distinct values (i.e. no duplicates) Grouping duplicates Subqueries Join - retrieving data from more than one table
15
ORDERING A LISTING
SQLs ORDER BY clause is used to produce a listing in a specific sequence. Syntax: ORDER BY <attributes> Produces a list in ascending order. Syntax: ORDER BY <attributes> DESC
ORDERING A LISTING
Example: List the contents of the PATIENTs table in order by patient name (descending) within physician ID (ascending). Account Doctor Number Name Age Gender Balance ID 10001 10004 10002 10003 Tootsie 10 Female 100.00 V11 Trigger 20 Male 99.00 V12 Rambo 7 Male 0.00 V14 Whitey 1 Male 550.00 V14
SELECT * FROM PATIENT ORDER BY DoctorID, Name DESC; Example: List the contents of the PHYSICIAN table in order by area code.
PhysicianID PhysicianName AreaCode LocalNumber V13 V11 V12 V14 Nolte Kalayta Roberts Gibson 312 773 847 666-6666 333-3333 888-8888 777-7777
Records with a null area code will be listed first,then the remaining records in ascending sequence.
Write the SELECT statement to create a telephone listing for physicians. SELECT PhysicianName, AreaCode, LocalNumber FROM PHYSICIAN ORDER BY PhysicianName;
MULTIPLE RESTRICTIONS
ORDER BY clause may be used in conjunction with other SQL clauses. Note: If columns contain nulls, the nulls are always listed first, regardless of an ascending or descending sequence. Note: The ORDER BY must always be listed last in the command sequence. Example: Produce a listing of all male patients by age. Account Doctor Number Name Age Gender Balance ID 10003 Whitey 1 Male 550.00 V14 10002 Rambo 7 Male 0.00 V14 10004 Trigger 20 Male 99.00 V12
18
Example:
Produce a listing of all physicians Ids that are currently treating patients. Doctor ID V11 V12 V14 V14
To remove the duplicates, use the DISTINCT Clause. SELECT DISTINCT DoctorID FROM PATIENT;
Doctor ID
V11 V12 V14 19
Example:
Name of Expression
SELECT COUNT (Distinct AreaCode) AS NumberOfAreaCodes FROM PHYSICIAN; SELECT COUNT (*) AS NumberOfAreaCodes FROM PHYSICIAN;
NumberOfAreaCodes 3 Does not count nulls unless the wildcard character is used.
NumberOfAreaCodes 4
20
MIN MAX
SQL will perform various mathematical summaries. FUNCTION COUNT MIN MAX SUM AVG OUTPUT The number of rows containing the specified attribute The minimum attribute value encountered The maximum attribute value encountered The sum of all values for a selected attribute The arithmetic average for the specified attribute
Youngest 1
21
Although these queries seem like they should work, we do not get the expected results because SELECT yields a list of many NAMES, and the numeric functions yield only one value based on all the values found in the table, i.e. a single maximum value, a single minimum value, a single count, etc.
Expr1001 7 10 20 1
For each group of Rambos the max age is 7, for each group of Tootsies the max age is 10, etc.
22
SUBQUERIES
Example: What is the name and age of the oldest patient? Overcome the limitation of a single value by using a procedure known as a nested query (Subquery).
A nested query (subquery) is a query within a query. The nested query is composed of two parts: The inner loop which is executed first. The outer loop which is executed last. The outer loop is always the first SQL command (Select) encountered in the command sequence. SELECT Name, Age FROM PATIENT WHERE Age = (SELECT MAX (Age) AS Oldest FROM PATIENT); Name Trigger Age 20
23
Sum
Computes the total for any specified attribute, using whatever condition(s) are specified. Example: Sum the ages of all the patients. TotalAges 38 SELECT SUM (Age) AS TotalAges FROM PATIENT;
SQL commands are often used in conjunction with the following arithmetic operators: Operator * / + Example: Description Multiply Divide Add Subtract Include a 10% handling fee on all balances over $99.00.
name balance New Balance
SELECT Name, Balance, (Balance * 1.10) as New Balance from Patient where Balance > 99;
Tootsie
Whitey
100
550
110
605
24
AVG (Average)
AVG function conforms to that of MIN and MAX and is subject to the same operating instructions. Example: What is the average patient age? AverageAge 9.5
What is the average age of each physicians patients? Want to obtain the following results:
DoctorID
V11 V12 V14
AverageAge
10 20 4
25
Grouping Data
GROUP BY clause creates frequency distributions.
SELECT DoctorID, AVG (Age) AS AverageAge FROM PATIENT GROUP BY DoctorID; DoctorID V11 V12 V14
AverageAge 10 20 4
GROUP BY clause cannot keep track of attributes that have not been specified in the SELECT command. Example: SELECT * FROM PATIENT GROUP BY DoctorID;
26
HAVING CLAUSE
Having Clause can be used to identify a subset of groups. Example: List number of patients by gender.
Number of Patient 1 3
Example:
List the gender and number of patients for each gender, where the number of patients is greater than 2
Select gender, count(*) as Number of Patients From Patient Group by gender Having count(*) > 2;
gender Male
Number of Patient 3
27
Requires the retrieval of data from two tables: PATIENT - Name PHYSICIAN PhysicianName, AreaCode & LocalNumber SELECT Name, PhysicianName, AreaCode, LocalNumber FROM PHYSICIAN, PATIENT; Returns PRODUCT of PHYSICIAN & PATIENT 4 x 4 = 16 rows
28
SQL JOIN
SELECT Name, PHYSICIAN.PhysicianName, AreaCode, LocalNumber FROM PATIENT, PHYSICIAN WHERE PhysicianID = DoctorID; The patient Name is part of the PATIENT table; the PhysicianName, AreaCode and LocalNumber are part of the PHYSICIAN table. The two tables are related by the presence of a physician ID in both tables. (primary key of the PHYSICIAN table and foreign key of the PATIENT table) The query to satisfy the information requested therefore requires an join of the two tables on the physician ID. The result is ... Name Tootsie Trigger Rambo Whitey PhysicianName Kalayta Roberts Gibson Gibson AreaCode 312 773 847 847 LocalNumber 333-3333 888-8888 777-7777 777-7777
The join is between a primary key in one table and a foreign key in another.
29
LEFT JOIN
SELECT Name, PhysicianName, AreaCode, LocalNumber FROM PATIENT LEFT JOIN PHYSICIAN ON PATIENT.DoctorID = PHYSICIAN.PhysicianID;
In this example, this is the same as an Natural Join because it is impossible to have a patient without a physician. If there could be a patient without a physician, then the patients name would be listed and the remaining fields would be null.
30
RIGHT JOIN
SELECT Name, PHYSICIAN.PhysicianName, AreaCode, LocalNumber FROM PATIENT RIGHT JOIN PHYSICIAN ON PATIENT.PhysicianName = PHYSICIAN.PhysicianName;
31
An alias may be used to identify the table from which the date are taken. Used aliases A and B to label the PATIENT and PHYSICIAN tables. Any legal table name may be used as an alias.
32
EXERCISES
Q1. List each doctors name and the number of patients assigned to them. SELECT PhysicianName, count(name) as [Number of Patients] from physician as A left join patient As B on A.physicianID = B.doctorID group by B.doctorid, A.physicianname PhysicianName
Nolte Kalayta Roberts Gibson
Need to do a LEFT JOIN because the request implies that doctors with no patients should be included in the listing
Number of Patients 0 1 1 2
Q2. List the doctors name and their patients name for those doctors that have more than 1 patient. Select PhysicianName, name from physician, patient where physicianid = doctorid and doctorid in (Select doctorid from patient group by doctorid having count(doctorid) > 1 )
33
COMPANY DATABASE
EMPLOYEE (fname, minit, lname, ssn, bdate, address, gender, salary, superssn, dno) Foreign Key1 superssn references EMPLOYEE(ssn) Foreign Key2 dno references DEPARTMENT (dnumber) DEPARTMENT (dname, dnumber, mgrssn, mgrstartdate) Foreign Key mgrssn references EMPLOYEE(ssn) PROJECT (pname, pnumber, plocation, dnum) Foreign Key dnum references DEPARTMENT (dnumber) DEPT_LOCATIONS (dnumber, dlocation) Foreign Key dnumber references DEPARTMENT(dnumber) ASSIGNMENT (essn, pno, hours) Foreign Key1 essn references EMPLOYEE (ssn) Foreign Key2 pno references PROJECTS (pnumber) DEPENDENT (essn, dependent_name, gender, bdate, relationship) Foreign Key essn references EMPLOYEE (ssn)
34
QUERY REQUESTS
1.
2.
35
QUERY REQUESTS
3.
4.
What are the names of the employees making more than $30,000 per year?
36
QUERY REQUESTS
5.
6.
37
QUERY REQUESTS
7.
8.
38
QUERY REQUESTS
9.
10.
39
QUERY REQUESTS
11.
List the name and address of every employee who works in Research department
12.
40
QUERY REQUESTS
13.
List the names of all employees and the name of their dependent(s). If the employee has no dependents, then just list the employees name.
41
QUERY REQUEST
14.
List the names of all employees and the name of their supervisor. Employees without a supervisor should also be listed.
42
QUERY REQUEST
15.
For every project located in Stafford, list the project number, the controlling department number, and the department managers last name, address and birth date.
43
ASSIGNMENT SEVEN
Review
44