0% found this document useful (0 votes)
26 views

SD SQL LabWork

Uploaded by

datpro0523
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

SD SQL LabWork

Uploaded by

datpro0523
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

MS SQL Server Labs 1 and 2

1. The simple League results database in SQL


This week you will be shown and asked to experiment with SQL code to create the simple league
results database. Before you begin writing some SQL we will need to tidy up what we previously
created using the GUI. This involves deleting the tables and diagrams that you created last week.
This week we will be recreating them in SQL code.

The ERD for the simple League Results DB that we shall create this week is shown below (Note: it’s
the same as last week’s ERD):

System Building 1 Page 1


MS SQL Server Labs 1 and 2

Cleaning up from last week before you begin


Before we begin writing some SQL we need to delete everything from last week. This involves
deleting:

1. Your diagram
2. Your tables

Tables can be deleted by running the following SQL.

DROP TABLE Player;


DROP TABLE Result;
DROP TABLE Team;
DROP TABLE League;

Your diagrams can be deleting via the GUI. Open up the diagrams area and Right Button Click on the
diagram and select Delete.

You may also need to clean out an automatically


generated System Table for your diagram. You can do this
via opening Tables | System Tables and then Right Hand
Click on the dbo.sysdiagrams and select Delete.

House keeping
Its good practice to keep a log of your SQL in some text format so that you can copy and paste
portions as you require. Try to organise your SQL into a set of text files ( .txt ) of SQL scripts ( .sql ) as
you work. The aim is to generate a set of scripts that can be used for:

1. Creating your tables (perhaps called create.sql or create.txt).


2. Inserting data into your tables (perhaps called insert.sql or insert.txt).
3. Retrieval sql (perhaps called select.sql or select.txt).

Regardless of how you choose to organise the SQL that you write you should at least keep a
document with the code that you author so that you can easily cut and paste from it.

System Building 1 Page 2


MS SQL Server Labs 1 and 2

2. Ceating Tables
We first need to create the definitions for our tables. We do this using the CREATE TABLE
SQL keywords. Since we are going to be creating CONSTRAINTS to reference foreign keys to
primary keys we need to create the tables in the correct order. We do this as we cannot
enforce a constraint to act on something that does not exist. Typically we create the owner
tables first.

(Recall: The parent of the relationship is the ONE side of a ONE-MANY relationship, i.e. the
primary key, the child in the relationship is the relation that receives the many foreign keys,
for example League is the Parent of Team, Team is the child).

?
QUESTION
Sketch the order that the tables will need to be created. Ask your tutor
if you are unsure.

The SQL code below creates three of the tables.

CREATE TABLE League(


LeagueID INT PRIMARY KEY IDENTITY,
Name VARCHAR(40),
);
CREATE TABLE Team(
TeamID INT PRIMARY KEY IDENTITY,
Name VARCHAR(40),
LeagueID INT,
CONSTRAINT fk_LeagueID FOREIGN KEY (LeagueID)
REFERENCES League(LeagueID)
);
CREATE TABLE Result(
ResultID INT PRIMARY KEY IDENTITY,
HomeTeamID INT,
AwayTeamID INT,
HomeScore INT,
AwayScore INT,
HomePoints INT,
AwayPoints INT,
LeagueID INT,
CONSTRAINT fk_HomeTeamID FOREIGN KEY (HomeTeamID)
REFERENCES Team(TeamID),
CONSTRAINT fk_AwayTeamID FOREIGN KEY (AwayTeamID)
REFERENCES Team(TeamID),
CONSTRAINT fk_ResultLeagueID FOREIGN KEY (LeagueID)
REFERENCES League(LeagueID)
);

Study the syntax for creating CONSTRAINT. Each CONSTRAINT is given a unique name,
fk_LeagueID or fk_TeamID. The type of CONSTRAINT is then distinguished via the FOREIGN
System Building 1 Page 3
MS SQL Server Labs 1 and 2
KEY keywords followed by the field that will have the FORIEGN KEY constraint, i.e. FOREIGN
KEY (TeamID). We then specify the table and field that will provide the foreign Key
references, i.e. the Team(TeamID).

We still need to create the Player table. You can write the SQL to do this yourself.

TASK:
1. Write the SQL code youself to create the Player table.

3. Inserting data
Adding data to tables is accomplished using the INSERT statement. The following SQL
inserts data into the League table adding three records. Note that we have not attempted
to add the automatically calculated INDENTITY values.
INSERT INTO League VALUES ('League One');
INSERT INTO League VALUES ('World Cup A');
INSERT INTO League VALUES ('World Cup B');

Again, the order in which we add data must follow the rules of Owner first then Children so that the
data does not breach Referential Integrity rules.

Once we have data in the League table we can add some records that will reference the Leagues.

INSERT INTO Team VALUES ('Liverpool',1);


INSERT INTO Team VALUES ('Arsenal',1);
INSERT INTO Team VALUES ('Manchester United',1);

This code adds three teams to LeagueID 1. It assigned the records a Name and a LeagueID, the
Primary Key is automatically determined by the IDENTITY field.

TASK: 1. Add 5 more teams into LeagueID=1


2. Query the data in Team, using the SQL:
SELECT * FROM Team

Note that the VALUES are ordered according to the initial order in which we defined the fields when
we created the TABLE.

The SQL below specifically explicitly states the ordering (Name, LeagueID) for the fields prior to the
VALUES being defined.

INSERT INTO Team (Name,LeagueID) VALUES ('Liverpool',1);

TASK: 1. Add some players to the players table using the method shown above.
2. Query the data in Player using the SQL:
SELECT * FROM Player

System Building 1 Page 4


MS SQL Server Labs 1 and 2

The SQL below shows the insert statement for adding data to the result table. Again the IDENTITY
field is omitted.

INSERT INTO result VALUES (1,2,4,0,3,0,1);

?
QUESTION
Look at the Result table creation SQL on page 3 and determine what
each of the numerical values in the above INSERT statement represent.

1. Add some more data to the Result table (adding around 4 results per team
TASK: will suffice).
2. Query the data in Team
SELECT * FROM Result

System Building 1 Page 5


MS SQL Server Labs 1 and 2

4. Simple SQL Queries (data retrieval)


The following SQL examples query the Team table and display ALL FIELDS (Note: the use of
an * (asterix) to select all fields) for a specific LeagueID. The * means wild card or
everything, and in these examples selects all of the fields from the League table.
SELECT * FROM team WHERE leagueID = 1;
SELECT * FROM team WHERE leagueID = 2;

TASK: 1. Query your other tables to inspect their contents.

The next query selects ONLY the Name from the Team given a LeagueID.
SELECT Name FROM team WHERE leagueID = 2;

Write some more query to retrive the following:

TASK: 1. Just the FirstName field from the Player table


2. The Player’s FristName and LastName from the Player table
3. Concatenate FristName and Lastname together using an Alais (see
lecture SQL-1).

Retrieving data from multiple tables (JOINS)


In order to retrieve the Team.Name and the League.Name together we need to use an
INNER JOIN. We do this to join together the contents of the two tables based on some
criteria.

?
QUESTION
What criteria might we use for joining together data from Team and
League?

Study the SQL code below.

SELECT Team.Name, League.Name FROM team INNER JOIN


League ON Team.LeagueID = League.LeagueID
WHERE Team.LeagueID=1;

Notice that we prefix the Table before the field, i.e. Team.Name. We do this to avoid
confusion as we are dealing with two different instance of fields both called Name, one from
System Building 1 Page 6
MS SQL Server Labs 1 and 2
Team and one from League. We need to tell SQL specifically which we are referring to,
hence we use a more specific identifier, i.e. Table.Fieldname.

SELECT Team.Name, League.Name FROM team INNER JOIN


League ON Team.LeagueID = League.LeagueID
WHERE Team.LeagueID=1;

The above SQL statement tells MS SQL Server to SELECT the Team.Name and League.Name
from (the FROM keyword) the team table. The team table will then be joined with the
League table, the join uses the syntax INNER JOIN. Next the statement provides the fields
that wil be used to make the join using the ON keyword, i.e. ON team.TeamID =
league.LeagueID. The optional WHERE clause simply selects a single LeagueID from the
Team table rather than joining together everything from the Team table.

Simple Aggregatation SQL Examples


The following two examples demonstrate the use of two different aggregations. The first
query will COUNT the occurences of ResultID for the different HomeTeamID.
SELECT COUNT(ResultID) AS HomeGamesPlayed, HomeTeamID FROM Result
GROUP BY HomeTeamID;

The next query will SUM the occurences of HomePoints for the different HomeTeamID.

SELECT SUM(HomePoints) AS "Home Points", HomeTeamID FROM Result


GROUP BY HomeTeamID;

TASK: 1. Author an additional querry to show the AwayPoints total using the
SUM function.

The GROUP BY keywords tells SQL which groupings of HomePoints to display. In the previous
example we want GROUPs of HomePoints for each HomeTeamID.

System Building 1 Page 7


MS SQL Server Labs 1 and 2
Aggregations and joins
Rather than displaying the TeamID it would be more useful to display the Team.Name from
the Team table. To do this we need to JOIN our aggregation query with the Team table using
the TeamID as the binding criteria for the join. We can then ask SQL to show the relevant
Team.Name in place of the TeamID.
/* Example 1: COUNT home games played and join the result to Team to show
the Team.Name */

SELECT COUNT(ResultID) AS HomeGamesPlayed, Team.Name


FROM Result INNER JOIN Team ON Team.TeamID=Result.HomeTeamID
GROUP BY Team.Name;

/* Example 2: SUM home games points and join the result to Team to show the
Team name */

SELECT SUM(HomePoints) AS "Home Points", Team.Name


FROM Result INNER JOIN Team ON Team.TeamID=Result.HomeTeamID
GROUP BY Team.Name;

/* Example 3: SUM home and away points and join the result to Team to show
the Team name, note: the use of HomeTeamID OR AwayTeamID */

SELECT SUM(HomePoints) AS "Home Points", SUM(AwayPoints) as "Away Points",


Team.Name
FROM Result INNER JOIN Team ON
Team.TeamID=Result.HomeTeamID OR Team.TeamID=Result.AwayTeamID
GROUP BY Team.Name;

Advanced example (aggregation, join and nesting)


This SQL shown below queries the resultset of another query, this is known as nesting and
allows very complex query to be build up one on top of the other. In this example we use
nesting to total the points of home and away games and then from that we create a new query
that shows the total points and team names.
SELECT (PointsResultSet.HomePoints + PointsResultSet.AwayPoints) as Points,
PointsResultSet.Name from
(SELECT SUM(HomePoints) AS "HomePoints", SUM(AwayPoints) as
"AwayPoints", Team.Name
FROM Result INNER JOIN Team ON Team.TeamID=Result.HomeTeamID OR
Team.TeamID=Result.AwayTeamID
GROUP BY Team.Name) as PointsResultSet;

System Building 1 Page 8


MS SQL Server Labs 1 and 2
Ordering results
Order the results using the keywords ‘ORDER BY Points DESC’.

SELECT (PointsResultSet.HomePoints + PointsResultSet.AwayPoints) as Points,


PointsResultSet.Name from
(SELECT SUM(HomePoints) AS "HomePoints", SUM(AwayPoints) as
"AwayPoints", Team.Name
FROM Result INNER JOIN Team ON Team.TeamID=Result.HomeTeamID OR
Team.TeamID=Result.AwayTeamID
GROUP BY Team.Name) as PointsResultSet ORDER BY Points DESC;

5. Updating data
The syntax for updating data is shown below:

UPDATE Team SET Name='Liverpool FC' WHERE Name='Liverpool'

Note that an update typically uses a WHERE clause to specify some criteria for the UPDATE. The
example below updates WHERE the TeamID = 1 instead.

UPDATE Team SET Name='Liverpool FC' WHERE TeamID=1

Since the UPDATE uses the WHERE clause all the normal rules an syntax for retrieval apply. Quite
complex query can be constructed perhaps joining together multiple tables, aggregating results and
the performing an update based on the results.

6. Deleting things (data, tables, etc.)


Deleting data from tables can be accomplished using the DELETE FROM keywords followed by the
table name that you wish to delete data from. Care should be taken when trying to delete data as
Referential Integrity will not allow us to delete primary keys that are being referenced in other
tables. We therefore need to consider the order in which we wish to delete. The general rule is
that we must delete the child records in the relationship before we can delete the owner records.

The following four statements delete all data from our four tables, note the ordering of the
statements.

DELETE FROM Player;


DELETE FROM Result;
DELETE FROM Team;
DELETE FROM League;

TASK: 1. Try adding some to your recently deleted tables

System Building 1 Page 9


MS SQL Server Labs 1 and 2

?
What has happened to the automatically assigned IDENTITY primary key
data when you attempt to recreate your tables after deleting some
QUESTION
records?

Deleting tables AND any data is accomplished using the SQL keywords DROP TABLE followed by the
table that you wish to drop. The following 4 statements will drop (Delete) all of your tables.

DROP TABLE Player;


DROP TABLE Result;
DROP TABLE Team;
DROP TABLE League;

We can add conditions to our delete commands using the WHERE clause. The rules and operation of
the WHERE clause are similar to that of data retrieval.

7. Creating a diagram
MS SQL Server will create a diagram automatically based on the table definitions that you have input
via SQL.

1. Create a diagram using the MS SQL Server GUI.


TASK: HINT: Just add the four tables Player, Team, Result and League and SQL
Server will do the rest.

System Building 1 Page 10


MS SQL Server Labs 1 and 2

8. Improving our Database


Some teams for example may play in a domestic league in their home country as well as a European
or Global league.

?
QUESTION
1. How would you change the ERD to allow for a team to belong to
many League?

TASK: 1. Create a new ERD that allows Teams to belong to Many leagues

1. Delete your database (you should have kept scripts or text files of the
TASK: SQL so that you can rebuild it again if required).
2. Implement your new design, creating tables, populating them and
retrieving data.

1. Write some SQL to create the entire League table, this should include
TASK: Total Games played and Points.
(HARD TASK)

System Building 1 Page 11

You might also like