sql key assignment - brkada.combrkada.com/graphics/works/sql.pdf · sql key assignment 10 phase 2...

34
SQL Key Assignment 0 SQL Key Assignment CS362-1202A-03 : Structured Query Language for Data Management Emily Hegge 4/16/2012 This is the Key Assignment for CS362-1202A-03: Structured Query Language for Data Management. Phase 1 Creation of Tables within SQL database. Phase 2 using INSERT, UPDATE, and DELETE to change data within a table. Phase 3 using SELECT statements for queries. Phase 4 Creating a table to add degrees. Phase 5 create udf, stored procedures, and indexes.

Upload: buikiet

Post on 07-May-2018

217 views

Category:

Documents


1 download

TRANSCRIPT

SQL Key Assignment

0

SQL Key Assignment CS362-1202A-03 : Structured Query Language for

Data Management

Emily Hegge

4/16/2012

This is the Key Assignment for CS362-1202A-03: Structured Query Language for Data

Management. Phase 1 Creation of Tables within SQL database. Phase 2 using INSERT,

UPDATE, and DELETE to change data within a table. Phase 3 using SELECT statements for

queries. Phase 4 Creating a table to add degrees. Phase 5 create udf, stored procedures, and

indexes.

SQL Key Assignment

1 Table of Contents Phase 1 IP ...................................................................................................................................................... 4

Relationships (ERD) ................................................................................................................................... 4

Students Table .......................................................................................................................................... 4

Script ..................................................................................................................................................... 4

Screen Shot ........................................................................................................................................... 5

Advisors Table ........................................................................................................................................... 6

Script ..................................................................................................................................................... 6

Screen Shot ........................................................................................................................................... 6

Classes Table ............................................................................................................................................. 6

Script ..................................................................................................................................................... 6

Screen Shot ........................................................................................................................................... 7

Students_Classes Table ............................................................................................................................. 7

Script ..................................................................................................................................................... 7

Screen Shot ........................................................................................................................................... 9

Phase 2 IP .................................................................................................................................................... 10

Commands .............................................................................................................................................. 10

Classes Table Code .................................................................................................................................. 10

Advisors Table ......................................................................................................................................... 12

Students Table ........................................................................................................................................ 14

Delete Class ............................................................................................................................................. 19

Update Student ....................................................................................................................................... 19

Phase 3 IP .................................................................................................................................................... 20

SELECT Statements.................................................................................................................................. 20

1. List all active male students assigned to Advisors 1 or 3 ............................................................ 20

SQL Statement 1 ................................................................................................................................. 20

SQL Statement 2 ................................................................................................................................. 20

Original Table ...................................................................................................................................... 20

Screen Shot 1 ...................................................................................................................................... 20

Screen Shot 2 ...................................................................................................................................... 20

Description: ......................................................................................................................................... 21

2. Provide a list of all students without a biography. ........................................................................ 21

SQL Key Assignment

2 SQL Statement 1 ................................................................................................................................. 21

SQL Statement 2 ................................................................................................................................. 21

Original Table ...................................................................................................................................... 21

Screen Shot 1 ...................................................................................................................................... 21

Screen Shot 2 ...................................................................................................................................... 22

Description: ......................................................................................................................................... 22

3. What classes are in the English department? ................................................................................ 22

SQL Statement .................................................................................................................................... 22

Original Table ...................................................................................................................................... 22

Screen Shot ......................................................................................................................................... 22

Description: ......................................................................................................................................... 22

4. Create a list of all students and their advisors. Sort by the advisor’s name and then the student’s

name. Include the student’s birth date, gender, and GPA. ................................................................ 23

SQL Statement .................................................................................................................................... 23

Original Table ...................................................................................................................................... 23

Screen Shot ......................................................................................................................................... 23

Description: ......................................................................................................................................... 23

5. How many students were born in the 1980s? ................................................................................ 24

SQL Statement .................................................................................................................................... 24

Original Table ...................................................................................................................................... 24

Screen Shot ......................................................................................................................................... 24

Description: ......................................................................................................................................... 24

6. Write a query to show the average GPA by gender. ...................................................................... 24

SQL Statement .................................................................................................................................... 24

Original Table ...................................................................................................................................... 25

Screen Shot ......................................................................................................................................... 25

Description: ......................................................................................................................................... 25

7. Provide a list of all advisors and the number of active students assigned to each. Filter out any

advisors with more than 1 student. .................................................................................................... 25

SQL Statement .................................................................................................................................... 25

Original Table ...................................................................................................................................... 25

Screen Shot ......................................................................................................................................... 26

SQL Key Assignment

3 Description: ......................................................................................................................................... 26

Phase 4 IP .................................................................................................................................................... 27

Relationship (ERD) .................................................................................................................................. 27

Create Table Degrees .......................................................................................................................... 27

Create Table Degrees_Classes ................................................................................................................ 27

Adding to Students ................................................................................................................................. 28

Insert Into Degrees.................................................................................................................................. 28

Screen Shot ......................................................................................................................................... 29

Insert Into Degrees_Classes .................................................................................................................... 29

Screen Shot ......................................................................................................................................... 30

Updating Student Table ...................................................................................................................... 31

Screen Shot ......................................................................................................................................... 31

Phase 5 IP .................................................................................................................................................... 32

User Defined Function ............................................................................................................................ 32

Script to Call Function ............................................................................................................................. 32

Stored Procedure .................................................................................................................................... 32

Call Procedure ......................................................................................................................................... 33

Screen Shot ............................................................................................................................................. 33

Indexes .................................................................................................................................................... 33

SQL Key Assignment

4 Phase 1 IP

Relationships (ERD)

Students Table

Script

CREATE TABLE Students

(StudentID INT AUTO_INCREMENT,

FirstName VARCHAR(30),

LastName VARCHAR(30),

BirthDate DATE ,

Gender CHAR(1) ,

StartDate DATE,

GPA DECIMAL(5,2),

IsActive INT ,

Bio TEXT ,

AdvisorID INT,

SQL Key Assignment

5 CONSTRAINT StudentID_PK

PRIMARY KEY (SrudentID),

CONSTRAINT Gender_Chk

CHECK (Gender = F OR M DEFAULT NULL) ,

CONSTRAINT StartDate_Chk

CHECK (StartDate >= DATE '2012-01-01') ,

CONSTRAINT GPA_Chk

CHECK (GPA BETWEEN 0.00 AND 4.00) ,

CONSTRAINT AdvisorID_FK

FOREIGN KEY (AdvisorID)

REFERENCES Advisors(AdvisorID) );

Screen Shot

SQL Key Assignment

6 Advisors Table

Script

CREATE TABLE Advisors

(AdvisorID INT AUTO_INCREMENT,

FirstName VARCHAR(30) NOT NULL,

LastName VARCHAR(30) NOT NULL,

EmailAddr VARCHAR(100),

CONSTRAINT AdvisorID_PK

PRIMARY KEY (AdvisorID));

Screen Shot

Classes Table

Script

CREATE TABLE Classes

(ClassID INT AUTO_INCREMENT,

ClassCode INT,

ClassName INT,

SQL Key Assignment

7 Description DATE,

CONSTRAINT ClassID_PK

PRIMARY KEY (ClassID) );

Screen Shot

Students_Classes Table

Script

CREATE TABLE Students_Classes

(StudentClassID INT AUTO_INCREMENT,

StudentID INT,

ClassID INT,

StartDate DATE,

Assignment1 INT,

Assignment2 INT,

Assignment3 INT,

Assignment4 INT,

SQL Key Assignment

8 ClassGPA DECIMAL,

CONSTRAINT StudentClassID_PK

PRIMARY KEY (StudentClassID)

CONSTRAINT StudentID_FK

FOREIGN KEY (StudentID)

REFERENCES Students(StudentID),

CONSTRAINT ClassID_FK

FOREIGN KEY (ClassID)

REFERENCES Classes(ClassID),

CONSTRAINT Assignment_Chk

CHECK (Assignment1, Assignment2, Assignment3, Assignment4 BETWEEN

0 AND 100)

CONSTRAINT ClassGPA_Chk

CHECK (ClassGPA BETWEEN 0.00 AND 4.00) );

SQL Key Assignment

9 Screen Shot

SQL Key Assignment

10 Phase 2 IP

Commands

This week’s focus is INSERT, UPDATE, and DELETE. These commands are important

for changing data within the tables. INSERT is used to add new data to a table. UPDATE is used

for changing data including errors that may have been made when inputting the data. DELETE is

used to delete data, rows, and even entire tab les. Without these commands data would not be

able to be added or changed within a database.

Classes Table Code

INSERT INTO Classes

(ClassCode,

ClassName,

Description)

VALUES

('ACCT306',

'Accounting 1',

'This course introduces accounting concepts and explores the accounting environment. It

covers the basic structure of accounting, how to maintain accounts, use account balances

SQL Key Assignment

11 to prepare financial statements, and complete the accounting cycle. It also introduces the

concept of internal control and how to account for assets.');

INSERT INTO Classes

(ClassCode,

ClassName,

Description)

VALUES

('CS362',

'Structured Query Language for Data Management',

'This course gives complete coverage of SQL, with an emphasis on storage, retrieval, and

manipulation of data.');

INSERT INTO Classes

(ClassCode,

ClassName,

Description)

VALUES

('ENG115',

'English Composition',

SQL Key Assignment

12 'In this course, students focus on developing writing skills through practice and revision.

Students will examine expository, critical, and persuasive essay techniques.');

INSERT INTO Classes

(ClassCode,

ClassName,

Description)

VALUES

('FIN322',

'Investments',

'This course focuses on investments and investment strategies. Various investment

vehicles such as stocks, bonds, and commodities are examined. Students will explore the

principles of security analysis and valuation.' );

Advisors Table

INSERT INTO Advisors

SQL Key Assignment

13 (FirstName,

LastName,

EmailAddr)

VALUES

('Fred',

'Stone',

'[email protected]');

INSERT INTO Advisors

(FirstName,

LastName,

EmailAddr)

VALUES

('Bob',

'Gordon',

'[email protected]');

INSERT INTO Advisors

(FirstName,

SQL Key Assignment

14 LastName,

EmailAddr)

VALUES

('Jack',

'Simpson',

'[email protected]');

Students Table

INSERT INTO Students

(FirstName,

LastName,

BirthDate,

Gender,

StartDate,

GPA,

SQL Key Assignment

15 IsActive,

AdvisorID)

VALUES

('Craig',

'Franklin',

'1970-03-15',

'Male',

'2010-05-30',

'3.10',

'Yes',

'3');

INSERT INTO Students

(FirstName,

LastName,

BirthDate,

Gender,

StartDate,

SQL Key Assignment

16 GPA,

IsActive,

AdvisorID)

VALUES

('Harriet',

'Smith',

'1982-04-15',

'Female',

'2010-05-30',

'3.22',

'Yes',

'1');

INSERT INTO Students

(FirstName,

LastName,

BirthDate,

Gender,

SQL Key Assignment

17 StartDate,

GPA,

IsActive,

AdvisorID)

VALUES

('George,'

'David',

'1984-11-05',

'Male',

'2010-10-01',

'0.00',

'Yes',

'3');

INSERT INTO Students

(FirstName,

LastName,

BirthDate,

SQL Key Assignment

18 Gender,

StartDate,

GPA,

IsActive,

AdvisorID)

VALUES

('Ben',

'Jefferson',

'1976-09-25',

'Male',

'2009-02-21',

'1.80',

'No, the student has gone on temporary leave to pursue other opportunities but plans on

returning in 1 year.',

'3');

SQL Key Assignment

19

Delete Class

DELETE FROM Classes

WHERE ClassCode = 'FIN322';

Update Student UPDATE Students

SET BirthDate = '1982-04-25'

WHERE StudentID = '2';

UPDATE Students

SET GPA = '3.25'

WHERE StudentID = '2';

SQL Key Assignment

20 Phase 3 IP

SELECT Statements

1. List all active male students assigned to Advisors 1 or 3

SQL Statement 1

SELECT Gender, IsActive, AdvisorID

FROM Students

WHERE (Gender = 'M')

AND (IsActive = 'Yes')

AND (AdvisorID = '1' OR '3');

SQL Statement 2

SELECT *

FROM Students

WHERE (Gender = 'M')

AND (IsActive = 'Yes')

AND (AdvisorID = '1' OR '3');

Original Table

Screen Shot 1

Screen Shot 2

SQL Key Assignment

21 Description:

In statement one using SELECT I called for the columns Gender, IsActive, and

AdvisorID then using FROM stated that they were in the Sudents table. The WHERE statement

describes any special requirements as shown above Gender = M, IsAvtive=Yes, and AdvisorID =

1 or 3. The second statement is equal to the first but displays all of the columns and only the

specified rows.

2. Provide a list of all students without a biography.

SQL Statement 1

SELECT StudentID, FirstName, LastName, Bio

FROM `Students`

WHERE Bio IS NULL

SQL Statement 2

SELECT *

FROM `Students`

WHERE Bio IS NULL

Original Table

Screen Shot 1

SQL Key Assignment

22 Screen Shot 2

Description:

Here the SELECT calls for StudentID, FirstName, LastName, and Bio FROM the Students table and

the WHERE statements says if the Bio IS NULL which means that there is no data in it. The second

statement says the same except it shows all of the columns in the Students table.

3. What classes are in the English department?

SQL Statement

SELECT *

FROM `Classes`

WHERE ClassCode LIKE 'ENG___';

Original Table

Screen Shot

Description:

Since all English courses ClassCode begin with ENG and end with three numbers I chose to use it

as my definer. SELECT says get all columns FROM the Classes table WHERE ClassCode LIKE ‘ENG___’ the

LIKE is used to find any ClassCodes that have ENG and the three underscores state that there are three

letters or numbers after the ENG.

SQL Key Assignment

23 4. Create a list of all students and their advisors. Sort by the advisor’s name and then the

student’s name. Include the student’s birth date, gender, and GPA.

SQL Statement

SELECT Students.AdvisorID, Advisors.FirstName, Advisors.LastName, Students.FirstName,

Students.LastName, BirthDate, Gender, GPA

FROM Students, Advisors

WHERE Students.AdvisorID = Advisors.AdvisorID

ORDER BY Advisors.LastName ASC, Students.LastName ASC;

Original Table

Students

Advisors

Screen Shot

Description:

This SELECT statement says get Students.AdvisorID (Students specifies the table add a period

and then specify the column name AdvisorID ), Advisors.FirstName, Advisors.LastName,

Students.FirstName, Students.LastName, BirthDate, Gender, GPA. FROM both the Students table and

Advisors Table. WHERE Students.AdvisorID = Advisors.AdvisorID, this says that the AdvisorID in the

Students table must match with the AdvisorID in the Advisors table so that the appropriate information

for that Advisor is displayed with the correct student. ORDER BY Advisors.LastName ASC,

SQL Key Assignment

24 Students.LastName ASC this says that the data should be placed in ascending order(ASC) by Advisors

Last name and then by Students last name.

5. How many students were born in the 1980s?

SQL Statement

SELECT *

FROM Students

WHERE BirthDate LIKE '198_%';

Original Table

Screen Shot

Description:

SELECT all columns FROM the Students table WHERE BirthDate LIKE ‘198_%’ the underscore says

there is one letter or number after the 198 and the percent sign states that there is more information

after that so it will find anything that starts with 198 and whatever else is in that string.

6. Write a query to show the average GPA by gender.

SQL Statement

SELECT AVG(GPA) AS "AVG(GPAM)", Gender

FROM Students

Where Gender = 'M';

SELECT AVG(GPA) AS "AVG(GPAF)", Gender

SQL Key Assignment

25 FROM Students

Where Gender = 'F';

Original Table

Screen Shot

Description:

SELECT AVG(GPA) AS “AVG(GPAM)”, Gender , the AVG says to find the average of all the

numbers in the GPA column FROM the Students table while the AS “AVG(GPAM)” tells it how to display

the results of the search. WHERE Gender =M says to only find the average GPA for the male gender.

7. Provide a list of all advisors and the number of active students assigned to each. Filter out

any advisors with more than 1 student.

SQL Statement

SELECT a.AdvisorID, a.LastName, a.FirstName, COUNT( s.StudentID ) AS "COUNT(Students)"

FROM Advisors a

JOIN Students s

ON a.AdvisorID = s.AdvisorID

GROUP BY a.AdvisorID

HAVING COUNT(s.StudentID)='1';

Original Table

SQL Key Assignment

26 Screen Shot

Description:

SELECT a.AdvisorID, a.LastName, a.FirstName, COUNT( s.StudentID ) AS

"COUNT(Students)" this specifies which columns to select and the COUNT says to count the

students. FROM Advisors a JOIN Students s ON a.AdvisorID = s.AdvisorID this says to join the

Advisors table with the Students table on the AdvisorID column. GROUP BY a.AdvisorID tells

how the data should be grouped. HAVING COUNT(s.StudentID)='1' says to show only advisors

that have one student.

SQL Key Assignment

27 Phase 4 IP

Relationship (ERD)

Create Table Degrees

CREATE TABLE Degrees

(DegreeID INT AUTO_INCREMENT,

DegreeName VARCHAR(100),

Description TEXT,

CONSTRAINT DegreeID_PK

PRIMARY KEY (DegreeID) );

Create Table Degrees_Classes CREATE TABLE Degrees_Classes

(DegreeClassID INT AUTO_INCREMENT,

ClassID INT,

DegreeID INT,

ClassCode VARCHAR(30),

ClassName VARCHAR(100),

Description TEXT,

SQL Key Assignment

28 CONSTRAINT DegreeClassID_PK

PRIMARY KEY (DegreeClassID),

CONSTRAINT ClassID_FK

FOREIGN KEY (ClassID)

REFERENCES Classes(ClassID),

CONSTRAINT DegreeID_FK

FOREIGN KEY (DegreeID)

REFERENCES Degrees(DegreeID) );

Adding to Students ALTER TABLE Students

ADD DegreeID INT

CONSTRAINT DegreeID_FK

FOREIGN KEY (DegreeID)

REFERENCES Degrees(DegreeID) ;

Insert Into Degrees 1. INSERT INTO Degrees

(DegreeName,

Description)

VALUES

('Bachelor of Science in Information Technology',

'Learn the latest in information technology and become you offices computer geek. Theyre all the

rage this year.');

2. INSERT INTO Degrees

(DegreeName,

Description)

SQL Key Assignment

29 VALUES

('Bachelor of Science in Finance',

'Learn how to handle finances.');

3. INSERT INTO Degrees

(DegreeName,

Description)

VALUES

('Bachelor of Science in Nursing',

'Learn how to be the best in health care. ');

Screen Shot

Insert Into Degrees_Classes 1. INSERT INTO Degrees_Classes (DegreeID, DegreeName, ClassID, ClassCode, ClassName,

ClassDescription)

SELECT d.DegreeID, d.DegreeName, c.ClassID, c.ClassCode, c.ClassName, c.Description

FROM Degrees d, Classes c

WHERE DegreeID="1"

AND ClassID="2";

2. INSERT INTO Degrees_Classes (DegreeID, DegreeName, ClassID, ClassCode, ClassName,

ClassDescription)

SELECT d.DegreeID, d.DegreeName, c.ClassID, c.ClassCode, c.ClassName, c.Description

FROM Degrees d, Classes c

WHERE DegreeID="1"

AND ClassID="3";

SQL Key Assignment

30 3. INSERT INTO Degrees_Classes (DegreeID, DegreeName, ClassID, ClassCode, ClassName,

ClassDescription)

SELECT d.DegreeID, d.DegreeName, c.ClassID, c.ClassCode, c.ClassName, c.Description

FROM Degrees d, Classes c

WHERE DegreeID="2"

AND ClassID="1";

4. INSERT INTO Degrees_Classes (DegreeID, DegreeName, ClassID, ClassCode, ClassName,

ClassDescription)

SELECT d.DegreeID, d.DegreeName, c.ClassID, c.ClassCode, c.ClassName, c.Description

FROM Degrees d, Classes c

WHERE DegreeID="2"

AND ClassID="3";

5. INSERT INTO Degrees_Classes (DegreeID, DegreeName, ClassID, ClassCode, ClassName,

ClassDescription)

SELECT d.DegreeID, d.DegreeName, c.ClassID, c.ClassCode, c.ClassName, c.Description

FROM Degrees d, Classes c

WHERE DegreeID="3"

AND ClassID="3";

Screen Shot

SQL Key Assignment

31

Updating Student Table

1. UPDATE Students

SET DegreeID = '2'

WHERE StudentID = '1';

2. UPDATE Students

SET DegreeID = '3'

WHERE StudentID = '2';

3. UPDATE Students

SET DegreeID = '1'

WHERE StudentID = '3';

4. UPDATE Students

SET DegreeID = '2'

WHERE StudentID = '4';

Screen Shot

SQL Key Assignment

32 Phase 5 IP

User Defined Function DROP FUNCTION IF EXISTS StudentGPA;

DELIMITER |

CREATE FUNCTION StudentGPA ( sID int, csds date, csde date )

RETURNS DECIMAL(5,2)

READS SQL DATA

DETERMINISTIC

BEGIN

DECLARE AverageGPA decimal(5,2);

SET AverageGPA = ( SELECT AVG(ClassGPA) FROM Students_Classes WHERE StudentID = sID

AND StartDate BETWEEN csds AND csde );

RETURN AverageGPA;

END; |

DELIMITER ;

Script to Call Function SELECT StudentGPA(1,'2012-1-1','2012-2-1');

Stored Procedure DELIMITER |

DROP PROCEDURE IF EXISTS GradeBook |

CREATE PROCEDURE GradeBook(IN cID INT)

BEGIN

SELECT s.FirstName, s.LastName, c.Assignment1, c.Assignment2, c.Assignment3, c.Assignment4,

c.ClassGPA

FROM Students_Classes c

JOIN Students s

ON s.StudentID = c.StudentID

SQL Key Assignment

33 WHERE ClassID = cID

GROUP BY c.StudentID;

END|

Call Procedure CALL GradeBook(‘1’);

Screen Shot

Indexes CREATE INDEX name_index ON Students (LastName, FirstName);

Use this to help make searches on students name and ordering student names.

CREATE INDEX degree_index ON Students (DegreeName);

To search for the degree each student is taking so it can be seen what classes they’ve taken and

what classes need to be taken.

CREATE INDEX advisor_index ON Students (AdvisorID);

To help sort students that go with the advisors so the advisors can see what students they have.

CREATE INDEX degreeclasses_index ON Degrees_Classes (DegreeName);

To make it easy to order degrees together and see what classes correspond with each degree.

CREATE INDEX classid_index ON Students_Classes (ClassID);

So instructors can search by class id to see what students are in the class and look at student’s

grades.