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

Chapter 8 Databases

The document outlines the objectives and features of database systems, contrasting traditional file-based systems with Database Management Systems (DBMS). It discusses the limitations of file-based systems, such as data redundancy and inconsistency, and emphasizes the advantages of DBMS, including data integrity, security, and multi-user access. Additionally, it covers essential database concepts, structures, and the importance of ACID properties in transaction management.

Uploaded by

chiyanjapeter7
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)
4 views

Chapter 8 Databases

The document outlines the objectives and features of database systems, contrasting traditional file-based systems with Database Management Systems (DBMS). It discusses the limitations of file-based systems, such as data redundancy and inconsistency, and emphasizes the advantages of DBMS, including data integrity, security, and multi-user access. Additionally, it covers essential database concepts, structures, and the importance of ACID properties in transaction management.

Uploaded by

chiyanjapeter7
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/ 66

C P R8:

DATABASES

Chapter Objectives
Learners should be able to:
. describe the file based approach database system
. outline features of a Database Management System (DBMS)
. describe features of relational database which address limitations ofa file based approach
. explain different database views
. write SQL commands
. access data in a database through a high level language
. design database applications using entity relationship diagrams (ERDs)
o convert ERDs to relational databases schema in standard normal form
. normalise database tables up to second normal form

Introduction
Before the advent of computers, a manual 6le system was used to maintain records and files. All the
data was stored in separate files. But this system was good only for small organisations having small
number of items. The manual file system was also labour intensive, time consuming and inefficient.
To overcome these disadvantages and to make the processing fast, traditional filc processing system
was introduced. The 6le processing system had also its drawbacks such as data duplication. Generally,
traditional file processing systems were good in many cases in comparison to manual non computer
based system but still it had many disadvantages that were overcome by database management
sy6tem.

Traditional File Based Database Systems


File based database systems are totally computer based system where all the information is stored
in different computer files. Files can be in simple rows and columns with no relationships or links
between the files. The data is stored in such a manner that all the departments ofan organisation have
their own set of data frles and application programs to manipulate the data files. These application
programs have been written on request ofthe users in the organisation. New application will be added
to the system as the need arises. Files in Traditional File Processing Systems are called flat fiIes.

Example I
To illustrate traditional file database system, let us take an example ofa school where a student record
for an examination is stored in another file, his library record is stored in a different file and his
registration record is again stored in a di-fferent file that creates many duplicate values like Student
Number and Name.

335

)
Fig 8.1 Traditional file based d.atabase system
for a school

and programs depend upon each other.


And due to this, any chanse in one fite
l#:Ti..l::L":i will

Example 2
consider a traditional banking system which
uses the file-based system in managing
data in the picture below. As we can see, the organisation,s
there are different departments in the banh
has its own applications which manage each of them
and ;il;;;;fferent
data 61.;. F;;;;;ng
system,
the programs can be the one to debit
credit i i"a tr,. oJ*1..r- ;""";;
mortgage loan or generate monthly statements ""
etc
"i-r"r, add a new

Persolael
Dep artmerr
tt
.{ccou!r Deplmrear
@
Loal Deprrmrelr

@F
@@
Fig 8.2 Tratlitional fle based database system
for a banking system

Characteristics of traditional file based database


system
. It stores the data ofan organisation in group of separate
. Files storing data are indipendent of ea'ch other. ' - files.
' Each fiIe contains data for some speci'c area or department like ribrary, student fees, and
student examinations.
. It is less flexible and has many limitations.

336

)
l-
. It is very difficult to maintain the file processing system.
. Any change in one file affects all the files which creates burden on the programmer.
' Data files and application programs are created by different programmers ofvarious depart-
ments.

Disadvantages of traditional file based database system


* Data R€dundancy
' Since data files and application progr:rms are created by different programmers of various
departments, the same information may be kept in several difierent files in different depart-
ments.
. Data duplication results in wastage of storage space and duplication of effort.

* Dati Inconsistency
. Inconsistency in data format,
. Data inconsistency may arise since different copies ofthe same data are kept in diferent de-
partments. The data in these departments may be conflicting.

* Data Isolation
. It is diftcult for a new application to retrieve the appropriate data which might be stored in
various files that belong to other departments.
' Since files may be in different formats, writing new application programs to retrieve the ap-
propriate data is dificult.

'+ Integrity Problems


Data values must satisfy certain consistency constraints which are specified in the application
Programs.
It is difficult to add or change the progrnms to enforce new constraints.

* Security Problems
There are constraints regarding accessing privileges.
Application is added to the system in the ad-hoc manner so it is difficult to enforce those
constraints.

* Concurrent - access anomalies


. Data may be accessed by many applications that have not been coordinated previously so it is
not easy to provide a strategy to support multiple users to update data simultaneously.

* Dqrendency on Application Programs


. Changing files would lead to change in application programs.

Database Approach
. The limitations ofthe traditional file based database system prompted the development ofthe
database approach as a new approach in managing large amount of organisationil informa-
tion.

337
Jr-d

f
I

il

l..tx ll,|]t

Fig 8.j The database approach


for a banking system

' The primary goar of thc Database


Management system (DBMS) is to provide
an environment
that is both convenient
and eftcient for isers io rltri..,. und
rtore information.
' Application programs access the data stored
in th. a"t"r"re by.il;;;;; ,o the DBMS.
Applications of Databases
Databases are used in afea as long as there is need to keep
'rny records of information. The following
are some common areas where databases are used:
. Telecommunication: There is a
database in tel€
i"ro'-"tior,."gurd;s o"o' track of the
cans made, network usage, ::'.ffi:fi:|Tl.tu'
' Industry: whether it is a manuru"t*ing
utrit, rir.iouse or distribution centre,
each one needs
a database to keep the records
of proauLrc.ffiJ or delivered.
. Banking System: For storing customer
information, tracking day to day credit
transactions, generating bank statements and debit
etc.
' For storing patients' information, drug
information, suppliers, detairs and equipment
fl",Xilr
' Education sector: Database systems are frequentry
used in schoors and colleges to store and
retrieve the data regarding student detairs,
rt"r j.t"itr, course detairs, .*u-i.t"ilr, p"y.oLl
data, attendance details, fees details
etc.
' online shopping: online shopping websites such
as Amazon store the product information,
customers' addresses and preferences and
credit detairs in
with the relevant list of products based on
il;b"J'il;
p.o'id.
"iro
a query using a database management
||ri:t#*o
Database Concepts

Database
' A database is a single organised collection ofstructured and related data, stored with minimum
duplication of data items so as to provide
. Databases can be accessed usingiitrerent
consistent *a .orrt.ou.l a"i" *,ir"l"
Jg*o",r"".
application sottware.
' Data stored in databases can be-accessed
by afl system users, but with diferent access
rights.
' Database operations may include addition of r.. .".o.d., deletion ,^"-i.a records,
338
"r
amendments to existing records, creation of relationships between files, searching a record
and removal or addition of fields.

Building blocks of a database


Database

t
File

t
Record

t
Field

I
i( Byte

T-
Bit
Fig 8.4 Buikling block of a database

* Bit
A single binary digit, for example,0 or l A bit is the smallest unit of storage in the computer
system.

* Byte
A collection ofbits usually 8 bits representing a character, for example, 10000001.

* Field
A collection of bpes describing an entity, for example, Name, Sex, ProductlD.
A field is also called an attribute. i1
In a relational database, a field is represented by the column'

* Record
A collection of related fields describing an entity, for example, patient record.
A record is also known as a tuple.
In a relational database, a record is represented by the row.

339

)
1 File
. A collection ofrelated records, for example,
customers file.
. In a relationat database, a fle is represent"j
Ufii. tuUf".
* Database
' ffH:Tffi::1fiffi:';j"'**ole a school database with teacher fi.Ie, student file, supptier

Database Management System (DBMS)


' Database Management system (DBMS) is a collection of progr.rms that enable users to create,
maintain database' control access to the database
and provides interface between the database
and application programs.
' The DBMS a'ocates storage to data,
alrows users to access the database
concurrently etc.
' The primary goal of the DBMS is to provide
an environment that is both convenient
and effi-
cient for user to retrieve and store iniormation.
' ltrllffil:Ti.i.T"*'"8' Microsoft Access' cassandra, Redis, MvsQL,
Microsoft sel
Objectives of a DBMS
The main objectives ofa DBMS are
data availability, data integrity and
. Data Availability data security.
Data integrity means that the data are
made available to wide variety of users
at reasonable cost so that the users in a meaningful format
can easily access the data.

. Data Integritl
Data integrity means the correctness
of the data in the database. In other words,
the database is reliable and consistent the data available in
data.

. Data Security
Data security refers to the fact that
only authorised users can access the data.
enforced by usernames and passwora, Data security can be
ur". -a nglr".
f.irif"S.
Features of Database Management
System
Data Dictionary Management
The Data Dictionary is wh-ere the DBMS
stores definitions of the data elements
(metadata). The DBMS uses this and their relationships
function ,o roJ ofiir."r.quired data component
relationships. when programs access structures and
data in a database they are basically going
The Data Dictionary is often hidden from through the DBMs.
Programmers.
the ;;;il]. used by Database Administrators and

Data Storage Management


The DBMS manages the storage-ofdata
and any related data entry forms or screen
definitions, validation rure, definitions, report
users do not neea ,o t ro*lo, ,rre data
"rc. is stored or manipulated.

340

)
Data Transformation and Presentation
The DBMS can use the data transformation and presentation function to determine the difference
between logical and physical data formats. This function exists to change any data enteretl into required
data structures.

Security Management
Security management sets rules that determine specific users that are allowed to access the database.
These function restraints on what specific data any user can see or manage.

Backup and Recovery Management


Backup and recovgry is important whenever there are potential threats to the database such as power
outage. Recovery management is how long it takes to recover the database after the outrage. Backup
management refers to the data safety and integrity; for example backing up the data files on a disk.

Data Integrity Management


Data integrity refers to the accuracy and consistency of data stored in a database. The DBMS enforces
these rules to reduce things such as data redundancy and maximize data consistency, making sure the
database is returning the same result each time the same question is asked.

Multiuser Access Control


Multiuser access control is very usefirl as it enables multiple users to access the database simultaneously
without affecting the integrity of data. Multiuser Access Control will ensure data integrity and data
consistencT,

Database Communication Interface


This refers to how the DBMS can accept different end user requests through different network requests,
for example, on the internet a DBMS can provide access to the database through web browsers such as
Mozilla Firefox, Internet Explorer etc.

Database Access Languages and Application Programming Interfaces


A query language is a non-procedural language, for example, Structured euery Language (sel). The
use of this language makes it easy for a user to specif what they want done withoul explaining how
to specifically do it.

Transaction Management
A transaction is a unit of program that updates various data items. This refers to how a DBMS must
supply a method that will guarantee that all the updates in a given transaction are made or not made.
All transaction must follow the ACID properties.

ACID properties in DBMS


To ensure the integrity ofdata during a transaction, the database system maintains the what are widely
known as ACID properties: r
Atomicity
. A transaction is an indivisible unit that is either performed as a whole and not by its parts, or I
not performed at all. The recovery management must make sure that this takes place,

341
This property ensures
that eirl all the operations ofa
Let's take an example transaction..fl..t in database or nonc.
of6"16ll tY"tm to understand
of $400 and Accounr B h..
$7t8
this'supp6s.4..;;;;;;;";-
'a transferring
lhis is a transaction is rransrerrins
rs
This ,r.,
transartin. that has
two oPerations
$l00to Account B.
$r00to Bb baran;;#; "^^19.-1..ount.A a) Debiting
oPttution passed successfrrlly
$r00f.";;i;;;ce b) creatins
A's balance would be while second failed, in this
ilt B would be having $700instead
$roo*t---le casc
in a banking system. "rsi-oo.
riiJu
troperry ensures that either the transaction
"ri".llJ,*n
Hi:":::y
of theoPeration rri"rri pr".l;#iftff shorrl.l r.;r r^.i+L^..a
should fail ,-
without executing any
Lonststency "irr #action

*tli:Tffi":T"'#1]:[:."j"*:*::{he execution ortransaction


-'*'req!'rvr! lrru'rq
shourd take prace in
already running). run concurrently when there
is a transaction
' Account A is having a barance
fi ril,i:' of $400 and ir is transferring
$100 to account B
. So we have two transactions
here. Let,s say these t
;;T':"fi1:i:;':il''b'I*';;;;;;:ff :':ffi :*:::n?::iiT:i:ffi 1*:$J:;
. If the transaction were to run
in isolation, then th
.. ;:"'"'Jjl'-ce $300 (before d.ililffij ;;:: il: ;:::1,1":H:'JnJ:::1*n...* ..
Tiansactions must be€xecuted
independently ofon,
should not be abl" to b....n Part of a transaction in progress
. by another trans"oionl-oft"t'
transactions, ;*;;;;;
ffffi::.lr:fiof """ ri"ura ,,"', execution only
when the other
; The example ofisolation
'ra qrc.q/
"' has already ucen
been crscussed
discussed in the consistency
property above.
Durability
rlT:'il#:ili::;,T:l:"'.'.'ffi::tHJJ:e changes it has made into
the database shourd
component of database systems
,lli.rrrouro--anagement ensures the durabirity
of transac-

Relational Databases
A relational database is a collection
ofnormalised
vr uurruauseo retations
relations with distinct names
to link the relations. allowing users
A relation is a table with columns
and rows.
A table is a collection of records
It only applies to losical structure
stored urr"g
-rr, *a column structure.
a",iU"r", ,i",-.f,linrr,." structure.
Each column ..pr"i=.nt, "fO.
.E acn row represents
-attribute
a tuple or record.
or field
tach attribute has a distinct
name.
Degree is the number of
attributes in a relation.
Cardinality is the number of
tupt., in
Each cell ofrelation contains "..i"ti*
exactly one atomic (single)
value.
v.u
no jupri."t. iupi\qr,Er!.,
Each tuple is distinct; there are

342

)
. Order ofattributes and tuples has no significance.
' Relational databases have replaced hierarchical databases and network databases because
they are easier to implement and administer.

Relation name/table name

-j ;:".*
- ,t
rr/+
/

, Descriprion . euanrny
PlimarY KeY AttribYte/field

11001 Mouse Black 700 <l'ple/record


lTO02 Speakers Elack and White 20
lTO03 Printer White 5
',.9 IIm4 (eyboard Blact 7A
i rlF

Fig 8.5 Microsolt Access relational database

Advantages of Relational Databases


' Relational databases organise data in a flexible manner, which minimizes the size of the
database as well as the likelihood of mistakes.

'' Each record, has a unique identifier that makes it easy to locate data when a user needs to
access a record.

' Each user can view the same data set in the most appropriate way for their needs.
' Security control may also be implemented by moving sensitive attributes in a given relation
into a separate relation with its own authorization and access rights.
' Diferent tables from which information has to be linked and extracted can be easily
manipulated by operators.
. They are easy to design, implement and manage.
. Ensures structural independence by use of normalization.
. Ensures ad hoc query capability, for example, sel is easy with relational databases.

Disadvantages of a Relational Database


. Difficult to design than a flat file database.
' Substantial hardware and system software overhead especially ifthe number oftables are large
and this affect the performance when responding to SeL queries.
. Tables used in relational databases do not usually map to objects very well.
. They are not good at modelling certain kinds ofdata such as graphs.
' Creating a complex relational database requires high skill and expertise ranging from RDBMS
administrators and report developers.
. May promote "islands of informationi' problems.
' It's diftcult to come up with relationships among tables in the database. If relationships are
poorly developed it may lead to broken keys and records.

343
Relational Dahbase
. Simple kev Kevs
A simple key contins
a single attribute,
for example, customer_id.
. Composite kev

#I;ff]"'n';:ffi:'"ffi:.T-!ne artribute rhar can


r
student-ili'el'a,';rr],.;: to identi$ a record, for.
composite key although
t^1._ .":d exampls
th... u." "tom, ch.rr-..r;Lilffi;iame + Date-of-Birth can u. ur.a .
. Superkey
A super key is an aftribute
'up.it.vair",lffifffi:,:i.'ri:H:,",',':jll'"lily:1f^'i:ntines a tupre within a reration. A
not strictly required
*re""""r, ;i.".i Jr;);fi.:uire the non-redr"a."./p-p".ty and is
to ensure

. Candidate kev
A candidate key is an'attribrrt.
lrnr <^+ ^r^__.r ,.
;fl;;i..l"{il;;:i:iiilliiilr'i.t!"i.f', euarines ror uniqueness
lhat oreach row,tupre A
rryi*qyq:;ril:;h:L:,,'"1ilff
:*T:lll#;:;;lHix::kff;,ff
illi.Io",
**:#*#$,'"g;,ilg#;;il.';rjpt'-s?.:ffi i:il::,:*,il:;"..',,
.
primary kev
It is a candidatek.y
thut i,
contain a p.rimafie]. rrom a reration. Every
rsphvsicarv impremented. ff*#tli,f'"ffi',:ff.,;:;::^..o...1 reration must
"*: For exampre,
" il;'#; I::,'.'.f.*i::1":T *:;ru:,;gr,;.p"";
o ,^..-..
j.l:r+ k:y/Referencing key

;":,:il',:i?,.;l?;::t,;lf.ff i:TT.,:.Tf.:ffJ:*r:*,:*elheprimarvkevnerdfrom
*,;:*I1nTr.**ffi fi Ifl :*,."rerer",""rft H"iiiliil1:i#:*i'i::nr,*;
. Alternate kev
A candidate column
in a rel th"t haspotential to be
a prtmary key in
that ..luu"lttT- r

reration, ir,*'si"a.,,_t#J,l;l:'"Til:i:;:lfl:T;3:;.Tfl#I::ooll,ll:il,|f;'d:,:;1"ff;
.Secondary kev
A field used to identify
mor" than one record
at a time, for example,
a surname,
S.".-l",ic key/Natural
- ^:_ key
n^ semantic key is a key for wh
.or exampre, a semantic o:*ible values have ar
o..u,,.n."d.,.,iffi:ffi,ffi'{,i.';ili,i::i?$tit*,:f,,#$;.#il',1:T":H:ffi,'T:il:
"r,;lll-llt
344
.
Technical key/Surrogate key/Artificial key
A technical key is a key for which the possible values have no obvious meaning to the user or the
data.
These are used instead of semantic keys when none ofthe existing attributes c-an be used
to guarantee
uniqueness. In this case adding an attribute whose value is generated by the system may be the only
way to provide a unique value, for example, an oRDER_ID or INVOICE_ID value,12345'has no
meaning to the user as it conveys nothing about the entity to which it relates.

A relation is subject to the following rules:


l. Relation (fiIe, table) is a rwo-dimensional table.
2. Attribute (i.e. field or data item) is a column in the table.
3. Each column in the table has a unique name within that table.
4. Each column is homogeneous. Thus the entries in any column are all of the same tFpe (e.g. age,
name, employee_number, etc.).
5. Each column has a domain, the set ofpossible values that can appear in that column.
5. A Tuple (i.e. record) is a row in the table.
7. The order of the rows and columns is not important.
8. Values ofa row all relate to something or portion ofa thing.
9. Repeating groups (collections oflogically related attributes that occur multiple times within one
record occurrence) are not allowed.
10. Duplicate rows are not allowed (candidate keys are designed to prevent this).

Relational Database Management System (RDBMS)


' A relational database management system (RDBMS) is software that allows users to create,
update, administer and interact wiih a relational database.
' A RDBMS is based on the relational model invented by Edgar F. Codd - the father of modern
relational database design at IBM's San Jose Research Laboratory in 1970.
. Most commercial RDBMSes use structured euery Language (sel) to access the database.
Features of a Relational Database Management System (RDBMS)
The features of a RDBMS can also be viewed as the advantages of a RDBMS. The following are the
features of using a RDBMS:

. Minimise Data Redundancy


Duplication of data means same data being stored more than once in diferent tables. Duplication
of data leads to wastage of storage space, data inconsistency and loss of data integrity. In Database
Management System, all the files are integrated in a single database. The whole data is stored only
once at a single place so there is no chance of duplicate data. For example, a student record in library
or examination can contain duplicate values, but when they are converted into a single database, all
the duplicate values are removed. However, in some case redundancy, but it is controlled and kept to
a minimum. DBMS controls data redundancy that saves lots of labour and time.

. Allows Data Sharing


In DBMS, data can be shared in between authorised user of database. All the users have their own
right to access the database up to a certain level. The Database Administrator has complete access of
the database. S/he can assign users to access the database.

345 /
. Data Consistencv

ff 3:#t :ff"".:l;*fl'-" which in turn controtscomparison


data consistency. rn DBMS,
data is stored
"pa",.a"".ru., *;";'i"* i"T,',ff:ffJilffi':T,ln
. nr. p.".*r',,g1y,,"'. e,rro

Ensures Data Integrity


Data integrity refers to
the
uL/",.,, il..,it:,.',"T,1';',,.::1,:t",lti:1ilj"tabases. In DBMs data is stored in dirrerent
t"ur.'.
between data items. rrr. to maintain data items and
osMi ;:.,."".|"-:,^:_rlllortanr associatioo
rr,.,"uy,.-m',in';;#;.lfi, ";",;;""
because most of the r::ijfi,:#,,,::1,":":ru:,".mT,J.1ff#iTfir"*fl
informati- r. .tor.J'orrftorrl.
from wrong/inappropriate processing ti',.*rrr, is also enhanced u, juiu
therebf r'eJ;;; ;;r.., rrusting the.correctness i, protected
of data.
Ensures Data Independence

;1ffi*!:*T::fff:lT:lTi.",T:ig::H,'jlf::onprogramsandthesvstemdata
jilffi Achange
*anot.i,iJ .";;ilr:fr:"".j"*:#i:";,:,,fl l;li l::;,.::*ig#.?,y,:
;HT::Tll j:;:Tf :*:Hi#j:ili,.i'"*;l:l{..i,*u,..-;:;;;;i-.uuo,,p.o,,u_
.'vst'rcuuus nave ro be made in the
has to be rewritten. data, then the ap-plicat,on
progr.m

. Improves Securitv
from unauthorised access.-only
*if;Wrliil:.:fl:.$glata authorised users must have
preventingu,.,,r,om,l*i'.ti-it:T:ff
;:,":,'tS:{:.ni**.;":."1}:i:Xl*,:
arternative J."'.;.;,";"Hes
;:f?:trTJ":r_,:H,:j#.: and passwords can be u,Jd ,o p,o,..,
*, u. "..Ji",;"#::.ffi';rf:T."tyr during updatingd";;;;;.;yi il",i"ra","u",.
Backup and Recovery
In a traditional fiJe processing
system, a user needs to back
time that wastes rots of time up the database after a regular
aid'rer"";..;. il;;;;;."Ji., tr,i. p-ur.-
interval of
of taking ba-Jup again and
;:::.*1i#:1ilL"J1ftt"*"r ';ii;';J.,1i1,.,n .",. orhardware aird software rairure.
,' *r,'.r, i*"t*;;:il#.Li1;:';*Xl3l'.",;.'.:;[",r'. osili:;;i#lills orthe state

Enforces Integrity Constraints


Jlnce many users feed data
into^the database, constraints are needed to ensure
that accwate data is
:ffi1i::ii#:::'"","T,?;'.*::T*1',.ffit;;:ffistodenneanienii..J.ii",,"o,,,,.*,,
. vr s..o,'prs, me rnaxrmum
never be more ihanloo. marks obtained by the students
can

Search Capability
lnere are nturerous queries ur mar ask about the data' Search
produce di;J;;;;'sers
^- -
speed of the database must
be fast to
ir'. a","tirl.

346
r''-
.
Concurrency Control
If two users are accessing data simultaneously and they both want to update values
ofthe same record,
then it may create concurrency. The DBMS has the power to control ;ncurrency
so that users trying
to update the same data do so in a controlled mannei and no transactions are lost
and the result of the
update is correct.

' StandardsEnforcement
As DBMS have central control of database so a Database Administrator (DBA)
can ensure that all the
applications follow some standards such as format ofdata. These standards heip
in data migrations or
in interchanging the data.

. Simplicity
Simplicity means to rePresent the overall logical view of data in a simple and clear manner.
The DBMS
is very simple for its users who use it. All the operations like insert, ielete,
create and update are very
simple to implement.

. Data Atomicity
An atomic.unit is any complete transaction in database. If any transaction is partially
completed, then
it rolls backs them. It is the duty of the DBMS to store a complete transactioi in database.

.
Data Migration
Data migration means storing data according to its popularity. In a database, some
data is accessed
frequently and at the same time some data ii accessed occasionally. So the DBMS store
frequently
accessed data in a manner that it can be accessed quickly.

.
Powerfrrl User Language
A DBMS permits end users to use database without having special training or expertise.
Any untrained
user can easily query search and uPdate data in the database. The user ian easily generate
report or
documents with less knowledge.

.
Provides Multiple Views of Data
A view may be a subset ofthe database. Various users may have different views ofthe database
itself,
for example, the bank teller has his view ofthe database diferent from that ofthe bank
manager who
can view the whole database. Users may not need to be aware ofhow and where
the data they refer to
is stored.

Disadvantages of Database Management System


* Cost
.' The organization also has to pay concurrent annual maintenance cost. staff.
DBMS requires high initial investment for hardware, software and trained

* Complexity
' A DBMS fi.rlfill lots of requirement and it solves many problems related to database. But all
these functionality has made DBMS extremely complex ioftware.
' DeveloPer, designer, DBA and end user of database must have complete skills if they want to
user it properly to avoid loss of data or database failure.

347
* TechnicalstaftRequirement
A team of technical staf such as the database developer, database designer
and database
administrator is required who understand DBMS and thJ organization
has i'o p"y larg" s"r"rie,
to them too.

' Database Failure


As.we know that in DBMS, all the files are stored in single database so
chances of database
failure become more. Any accidental failure of componJnt
r nls ls really a brg headache for big firms.
-"y cause loss of valuabre data.
Recovering from a huge database failure is costly.

* Extra Cost of Hardware


A DBMS requires disk storage for the data and sometimes you need to purchase extra space
to store your data.
There is also need to have a dedicated machine for better performance of database.
These
machines and storage space increase extra costs of hardware.

* Size
' As DBMS becomes big software due to its functionalities so it requires lots of space and
memory to run its application eficiently.
. As more data is fed in it so the size ofthe database increases.

{ Cost of data conversion


. Dul? conversion may require a lot of time and is costly to the organisation. Kit can
be more
:ostly t9 the than the costs of DBMS hardware and riachine combined.
. Trained staff-organisation
is needed to convert data
-to new system. It is a key reason ihJ-most of the
organisations are still working on their old DBMS due to high cost bf data conversion.
* Performance
' It"t lq4 nles system was verygood for small organisations as theygive splendid performance.
But DBMS gives poor performance for small scale 6rms as its speed is sl'ow

Table l: Relational Database versus Flat Files


Relational databases Flat files
Less duplication ofdata as data does not need to Too much duplication of data since every table
in every table repeats data
Ofer greater data integrity as there is little No data integrity is guaranteed due to too much
chance of geuilg duplicate of data duplication ofdata
Data is available to all users ofthe system as there Data not available everywhere
as there is no
are no problems of software incompatibility. sharing offiles
Thus users share files
Creates different user views within the DBMS No diferent user views are created
Easy to access data from different table due to Diftcult to access data from
different files as the
relationships between the tables files are not linked
Retrieval ofrecords from diferent files is faster Retrieval ofrecords from different files
is slower
Better security ofrecords is enhanced Less security of data from unauthorised access
Promote program data independence There is program data dependence

348
_T

There is centralised management of data which No central data


management, difficult to manage
is more efficient and less securitv

Activity I
l ' In piitsfinit out the benefits and problems of computet batsed database systems as compared to
manual fiIing systems.

A Database Environment
' The database environment is a collection of components that control the collection,
manage-
ment and use ofdata.
. A database environment is made up of the following components:
L hardware
II. software
III. data
IV. procedures
V people
ZDrr)
Hardware Software Procedures People
Bridge
Machine Human
Fig 8.6 Database Enyironment Components
* Hardware
' Hardware can range from a personal computer to a network of computers where the database
is run.

* Software
The software includes DBMS software, operating system, network software (if necessary)
and
also the application programs.

r Data
Includes data used by the organisation and a description of this data called the schema.
The data in the database is persistent, integrated, stiuctured, and shared.

* Procedures
Rules and instructions that should be applied to the design and use ofthe database and DBMS.
The procedure may contain information on how to log on to the DBMS, how to recover
the
database etc.

* People
These include the database designer, database developer, database administrator, application
programmer and end users who operate the database.

349
Roles of a Database Administrator (DBA)
.
Setting up and creating.the database
together with the programmers.
.
Maintains the data dictionar y.
y::::::*3erfor1a31e oithe database to see if any problem wilt surface.
.'[::#::',f
'fi::i""j:::t;:'ll*d:j{;;;.i#;J;,T'##i;,rorexamp,e,ir
.. *:,,:::::"r:'_T1l
Train users :{ 1 o-i':i"'
naa'J""g.i;; #'u*"i ;ji.:::'jJl
on how to use the database.
Implement error identification and correction
routines.
. Ensuring that the database meets the
needs oith. o.g*irutiorr.
. Control, manage and maintain the database.
. Define, implement and control database
storase.
. Ensure that policies and procedures
are estabh'Jed.
. Guarantee effective production, control
and or. ofa"r".
. Define the strategy of backup storage
and recove;;;;_ system breakdown.
. Supervise amendments to the dataiase.
. Ensures that the data is secure from
unauthorised access.
. Controls the database environment.
. Standardise the use ofdatabase and
associated software.
. Support the development and maintenance
ofa"tub"r. upptication proiects.
' Ensure all documentation rerated
to standard, *Ji-pt.*.ntation is up-to-date.
' Liaison with the management on what
suitabr" h".i*"r. und .oftware to purchase
in order
to implement the database.

Database Software Components

* Data Dictionary
' The database dictionary contains
names and descriptions ofevery data
element in the database.
' Descriptions are on how a". .i.-."ir
*" ;d;il.each other. The Data Dictionary (DD)
stores data in a consistent memory,
reducing data redundancy.
* Data Languages
' A special language used to describe the
characteristics ofa data element placed
into the Data
Dictionary. This language is called the
Data D.C.riU* f,"r,g*ge (DDL).
* Security Software
' Provides toors used to protect the database
from unauthorised access.
* Recovery and Archiving System
. These allow data to be copied onto
backups in case ofdisaster.
* Report Writers
' These are programs used to design
output reports without writing an algorithm
in any
programming language.

* TeleprocessingMonitors
' software that manages communication
between the database and remote terminars.
350
Database Views and Schemas
* Viewe
' A view refers to how a user sees data stored in a database. Each user has his/her
own view of
data, for example, a standard database user can be restricted from seeing (viewing)
sensitive
data that only managers can view.
. Thus, these two have different views ofthe database.
' Contents ofa view are defined as a query on one or more base relations
and the view does not
necessarily actually exist in the database but is produced upon request,
at time ofrequest.

Advantages of Views
' Views are dynamic' meaning that changes made to base relations that affect view attributes are
immediately reflected in the view.
' Provides powerful and flexible security mechanism by hiding parts of database from certain
users.
' Permits users to access data in a customised way, so that same data can be seen
by different
users in dilferent ways, at same time.
. Can simplify complex operations on base relations.
. A user's view is immune to changes made in other views.
. Users should not need to know physical database storage details.

* Schemas
It.refers to the- overall design of the database. It can be a collection of named
objects such as
tables, views, functions, packages, and other packages.
Schemas provide a logical classification ofobjects G the database.
A Sub-schema describe different views ofdatabase.
It consists of three levels namely external level, conceptual level and internal level.

351
User n
External
level I vi.*n I

Conceptual
level

lnterna
level

Physical data
organization
Database

* External Level (View)


External view refers to diferent views of the data seen by each user ofthe database.
Each user ofa database has his/her own views ofthe database, for example, a general
database
user sees and describe the database differently as done by the managers beiause they have
different views ofthe same database.
Thus other users cannot view some data that the managers can view
Describes that part of database that is relevant to a particular user.

* ConceptuaVlogical Level (View)


The conceptual view is an abstract representation ofthe whole database.
The logical level describes what data are stored in the database and what relationships exist
among those data.
It describes what data is stored in database and relationships among the data.
Involves identi6cation of entity types and unique identifiers.
Database administrator uses the logical level ofabstraction.

* InternaVPhysical Level (View)


The intetnal level is the physical representation ofthe database on the computer.
It describes how the data is stored in the database on the physical media and the structure used
for storage ofdata.

352
Data Independence
o Data independence is the immunity of application programs
to changes in storage structures
and.access- techniques. For exampre, in iiaditionui
firJ processing
attribute, change index structure then, the applications are
,i""^, r *l add a new
affected.
' Thus, data independenge.renderl application programs
immune to changes in the rogical and
physical organisation ofdata in the system.
' It means that programs are isolated from changes in the way the
data are structured and stored.

I' 'Logical organisation refers to


changes in the schema such as adding a column or
tuples does
not stop queries from working.
II. Physical organisation refers to changes in indices or file organisations.

f ogical data independence

Conceptual/internal
mapping ' - Physical data indepenclence

Fig 8.9 Data Independence

* Physical data independence


' Physical data indePendence is the ability to modifi physical
schema without causing the
concepfual schema or application programs to be lewritten.
. It_ is the immunity of conceptual schema
to changes in the internal schema.
' The applications need not worry about how the Jata are physically
structured and stored.
' Internal schema changes (for- example, using different fiI. org"nl*"tio.r,
storage-structures o.
devices) should not require change to conceltual or external
schemas.
* Logical data independence
' Logical data independence is the ability to modify the conceptual schema
without having to
change the external schemas or application progr{rms.
. It is the immunity of external schemas to changis in conceptual schema.
' Conceptual schema changes (for example, addition or removal of
entities) should not require
changes to external schema or rewrites of application programs.

Database Languages
' Since a database supports a number ofuser groups, the DBMS
must have languages that
support each user group.

353
* Structured Query Language (SQL)
There is a differ'ence between SQL and MySQL.
SQL is a programming language that is used to communicate and manipulate a database.
MySQL is a popular relational database management system (RDBMS) developed by Oracle
that has SQL built in it.
SQL commands consist of Englishlike statements which are used to query, insert, update, and
delete data in a database.
Since SQL commands resemble English language sentences in their construction and use they
are therefore easy to learn and understand.
SQL is referred to as non-procedural database language, which means that, when we want to
retrieve data from the database it is enough to tell SQL what data to be retrieved, rather than
how to retrieve it.
SQL uses a set of commands to manipulate data in database.
SQL commands are dMded into four subgroups namely Data Definition Language (DDL),
Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control
Language (TCL).

SQL
corirrnandg

I
I I
DDL OML lCL
(:REAIF SELE(:] (I()i.rt tIr

^\LT€R lltSERT ROL;,-BAcK


Dli()F .]POATE
TRUNCATE OELETE SET TRANSA(]TIC)N
(j( rt tr,r E rt f \tE lt(i E
RENAI,IE (:ALI
€ XPL AIN PLAN
LOC( TAgLE

Fig 8.lO Structured Query Language Subgroups and Commands

a. Data Definition Language (DDL)


DDL deals with database schemas and descriptions, of how the data should reside in the
database.
It is used by the DBA and database designers to define the conceptual and internal schemas.
The DBMS has a DDL compiler to process DDL statements in order to identify the schema
constructs, and to store the description in the catalogue.
DDL specifies the data in the database, defines the structure ofthe tables, data types, constraints
and validation rules on the data.
For example, using Structured Query Language (SQL), it would be statements such as CREAT$
ALTER, COMMENT, TRUNCATE, RENAME etc.

3s4
-\^ - --\

b. Data Manipulation Language (DML)


. once the schemas are compiled, and the database is populated with data, users
need to
manipulate the database.
' DML deals with manipulation of data in the database such as retrieval, insertion,
updating,
deletion and modification of data in the database.
' For example, using stluctured euery Language (sel), it would be statements
such as the
following:

' SELECT - retrieve data from a database


/NSERT - insert data into a table
UPDATE - update existing data within a table
DELETE - delete records from a database table
LOCK TABLE - concurrency control

c. Data Control Language (DCL)


' D-ata control Language (DCL) is mostly concerned with rights, permission and other controls
of the database system.
' For example, using structured euery Language (sel), it would be statements such asthe
following:
. GMNT :- allow users access privileges to the database
. REVOKE :- withdraw user's access privileges given by the GRANT command.

Transaction Control Language (TCL)


' Tiansaction control Language (TCL) deals with transactions within a database.
' For example, using stluctured euery Language (sel), it would be statements such asthe
following:
COMMIT - commits a transaction
ROLLBACK _ rollback a transaction in case of any error occurring
SAVEPOINT _ to rollback the
transaction making points within groups
SEf TRANSACflON - specifr characteristics for the traniaction

DBMS Interfaces
Tlpes of interfaces provided by the DBMS include:

a. Menu-Based Interfaces for Web Clients or Browsing


. Present users with list of options (menus)
. Lead user through formulation ofrequest
. Query is composed of selection options from menu displayed by system.

b. Forms-Basedlnterfaces
. Displays a form to each user.
. User can fill out form to insert new data or fill out only certain entries.
' Designed and programmed for naiVe users as interfaces to canned transactions.
c. (Graphical User Interfaces
. Displays a sc\ema to the user in diagram form.
355
. The user can speciry a query by manipulating the diagram.
. GUIs use both forms and menus.

d. Natural Language Interfaces


. Accept requests in written English or other languages and attempt to understand them.
. Interface has its own schema, and a dictionary of important words.
. Uses the schema and dictionary to interpret a natural language request.

Database Security
Database security refers to methods ofkeeping data in a database safe from various hazards and
from unauthorised access.

Threats to Database Security


. Natural hazards such as fire, cyclones and floods.
. Deliberate destruction/corruption by former employees or by terrorists.
. Illegal access to data by hackers, who may steel, amend or destroy the data.
. Accidental loss ofdata due to hardware failure and software failure.
Database Security Measures
A number ofdatabase security measures must be able to secure data from fraudulent or malicious
damage. The database security measures include the following:
. User IDs and passwords
. Encryption ofdata
. Access rights and u.ser permissions
. Use of database views
. Biometric measures
. Periodic backups
. Use of antivirus programs
. Audit trails
. System restore and rollback facilities
. Record locking

Activity 2
l. In pairs, research and trite down the functions of the follo$ing ilatabase personnel:
a) Database designer
h) Database developet
c) Application programmer
d) End user
2. Write notes on the two main types of Data Manipulation Langrages (DMLs) namely:
* high-levelhonprocedural
* Ior+-le,vellprocedutal.

Structured Query Language (SQL) Commands


. SQL commands are instructions, coded into SQL statements, which are used to communi-
cate with the database to perforrn specific tasks and queries with data.
. SQL commands can also be used to perform various other functions like, creating a database,
creating tables, adding data to tables, or modifring data and set permissions for users.

356
/
Basic SQL Commands
*
Create a database
.A relational database is made up ofa collection of related tables. So the first thing is to create a
database which will then contains one or more tables (relations).
.To create an SQL database, the create database statement is used.
.The syntax is given below:
CREATE DATABASE databasename;

Example:
CREATE DATABASE Entertainment; I
. To check whether the database is created you can write the SQL command:
SHOWDATABASES;

* Delete a database
. The drop database statement is used to delete an existing SQL database.
. Deleting a database will result in loss of complete information stored in the database.

. The syntax is given below:


DROP DATABASE databasename;

Example:
DROP DATABASE Entertainment;

* Create a database table


The create table statement is used to create a new table.
The create table statement is followed by the table name, followed by an oPen Parenthesis'
followed by the first column name, followed by the data type for that column, followed by
any optional constraints, and followed by a closing parenthesis.
Use an open parenthesis before the beginning table, and a closing parenthesis after the end of
the last column definition.
Each column definition is separated by a comma.
All SQL statements should end with a ";".

The syntax of the create table statement is given below:


CREATE TABLE'tablename"
('columnl"data type',
'column2"deta tiTe',
'column3"data type');
,
Data types specify what the type of data can be for that particular column. If a column I
i

called "Last-Name" is to be used to hold names, then that particular column should have a
"varchar" (variable-length character) data rype. a.' )

357
a SQL Constraints
corstraints refer tocertain properties that data in a database must comply with and
are used
to limit the type of data that can go into a table.
' Thus, a constraint is a rule associated with a column that the data entered
into that column
must follow.
' Constraints enforce limits to the data or tlpe of data that can be inserted/updated/deleted
from a table.
The whole purpose ofconstraints is to maintain data integrity when such operations
as updat-
ing/deletion/insertion are being performed on data in a table.
This ensures the accuracy and reliability of the data in the table.
Ifthere is any violation between the constraint and the data action, the action is aborted.
constraints can be column level or table level. column level constraints apply to a column,
and table level constraints apply to the whole table.
Constraints are used to limit the type ofdata that can go into a table.
The following table shows constraints commonly used in SeL:

Constraint DescriDtion
NOTNULL Ensures that a column cannot have a NULL value, for example, p.ir""ry
key must not be left blank "
UNIQUE Ensures that all values in a column are different, for .x"-ple, p.i-".y k y
field must have unique values. "
PRIMARY KEY Uniquely identifies each row in a table. The primary key must satisfr the
NOT NULL and UNIQUE constraint.
FOREIGN KEY Uniquely identifies a rodrecord in anothe! table
DEFAULT Sets a default value
for a column when no value is specified
INDEX Used to create and retrieve data from the databale very quickly
. lhe syntax ot the table if you were to use optional constraints is grven
CREATE TABTE'rablename'
("columnl " "dara rype'
Iconstraint],
"column2" "data rype"
Iconstraint],
"column3'"data type"
Iconstraint]);

Note: You may have as many columns as you'd like, and the constraints are optional.

Example:
CREATE TAILE Employee
(lD int NOT NULL UNTQUE
First_name varcha(l 5) NOT NUtL
t
Last_name varchad20) t{OT NUtL
Age number(3)NOT NULI
City varchar(20) DEFAU[T'MUTARI',
PRIMARY KEY (ID));

358
In the example above' First-name, Last-name, Age and City will be the name of the fields or columns
of the Employeet table. Different constraints have been set for different columns of the Employee
table, for example, the NOT NULL, UNIQUE and PRIMARY KEy constraints have been
set on the
'ID'column.

Rules for naming tables and columns in SeL


'
The table and column names must start with a letter and can be followed by letters, numbers,
or underscores
' Table and column names must not to exceed a total of30 characters in length.
. Do not use any SQL reserved keywords such as "select'] 'treate", "insert; etc. as names for
tables or column names.
Common Data Tlpes in MySQL

Data Type DescriFtion


char(size) Fixed-length character string. Size is specified in parenthesis. Max 255 bles
number(size,d) Number value with a maximum number of digits of "size" total, with a maximum
number of "d" digits to the right of the decimal.
varchar(size) Variable-length character string. Max size is specified in parenthesis..
number(size) Number value with a max nlmber of columq digits specified in parenthesis.
Date Date value

Create a database table using another table


. A copy ofan existing table can also be created using create table.
' The new table gets the same column definitions. All colurnns or specific columns can be
selected for the new table.
. The new table created will be filled with the existing values from the old table.
. The syntax is as follows:
CREATE TABLE new_table_name AS
SELECT colum nl, c olumn2,...
F ROM e x i s t in g_t able _n am e

Example:
CREATE TABLE Customer AS
SELECT First_N4 me, Last_Name, Age, City
FROMEmpbyee;

. In the abov,e example, SQL creates a new table called "customer" (which is a copy of the
"Employed' table).

* Insert data in a database table


The create table statement iust creates an empty table with 6eld names only. The table must be
filled with data.
The insert into command is used to insert records into the table.
To insert records into a table, enter the kii words insert into followed by the table name,
3s9
fgflowed by an open parenthesis, followed by a list of column names separated by commas,
followed by a closing parenthesis, followed by the keyword values, followed by the hst ofvalues
enclosed in parenthesis.
The values that you enter will be held in the rows and they will match up with the column
names that you speciS.
Strings should be enclosed in single quotes, and numbers should not.
The syntax is as follows:
INSERT INTO,.TABLENAME"

(FtRsT_ctrLUMN,..,LAST coLUMN)

VATUES ( FtR sr_vaLu E, . . . LAsr_vALU E );

Example:
INSERT INTO EMPLEYEE
(FIRST-NAME, LAST-NAME, AGE, GITY)
VATUES (.AsHELy', .MaNvERUKE', I 6, .MurARE');
' In the example above, Ashely' will be inserted into the First-Name column, followed by
'Manyerukd into the Last-Name column, followed by 16 into the Age column and 'Mutare'
into the City column.
. It is imPortant to note that if you are adding values for all the columns of the table, there is
no need to specifr the column names in the sQL query. However, make sure the order of the
values is in the same order as the columns in the table.
. The syntax is as follows:
INSERT INTO TaBLE-NAME
VALUES (vaLUEt, vaLUEz, vaLUEg, ,..);

Example:
INSERT INTO EMPLoYEE
VALIJES (.wayNE', .MaNvERUKE', I B, .HaRARE,);
. The values will be added in the table columns in the order they are given.

Activity j
1. Write SQL commands to
a) Create a table called *Employee" to enter details of employees in an organisation. The table must
contain the folloting information about your employees: employee_no, firstname,lastname, title,
age, d4rafiment and salary. Salary must have 2 decimal places.
b) Enter the following recotd in the "Employed' table
8001, Ryan,Magaya, Dr, 45, Accounk,4500,00

Hint: set employee-no as the Primary key. All the fields must contain data. Set appropriate data
types and sizes for your fields

* Delete table in a database


. The drop table command is used to delete a table and all rows in the table including the con-

360
, straint information.
. The syntax is as follows:

DROP TABLE tablename

Example:
DROP TABLE Employee
. To delete thi data inside a table and leave the table as it is use the truncate table statement'
. The syntax is as follows:
TRT NCATE TABLE tablename

Example:
TRIJNCATE TABLE EmPloYee
* Deleting data in a database table
. The delete statement is used to delete records or rows from the table'

The syntax is as follows:


DELETE FROM table-name WHER-E condition;

The WHERE.clause contains the condition which specifes which record(s) should be deleted.
If you leave the WHERE clause all records in the table will be deleted'
The whe.e clause is also used in update or select statements when modiffing or searching
data in tables.

Example:
DELETE FROM EmPloYee
WHERE CitY = 'Mutard;
. In the above example, all records that contains 'Mutare' in the city column will be deleted.

Example:
DELETEFROM EmPloYee
WHERE City = 'Mutare Or First-Name = 'Munashe';
. 'Munashe' in
In the above example, all records that contains 'Mutare in the City column or
the First-Name field will be deleted.

Example:
DELETE FROM EmPloYee
WHER.E First-Name = 'Cecilia' and Age = 30;
. In the above example, all records that contains 'Cecilia' in the First-Name column and 30 in
Age column will be deleted.

Example:
DELETE FROM EmPloYee;

. In the above example, all records in the Employee table will be deleted' '

361
* euery data in a database table
' In most cases users ofa database perform
search operations to find specific
data from a
based on specific conditions- Foi
example;;-;;;ug., ,,,,"y want to display records database
employees who earn $750.00 and ofall those
below.
. The data returned is stored in a result
table called the result_set.
' The select statement is used to query
the d;;;" and retrieve serected data that match
criteria that is specified. the
. The syntax of the select statement
is given below:

SELECT columnl, column2, column3,


...
FROM.tablename"
IWHERE.tondition'Ji
U = optiond

. that follow the select keyword determine


which columns wilt be returned
ffi:"itri:r:ames
. The "*" can be sued to select all columns
form the table.
' The table that will be queried to..tri"u.
tt. i.slred resutts is written after the keyword from.
' t
The criteria/condition after th. ytt-a
ttrt... iJiptiorrut urra it specifies which data values
rows will be returned or displayed'. or
' The like operator is also'rsei inthe conditional selection
ofthe where clause to select rows that
are "like" what you specifr.

Example:
SELECT First_Name, Lasr_Name,
Ciry
FROM Students
WHERE City = 'Masvingo;

' The query will display first name,


last name and city
- ---' from students table for all records which
match Masvingo as the City.
Exarnple:
SELECT *
FROM Students
WHERE First_Name = ..fohn,;
. The query will display all columns for
everyone whose first name is
lohn.
Erample:
SELECT First_Name, City
FROM Students;
Displays first name and city for everyone
in the Students table.
a. SQL Wildcard Characters
wildcard characters are used with the SQL
rike operator to substitute any other
in a string. character(s)
I. 9o (percentage) is used to match any number of characters
that appear before or after the
362
characters that appears.
II. - (underscore) is used to represent a single character.

Example:
SELECT First-Name, Last-Name, City
FROM Students
WHERE First-Name Like A%';
. Will display first name, last name and city from Students table for all records with first names
that starts with ?t and ends with any character(s).

Example:
SELECT First-Name, Last-Name, City
FROM Students
WHER.E City Like'-a%';
Will display first name, last name and city from Students table for all records with city that
starts with any single character followed by'a and any character(s).

b) SQL Conditional Selections


The where clause also uses the following conditional selections:
(i) = Equal
(ii) > Greater than
(iii) < Less than
(iv)
(v)
(vi)

Example:
SELECT First_Name, Age, City
FROM Teachers
WHERE Age > 40;

. Will display first name, age and city from Teachers table for all records with age greater than
40.

Example:
SELECT First-Name, CitY
FROM Teachers
WHERE City <> 'Harard;

. Will display fust name and city from Teachers table for all records with city that does not
include 'Harare',

c) SQL Operators
The where clause can be combined with AND, OR, and NOT operators tofilter records based
on more than one condition.
The AND operator displays a record if all the conditions separated by AND is TRUE.

363
. The OR operator displays a record if any of the conditions separated by OR is TRUE.
. The NOT operator displays a record if the condition(s) is NOT TRUE.

Exarnple:
SELECT Name, Title, Hobby, City
FROM Patrons
WHERE Title ='Mr' AND Hobby ='g[6s5''

. Will display name, title, hobby and city from Patrons table for all records whose title matches
'Mr' and hobby matches 'Chess'. Only the records that satisff both conditions will be displayed.

Example:
SELECT Name, Title, Hobby, City
FROMPatrons
WIIEREName = 'Makanaka' ORCity = 'Gweru';

. Will display name, title, hobby and city from Patrons table for all records whose name matches
'Makanaka' or city matches 'Gweru'. Only the records that satisfr one or both of the conditions
will be displayed.

Example:
SELECT't
FROM Patrons
WHERENOT City = 'Harare';

. WiU display all records and columns that matches any city that excludes 'Harare'. Al1 records
with city that is not 'Harard will be displayed.

Activity 4
I. the following SQL queria will display:
Explain what
a) SELECT *
FROMI Patrons
WHERE Title ='Mrs' AND (Hobby ='Swimmiry! OR City ='Bulavalo';

b) SELECT Name, City, Counby


FROM Customers
WHERENameLIKE'%ta%t

c) SELECT Name, Surrame, Age

I
FROM Cttstomers
WHERENOT Name ='Trish'AND Age <= 25;
.l) SELECT Name, Surname, Age
FROM Customers
WHERE Surname LIKE'- a';
---- ,l
I

* Modify/Update data in database table I

,l

364
The update statement is used to update or change existing records in a table that match a spec-
ified criteria.
The syntax of the update statement is given below:
UPDATE tablename
SET columnl = valuel, column2 = value2,...
WHEREcondition

. The where clause specifies which record(s) that should be updated.


. The where clause is optional but ifit is omitted, all records in the table will be updated.

Example:
UPDATE Patrons
SET Title = 'Profi Hobby = 'Rugbyi Age = age + l, City = .11ur".0
WHERE Name = 'Ryan';

. The above sQL statement updates the title to 'prof', hobby to 'Rugby', age to age plus l and
city to 'Harard where the Patron's name is 'Ryanl
. If the age in the age column was 35 the age will be set to 36 (35 + l).

Example:
UPDATE Patrons
SET Hobby = 'Rugbyl City = 'Harard - i.

' In the above SQL statement all the records are going to be updated to 'Rugby' and 'Harard in
the hobby and city columns respectively since the where clause has been left.
. So be carefirl when you omit the where clause.
. The where clause also determines how many records will be updated.

Example:
UPDATE Patrons
SET Hobby = 'Netball'
WHERE City = 'Mutare';
. The following SQL statement will update the hobby to 'Netball' foi all records where city is
'Mutarel

Activity 5
A relation named contains the alttibutes:

Write SQL statements to update the following:


The supplier with Supplier_ID'SOO2' has changeil cityfrom,Harare' to,Bulatayo'.
?)
b) AII deiry products are now cqlled 'mille',
4 All beef products have their quantity changed to S0 and City changed to,Masvingo,.

36s
Relational Database Modeling
' The main objective of.relational data analysis
is to organise all of the data items used by the
system into a set of well normalised relations.
' This is done to eliminate unnecessary duplication (redundancy)
of data items in different
relations, and ensures.data accuracy andrntegrity (the
possibility of probrems arising when we
modifr, insert or delete data _ usua'lly referrj to a,
d"iab"se
"no_ai"r).
*. Database Entity Relationship Diagrams (ERDc)
' An entity relationshiP diagram is a diagrammatic way of
representing the relationships between
the entities in a database.
' An ERD defines entities, their attributes, and show the relationships
between the entities.
' ERDs are created during conceptuar database design
and during iogical a"tuuur. design; the
ERDs are converted into relational data models.

Uses of ERDs
.
To illustrate the logical structure ofa database.
.
To sketch out the design ofa database.

Entity Relationship Diagram Symbols

a. Entity
. An entity is an object or concept about which data
is to be held, for example, place, person,
event etc.
An entity is named using single_ nouns, for example, students,
courses, employers etc.
A specific example ofan entity is called an instance.
Each instance of an entity becomes a record or a row
in a table. For example, the customer
Praise Mungazi is a record in a table called customer.
An entity is represented by a rectangle.

i) Strong Entity
AJtrong entity is one whose existence does not depend
on the existence of any other entity in
a scnema-
It is denoted by a single rectangle.
A strong entity always has the primary key in the set ofattributes
indicating that each entity in
a strong entity set can be uniquely identified.
The relationship between two strong entities is denoted
by a single diamond.

u) Weak Entity
A weak entity is an entity that depends on the existence
of its owner entity, i.e. stronger entity.
For example, the order item entity depends on the existence
rht";;;;rtity.
A weak entity does not have a prjmaryley instead it "f
has a partial key that unilueiy aiscriminates
the weak entities.
The primary key of a weak entity. is a composite key
formed from the primary key of the strong
entity and partial key ofthe weak entity.
The relationship between a strong entity and a weak
entity is denoted by a doubre diamond.

366
/
Loan

stro.g.l.,tity I
Weak entity
. In the ER_diagram above, for
each loan, there should
loan would no1 u. mtJ tte at least one borrower otherwise
. The customer entity does
in Loan enuty set. that
not depend on a loan entitv
borrow any loan it rl'JJu. even if a customer does
. urt.d in customer enu*;.,ltt"utt
oth:r.lhing to note is that
not
lhepartial
the
a weakei;.ril;ji;: primary key. So the Loan_name,
key of the weak
t y "rr"* ffi-'' er1;o,;;
wcaK entit/ ;il;",;:",::::-:i" oi.ur-tori,;;:"",r;;;:Lr,-",,
and cust-ID prim*v k.y "
. To identifr who had borrowed a given loan can
be don t with the help
weak entity (Loan-n"m.l curtJo). of primary key of the

b. Attribute

i${fi l|:l:';Hff fl,:.}r.:ffi:1[::ffi ll',";.rds)oratabre(ent*v)


' *i.TH"' Nums." il"r., c',iil"'l*d
Registration
il;;"li'iliK*,,an enrity
. An attribute is represented
by an oval shape.

Composite Attribute

.'
composite attributes are specific
attributes for other attributes.
For example, the attributeihaar"*,,.-
attributes are called comfosite
l-"u.";:;illi tes number, street and
attributes. city. These

367
Multivalued Attribute
A multivalued attribute is an attribute that can have more than one value.
This is diferent from an attribute having its own attributes.
For example, a learner entity can have multiple subject values.

iii) Derived Attribute


A derived attribute is one that is based on another attribute. It is not common in ER dia-
grams.
For example, for a circle, the area can be derived from the radius.

358
/
Circle

Area I

Radius

c. Relationship
'"-t.iJ,t'""titp -:-.:^- L-+.rapn Fniities.
entities' It shows how two entities share
is a link or association between
"*"tabresin*l1l'^:T::-:i:"i:'"i:;11:["n,1ff;:n*
f ?:rTfiiilt'01ffi :fi iit L"g 'p'"nt; otle may have any number of
relationship where an ott*tl# "t -o'
o" tht'-uny'or thild'table' ' ' back the primarv kev on
the
^"*;#.:;;t"'
ro achieve this, the thild t"bli;;lt;;;
itiit *r'itrt [nk
kty, and the parent table is
,i. table are known u. " foi.ign
t'J#;il.;;;le"
narent table. These 6elds ", "friia oe viewpoint of th:.:hild)'
our' ir"-
'*i't
*itt'-""t:mfm:tl3;::'ffi:"f:
it is possible for a rccord """il:;;;;.;;!i"-t"
possible for an entrv on
;ifili;;;;iit should not be
as rererentiar
to be managed bv rures known
;:*i:t'*f:ffi:,'5jff::lll}|.1ips on
f,'-*iiq"':ledif the foreign kevdoes not exist
Hi.t;T;:ff',-:"i:JJl"itlt["o'*#iT"irl, *htitht ent-ry on'the parent table
is
the oarent table, or *i' d"of "i.fttfa"t"bl.,
example' teaches is the
are described by verbs' for
;trt"# f^ttii"!,"- "t"tio"ships
and learner'
,-.i"tiorrtttip U.t*ein teacher diamond shape'
ai.i",,"tritp tr action is represented by a

Learner
Teacher

i) *'"n.
.1":;'iff'l::iffi :flriswhenthe'"-':"'Yl*:'::::,T:i$#::i:;""::'f
i"'"tt"' i* supervise other teachers and
can
. This creates ttlf-linktd
" "ilffi't;;:t;;;;
also be suPervised' ,t
:1
I
369

i
Teacher

Supervisioi

Tlpes ofRelationships
. There are 3 types of relationships in relational
database design namely:

a.One-to-One
b. One-to-Many (or Many-to-One)
c. Many-to-Many
d. The Crow's Foot Relationship Symbols
are used to represent relationships.

a, One-to-One Relationship (l:l)


' A single entity instance in one entity class is related
to a single entity instance in another
entity class.
' In other words, a row in table A can have only
one matching row in table B, and vice versa_

Employeeld
FirstName
LastName P"yld
Payld HourlyRate

This is not a common relationship type, as the


data stored in table B courd just have easily
stored in table A. been
it can be used for security purposes or to divide
a large table into smaller manageable
f;;;;:r,
Exarnples:
Each learner 6lls one seat and one seat is assigned
to only one learner.

370
/
Learner Fills

Each teacher has one oftce space.

Teacher Office

b. One-to-Many (or Many-to-One) Relationship (l:M)


A single entity instance in one entity class (parent) is related to multiple entity instances in
another entity class (child).
In other words, a row in table A can have many matching rows in table B, but a row in table B
can have only one matching row in table A.
One-to-Many relationships can also be viewed as Many-to-One relationships, depending on
which way you look at it.

Crtyld
Customerild
CityName
FirstName
LastName
Cityld

. This is the most common relationship type.


. In the above example, each customer can only be assigned one city and one city can be assigned
to many customers.

Examples:
An inspector supervises many schools, but each school has only one insPector,

Inspector School

One professor can teach many courses, but one course can only be taught by one professor,

371

)
Course
Professor
Many-to-Many Relationship (M:M)
Each entity instance in one entity class is related to
multiple entity instances in another entity
class; and vice versa-
In other words, a row in table A can have many matching rows in
table B, and vice versa.
i: difficult to represent many-to-many relationslhips in a database, a many_ ,o_,o*y
9:1" i,
(M:M) relationship is decomposed into two one-to-many
ir:M) relationships.
To decompose a many-to-mrly relationship into iwo one_to_many relationships
an
intermediary table or ')unction table" or 'reference table" is used
to lirrt tt . t*o t"bt.,-,o-jon",.
The intermediary table must have two fields that reference the
primary key ofeach ofthJother
two tables.

.'! 5":!:::l r=; H*e.rriE


Customcrs Order: Products
I crsto"irid I
FirltN!mr lrt oroirrJ
Cuttomerld
aoorcro
PtodudN!mr
L.dN!m. Produrtld hiCr
DttcCr.!t!d OrtaCrcrtad DatrCrcd.d

Fig 8 11 A many-to-many relationship createil


from Customers toble and Products table usingMicrosofi Access

' In order to create a many-to-many relationship between the Customers


table and the products
table, a new table called Orders was created.
' The Orders table, contain Customerld and Productld from Customers
and products table
respectively.
' The values that these fields contain should correspond with
i value in the corresponding field
in the referenced table.
' So any given value in Orders.Customerld should also exist in
the Customer.Customerld field.
' If this wasnt the case then we could have orders for customers that dont actually exist. We
could also have orders for products that dont exist.
' Most databases_allow you to enforce referential integrity so that when a user
attempts
--' to insert
a foreign keyvalue that doesn t exist in the primary ley'fierd,
un .rro. *ill o..ur.
' In the example, the orders.Customerld fiild is a foreign key to the customers.customerld
(which is the primary key of that table) and the orders.-Productld
field is u for.ign key to the
Products.Productld field (which is the primary key of that table).

Examples:
A ticket holder may attend a number ofconcert performances, and each concert may be attended by
many ticket holders.

372
Ticket_holder Concert
attends

Many-to-Many relationships are not encouraged in E-R diagrams since they violate the 3NF
ofdatabases.
I
To remove M-N relationships, a link entity is used to link entities,
Another entity called ticket is created to decompose the many-to-many relationship

There is a one-to-many relationship between a ticket holder and a ticket (each ticket holder
may have several tickets, but each ticket will be held by onty one person)
There is also a one-to-many relationship between .orr...t ani a ticket (each concert may
" concert)
have several tickets, but each ticket will belong to one

In general, the relationship types are as follows:

One-to-One
One-to-Many

Many-to-Many

Creating Entity Relationship Diagrams


The following are tips for constructing an entity relation diagram:
I. Identify the entities
. The first steP is to identifr all of the entities that are to be used. This could be a patient, doc-
tor, ward, schedule etc.

II. Identify relationships


. Look at two entities and ifthey are related draw a solid line connecting them.

III. Describe the relationship


. Draw an action diamond between the two entities on the solid line you just added.
. Write a brief description of how they are related in the diamond.

IV. Add attributes


. Identify the key attributes ofthe entities and add them using oval-shaped symbols.

373
V. Complete the diagram
' connect all the entities with lines, and add
diamonds to describe each relationship until
all
relationships have been described.
' Some entities may not have any relationships
while others may have multiple relationships.

Hint: i)Removeredundanl
ii..provide r;ffi?T."Ifr :;:TlT*%l.iliil*o'i,l,,rute,
" and rerationship in
the diagram.
iii. Use singular nouns in naming entities.
iv. Never connect a relationship io another
relationship.

Benefits of Entity Relations Diagrams


' ER diagrams are easy to understand. Thus,
designers can use ER diagrams to easiry
commu_
nicate with developerq customers, and end
useis, regardless oftheir IT proficiency.
' otl"t'::jrT'are
readilv transratabre into rerationur tiu", wr,i.rrl;
;; ffi;;ickry build
' ER diagrams can directly be-used by database
developers as the blueprint for imprementing
data in specific software applications.
' ER diagrams maybe applied in other contexts
such as describing the different relationships
and operations within an organisation.

Example
ABC Bus comp.ny owns a number ofbuses.
Each bus is allocated to a particular route,
routes may have several busses. Each route passes although some
through a number of towns. one or more drivers
are allocated to each stage ofa route, which
corresponarlT ioo.rr.y through some or all
on a route' some ofthe towns have a garage ofthe towns
wh..i bur., are" kept and each ofthe buses are identified
by the registration number at a ."n cir.yiir...nt
,ro.t.r, ofpassengers, ,i"." ,lr" ,.ila.s vary in
size.and can be single or double-decked.
iach rout. ir ia."iin.a uy a route number and information
available on the average number of pur..r,g".. is
p..i"y ro, .u"r, D;]";;;r;'*
-"1"-
""r.i.dn'umber.
number, name, address, and sometimes aielephone
"-ploy".
a. Entities
. Bus
. Route
. Town
. Driver
. Stage
. Routes
. Garage

b. Relationships
. A bus is allocated to a route and a route may have
several buses.
. Bus-route (m:l) is serviced by
. A route comprises ofone or more stages.
. route-stage (l:m) comprises
. One or more drivers are allocated to each stage.
. driver-stage (m:l) is allocated

374
A stage passes through some or all of the towns on a route.
stage-town (m:n) passes-through
A route passes through some or all of the towns
route-town (m:n) passes-through
Some ofthe towns have a garage
garage-town (l: I ) is situated
A garage keeps buses and each bus has one 'home'garage
garage-bus (m: I ) is garaged

c. Attributes
. Bus (reg_no, make, size, deck, no_pass)
. Route (route_no, av_pass)
. Driver (emp-no,name, address,tel_no)
. Town (name)
. Stage (stage number)
. Garage (name, address)
Hint: Underlined attributes are key attributes/key fields
E-A-R Diagram

Activity 6
I. Create an entity relationship diagram for the following scenario:
a) A cinema shows many films and a film is shown at many cinemas.
b) Each student can take many classes, and each class can be taken by many students.
Converting ERDs to Relational Databases Schema in Standard Normal Form
The ER diagram rePresents the conceptual level of database design while the relational schema is the
logical level for the database design.
When converting ER diagram to relational schema it is important to take note of the following:
a. Speciff schema of relation itself.
b. For an entity-set E with attributes al, a2, ...,an create a relational schema with same name E,
and same aftributes al, a2, .. ,, an.

375
c. Specifi primary key on the relation.
d. Primary key of relational schema is same as primary key of entity_set.
e. Specifr any foreign key references to other relations.

Taking the following ER diagram as an example

Personld

Phone

. The relational schema is expressed in the following format:


Person(pg5ggif,, name, lastname, emaiL phone)
. The primary key is personid.

Dealing with Multi-Valued Attributes


A multi-valued attribute is usually represented with a double-line oval.

Take the multi-valued attribute and turn it into a new entity or table ofits own. Then make
a l:N relationship between the new entity and the existing one, that is, create a table for the
attribute and add the primary (id) column of the parent entity as a foreign key within the
new table as shown below:

376
/
Person(Igsen.id , name, lastname, email )
Phone( ghgnsid , personid, phone )

. Personid within the table Phone is a foreign key referring to the personid ofperson.

Dealing with Composite Attributes


.
Each component ofthe composite attribute becomes a separate attribute.

. Address is a comPosite attribute, therefore, each component of address becomes a separate


attribute.

customer(cus'l!1f name, strcet, city, state, zipcode)

Dealing with Relationships


*
One-to-One (l:l) Relationships
. For simplicity and better performances at data retrieval, it is recommended to use attributes
to represent such relationship.
. For example, let us consider the case where the Person has or optionally has one car.

377
one can place the primary key of the car within the table of the person which we call in this
case foreign key as shown below:
Person(Ielse4:is! , name, lastname, phone, email , canegno )
Car( carregno , name )

The other method is to put the personid as a foreign key within the car table as shown be-
low:
Person( pgfsegi(L, name, lastname, email )
Car( carregno , name , personid)
For situations when the Person does not have a car, that is, has no carregno, the attribute can
set to NULL

* One-to-Many (l:M) Relationships


we use attributes in the same way as l: I relationship but we have only one choice as opposed
to two choices.
For instance, the Person can have a Houee from zero to many, but a House can have only
one Person.

378
/
. To rePresent such relationship, the personid as the Parent table must be placed within the
Child table as a foreign key but not the other way around.

Person(pggon:(! , name, lastname, email, phone )


House( houseid , num , address, p ersonil)

r Many-to-Many(N:N)Relationships
For instance, the Person can live or work in many countries. Also, a country can have many people,

379
To express this relationship within a relational schema we use a separate table as shown be-
low:

Person(+gsen:id , name, lastname, email, phone


)
Country (:s_qdlgd, name, code)
HasRelat ( hasrelatid, personid, countryid)

job(ltlelevel)
employee(ernployee id. employee_name)
branch(bfaush_&aqe, branch_ciry assets)
works_on(einployee id. branch name. title)

Example

380
customer(cust id, name, street-address, city)
loan(loan id. amount)
borrower(eust id. loan id)

. Borrower could also use loan_id for primary key.


. The other way is to combine borrower schema into customer or loan schema. Combining
borrower into customer would require null values for customers without loans.
. Itt better to combine borrower into loan schema as no NuIl values will be created.

customer(custjd, name, street-address, city)


loan(loan id, custjd, amount)

Activity 7
Map the following EAR diagram into a relational schema:

38r
adress

Anomalies in DBMS
' Database anomalies are faults or weaknesses in a database as a result ofpoor planning and
storing everything in a flat database.
. Database anomalies are usually removed by normalisation.
' There are three types of anomalies that occur when tie database is
not normalised. These are
insertion anomaly, update anomaly and deletion anomaly.
. Let's take an example to understand this.
Example
' suppose a manufacturing co-mpany stores the employee details in a table named
employee that
has four attributes: emp-id for storing employee's id, emp_name for storing
employeet name,
emp-address for storing employeet address and emp_dept for storing the
iepaiment details
in Which the employee
emnlovee wnrkc Af some
works. At cntnp h^i61 of +i-- the
^f time l^Lr^ looks
+t - table
like rL:-
r^^r-^ r:r-- this:
emp_id emp_n.rme emp_ad&ess emp_dept
101 Bolgani Mutare D001
101 Bongani Mutare D002
-
123 Abdul Bulawayo D890
166 Glenn Harare D900
166 Glenn Harare D004

382
' The above table is not normarised. we
wilr see the problems that we face when a tabre
is not
normalised.

a. Update Anomaly
In the above table we have two rows for employee
Bongani as he belongs to two departments
ofthe company.
If we have to update the address of Bongani, then
we have to update the same in two rows or
the data will become inconsistent.
If somehow, the correct address gcts updated in one
department but not in other then Bongani
would be having two diferent which is
data. "ddr"rr.., ""i.;;:;;;;;;fi;;;"';'.'""#:,"r,
b. Insert Anomaly
' An insertion anomaly is-a failure to place information
about a new database entry into all the
places in the database where info.-utio'
about that new entry needs to be stored.
' In a normalised database, information about a new
entry n.id* to be inserted into only one
place in the database.
' In an inadequately normalised database, information
about a new entry mayneed to be inserted
into more than one place' and, some of the needed
addition"l t;r"ttil;;"y b] mirsed.
' Suppose a new employee joins the company, who
is under training anJ.*rJ.rity no,
we would not be able to insert the data int tn. "rrigrr.a
::ila*i#ffT.then tutt" ii-.,_p_deptield

c. Delete Anomaly
' A deletion anomaly is a failure to remove information about an existing database entry when
it is time to remove that entry.
' In a ProPerly normalised database, information about
an old, to-be-gotten-rid-ofentry needs
to be deleted from only one place in the database.
' In.an in-adequately normalised database, information
about that old entry may need to be
deleted from more than one place, and, some of th"
' "..d;;lli.i""Ji"i.u."r;rbe
suppose, if at one time the company croses the department missed.
Dg90 then deleting ihe rows that
are having emp-dept as D890 would also delete
th^e information
is assigned only to this department. "r"*pr.y.. fuiul since she
' To overcome these anomalies, the data in the database
need to be qormalised.

Database Normalisation
' Normalisation is a process oforganising the data in a database
to avoid data redundancy,
insertion anomaly, update anomaly and deletion anomaly.

Benefits of Database Normalisation


a' Normalisation eliminates data duplication data and this
also reduces the overall size of the
database.
b' Normalisation ensures better performance of the database
as searches can be made faster on
a database with a reduced size.
c' Normalisation can also be helpful in reducing and finding
anomaries within data.
d. Normalisation results in tables with few.r.oium's whicriailows
f.. -;;;;;;;cords per
Page.

383
e'
Normalisation provides indexing which speeds up the access ofdata and also increasing up-
dating and deleting performance.
f. Normalization breaks the database into smaller tables making it much easier for database
administrators to provide security control to the different tables.

Drawbacks of Database Normalisation


a. Knowledge is required on the different normal forms to perform the normalisation process
efficiently.
b. Normalisation results in more tables being produced which require joining and this is a
tedious task.
c. Performance of the database becomes slower and slower as normalisation ofthe database
moves from one form to another.

. The most commonly followed steps in the process of normalisation are:


a. First Normal Form (f NF)
b. Second Normal Form (2NF)
c. Third Normal Form (3NF)
d. Boyce & Codd Normal Form (BCNF)

Focus will be on the first normal form and second normal form only.

* First Normal Form (lNF)


. A table is in First Normal Form if it satisfies the following conditions:
i. All the key attributes have been defined.
ii' It contains no repeating groups, that is, an attribute (column) of a table cannot hold many.
values. It should hold only atomic values.
. When a value is atomic, the values cannot be further subdivided. For example, the value
"Mouse" is atomic; whereas "Mouse; Keyboard; Monitor" is not,
. AIso, a table should not contain repeating groups of columns such as StudentllD_Number,
Student2lD_Number, and Student3lD Number.

Example
. A table is created to store student data which will have student's roll no., their name and the
name ofsubjects they have opted for as shown below.

roll-no Name Subject


l0l Tafadzwa OS, CN
103 Munashe fava
t02 David C, VB

But out of the 3 students in our table, 2 have opted for more than I subject. And we have
stored the subject names in a single column. But as per the lst normal form each column must
contain atomic value.
In order to solve this, we have to break the values into atomic values. The table below is now
the updated table that now satisfies the First Normal Form.

384
roll no Name Subject
l0I Tkrfadzwa OS
l0l Tafadzwa CN
103 Munashe Iava
l02 David C
t02 David VB

' By doing so, although a few values are getting repeated but values for the subject column are
now atomic for each record/row.
' Using the First Normal Form, data redundancy increases, as there will be many columns with
same data in multiple rows but each row as a whole will be unique.

* Second Normal Form (2NF)


. A table is in second Normal Form (2NF) if it satisfies the following conditions:
I. It is in First Normal Form (lNF)
II. Every non key attribute is firlly functional dependent on the whole ofthe primary key (i.e. there
are no partial dependencies or no aftribrlte is dependent on only part of-the key).

, 2NF only applies to tables with composite primary keys (more than one primary key).
. Therefore, any relation having a key with a single attribute is in Second Iiormal'Form.

Example
. Let's have a table called Student, to store student infonnation as shown below.

studentjd Name reg_no Branch Address


l0 Tungamirai 07-wY CSE Mutasa
lt Cecilia 08-wY IT Goromonzi
. From the we can use student_id to correct record.
Hence, a primary key for a table is the column or a group of columns (composite key) which
can uniquely identifi each record in the table.
One can ask from branch name ofa student with studenr_id l0 and get it.
Similarly, if one can ask for a name of student with student_id l0 or i I and get it.
what is only needed is the student-id and every other column depends on it, or can be fetched
using it. This is dependency popularly called functional dependency.
Let'shave another table subiect, to store subject information as shown below. The primary key
is subject_id.
subject-id subject-name
I lava
2 C++
3 VB.Net

Let's have another table Score, to store the marks obtained by students in.the different sub-
jects. We will also store name of the teacher who teaches that subiect along with.marks.

38s
score_id student id
I
lQq.ua Marks Teacher
IO I 70 Java Teacher
2 l0 2 75 C++ Teacher
3 ll 3 80 VB.Net Teacher
. In the score table we are saving the studenr_id
to know which studentt marks are these
subject id to know for which ,uUi".t and
tt . _".t *.
fo..
' It is not possible to get marks for a student
usrng student_id only because we
dont know for
which subject.
' possible to use the subjectjd to get the marks because we don't know
i,il.1lrhHnot for
. Hence we need student_id + subjectjd
to uniquely identifi any row. Together,
student id +
subject-id forms a candidate Key for this
t"ur.] *rii.r, .- f#;;ru";";;;.' "
Partial Dependency
' In the Score table, we have a corumn named
teacher which is only dependent
for Java itt Java Teacher and for c++ on the subject,
it, cii r.Jii", ro, vB.Net
' As mentioned earlier, the.primary -a
key ro. tttir tuul. i. a composition
its vB.Net Teacher.
student-id and subject-id but ttt. t.""tt"rt'u-.-o-nry of two columns which is
id, and has nothing to do with student_ij.
d.p.rdr;;;;ii..i, rr"#im subjecr_
' This is partiar dependency, when
for a-c-omposite primary key, any attribute
in the table depends
only on a part of the primary key
-a o" ifr.'"o_pfete primary key.
"ot
How to remove partial Dependency
' To remove partial dependency' we can divide the table, remove the attribute which is causing
yarlial^dependency, and move it to ,o,,,. ott..iubt..,'t ere
it fits well.
' In the score table, the sorution ir to..-ou..otoni' teacher frominscore tabre and add it to the
Subject table.
. The Subject table will appear as shown below:

subject_id subject_name Teacher


I lava Java Teacher
2 C++ C++ Teacher
3 VB.Net VB.Net Teacher
. The Score table is now in the second
normal form, with no partial dependency.

Example
. Let's look at the unormalised Sales table
below
386
/
i
SalesStaff table

EmployeelD SalesRepresentative Branch Customerl Custome12 Custome13


103 Lovemore Zaka GMB ZESA
104 Edith Bindura ZINARA DMB NRZ
105 Cleopatria Chipinge CSC
. The table above is not normalised and has the foilowing drawb;6
a. The table is limited only to accommodate a maximum of three customers.
b. It is not possible to sort or filter the table by Customer.
c. It has some deletion anomalies as deleting a customer may end up deleting the salesRepre-
sentative row,

First Normal Form


' Although the Sales Table columns have atomic values, the table is not yet in INF as it has
repeating groups for Customerl, Customer2 and Customer3.
' To Put the table to first normal form, we place the repeating supplier related columns into
their own table.

SalesStaff table

EmployeelD SalesRepresentative Branch


r03 Lovemore Z^k^
104 Edith Bindura
l0s Cleopatria Chipinge

Customer table
CustomerlD EmployeelD Branch CustomerName
s00r 103 Z^ka GMB
s002 103 Zaka ZESA
s003 104 Bindura ZINARA
s004 104 Bindura DMB
s005 104 Bindura NRZ
s005 105 Chipinge csc
Second Normal Form
. To decide whether our table is in 2NF let us look at the following issues:
I. The SalesStafftable has one column (Branch) which is not dependent on the EmployeelD. The
Branch column does not help in any way to describe yho the employee is.
II. There are several attributes which do not completely rely on the entire Customer table primary
key' For a given customer, it does not make sense that you should have to know both the
CustomerlD and EmployeelD to find the Customer. You need only to kn6w the CustomerlD.

387

I
' Therefore, the columns that are not completely dependent
on the fu primary key in both
cases are moved to new tables.

' In the case of Branch, a Branchofice was created. A foreign key (BranchlD)
was then added
to salesstafftable so we can still describe in which branch sal"i p"rron
i is based.

BranchOffice table
BranchID Branch
B0l Zaka
B,02 Bindura
B03 Chipinge
SalesStafftable

EmployeelD SaleqRepresentative BranchID


103 Lovemore B0l
l04 Edith B,02
105 Cleopatria B03

. To make Customer a second normal form table is a little bit trickier.


' Rather than-moving the columns CustomerName and Branch to a new table,
note that the
issue is EmployeelD. The two columns do not depend on this part ofthe
key.
. Really the table is trying to serve two purposes:
i. To indicate which customers are called upon by each employee.
ii. To identifr customers and their locations.
' For the moment remove EmployeelD from the table. Now the table's purpose
is clear, it is to
identi$ and describe each customer.

Customer table
CustomerlD Branch CustomerName
s00l Zaka GMB
s002 Zaka ZESA
s003 Bindura ZINARA'
s0M Bindura DMB
s005 Bindura NRZ
s006 Chipinge CSC

Now lett create a table named salesStaffcustomer with two columns customerlD and
EmployeelD to describe which customers a sales person calls upon.
Together, they form a primary key. Separately, they are foreign keys to the
customer and
SalesStaff table respectively.

SalesStaffCustomer table

388
CustomerlD EmployeelD
s001 I03
s002 103
s003 104
s004 104
s005 104
s006 t05
. with thesechangesmade the dataffi, isshownbelow

Customer
CustomerlD
Branch
CustomerName

SalesStaffCustomer
CustomerlD (FK)
EmployeelD (FK)

SalesStaff
EmployeelD
SalesRepresentative
BranchlD (FK)

BranchOffice
BranchlD
Branch

. The salesStaffcustomer contains only keys and it is called an intersection table.


. An intersection table is usefirl when you need to model a many-to-many relationship.

Actit'ity 8
I' A school uants to store the data of teachers and the subjects they teach, They create a table
shown belou.
teacher_id Subject teacher_age
lll Maths 38
ltl Physics 38
222 Computer Science 38
333 Physics 40
333 Chemistry 40

Candidate keys: {teacher_iil, subj ect}


Non key attributes: [teacher_age]

389 /
i
o) in lNF or not. Give a reason.
State whether the table is
b) (i) Explain why the table is not in 2NF.
(ii) Illustrate how to normalise the table into 2NF.

Accessing Data in a Database through a High Level Language


. When developing a computer based information systems, a high level programming language
such as Microsoft Visual Basic is used to create user interfaces that the user of the system
interacts with.
. For the storage of data in the system there is need to have a database such as My SQL or
Microsoft Access. Therefore, there is need to connect the high level programming language to
the database for the system to be functional

Connecting Microsoft Visual Basic.Net 2010 to Microsoft Access Database 2007

. Open Microsoft Access Database application.


. Create a database and give it a name of your choice. In this case the name of the database is
Davey_Enterprise-System.
. It is recommended that the database and the Microsoft Visual Basic.Net proiect should be
stored in the same folder. Therefore, save the database in the same folder you are going to save
your Microsoft Visual Basic project.
. The following shows the Microsoft Access database created using Microsoft Access 2007

thd
I ;
'_ hbhlcol! 0arg;lnterprirqSidmr0atrbrxiAaer2,lii].MicrosoftAccttt

t1
.' ho'ri (rralt ftrmlDlti Drtibrlrlo0lr orbtlRd

Iii d[(,I cdhi .,.EEE,:=:r, f] o-*n xhtah il i 4s,r,t*'


.j[o$ I ds,u ?sptt,ts il ' flom'rtu'
u,l I r u a.J.ffi.rJ. _= x*nu.lur,.
F,lt,, *1,11n
.,
=
\ie$r iiilrrifrl 't Fonl i Rrciltd R ordJ lotl8iftltet

: Prtn.nt-fiilhbh

tfuol-tih

I ctir{rm,lur

. Open a new proiect in Microsoft Visual Basic.Net 2010

390
oo llindc$,!Applicltion1 - t",ti<rcsoft ViJU.l Studio
Fih Edrt Vicw Proj.ct Build O.brjg T.rm O.ta Toolr fuchttadura
Format tart Ah!ty!!
iio;i-e{ d - ':4-
, - 6ILI
' =

r- Prym.nt Fil.

' Click Project menu when you are using vB.Net 2013 or crick Data menu
when using vB.Net
2010. Then select and click Add New Data Source as shown
below:
Microsoft Visual Basic.Net 2013

Microsoft Visual Basic.Net 2010

39r
11 irrihdc!v!Appta<rti6nl . l,1i.rcjcft Vir!!l Studic
F'k tdil Vi.w p.oJ.ct Butd O.bug Tc.n For6d -foob Archh.ctuE Tcst A..ty:.
-J show Drt. sourEcr shtft- Att- o
I
Add N.w D.t Sosrc....

,I
F'IFEI

Tr.nr.ct-sQl Ed'tor

. Select Database and click Next


D.t. Sour<. Contigurltion V,/i:ard

Cha'cr. a Olta Sourc. Typ.


a. - -'

lYh..c ir$ rhG.ppnc.t oo C.t d.t trofi?


il t L.
!-i tG dn
il o.,.L'. I s.-;-* Sh.r.Poirn

ht' y.":;;"a r"-. a.t.;; .-ia .r"J"* t,l anili* lr.il.d r", F;; ji,prr.a;.n.

Select Dataset and click Next

392
DBt. 5curcc icnfigur.ticn llrir!rd X

Choon r O.bb r Modal

Wh.l ttpe ot d.t bllr! modcl do rrnt lo l6a?


!i 'ou
i i ./.
ii j
:- .- .Dlt!s_d. * tnthy D.t!
Modd

I
Th. drt.b.t. modcl you choot! dltcrmin.r th? typ* of drtr objcctl jouirppliiation ccdc us.5. A dltr3dtil. wi b..ddcd to
your proj.ct.
I
I

< Prcvious C.n(al

There is need to browse and locate the correct database, in our case, the database is Davev
Enterprise_System. Therefore, click New Connection.

Drt! Sour(. Ccnfigur.ricn t//i!.rd

i Chcc.. Ycar Dtt Conn.cdon

Whkh d.t Gonnc.tbn rlloull tour.pp0c.ib.l stc to cdnl.cr ro dE AirS-.?


.ny d.t.b.r.....db

+ Ccnn.d'cn n.ing

Click Browse to locate your database

393
Add fc hnecticn X

Enter information to connect to the 5.lect€d ddt! sourcc or clirk


"Change" to choose a diffcrent d.ta sout(e.nd./or provider.

Data 50urcc:

i Micro soft Access Datab asc File (OLE DB] I cnong.,..


Database filc nrme:
I
I

Log on to thc dltrblse


lL tarl.. l
I- .'
-
Urer name: lndmin- ;

t-_-
Parsword: I I
[ Srve my password

Advanced.,.

Tc5t Connaction Cancd

. Select database and click


Sel.<t Microsofjt Acccsa Dltabn5a File X
.. Dcrk,., D.!.c),-Enterpri!a-lnfo.m.tio,,. i.i :1, Ll. € tr l;,1 ,:i 1,-,

Org.ni:c r N.w folder .: - ,l O


lJi,,r.
6 OncDrivc ^
ql Dlvcy-Errt rprirqs)'licn! j : .:::: i,.l€ Fl.1 1,1,:'r:.fi,-1fn.r -
El thie Pc
I O.5ktop
:l Oocumcntj
+ Downloldi
.Jr Music
; Picturcs

fl viacos
'j- Lo<.1Dirk (Cr)
R.covcry (Dr)
-
HP-TOOLS (t'
-
E N!t'\,ork

-] M;croroft Lcccii Dlt.b.sas ('.r -

Click on Test Connection to test whether the database was connected successful.

394
Entcr inlorrn.tion tc conn.ct to th. s.l.ct.d d!t. tout<. o. click
''Ch.nq. to choosc . dificr.nt d.t. 5cu.c. .nd /or p.ovid...
Dtt. sourcc:
' t't;c,oroft n...,s Databa:c Filc {OLE DB} ; Ch.ng....

T.n Cohh.ction

. If connection succeeded, click the OK button adjacent to test connection button'


. The followingdialogboxisthen displayed, verify the name ofyour database, theonehighlighted.
o Click Next
D.t. Sourcc Configur!ticn Wi!rrd

Choo.. Your Drtr Connacdon

.pptrG.tloo u.c lo codE€t to tihc d.t b-c?


Ns Conncction-.

+ Connaction irinq

< Pr.\,,ioui

Click No on the following dialog box.


Ifyou click Yes, your database would be duplicated and the copy is stored inside the vb.net
folder. This would cause several problems, including missing the data entered into the database
from the vb.net interface.

395
Choo'. Your D.tr CoFnaGidon
,
Wbkh 6tr (ollncctbn thoutd you..pp&.tton ul5? to (orBr.ct to ihc d.t b.rc?
D.vry_Enierprir._Syn.m..c.db
Ncw Conocction...

l,'li.roioft Viru!l Studic

Conhaclion
Th! conncdionyou rclcct.d ui.5 r lo<.ldrt. tilG th.r ir not in the
cuncnt projcc!. Would you likcto copytht fil.to your proj.ct.nd
modify thc <onn.<tion?

Ityou copy th. d.i. ril.to yolr proj.<t it vri bc (opied io thr proj.ct.5
odpd dir.<to.y ..ch ti . you run th. .ppticltion. pr.$ Fl lo; '
irtorm.tion on controlling this bchrvior,

the name of the connection If the connection click Next.


D.t. Scur<. Contigur.tion Wir6rd 7 X
Srvo tlro Coltnac$on Slrlhg to d!a, Appllcrdcn Contlgurttton Fll.
,.
.1r
S.oJing <oh^.<tion dringr ih.your .Ppli<.tion contigu..tion tiL..r.r m.inr.n.ncc.od d.ptoym.nr. to B.v.tt! <onnc.tion
nft.lg thc rptrliction configur.rion titc, Gnt.r. nrm. in th. bstndth.i (tict Ne<t.
tn
Do to! w.it ro .rvc thc romFctlon nrlE to th..pplc.rbll .onflgrrr.tlon fiG?
El Y.t srv! th. ronhcction rs:

lo.".y-r.i.if'r,._sy't.-c """..tio"it,-s I

<P'.Yiour t.-j:-f
Click to select Tables and Views.
If need be, one may change the Dataset name, however, the default name is mostly recom-
mended.
Click Finish

396
Dtt. Scu.<. Contiqur.tion Wiz.rd
rxl
Choor Your O.t br'. ObJ.ct

Whrch d.t.b!rc objcct, do )ou w.nt in )our dat.let?


IYJ5 Tabtes
El 3 Vicwr

DaaSa namc
l!r"V_Entcnrisr_SVstcmOaeSa-
J

' click viedother windows/Data s-ource if you are using Microsoft Msuar sasic.Net 2;t3
h:l'*.:ffiillfi iii:T:.- irvou are i',in! r'lr..;n visuar BasicNe;;;il;. p,.,,
. Select the colrect data source ifyou
have more than one data sources,
' the table you want to rink with ruri.to.ort
viruJ iasic.Net, in this case serect payment_
Fiick
oo tJindowrApplicrtionl - Mi(.osott Visurt studic
Filc Edit vilw proj.ct B! d D.bug T.rm Drt! Toolr Ar.hitcctur. T.rt
i."r_!rit-,ddt,,, - ilr : ;! Show Oatr Source
An bac Window Hclp

Dltr Sou,aci J Add Ncw D.t. source..,


I rb@i r khc'nr Comprrc
- *{ Drvq_iniqrisc_ Dlt Comp.E t
J Clilnt-Fit!
Trrnrrct-SQL Editor -)
'J@-
d Rd-No S.h.ma Vi.w )
;.a. Clicnl_lD
.tl N!m.
rtt SrJmcmr
l*t Quantity
idt Unit-pri<!
'.ht Amount_plid

' click the down arrow on payment_File as shown below and crick Details

397
Drta Sourccs Prymcnt Filc.vb [Ocignl' .

I.Id'
J la-l-r C

w :}'t D.v!r-
J Clicrt_Filc

H"
DltrGridl4lw
DdrilE

lNoncl

Customire...

.u Amount-P.id

click and drag the icon to the left of the Payment_File name as shown below. Drag and releasc
the icon on the form and all the fields from the payment_File table will be sho*rr1t on"..
The other method is to click and drag each field from the paymenr_File separately and placc
it on the form.
Paym.nt Filc.vb lDcsignl* x
,-, rl5 9i '.t
,{ Davcy_
tr PrFncnt Fh
J Clicnt-Filc
,! Prymcnt_File - ll ( 0 ot{o} | }l ',r Xd
LOt Rrf_No o-- '.. .,

idl Clicnt_lD inANo,:


i_r!i Name
ig91'lP, i
Ld: Sumlm. a- -. .--:
bU Quantity i!!.q*, i
[9!1 Unh_Price
a ..---''.'.. ,

:9HBr-: i
i.bl Anrount_P!id a-- ---
iqg!ry,.
t'.--.- '-.. ,

i.U'l..l|F, :

Dre3 thlr icon onto a--',-- -- --


i Arno(ft P.id:
thr form

If you are using Microsft visual Basic.Net 2013 when one clicks the details option, the icon
immed.iately to the left of Payment-File changes from 9f dlla
Drag and drop that icon on the respective form. In this case, the payment_File form
Adjust textboxes and labels as required by dragging and resizing them as shown below.

398
/
i
.:r Prymrnt Filc .. |.,EI
l< { c ct{o} , il ;XiJ
Rol llor

Clea lD:

llunc:

Sumadrcl

Ou.r{fy: II
il
tH Pnc.:

Anourt P.id: t.

. Run the system, the data in the database is then displayed on the vb.net form.

r
'l " XrJ
t ol2

Lffi*,__l
cl..r lD:
lelr l
-
lo.'.y l
It-'"E - I
ttt-
{i-
li---
I

-I r

Click the Move Next icon and Move Previous to view the next record or previous record
respectively, if any.

t
'-l
I

399
L1 l
i19 I

400

You might also like