Mysql Database Administration
Mysql Database Administration
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
HND SWL2
Database Fundamentals
Database Design
SQL Basics
Data Sorting
Database Fundamentals
What is Data?
What is a database?
What is a Database Management System?
Types of DBMS
What is SQL?
What is NoSQL?
Why it makes sense to learn SQL after NOSQL?
What is Data?
In simple words data can be facts related to any object in consideration. For example your name, age,
height, weight, etc. are some data related to you. A picture, image, file, pdf etc. can also be considered
data.
What is a Database?
Database is a systematic collection of data. Databases support storage and manipulation of data.
Databases make data management easy. Let's discuss few examples. An online telephone directory
would definitely use database to store data pertaining to people, phone numbers, other contact details,
Page 2 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
etc. Your electricity service provider is obviously using a database to manage billing, client related issues,
to handle fault data, etc. Let's also consider the Facebook. It needs to store, manipulate and present data
related to members, their friends, member activities, messages, advertisements and lot more. We can
provide countless number of examples for usage of databases.
What is a Database Management System (DBMS)?
Database Management System (DBMS) is a collection of programs which enables its users to access
database, manipulate data, reporting / representation of data. It also helps to control access to the database.
Database Management Systems are not a new concept and as such had been first implemented in 1960s.
Charles Bachmen's Integrated Data Store (IDS) is said to be the first DBMS in history. With time database
technologies evolved a lot while usage and expected functionalities of databases have been increased
immensely.
Types of DBMS
Let's see how the DBMS family got evolved with the time. Following diagram shows the evolution of
DBMS categories.
There are 4 major types of DBMS. Let's look into them in detail.
Hierarchical - this type of DBMS employs the "parent-child" relationship of storing data. This
type of DBMS is rarely used nowadays. Its structure is like a tree with nodes representing records
and branches representing fields. The windows registry used in Windows XP is an example of a
hierarchical database. Configuration settings are stored as tree structures with nodes.
Network DBMS - this type of DBMS supports many-to many relations. This usually results in
complex database structures. RDM Server is an example of a database management system that
implements the network model.
Page 3 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Relational DBMS - this type of DBMS defines database relationships in form of tables, also
known as relations. Unlike network DBMS, RDBMS does not support many to many
relationships. Relational DBMS usually have pre-defined data types that they can support. This
is the most popular DBMS type in the market. Examples of relational database management
systems include MySQL, Oracle, and Microsoft SQL Server database.
Object Oriented Relation DBMS - this type supports storage of new data types. The data to be
stored is in form of objects. The objects to be stored in the database have attributes (i.e. gender,
age) and methods that define what to do with the data. PostgreSQL is an example of an object
oriented relational DBMS.
What is SQL?
SQL stands for Structured Query language, pronounced as "S-Q-L" or sometimes as "See-Quel". SQL
is the standard language for dealing with Relational Databases. SQL can be used to insert, search,
update and delete database records. SQL can do lots of other operations including optimizing and
maintenance of databases. Relational databases like MySQL Database, Oracle, Ms SQL server,
Sybase, etc uses SQL.
How to use sql syntaxes?
SQL Example
SELECT * FROM Members WHERE Age > 30
SQL syntaxes used in these databases are almost similar, except the fact that some are using few
different syntaxes and even proprietary SQL syntaxes.
What is NoSQL ?
NoSQL is an upcoming category of Database Management Systems. Its main characteristic is its non-
adherence to Relational Database Concepts. NOSQL means "Not only SQL".
Concept of NoSQL databases grew with internet giants such as Google, Facebook, and Amazon etc.
who deal with gigantic volumes of data.
When you use relational database for massive volumes of data, the system starts getting slow in terms
of response time. To overcome this, we could of course "scale up" our systems by upgrading our
Page 4 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
existing hardware. The alternative to the above problem would be to distribute our database load on
multiple hosts as the load increases.
This is known as "scaling out".
NOSQL database are non-relational databases that scale out better than relational databases and
are designed with web applications in mind.
They do not use SQL to query the data and do not follow strict schemas like relational models.With
NoSQL, ACID (Atomicity, Consistency, Isolation, and Durability) features are not guaranteed
always.
Why it makes sense to learn SQL after NOSQL?
With the advantages of NOSQL databases outlined above that scale out better than relational models,
you might be thinking why one would still want to learn about SQL database?
Well, NOSQL databases are sort of highly specialized systems and have their special usage and
limitations. NOSQL suit more for those who handles huge volumes of data. The vast majority, use
relational databases and associated tools.
Relational databases have the following advantages over NOSQL databases;
SQL(relational) databases have a mature data storage and management model . This is crucial for
enterprise users.
SQL databases support the notion of views which allow users to only see data that they are
authorized to view. The data that they are not authorized to see is kept hidden from them.
SQL databases support stored procedure sql which allow database developers to implement part
of the business logic into the database.
SQL databases have better security models compared to NoSQL databases.
The world has not deviated from use of relational databases. There is growing a demand for
professionals who can handle relational databases. Thus learning databases and SQL still holds merit.
Summary
DBMS stands for Database Management System.
We have four major types of DBMSs namely Hierarchical, Network, Relational, Object Oriented
Page 5 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
The most widely used DBMS is the relational model that saves data in table formats. It uses SQL
as the standard query language
SQL language is used to Sql query a database
The database approach has many advantages when it comes to storing data compared to the
traditional flat file based systems
MySQL Workbench Tutorial & MySQL Introduction
What is MySQL?
MySQL is an open source relational database. MySQL is cross platform which means it runs on a
number of different platforms such as Windows, Linux, and Mac OS etc.
In this lesson, you will learn-
What is MySQL?
Why use MySQL?
Introducing MySQL Workbench
MySQL workbench- Modeling and Design tool
MySQL workbench - SQL development tool
MySQL workbench - Administration tool
Install MySQL workbench Guide
Why use MySQL?
There are a number of relational database management systems on the market. Examples of relational
databases include Microsoft SQL Server, Microsoft Access, Oracle, DB2 etc. One may ask why we
would choose MySQL over the other database management systems. The answer to this question
depends on a number of factors.
Let's look at the strengths of MySQL compared to over relational databases such as SQL
Server
MySQL supports multiple storage engines each with its own specifications while other systems
like SQL server only support a single storage engine. In order to appreciate this statement, let's
look at two of the storage engines supported by MySQL.
Page 6 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
InnoDB: its default storage engine provided with MySQL as of version 5.5. InnoDB
supports foreign keys for referential integrity and also supports ACID-standard
transactions.
MyISAM: it was the default storage engine for MySQL prior to version 5.5. MyISAM
lacks support for transactions. Its advantages over InnoDB include simplicity and high
performance.
MySQL has high performance compared to other relation database systems. This is due to its
simplicity in design and support for multiple-storage engines.
Cost effective, it's relatively cheaper in terms of cost when compared to other relational databases.
In fact, the community edition is free. The commercial edition has a licensing fee which is also
cost effective compared to licensing fees for products such as Microsoft SQL Server.
Cross platform MySQL works on many platforms which means it can be deployed on most
machines. Other systems such as MS SQL Server only run on the windows platform.
In order to interact with MySQL, you will need a server access tool that can communicate with
MySQL server. MySQL supports multiple user connections.
Page 7 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 8 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 9 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
The figure shown below shows the SQL development window for MySQL Workbench.
User administration - visual utility for managing users that lets database administrators easily
add new and remove existing users if need arises, grant and drop privileges and view user profiles.
Server configuration - allows for advanced configuration of the server and fine tuning for
optimal performance.
Database backup and restorations - visual tool for exporting/importing MySQL dump files.
MySQL dump files contain SQL scripts for creating databases, tables, views, stored procedures
and insertion of data.
Page 10 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Server logs - visual tool for viewing MySQL server logs. The logs include error logs, binary logs
and InnodDB logs. These logs come in handy when performing diagnosis on the server. The
figure shown below shows the modeling window for MySQL Workbench.
The figure shown below shows the Admin panel for Workbench MySQL.
2) Install MySQL workbench. - You can install the workbench using a zip file or an msi installer
(recommended)
Note: You will require Administrator or Power User Privileges to perform installation.
Page 11 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Getting Started
1. Once you have finished installing above you need to set up MySQL Workbench as shown
below First step is launching the Workbench MySQL. What you see is called Home Window
2. Next you need to create your MySQL Server Connection which contains details about target database
server including how to connect to it. Click "+" in MySQL Workbench Home Window. This will
open Setup New Connection. Wizard.
Page 12 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
3. As a beginner you can create a connection for a locally installed server. Click Configure
Server Management button in Setup New Connection window to check the configuration of
the MySQL server.
Page 13 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
4. A new window opens named Configure Local Management. Click Next button to continue.
5. Next the Wizard will test connections to database. If test fails, go back and correct database
connection parameters.5. Next it will open a pop up window asking your root password to test
your connection with the local mysql server instance. The password is the one you set during
installation of MySQL Workbench. Enter your password and press OK.
Page 14 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
6. Next the Wizard will test connections to database. If test fails, go back and correct database
connection parameters. Else if all tests are successful click Next to continue.
Page 15 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
7. After that a new wizard will open about Local Service Management - It lets you switch between
multiple mysql severs installed on one machines. As a beginner you can bypass this and click
Next to continue.
Page 16 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
8. The Wizard will then check ability to access MySQL Server Configuration File, and test start/stop
commands.
9. Next you can review current configurations. After reviewing the configurations, Click Finish to finsh
server configuration.
Page 17 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
10. Next Step is to setup a connection, which can be used to connect to server. If you have not created a
connection already, you can use the default values given. Click on Test Connection [ 2 ] after entering
the Connection Name [ 1 ].
Page 18 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 19 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
11. A new dialog box will open asking you password to root/selected user. If your MySQL root user
has a password, you can enter that using Store in Vault feature. Click OK.
If the entered password for the user is correct then the following screen will show. Click on both OK
buttons and you will be good to go.
Page 20 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 22 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
In this Chapter, you will learn-
Why Database Design is Important?
Database development life cycle
Requirements analysis
Database designing
Implementation
Types of Database Techniques
Why Database Design is Important ?
It helps produce database systems
1. That meet the requirements of the users
2. Have high performance.
Database designing is crucial to high performance database system.
Note, the genius of a database is in its design . Data operations using SQL is relatively simple
Database development life cycle
The database development life cycle has a number of stages that are followed when developing database
systems.
The steps in the development life cycle do not necessary have to be followed religiously in a sequential
manner.
On small database systems, the database system development life cycle is usually very simple and does
not involve a lot of steps.
In order to fully appreciate the above diagram, let's look at the individual components listed in each step.
Page 23 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Requirements analysis
Planning - This stages concerns with planning of entire Database Development Life Cycle. It
takes into consideration the Information Systems strategy of the organization.
System definition - This stage defines the scope and boundaries of the proposed database system.
Database designing
Logical model - This stage is concerned with developing a database model based on
requirements. The entire design is on paper without any physical implementations or specific
DBMS considerations.
Physical model - This stage implements the logical model of the database taking into account the
DBMS and physical implementation factors.
Implementation
Data conversion and loading - this stage is concerned with importing and converting data from
the old system into the new database.
Testing - this stage is concerned with the identification of errors in the newly implemented
system .It checks the database against requirement specifications.
Two Types of Database Techniques
1. Normalization
2. ER Modeling
Let's study them one by one
1. Normalization
What is Normalization? 1NF, 2NF, 3NF & BCNF with Examples
NORMALIZATION is a database design technique that organizes tables in a manner that reduces
redundancy and dependency of data. Normalization divides larger tables into smaller tables and links
them using relationships. The purpose of Normalization is to eliminate redundant (useless) data and
ensure data is stored logically.
The inventor of the relational model Edgar Codd proposed the theory of normalization with the
introduction of the First Normal Form, and he continued to extend theory with Second and Third Normal
Page 24 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Form. Later he joined Raymond F. Boyce to develop the theory of Boyce-Codd Normal Form. In this
tutorial, you will learn.
1NF Rules
2NF Rules
3NF Rules
BCNF (Boyce-Codd Normal Form)
Database Normal Forms
The Theory of Data Normalization in SQL is still being developed further. For example, there are
discussions even on 6th Normal Form. However, in most practical applications, normalization achieves
its best in 3rd Normal Form. The evolution of Normalization theories is illustrated below
(Table1)
Here you see Movies Rented column has multiple values. Now let's move into 1st Normal Forms:
Page 25 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
1NF (First Normal Form) Rules
1NF Example
(Table1in1NF)
What is a KEY?
A KEY is a value used to identify a record in a table uniquely. A KEY could be a single column or
combination of multiple columns Note: Columns in a table that are NOT used to identify a record
uniquely are called non-key columns.
What is a Primary Key?
A primary is a single column value used to identify a database record uniquely.
Page 26 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
It has following attributes
A primary key cannot be NULL
A primary key value must be unique
The primary key values should rarely be changed
The primary key must be given a value when a new record is inserted.
Hence, we require both Full Name and Address to identify a record uniquely. That is a composite key.
Let's move into second normal form 2NF
2NF (Second Normal Form) Rules
Rule 1- Be in 1NF
Rule 2- Single Column Primary Key
It is clear that we can't move forward to make our simple database in 2nd Normalization form unless we
partition the table above.
Page 27 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id.
Foreign Key references the primary key of another Table! It helps connect
your Tables
A foreign key can have a different name from its primary key
It ensures rows in one table have corresponding rows in another
Unlike the Primary key, they do not have to be unique. Most often they
aren't
Foreign keys can be null even though primary keys can not
Page 28 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 29 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
You will only be able to insert values into your foreign key that exist in the unique key in the parent
table. This helps in referential integrity.
The above problem can be overcome by declaring membership id from Table2 as foreign key of
membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in the parent
table, an error will be shown!
What are transitive functional dependencies?
A transitive functional dependency is when changing a non-key column, might cause any of the other
non-key columns to change
Consider the table 1. Changing the non-key column Full Name may change Salutation.
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
TABLE 1
Table 2
Table 3
We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF
Page 31 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in Table
3
Now our little example is at a level that cannot further be decomposed to attain higher forms of
normalization. In fact, it is already in higher normalization forms. Separate efforts for moving into next
levels of normalizing data are normally needed in complex databases. However, we will be discussing
next levels of normalizations in brief in the following.
BCNF (Boyce-Codd Normal Form)
Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has more than
one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form.
4NF (Fourth Normal Form) Rules
If no database table instance contains two or more, independent and multivalued data describing the
relevant entity, then it is in 4th Normal Form.
5NF (Fifth Normal Form) Rules
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed into any number of smaller
tables without loss of data.
6NF (Sixth Normal Form) Proposed
6th Normal Form is not standardized, yet however, it is being discussed by database experts for some
time. Hopefully, we would have a clear & standardized definition for 6th Normal Form in the near future...
That's all to Normalization!!!
Summary
Database designing is critical to the successful implementation of a database management system
that meets the data requirements of an enterprise system.
Normalization helps produce database systems that are cost-effective and have better security
models.
Functional dependencies are a very important component of the normalize data process
Most database systems are normalized database up to the third normal forms.
Page 32 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
A primary key uniquely identifies are record in a Table and cannot be null
A foreign key helps connect table and references a primary key
ER Modeling?
What is ER Modeling?
Entity Relationship Model(ER Modeling) is a graphical approach to database design. It is a high-level
data model that defines data elements and their relationship for a specified software system. An ER model
is used to represent real-world objects.
An Entity is a thing or object in real world that is distinguishable from surrounding environment. For
example, each employee of an organization is a separate entity. Following are some of major
characteristics of entities.
An entity has a set of properties.
Entity properties can have values.
In this section, you will learn
Enhanced Entity Relationship (EER) Model
Why use ER Model?
Entities in the "MyFlix" library
Defining the relationships among entities
Let's consider our first example again. An employee of an organization is an entity. If "Peter" is a
programmer (an employee) at Microsoft, he can have attributes (properties) like name, age, weight,
height, etc. It is obvious that those do hold values relevant to him.
Each attribute can have Values. In most cases single attribute have one value. But it is possible for
attributes have multiple values also. For example Peter's age has a single value. But his "phone numbers"
property can have multiple values.
Entities can have relationships with each other. Let's consider the simplest example. Assume that each
Microsoft Programmer is given a Computer. It is clear that Peter's Computer is also an entity. Peter is
using that computer, and the same computer is used by Peter. In other words, there is a mutual relationship
between Peter and his computer.
In Entity Relationship Modeling, we model entities, their attributes and relationships among entities.
Page 33 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Enhanced Entity Relationship (EER) Model
Enhanced Entity Relationship (EER) Model is a high-level data model which provides extensions to
original Entity Relationship (ER) model. EER Models supports more details design. EER Modeling
emerged as a solution for modeling highly complex databases.
EER uses UML notation. UML is the acronym for Unified Modeling Language; it is a general-purpose
modeling language used when designing object-oriented systems. Entities are represented as class
diagrams. Relationships are represented as associations between entities. The diagram shown below
illustrates an ER diagram using the UML notation.
Page 34 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Let's look at the steps to develop EER diagram for this database-
1. Identify the entities and determine the relationships that exist among them.
2. Each entity, attribute, and relationship, should have appropriate names that can be easily
understood by the non-technical people as well.
3. Relationships should not be connected directly to each other. Relationships should connect
entities.
4. Each attribute in a given entity should have a unique name.
Entities in the "MyFlix" library
The entities to be included in our ER diagram are;
Members - this entity will hold member information.
Movies - this entity will hold information regarding movies
Categories - this entity will hold information that places movies into different categories such
as "Drama", "Action", and "Epic" etc.
Movie Rentals - this entity will hold information that about movies rented out to members.
Payments - this entity will hold information about the payments made by members.
Defining the relationships among entities
Members and movies
The following holds true regarding the interactions between the two entities.
A member can rent more 1 than movie in a given period.
A movie can be rented by more than one member in a given period.
From the above scenario, we can see that the nature of the relationship is many-to-many. Relational
databases do not support many-to-many relationships. We need to introduce a junction entity. This
is the role that the MovieRentals entity plays. It has a one-to-many relationship with the members table
and another one-to-many relationship with movies table.
Movies and categories entities
The following holds true about movies and categories.
A movie can only belong to one category but a category can have more than one movie. We can
deduce from this that the nature of the relation between categories and movies table is one-to-
many.
Page 35 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Members and payments entities
The following holds true about members and payments
A member can only have one account but can make a number of payments.
We can deduce from this that the nature of the relationship between members and payments entities is
one-to-many.
Now lets create EER model using MySQL Workbench
In the MySQL workbench , Click - "+" Button
Double click on Add Diagram button to open the workspace for ER diagrams.
Page 36 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 37 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Following window appears
Page 38 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Let's look at the two objects that we will work with.
The table object allows us to create entities and define the attributes associated with the
particular entity.
Page 39 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Next ,
1) Change table 1 to Members
2) Edit the default idtable1 to membership_number
3) Click on the next line to add the next field
4) Do the same for all the attributes identified in members' entity.
Page 40 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Your properties window should now look like this.
Your diagram workspace should now look like the one shown below.
Page 41 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
3) Click on reference_number in the MovieRentals table
Repeat above steps for other relationships. Your ER diagram should now look like this -
Summary
The full form of ER is Entity and Relationships Diagrams. They play a very important role in the
database designing process. They serve as a non-technical communication tool for technical and
non-technical people.
Page 42 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Entities represent real world things; they can be conceptual as a sales order or physical such as a
customer.
All entities must be given unique names.
ER models also allow the database designers to identify and define the relations that exist among
entities.
The entire ER Model is attached below. You can simply import it in MySQL Workbench
MySQL Create Database, Tables, Data Types
Steps for Create Database Mysql
Create Database in two ways
1) By executing a simple SQL query
2) By using forward engineering in MySQL Workbench
In this section, you will learn
Create Database
Creating Tables MySQL
Data types
MySQL workbench ER diagram forward Engineering
As SQL beginner, let's look into the query method first.
Create Database
CREATE DATABASE is the SQL command for creating a database.
Imagine you need to create a database with name "movies". You can do it by executing following SQL
command.
CREATE DATABASE movies;
Note: you can also use the command CREATE SCHEMA instead of CREATE DATABASE
Now let's improve our SQL query adding more parameters and specifications.
IF NOT EXISTS
A single MySQL server could have multiple databases. If you are not the only one accessing the same
MySQL server or if you have to deal with multiple databases there is a probability of attempting to create
a new database with name of an existing database. IF NOT EXISTS let you to instruct MySQL server
to check the existence of a database with a similar name prior to creating database.
Page 43 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
When IF NOT EXISTS is used database is created only if given name does not conflict with an existing
database's name. Without the use of IF NOT EXISTS MySQL throws an error.
CREATE DATABASE IF NOT EXISTS movies;
Collation and Character Set
Collation is set of rules used in comparison. Many people use MySQL to store data other than English.
Data is stored in MySQL using a specific character set. The character set can be defined at different levels
viz, server , database , table and columns.
You need to select the rules of collation which in turn depend on the character set chosen.
For instance, the Latin1 character set uses the latin1_swedish_ci collation which is the
Swedish case insensitive order.
CREATE DATABASE IF NOT EXISTS movies CHARACTER SET latin1 COLLATE latin1_swedish
_ci
The best practice while using local languages like Arabic , Chinese etc is to select Unicode (utf-8)
character set which has several collations or just stick to default collation utf8-general-ci.
You can see list of existing databases by running following SQL command.
SHOW DATABASES
Creating Tables MySQL
Tables can be created using CREATE TABLE statement and it actually has the following syntax.
CREATE TABLE [IF NOT EXISTS] `TableName` (`fieldname` dataType [optional parameters])
ENGINE = storage Engine;
"CREATE TABLE" is the one responsible for the creation of the table in the database.
"[IF NOT EXISTS]" is optional and only create the table if no matching table name is found.
"`fieldName`" is the name of the field and "data Type" defines the nature of the data to be stored
in the field.
"[optional parameters]" additional information about a field such as " AUTO_INCREMENT" ,
NOT NULL etc
Create Table Example
CREATE TABLE IF NOT EXISTS `MyFlixDB`.`Members` (
`membership_number` INT AUTOINCREMENT ,
`full_names` VARCHAR(150) NOT NULL ,
Page 44 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
`gender` VARCHAR(6) ,
`date_of_birth` DATE ,
`physical_address` VARCHAR(255) ,
`postal_address` VARCHAR(255) ,
`contact_number` VARCHAR(75) ,
`email` VARCHAR(255) ,
PRIMARY KEY (`membership_number`) )
ENGINE = InnoDB;
NB: Now let's see what the MySQL's data types are. You can use any of them depending on your need.
You should always try to not to underestimate or overestimate potential range of data when creating a
database.
Page 45 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
DATA TYPES
Data types define the nature of the data that can be stored in a particular column of a table
MySQL has 3 main categories of data types namely
1) Numeric,
2) Text
3) Date/time.
Numeric Data types
Numeric data types are used to store numeric values. It is very important to make sure range of your
data is between lower and upper boundaries of numeric data types.
DECIMAL( , ) A DOUBLE stored as a string , allowing for a fixed decimal point. Choice for
storing currency values.
Page 46 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Date / Time
DATE YYYY-MM-DD
TIMESTAMP YYYYMMDDHHMMSS
TIME HH:MM:SS
Apart from above there are some other data types in MySQL.
Page 47 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
ENUM To store text value chosen from a list of predefined text values
SET This is also used for storing text values chosen from a list of predefined text
values. It can have multiple values.
Now let's see a sample SQL query for creating a table which has data of all data types. Study it and
identify how each data type is defined.
CREATE TABLE`all_data_types` (
`varchar` VARCHAR( 20 ) ,
`tinyint` TINYINT ,
`text` TEXT ,
`date` DATE ,
`smallint` SMALLINT ,
`mediumint` MEDIUMINT ,
`int` INT ,
`bigint` BIGINT ,
`float` FLOAT( 10, 2 ) ,
`double` DOUBLE ,
`decimal` DECIMAL( 10, 2 ) ,
`datetime` DATETIME ,
`timestamp` TIMESTAMP ,
`time` TIME ,
`year` YEAR ,
`char` CHAR( 10 ) ,
Page 48 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
`tinyblob` TINYBLOB ,
`tinytext` TINYTEXT ,
`blob` BLOB ,
`mediumblob` MEDIUMBLOB ,
`mediumtext` MEDIUMTEXT ,
`longblob` LONGBLOB ,
`longtext` LONGTEXT ,
`enum` ENUM( '1', '2', '3' ) ,
`set` SET( '1', '2', '3' ) ,
`bool` BOOL ,
`binary` BINARY( 20 ) ,
`varbinary` VARBINARY( 20 )
) ENGINE= MYISAM ;
Best practices
Use upper case letters for SQL keywords i.e. "DROP SCHEMA IF EXISTS `MyFlixDB`;"
End all your SQL commands using semi colons.
Avoid using spaces in schema, table and field names. Use underscores instead to separate schema,
table or field names.
MySQL workbench ER diagram forward engineering
MySQL workbench has utilities that support forward engineering. Forward engineering is a technical
term is to describe the process of translating a logical model into a physical implement automatically.
We created an ER diagram on our ER modeling example above. We will now use that ER model to
generate the SQL scripts that will create our database.
Creating the MyFlix database from the MyFlix ER model
1) Open the ER model of MyFlix database that you created in earlier tutorial.
2) Click on the database menu. Select forward engineer
Page 49 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 50 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
3) The next window, allows you to connect to an instance of MySQL server. Click on the stored
connection drop down list and select local host. Click Execute
4) Select the options shown below in the wizard that appears. Click next
Page 51 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
5) The next screen shows the summary of objects in our EER diagram. Our MyFlix DB has 5
tables. Keep the selections default and click Next.
Page 52 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
6) The window shown below appears. This window allows you to preview the SQL script to create
our database. We can save the scripts to a *.sql" file or copy the scripts to the clipboard. Click on
next button.
Page 53 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Page 54 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
7. The window shown below appears after successfully creating the database on the selected MySQL
server instance.
Summary
Creating a database involves translating the logical database design model into the physical
database.
MySQL supports a number of data types for numeric, dates and strings values.
CREATE DATABASE command is used to create a database
CREATE TABLE command is used to create tables in a database
MySQL workbench supports forward engineering which involves automatically generating SQL
scripts from the logical database model that can be executed to create the physical database
The Database along with Dummy Data is attached. We will be using this DB for all our further practical.
Page 55 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
MySQL SELECT Statement with Examples
Databases store data for later retrieval. Ever wondered how that is achieved? It's the SELECT SQL
command that does the job. That's what it's all about, retrieving data from the database tables. It's part of
the data manipulation language that is responsible for query the data from the database.
SQL SELECT statement syntax
It is the most frequently used SQL command and has the following general syntax
SELECT [DISTINCT|ALL ] { * | [fieldExpression [AS newName]} FROM tableName [alias]
[WHERE condition][GROUP BY fieldName(s)] [HAVING condition] ORDER BY fieldName(s)
HERE
SELECT is the SQL keyword that lets the database know that you want to retrieve data.
[DISTINCT | ALL] are optional keywords that can be used to fine tune the results returned from
the SQL SELECT statement. If nothing is specified then ALL is assumed as the default.
{*| [fieldExpression [AS newName]} at least one part must be specified, "*" selected all the
fields from the specified table name, fieldExpression performs some computations on the
specified fields such as adding numbers or putting together two string fields into one.
FROM tableName is mandatory and must contain at least one table, multiple tables must be
separated using commas or joined using the JOIN keyword.
WHERE condition is optional, it can be used to specify criteria in the result set returned from the
query.
GROUP BY is used to put together records that have the same field values.
HAVING condition is used to specify criteria when working using the GROUP BY keyword.
ORDER BY is used to specify the sort order of the result set.
*
The Star symbol is used to select all the columns in table. An example of a simple SELECT statement
looks like the one shown below.
SELECT * FROM `members`;
The above statement selects all the fields from the members table. The semi-colon is a statement
terminate. It's not mandatory but is considered a good practice to end your statements like that.
Page 56 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Practical examples
Base on the result gotten from the forward engineering above, the myflix DB used for practical
examples.
You can learn to import the .sql file into MySQL WorkBench
The Examples are performed on the following two tables
Table 1: members table
membership_ date_of_ physical_ postal_ contct_
full_names gender email
number birth address address number
1 First Street Private 0759 253
Janet Jones Female 21-07-1980 [email protected]
Plot No 4 Bag 542
2 Melrose 123
Janet Smith Jones Female 23-06-1980 NULL NULL [email protected]
3rd Street
3
Robert Phil Male 12-07-1989 34 NULL 12345 [email protected]
2nd Street
4
Gloria Williams Female 14-02-1984 23 NULL NULL NULL
Page 57 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Let's suppose that we want to get a list of all the registered library members from our database, we
would use the script shown below to do that.
SELECT * FROM `members`;
Executing the above script in MySQL workbench produces the following results.
Our above query has returned all the rows and columns from the members table.
Let's say we are only interested in getting only the full_names, gender, physical_address and email fields
only. The following script would help us to achieve this.
SELECT `full_names`,`gender`,`physical_address`, `email` FROM `members`;
Executing the above script in MySQL workbench produces the following results.
full_names gender physical_address email
Janet Jones Female First Street Plot No 4 [email protected]
Janet Smith Jones Female Melrose 123 [email protected]
Robert Phil Male 3rd Street 34 [email protected]
Gloria Williams Female 2nd Street 23 NULL
Getting movies listing
Remember in our above discussion that we mention expressions been used in SELECT statements. Let's
say we want to get a list of movie from our database. We want to have the movie title and the name of
Page 58 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
the movie director in one field. The name of the movie director should be in brackets. We also want to
get the year that the movie was released. The following script helps us do that.
SELECT Concat(`title`, ' (', `director`, ')') , `year_released` FROM `movies`;
HERE
The Concat () MySQL function is used join the columns values together.
The line "Concat (`title`, ' (', `director`, ')') gets the title, adds an opening bracket followed by the
name of the director then adds the closing bracket.
String portions are separated using commas in the Concat () function.
Executing the above script in MySQL workbench produces the following result set.
Page 59 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
"[AS]" is the optional keyword before the alias name that denotes the expression, value or field
name will be returned as.
"`alias_name`" is the alias name that we want to return in our result set as the field name.
The above query with a more meaningful column name
SELECT Concat(`title`, ' (', `director`, ')') AS 'Concat', `year_released` FROM `movies`;
We get the following result
Concat year_released
Pirates of the Caribean 4 ( Rob Marshall) 2011
Forgetting Sarah Marshal (Nicholas Stoller) 2008
NULL 2008
Code Name Black (Edgar Jimz) 2010
NULL 2007
NULL 2007
NULL 2007
Honey mooners (John Schultz) 2005
NULL 2012
Getting members listing showing the year of birth
Suppose we want to get a list of all the members showing the membership number, full names and year
of birth, we can use the LEFT string function to extract the year of birth from the date of birth field. The
script shown below helps us to do that.
SELECT `membership_number`,`full_names`,LEFT(`date_of_birth`,4) AS `year_of_birth` FROM
members;
HERE
"LEFT(`date_of_birth`,4)" the LEFT string function accepts the date of birth as the parameter and only
returns 4 characters from the left.
"AS `year_of_birth`" is the column alias name that will be returned in our results. Note the AS keyword
is optional, you can leave it out and the query will still work.
Executing the above query in MySQL workbench against the myflixdb gives us the results shown
below.
Page 60 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
membership_number full_names year_of_birth
1
Janet Jones 1980
2
Janet Smith Jones 1980
3
Robert Phil 1989
4
Gloria Williams 1984
SQL using MySQL Workbench
We are now going to use MySQL workbench to generate the script that will display all the field names
from our categories table.
1. Right Click on the Categories Table. Click on "Select Rows - Limit 1000"
2. MySQL workbench will automatically create a SQL query and paste in the editor.
3. Query Results will be show
Notice that we didn't write the SELECT statement ourselves. MySQL workbench generated it for us.
Why use the SELECT SQL command when we have MySQL Workbench?
Page 61 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]
ABANG
28/04/2020
DATABASE ADMINISTRATION WITH MYSQL
Now, you might be thinking why learn the SQL SELECT command to query data from the database
when you can simply use a tool such as MySQL workbench's to get the same results without knowledge
of the SQL language. Of course that is possible, but learning how to use the SELECT command gives
you more flexibility and control over your SQL SELECT statements.
MySQL workbench falls in the category of "Query by Example" QBE tools. It's intended to help
generate SQL statements faster to increase the user productivity.
Learning the SQL SELECT command can enable you to create complex queries that cannot be easily
generated using Query by Example utilities such as MySQL workbench.
To improve productivity you can generate the code using MySQL workbench then customize it
to meet your requirements. This can only happen if you understand how the SQL statements work!
Summary
The SQL SELECT keyword is used to query data from the database and it's the most commonly
used command.
The simplest form has the syntax "SELECT * FROM tableName;"
Expressions can also be used in the select statement . Example "SELECT quantity + price
FROM Sales"
The SQL SELECT command can also have other optional parameters such as WHERE,
GROUP BY, HAVING, ORDER BY. They will be discussed later.
MySQL workbench can help develop SQL statements, execute them and produce the output
result in the same window.
Page 62 of 62
INTRUCTOR: ABANG TANYI ALAIN
TEL: 671541504
Email: [email protected]