Introduction to SQL

advertisement
LAB – INTRODUCTION TO SQL
O VERVIEW
In this lab, we will practice using DDL and DML SQL statements using our account on Microsoft SQL Server.
L EARNING O BJECTIVES
Upon completion of this learning unit you should be able to:

Describe and use basic SQL commands on SQL Server

Explain how and why SQL is used, and why its important

Compare and contrast DML and DDL

Use SQL commands to create metadata structures (tables and constraints) and perform CRUD operations to
add data.
W HAT
YOU WILL NEED
BY NOW YOU SHOULD BE PROFICIENT AT LOGGING ON TO YOUR HOSTED SQL SERVER
ACCOUNT. IF YOU AREN’T I SUGGEST PRACTICE, PRACTICE, PRACTICE!
Hopefully by now, you mastered connecting to your SQL Server instance. If not, review the previous lab.
L AB G OALS
This lab consists of 3 parts:
1.
In part one we will explore a new aspect of the Fudgemart database schema for use in the lab.
2.
In part two; you will follow along entering and executing the SQL commands that are displayed in the
screen shots. This lab will give you a brief explanation of what the commands are doing to help you
through the muddy points.
3.
In part three, you’re on your own. You will be required to create and execute SQL to solve a variety of
business problems.
P ART 1: FYI: T HE F UDGEMART D ATABASE S CHEMA
Throughout the semester we will use several different case studies to help enforce the concepts we learn in class.
One of the recurring case-studies we will use in class and the labs is the Fudgemart database. This database
supports the business operations of a fictitious mega-store retailer and e-tailer called Fudgemart. The Fudgemart
1 / 11
database supports all aspects of the business from human resources, to payroll, to sales transactions, and ecommerce. In each lab we will add new database objects and data to the Fudgemart schema.
1 A : E MPLOYEES AND T IMESHEETS C ONCEPTUAL M ODEL
Here is the conceptual model for Fudgemart employees and the management of their weekly submitted
timesheets. Each employee submits one or more timesheets (one each week, over time) but any give timesheet is
submitted by one and only one employee (as it should be). Furthermore each employee as one manager (also an
employee) but a manager supervises 0 or more employees.
AS YOU’VE PROBABLY ALREADY FIGURED OUT, THE BOXES WILL BE TABLES IN OUR FUDGEMART
DATABASE, AND THE LINES CONNECTING THE BOXES BECOME FOREIGN KEY CONSTRAINTS.
Timesheet
Supervises /
has manager
Employee
Submits / submitted by
1 B : E MPLOYEES AND T IMESHEETS L OGICAL M ODEL
Here is the logical model. Remember there is a 1-1 correspondence between the logical model and the internal /
external model. The key difference between the two models is that the logical model is independent of any
particular DBMS implementation, of course.
NOTE: DO NOT CREATE THESE TABLES AT THIS TIME. JUST REVIEW THE LOGICAL MODEL. THIS
SECTION SERVES MERELY AS A REFERENCE FOR PARTS 2 AND 3 IN THIS LAB.
Table: fudgemart_jobtitles_lookup: columns
Column Name
jobtitle_id
Data Type
Varchar(20)
Default Value
Table: fudgemart_jobtitles: constraints
Constraint Name
pk_jobtitle_id
Constraint Type
Primary key
2 / 11
Data
jobtitle_id
Allow Null?
No
Table: fudgemart_employees: columns
Column Name
employee_id
employee_ssn
employee_lastname
employee_firstname
employee_jobtitle
employee_birthdate
employee_hiredate
employee_termdate
employee_hourlywage
employee_supervisor_id
Data Type
Int
Char(9)
Varchar(50)
Varchar(50)
Varchar(20)
Datetime
Datetime
Datetime
Money
Int
Default Value
Getdate()
8
Allow Null?
No
No
No
No
No
No
No
Yes
No
Yes
Table: fudgemart_employees: constraints
Constraint Name
pk_employee_id
ck_employee_minimum_wage
u_employee_ssn
ck_employee_birthdate
fk_employee_department
Constraint Type
Primary key
Check
Unique
Check
Foreign key
fk_employee_jobtitle
Foreign key
Data
employee_id
employee_hourlywage >=8
employee_ssn
datediff(yy,employee_birthdate,getdate())>15
employee_department REFERENCES
fudgemart_departments_lookup(department_id)
employee_jobtitle REFERENCES
fudgemart_jobtitles_lookup(jobtitle_id)
Table: fudgemart_timesheets: columns
Column Name
timesheet_id
timesheet_payrolldate
timesheet_employee_id
timesheet_hours
Data Type
Int identity(1,1)
Datetime
Int
decimal(3,1)
Default Value
40.0
Allow Null?
No
No
No
No
Table: fudgemart_timesheets: constraints
Constraint Name
pk_timesheet_id
fk_timesheet_employee_id
Constraint Type
Primary key
Foreign key
ck_timesheet_hours
Check
Data
timesheet_id
timesheet_employee_id REFERENCES
fudgemart_employees(employee_id)
timesheet_hours between 0 and 60
P ART 2: W ALK - THRU F UDGEMART E MPLOYEES
In this part we will create the fudgemart_employees table objects and add the required data.
Connect to your catalog on SQL Server. (see Previous lab for details.) Select your database from the object explorer
and then open up a blank query window by clicking the
3 / 11
button in the toolbar.
S OME
EXTREMELY HELPFUL HINTS :

Check it before you wreck it! To check the syntax of your SQL, (without executing it on the server) click:
This will help you catch common problems without sending your code to the server. Check it before
you wreck it tells you to make sure the syntax is correct before sending the SQL command to the server.

To send your SQL to the SQL server and execute it, click:
This carries out the command on the
server. If the command makes a table, and the command works, you will see the message:


Help me help you - Turn on line numbers in the editor. Menu  Tools  Options Text Editor All
Languages  Display  Line Numbers (make sure it’s checked).
When you press execute, it executes ALL THE SQL CODE in the window. To only execute a specific
command, HIGHLIGHT the command text with your mouse before clicking Execute. For example this
only executes the command on lines 18-19

To open a new tab for typing a new query press, CTRL+N or click
So In summary your workflow should be:
1. Type in the SQL
2. Highlight it (to only execute the command what you want)
3.
Check it
to verify the syntax is correct
4.
5.
Once it passes (no syntax errors), then wreck it!
(execute on the server).
Once you execute it on the server successfully, there’s no need to execute it again unless you execute
a different command to delete the data or drop the object.
Task
Execute this SQL Statement
2.a) First, let’s check to see if the
fudgemart_departments_lookup
table is there in our database, if
not, let’s create the table.
Open a new window by pressing Ctrl+N in the new window type this sql
And then press
Do you see the fudgemart_departments_lookup table in the results? Under table
name?
If so, type this in and execute it (to delete the table):
drop table fudgemart_departments_lookup
Once you’ve verified the table is not there, open a new window (Ctrl+N) and type
in and execute this SQL:
4 / 11
This should create the fudgemart_departments_lookup table.
2.b) Check to see if there’s data in
the table, and if not, the following
data on the right.
Next, let’s add data to the table we just created. In the same window, Type in
these 4 INSERT statements to add 4 rows of data to the table.
Use your mouse to HIGHLIGHT THE 4 INSERT STATEMENTS. Then execute the SQL
code. If you are successful, you should see output like this:
Finally type and execute this statement in the same window, beneath the INSERT
statements. When you execute it, make sure to just highlight the SELECT
statement (No need to re-execute the inserts).
You should see results like this:
Save this script as fudgemart_departmens_lookup.sql This one file should contain
the CREATE TABLE statement, the 4 INSERT statements, and the SELECT
5 / 11
statement.
2.c) Lets create the
fudgemart_jobtitles_lookup table.
Open a new window by pressing Ctrl+N
Execute the following to create the table:
2.d) Now lets add the primary key
constraint to the table
Execute the following to add the primary key constraint:
2.e) Next let’s add some job titles
Add 4 rows of data to the table:
And then, of course, check to make sure the data is there:
Save the script as fudgemart_jobtitles_lookup.sql
2.f) Now that we have our two
lookup tables, its time to create
the big kahuna:
fudgemart_employees
Open a new window by pressing Ctrl+N
6 / 11
2.g) And add the foreign key
constraints, of course!
2.h) Finally! Its time to add some
employees:
Six of them:
7 / 11
And 5 more sales associates like this (Please note the top half of statement has
been omitted to save space, and you will need to include it in each subsequent
INSERT statements.)
8 / 11
And two department managers:
2.i) Show a listing of all 6
employees
Save this script as fudgemart_employees.sql
2.j) Show only those employees in
the ‘Electronics’ department
Open a new window by pressing Ctrl+N
2.k) Show only those employees in
the ‘Electronics’ department who
are do not have the title
Open a new window by pressing Ctrl+N
9 / 11
‘Department Manager’
2.l) Now, lets modify these people
so that their supervisor is is correct
=5 (since Isabelle is their manager)
Open a new window by pressing Ctrl+N
2.m) Finally only how the names,
and hourly wages of employees
who make more than 12 per hour,
sorted by wage.
Open a new window by pressing Ctrl+N
P ART 3: O N YOUR
OWN :
F UDGEMART E MPLOYEES
AND
T IMESHEETS
In this part we will create the fudgemart_timesheets table object and add some required data. Make sure you’ve
completed part 2 before working on this part. Since you will have to hand in some of these answers as part of the
lab, I recommend you saving the text of your SQL queries somewhere.
3.a) Write the SQL CREATE TABLE statement to create the fudgemart_timesheets table columns only as outlined in
section 1.b of the lab. Do not create any constraints at this time. Save this script as
fudgemart_timesheets_create.sql
3.b) Write the SQL ALTER TABLE statement to add all the constraints to the fudgemart_timesheets table
constraints as outlined in section 1.b of the lab. Save this script as fudgemart_timesheets_alter.sql
3.c) Write SQL INSERT statements to add one week of timesheets for each employee (6 inserts total) for the week
of 9/10/2007. Each employee worked 36 hours total. Save this script as fudgemart_timesheets_inserts.sql
3.d) Correction. The two department managers worked 40 hours and not 36 hours. Write ONE SQL UPDATE
statement to update both managers to 40 hours total. Save this script as fudgemart_timesheets_update_d.sql
3.e) Identity crisis! Lee Hvmeehom is tired of his name, and wants to change it to Mike Rofone. Write ONE SQL
UPDATE statement to make this name change. Save this script as fudgemart_timesheets_update_e.sql
3.f) Write an SQL UPDATE statement to set the supervisor id of the ‘Hardware’ department employees to the
employee id of the manager of that department. Save this script as fudgemart_timesheets_update_f.sql
10 / 11
P ART 4: L AB Q UESTIONS
4.1) Execute the following SQL. Explain in your own words why this command will not insert a row into the
table.
4.2) Execute the following SQL. Explain in your own words why this command will not insert a row into the
table.
4.3) Can you DROP a table if its primary key is used in a foreign key constraint? Why or why not?
4.4) Give one important advantage SQL DML has over building tables interactively via the GUI (graphical user
interface). Give one disadvantage, too.
11 / 11
Download