SD SQL LabWork
SD SQL LabWork
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):
1. Your diagram
2. Your tables
Your diagrams can be deleting via the GUI. Open up the diagrams area and Right Button Click on the
diagram 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:
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.
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.
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.
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.
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.
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
The SQL below shows the insert statement for adding data to the result table. Again the IDENTITY
field is omitted.
?
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
The next query selects ONLY the Name from the Team given a LeagueID.
SELECT Name FROM team WHERE leagueID = 2;
?
QUESTION
What criteria might we use for joining together data from Team and
League?
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.
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.
The next query will SUM the occurences of HomePoints for the different 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.
/* Example 2: SUM home games points and join the result to Team to show the
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 */
5. Updating data
The syntax for updating data is shown below:
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.
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.
The following four statements delete all data from our four tables, note the ordering of the
statements.
?
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.
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.
?
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)