You are on page 1of 44

CSC 451 Database Design

SQL QUERIES
1

SQL TEXTBOOK

Recommended DePaul Library 24x7 books

Practical Guide to Using SQL in Oracle


Chapter

2 Extended SELECT statement

SELECTing Attributes Using ORDER BY SELECTing Rows Using AND Using OR Using Between

Chapter

3 Joins Chapter 4 Functions

All except the Data Dictionary Revisited

INTRODUCTION TO SQL

Database language categories

Data definition - creates the database and its table structures


CREATE TABLE CREATE INDEX

Data management - uses a set of commands to enter, correct, delete, and update data within the database tables

INSERT UPDATE DELETE ALTER

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

PROJECTION USING SQL


Complete Table Listing: Syntax: SELECT * FROM <table name>;

Partial Table Listing (Vertical Subset): Example: SELECT * FROM PATIENT;

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

SELECTION USING SQL


Table Listing (horizontal subset): Syntax: SELECT * FROM <table name> WHERE <conditions>;

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

Example: SELECT * FROM PATIENT WHERE Gender = Male;


Account Doctor Number Name Age Gender Balance ID 10002 Rambo 7 Male 10003 Whitey 1 Male 10004 Trigger 20 Male 0.00 V14 550.00 V14 99.00 V12

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

SELECT * FROM PHYSICIAN WHERE AreaCode != 312;

LOGICAL OPERATORS
SYMBOL MEANING

AND
OR NOT
Example:

All conditions must be True


At least one condition must be True Negation

A listing of all male patients with a balance due

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:

All conditions must be True


At least one condition must be True Negation

A listing of patients names who are under 10 years of age or female.

SELECT Name FROM PATIENT WHERE Age < 10 OR Gender = Female;


Name Tootsie Rambo Whitey

SPECIAL OPERATORS
SYMBOL MEANING

BETWEEN
IS NULL LIKE IN

Used to define range limits


Used to check whether an attribute value is null Used to check for similar character strings Used to check whether an attribute value matches a value contained within a (sub)set of listed values

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;

Name Tootsie Rambo Whitey

11

IS NULL
Standard SQL allows the use of IS NULL to check for an attribute value that has never been entered.

Example:

A listing of all physician names that are missing an area code.

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

SELECT DoctorID FROM PATIENT WHERE Name LIKE T%; Example:

A listing of all patient named Toots or Tootsy or any similar spelling. Name Tootsie Name Rambo Whitey Trigger

SELECT Name FROM PATIENT WHERE Name LIKE Toots%;

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

SELECT Name FROM PATIENT WHERE DoctorID = V14 OR DoctorID = V12;

SELECT Name FROM PATIENT WHERE DoctorID IN (V14, V12);

14

COMPLEX SQL QUERIES

An advantage of SQL is its ability to let the user produce complex free-form queries SQL provides useful functions

count minimum value maximum value average value sum

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

Produces a list in descending order.


Example: List the contents of the PATIENTs table in order by physician ID. 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 16

SELECT * FROM PATIENT ORDER BY DoctorID;

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;

PhysicianName AreaCode LocalNumber


Gibson Kalayta Nolte Roberts 847 312 773 777-7777 333-3333 666-6666 888-8888 17

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

SELECT * FROM PATIENT WHERE Gender = Male ORDER BY Age;

18

LISTING UNIQUE VALUES


SQL does not automatically eliminate duplicates. SQLs DISTINCT Clause is designed to produce a list of only those values that are different from one another.

Example:

Produce a listing of all physicians Ids that are currently treating patients. Doctor ID V11 V12 V14 V14

SELECT DoctorID FROM PATIENT;

To remove the duplicates, use the DISTINCT Clause. SELECT DISTINCT DoctorID FROM PATIENT;

Doctor ID
V11 V12 V14 19

SQL NUMERIC FUNCTIONS


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

Example:

How many different area codes are there?

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

Example: SELECT MAX (Age) AS Oldest FROM PATIENT; Alias Oldest 20

SELECT MIN (Age) AS Youngest FROM PATIENT;

Youngest 1

21

SQL NUMERIC FUNCTIONS LIMITATION


What is the name and age of the oldest patient? SELECT Name, Age FROM PATIENT WHERE Age = MAX (Age); Cant have aggregate function in WHERE clause SELECT Name, MAX (Age) FROM PATIENT;

Name is not part of aggregate function

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.

SELECT Name, MAX (Age) FROM PATIENT GROUP BY Name;

Name Rambo Tootsie Trigger Whitey

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

SELECT AVG (Age) AS AverageAge FROM PATIENT;

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.

May be combined with any of the arithmetic functions.


Example: What is the average age of each physicians patients?

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;

Cant group on fields selected with *

26

HAVING CLAUSE
Having Clause can be used to identify a subset of groups. Example: List number of patients by gender.

Select gender, count(*) as Number of Patients From Patient Group by gender;

gender Female Male

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

RETRIEVING DATA FROM MORE THAN ONE TABLE: JOIN


Logical relationships between tables in relational databases are represented by matching primary and foreign key values. Given that there are no permanent connections between tables stored in the database, a DBMS must provide some way for users to match primary and foreign key values when needed. This capability is provided by the relational algebra join operation, which combines two tables based on a specified relationship between data they contain. Example: Produce a listing of all patients with their doctors name and phone number.

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;

Name Tootsie Trigger Rambo Whitey

PhysicianName Kalayta Roberts Gibson Gibson

AreaCode 312 773 847 847

LocalNumber 333-3333 888-8888 777-7777 777-7777

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;

Name Tootsie Trigger Rambo Whitey

PhysicianName Kalayta Nolte Roberts Gibson Gibson

AreaCode 312 773 847 847

LocalNumber 333-3333 666-6666 888-8888 777-7777 777-7777

Results are the same as the relational algebra OUTER JOIN

31

ALIAS TABLE NAME


SELECT Name, B.PhysicianName, AreaCode, LocalNumber FROM PATIENT as A , PHYSICIAN as B WHERE A.DoctorID = B.PhysicianID;

Name Tootsie Trigger Rambo Whitey

PhysicianName Kalayta Roberts Gibson Gibson

AreaCode 312 773 847 847

LocalNumber 333-3333 888-8888 777-7777 777-7777

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 )

PhysicianName Gibson Gibson

name Rambo Whitey

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.

How many employees are there?

2.

How many are male, female?

35

QUERY REQUESTS
3.

What is the highest salary?

4.

What are the names of the employees making more than $30,000 per year?

36

QUERY REQUESTS
5.

What is the average salary of female employees?

6.

What is the average salary of male employees?

37

QUERY REQUESTS
7.

What are the SSNs of the supervisors?

8.

How many employees does each supervisor supervise?

38

QUERY REQUESTS
9.

Who does not have a supervisor?

10.

Who is supervising at least 3 employess?

39

QUERY REQUESTS
11.

List the name and address of every employee who works in Research department

12.

List the name of all employees who have a dependent.

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

You might also like