0% found this document useful (0 votes)
40 views25 pages

LAB - ERDs, Create Databases and Tables

Uploaded by

Jeremiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views25 pages

LAB - ERDs, Create Databases and Tables

Uploaded by

Jeremiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Starting MySQL

MySQL is an open-source database system that you can download from the link below:
https://dev.mysql.com/downloads/mysql/
Your account consists of the following three components:
▪ Username: this is by default “root”
▪ Password: by default, this is empty. You can still leave it empty (No Password) or for
academic reasons of never forgetting it and easy configurations, you can still use
“root” as your password.

Accessing the MySQL Server


MySQL can be accessed using various tools and editors. However, to make the transition
towards learning database concepts easier, we will be using a graphical interface called
Toad for MySQL.
Other tools include the MySQL Workbench that comes by default when you install MySQL
Server software and the PhpMyAdmin interface that you get through installing MySQL using
WAMP Server software.
Please note that when you install WAMP Server first, or if you already have WAMP Server
installed on your computer, you do not need to install MySQL Server software separately (i.e.,
installing WAMP Server also installs MySQL Server software).

Using Toad for MySQL


Toad is a database management toolset from Quest Software for managing relational and
non-relational databases using SQL aimed at database administrators, database
developers, and data analysts. You can use the Toad toolset with the following supported
platforms: MySQL, Oracle, SQL Server, IBM DB2, SAP Solutions, Amazon Redshift,
PostgreSQL, Azure SQL DB, Cassandra, MongoDB, etc. A Toad product for data preparation
supports many data platforms.

Features of the Toad Toolset


• Connection Manager - Allow users to connect natively to the vendor’s database.
• Browser - Allow users to browse all the different database/schema objects and
manage their properties effectively.
• Editor - A way to create and maintain scripts and database code with debugging and
integration with source control.
• Unit Testing (Oracle) - Ensures code is functionally tested before it is released into
production.
• Static code review (Oracle) - Ensures code meets required quality level using a
rules-based system.
• SQL Optimization - Provides developers with a way to tune and optimize SQL
statements and database code without relying on a DBA. Advanced optimization
enables DBAs to tune SQL effectively in production.
• Scalability testing and database workload replay - Ensures that database code
and SQL will scale properly before it gets released into production.

Installing Toad
After downloading Toad, click on Run in Open File. The Toad Edge Setup wizard gets
launched. Click on Next as shown below.

Accept the End-User License Agreement and click on Next. Select a destination folder to
install Toad Edge and click on Next. Click on Install to start installation. The Installing Toad
Edge dialog displays for a few minutes while the software gets installed. When the
installation has completed click on Finish.
Launching Toad Edge
Select the Toad Edge icon to launch the toolset. If a connection had been previously
configured with MySQL database an Enter Password dialog gets displayed as shown in
below. Provide the Password and click on OK.

The Toad Edge toolset gets launched after verifying connection. The Toad Edge graphical user
interface gets launched, as shown below.
Toad Edge provides several Views of which Connections, Object Explorer, and Outline, are
open by default. All the different Views may be opened from View, as shown below.

Creating a Connection to MySQL Database


To connect to MySQL database, click on Connect in the toolbar and select New Connection,
as shown below.
In the New MySQL Connection dialog three tabs are provided to specify the connection
parameters: Connection Settings, SSL and SSH. In Connection Settings specify Host
(localhost), Database (mysql), User (root) and Password, as shown in below. The Options
Enable AutoCommit and Restore previous work after login are selected by default. We shall
be demonstrating committing a transaction with AutoCommit Off, for which the Enable
AutoCommit should be de-selected. The Connection Name, which gets auto-generated,
must be unique. Connection String Preview lists the connection URL. Click on Test
Connection and if the message is “Connection is OK” click on OK.

A new connection gets created and gets listed in Connections view as shown in below. A
SQL worksheet also gets added.
The Object Explorer view lists all the Databases and Users, as shown below. The databases
listed are information_Schema, mysql, performance_schema and sys with the active
database shown in blue as mysql. All the SQL statements run in a worksheet are run on the
active database.
Using the SQL Worksheet to Create a Database Table
In this section we shall discuss creating a database table using the Worksheet1. Additional
worksheets may be added by selecting Worksheet from the toolbar. Specify the
following CREATE TABLE SQL statement in the worksheet, as shown in below.

For DDL (Data definition language) statements such as CREATE TABLE we don’t need to
commit the transaction with AutoCommit or by selecting Commit Transaction, since
MySQL database implicitly commits the transaction after the statement is run.

Click on Execute SQL Statement as shown below.


As the message Create table processed in Figure below indicates, a database table gets
created.

The wlslog table gets created in mysql database and gets listed in Object Explorer, as shown
in the next Figure. The SQL Recall view lists the CREATE TABLE statement run.
The MySQL CLI lists the wlslog table with the SHOW TABLES command, as shown below.
Select the database with USE mysql command before listing tables.
Creating a New Table using the Graphical Interface
Note that no SQL code is written.
To explain this, use the Exercise question No. 4 (in this document). This question comes
with several source files provided in a zipped folder (compressed file).
Click on the Create table button.

This should open the “Create Table” window.

The first table to create is the Driver table, so type Driver into the Name box.
Now click on “Columns” in the left pane of the window. We will enter the columns of the
Driver table specified below:
Driver: Column Name Data Type Length
driverID VARCHAR 4
title ENUM values: ‘Mr’, ‘Ms’, ‘Mrs’
firstname VARCHAR 15
surname VARCHAR 15
address VARCHAR 30
city VARCHAR 20
postcode VARCHAR 10
dob DATE
telhome VARCHAR 15
telmobile VARCHAR 15
licenceNbr VARCHAR 20
pointsNbr INT 2

For each column, you need to enter the Column Name and Data Type in the upper area of
the window, and to set the column’s properties [e.g., Length] in the lower area.
The first column is “driverID”. We will enter it as follows:-
▪ Place the cursor in the Name box and type driverID
▪ Place the cursor in the DataType box and select VARCHAR.
▪ Place the cursor in the Length box and change it to 4

Follow the same actions to enter the rest of the columns. Simply click Add to add a new
column.
Also notice the Remove button which can be useful if you make a mistake and wanted to
remove a column. Don’t click OK at the bottom until you’ve added all the columns!
After you have finished adding all the columns, you need to specify a PRIMARY KEY for the
table.
This can be achieved by clicking on the General node in the left pane. Click the 3-dotted
button at the end of the Primary Key box:

Click Here
A window will pop out, allowing you to select the column (or columns) that act as a Primary
Key for the table. In our case, select driverID and click the arrow to move it to the right-hand
side of the window, then click OK. Click OK again when you return to the table window in
order to save the changes.

If you get an error message “Missing column name” when you try to save the
table, you’ll probably find that you have a blank column at the end of the list
of columns. To fix the problem, select and delete the blank column.

Getting Data into the Table


There are mainly two ways for entering data into a table. Either by directly typing in the data,
or by importing from an external file, such a text file or a spreadsheet if such a file exists.
Let’s start by the importing some existing data into the table. We will assume that the
QuickVan company has been keeping some drivers records in a text file called Driver.txt.
This file and others are available in a compressed file called Lab1Data.zip (has been
provided). Download and unzip this file into your H: drive. From the Menu bar, click on
Tools > Import > Import Wizard.
On the Welcome page, click Next.
On the following page, click Add File and browse to the location where you saved your files
and select Driver.txt.

This should bring the following window:

UN-check the box that says, “Column names as header”.


Click “Next”, and you should see a window listing the 12 fields in the text file.
Click “Next” again, and you should see the “Select Target” window. Select “Driver” from the
Tables menu.

From now on, just keep clicking “Next” and “OK”. Toad should import the data from driver.txt
into the Driver table which you have just created.
To check that the data has been imported correctly, click on the Data tab in the table editor:
Now, having seen how to load data from a file into a table, let’s now see the more basic way
of entering data by typing in the data manually.
In the screen shot shown below, notice the bar at the bottom of the editor. In particular,
clicking on the “+” button allows you to enter a new record into the table:

To save the newly entered record into the database, click the “✔” button. For now, we don’t
need this extra record, so simply click the “-” button to delete it.
Worked Example 1
A manufacturing company produces products. The following product information is stored:
product name, product ID and quantity on hand. These products are made up of many
components. Each component can be supplied by one or more suppliers. The following
component information is kept: component ID, name, description, suppliers who supply
them, and products in which they are used.
Create an ERD to show how you would track this information.
Show entity names, primary keys, attributes for each entity, relationships between the
entities and cardinality.
Assumptions
• A supplier can exist without providing components.
• A component does not have to be associated with a supplier.
• A component does not have to be associated with a product. Not all components are
used in products.
• A product cannot exist without components.
Answer:
Component(CompID, CompName, Description) PK=CompID
Product(ProdID, ProdName, QtyOnHand) PK=ProdID
Supplier(SuppID, SuppName) PK = SuppID
CompSupp(CompID, SuppID) PK = CompID, SuppID
Build(CompID, ProdID, QtyOfComp) PK= CompID, ProdID
Worked Example 2
Veterinary Doctor
A veterinary doctor keeps the information about his clients and their pets in a database.
Create an ERD to show how you would track this information.
1. QuickVan (QV) Delivery Company
QV deliver letters, packages, parcels, etc. using delivery vans. QV deals with customers
who have accounts that are billed monthly. When a call comes from a customer for a
delivery the nearest available driver/van picks up the goods, gets the customer to sign a
pick-up note, and then delivers the goods getting the receiver to sign a delivery note. The
rate charged to the customer depends on the weight of the goods and the distance from
pick-up point to destination. QV offer two kinds of service, Standard and Express. Drivers
are paid a basic monthly wage plus bonuses - based on the total amount they earn for
QV on deliveries. When drivers return to the depot the data on their pick-up and delivery
notes is entered into the database.
1. Create the Customer table using the following description:
Customer: Column Name Data Type Length
customerID VARCHAR 6
custName VARCHAR 30
address VARCHAR 30
city VARCHAR 20
postcode VARCHAR 10
telNbr VARCHAR 15
Define customerID as the primary key. Import data into the Customer table from
the file Customer.txt
2. Create the Delivery table using following description:
Delivery: Column Name Data Type Column Size
deliveryNbr VARCHAR 7
driverID VARCHAR 4
customerID VARCHAR 6
vehicleNbr VARCHAR 10
pickupDate DATE
pickupTime TIME
delDate DATE
delTime TIME
delAddress VARCHAR 40
distance DOUBLE
weight DOUBLE
rate BIT
charge DOUBLE
The rate column is of type Boolean (1/0 or TRUE/FALSE). We use it here to represent
the Standard and Express rate of parcel deliveries.
Define deliveryNbr as the primary key. Import data into the Delivery table from the
file Delivery.txt
3. Create the Payslip and Invoice tables using the following descriptions:
Payslip: Column Name Data Type Length
payslipNbr VARCHAR 9
payDate DATE
driverID VARCHAR 4
amount DOUBLE
Define payslipNbr as the primary key.
Import data into the Payslip table from the file Payslip.xlsx
Note that the first row of the Excel spreadsheet DOES contain headers, so this time
you should leave the “First row are header” box ticked.

Invoice: Column Name Data Type Length


invoiceNbr VARCHAR 8
invoiceDate DATE
customerID VARCHAR 6
amount DOUBLE
paid BIT
Define invoiceNbr as the primary key. Import data into the Invoice table from the file
Invoice.xlsx

Linking the Tables: Referential (or Foreign Key) Integrity Rules


MySQL allows non-primary key columns to be defined as foreign keys by linking them to the
primary keys of other tables.
For example, the Delivery table has a column customerID which should reference the
customerID column in the Customer table.
This is a mechanism that makes sure that whatever value appears in the customerID of
Delivery needs to exist in the customerID of Customer.
The complete list of links between tables is as follows:-

Table Primary Key Link Table Foreign Key


Driver driverID ............. Delivery driverID
Driver driverID ............. Payslip driverID
Customer customerID ............. Delivery customerID
Customer customerID ............. Invoice customerID

Let’s start by establishing the link between Delivery and Customer. This can be achieved by
adding a Constraint into the Delivery table.
From the menu bar select Tools > Database Explorer. Double-click the Delivery table and
select Constraints in the left pane:

Click Add to add a new constraint, and enter the details as shown below:
▪ Constraint Name: DeliveryCustomerFK (this can be a name of your choice, but has
to be unique)
▪ Source Columns: select customerID (this is the column in Delivery table which acts
as foreign key)
▪ Destination table: select customer (this is the table that contains the primary key you
want to reference)
▪ Destination column: select customerID (this is the primary key you want to
reference)
▪ On Delete/Update: select Cascade.
When we choose to cascade deletes/updates this will mean that any customers
deleted/updated in Customer will automatically be deleted/updated wherever they occur in
Delivery to ensure that all values of customerID in Delivery have matched values in
Customer.
We will usually impose these referential integrity rules with the cascade options on all foreign
key links that are established.
Define the links between the other tables. Make sure you do not use the same constraint
name twice. You can view all the links that you have established between the tables as
follows: Tools > Database Diagram.
Drag the tables from the “Object Explorer” and drop into the “Database Diagram”. You may
see this warning.

It’s just telling you that when you drag a table into the diagram, any linked tables will be added
automatically. This is convenient for you, so check “Do not prompt be again” and click “OK”.
You should be able to see the five linked tables (you can rearrange the tables in the diagram
to obtain something similar to the figure shown below):
Exercise 2
International School Database
An International School keeps a detailed database of the students’ information. For each
student, they keep personal information such as the student registration number, Full name,
nationality, and address. They also record the history of each student including former
school and last attended class.
Create an ERD to show how you would track this information.
Show entity names, primary keys, attributes for each entity, relationships between the
entities and cardinality.
Draw the Table Design for each entity.
Create the database in MySQL.

Exercise 3
University Department
The Faculty of Science and Technology (FST) department in the International University of
East Africa (IUEA) keeps the information about the students and courses offered in a
database. The course administrator manages the database. At the end of the semester, she
prepares a report about each course.
Create an ERD to show how you would track this information.
Show entity names, primary keys, attributes for each entity, relationships between the
entities and cardinality.
Draw the Table Design for each entity.
Create the database in MySQL.

Exercise 4
Create an ERD for a car dealership database. The dealership sells both new and used cars,
and it operates a service facility. Base your design on the following business rules:

• A salesperson may sell many cars, but each car is sold by only one salesperson.
• A customer may buy many cars, but each car is bought by only one customer.
• A salesperson writes a single invoice for each car he or she sells.
• A customer gets an invoice for each car he or she buys.
• A customer may come in just to have his or her car serviced; that is, a customer need
not buy a car to be classified as a customer.
• When a customer takes one or more cars in for repair or service, one service ticket is
written for each car.
• The car dealership maintains a service history for each of the cars serviced. The
service records are referenced by the car’s serial number.
• A car brought in for service can be worked on by many mechanics, and each
mechanic may work on many cars.
• A car that is serviced may or may not need parts (e.g., adjusting a carburetor or
cleaning a fuel injector nozzle does not require providing new parts).
Show entity names, primary keys, attributes for each entity, relationships between the
entities and cardinality.
Draw the Table Design for each entity.
Create the database in MySQL.

Useful Resources
This set of MySQL labs is not intended as a complete set of tutorials for MySQL. You are
therefore expected to find and use other resources to complement your learning.
Here are some pointers:
MySQL Reference Manual: http://dev.mysql.com/doc/refman/5.5/en/index.html

You might also like