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

BCS Database Programming Notes 1 - 12 (6)

The document provides an overview of database programming, covering topics such as database systems, data modeling, SQL, and database administration. It explains the advantages of using a Database Management System (DBMS) over traditional file systems, including data consistency, security, and recovery. Additionally, it discusses the importance of normalization and the relational model in organizing data efficiently to eliminate redundancy and anomalies.

Uploaded by

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

BCS Database Programming Notes 1 - 12 (6)

The document provides an overview of database programming, covering topics such as database systems, data modeling, SQL, and database administration. It explains the advantages of using a Database Management System (DBMS) over traditional file systems, including data consistency, security, and recovery. Additionally, it discusses the importance of normalization and the relational model in organizing data efficiently to eliminate redundancy and anomalies.

Uploaded by

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

Database Programming

By

Mwavu Rogers
[email protected]
(256)-700497421

Department of Computer Science


Faculty of Computing and Informatics
Mbarara University of Science and Technology
16/12/2023 11:38:21 CSC Alliance — 1
Overview

Introduction to database systems


Data Modeling: The Entity-Relationship Diagram
The Relational Model and Normalization
Physical Database Design
SQL - A Standard Navigation Language for Relational
Databases
Introduction to Two-Tier and Three-Tier Architectures,
and the Internet Database Environment

16/12/2023 11:38:21 CSC Alliance — 2


Overview

Introduction to Data Warehousing


Data Quality and Database Administration
Overview of Object-Oriented Databases

16/12/2023 11:38:21 CSC Alliance — 3


Introduction to database system
Before the emerging of database systems, data was manually
stored and managed using file processing system.

A file system is a method for storing and organizing


computer files and the data they contain to make it easy to
find and access them.

File systems may use a storage device such as a hard disk or


CD-ROM and involve maintaining the physical location of
the files.

16/12/2023 11:38:21 CSC Alliance — 4


Introduction to database system
Each file is placed in relevant folders for the ease of
access.

The filing system works well when the number of items


to be stored is small. However, the manual filing system
breaks down when we have to cross-reference or process
and manage relationship among information in the files.
This therefore explains the need for database
management Systems(DBMS).

16/12/2023 11:38:21 CSC Alliance — 5


Introduction to database system
A DBMS is a software system that uses a standard method
of cataloging, retrieving, and running queries on data.

The DBMS manages incoming data, organizes it, and


provides ways for the data to be modified or extracted by
users or other programs.

Some DBMS examples include MySQL, PostgreSQL,


Microsoft Access, SQL Server, FileMaker, Oracle, RDBMS,
dBase, Clipper, and FoxPro.

16/12/2023 11:38:22 CSC Alliance — 6


Some general functions of a DBMS

•Designed to allow the definition, creation, querying,


update, and administration of databases

•Define rules to validate the data and relieve users of


framing programs for data maintenance

•Convert an existing database, or archive a large and


growing one

16/12/2023 11:38:22 CSC Alliance — 7


Some general functions of a DBMS

•Run business applications, which perform the tasks of


managing business processes, interacting with end-users
and other applications, to capture and analyze data

16/12/2023 11:38:22 CSC Alliance — 8


DBMS over File System

No redundant data: Redundancy removed by data


normalization. No data duplication saves storage and
improves access time.

Data Consistency and Integrity: since data normalization


takes care of the data redundancy, data inconsistency also
been taken care of as part of it.

Flexible: Database systems are more flexible than file


processing systems.

16/12/2023 11:38:22 CSC Alliance — 9


DBMS over File System

Privacy: Limited access means privacy of data.

Easy recovery: Since database systems keeps the backup of


data, it is easier to do a full recovery of data in case of a
failure.

Data Security: It is easier to apply access constraints in


database systems so that only authorized user is able to access
the data. Each user has a different set of access thus data is
secured from the issues such as identity theft, data leaks and
misuse of data.
16/12/2023 11:38:22 CSC Alliance — 10
Components of Database environment

Hardware, Consists of a set of physical electronic devices


such as computers, I/O devices, storage devices, etc., this
provides the interface between computers and the real
world systems.

Software, This is the set of programs used to control and


manage the overall database. This includes the DBMS
software itself, the Operating System, the network software
being used to share the data among users, and the
application programs used to access data in the DBMS.
16/12/2023 11:38:22 CSC Alliance — 11
Components of Database environment

Data. DBMS exists to collect, store, process and access


data, the most important component. The database
contains both the actual or operational data and the
metadata.

Procedures, These are the instructions and rules that assist


on how to use the DBMS, and in designing and running
the database, using documented procedures, to guide the
users that operate and manage it.

16/12/2023 11:38:22 CSC Alliance — 12


Components of Database environment

People, these includes Database Administrators,


Application Programmer or Software Developer, End
User.

Database Application End User


Administrator Developer

16/12/2023 11:38:22 CSC Alliance — 13


Data Modeling:
The Entity-Relationship Diagram
An entity relationship model, also called an entity-
relationship (ER) diagram, is a graphical representation of
entities and their relationships to each other, Typically used
organization of data within database.

An entity is any object in the system that we want to model


and store information about.

Examples of entities are Employee, Student, Lecturer,


Department, Branch. An entity is similar to a table in the
relational model.
16/12/2023 11:38:22 CSC Alliance — 14
Data Modeling:
The Entity-Relationship Diagram

An entity occurrence is an instance of an entity. Example


a student record in the student entity.

A relationship is how the data is shared between entities.


There are three types of relationships between entities.

16/12/2023 11:38:22 CSC Alliance — 15


Relationships Between Entities

One-to-One

•One instance of an entity (A) is associated with one other


instance of another entity (B).

• For example, in a database of employees, each


employee name (A) is associated with only one social
security number (B).

16/12/2023 11:38:23 CSC Alliance — 16


Relationships Between Entities

One-to-Many

•One instance of an entity (A) is associated with zero, one


or many instances of another entity (B), but for one
instance of entity B there is only one instance of entity A.

• For example, for a company with all employees working


in one building, the building name (A) is associated with
many different employees (B), but those employees all
share the same singular association with entity A.

16/12/2023 11:38:23 CSC Alliance — 17


Relationships Between Entities
Many-to-Many

•One instance of an entity (A) is associated with one, zero


or many instances of another entity (B), and one instance
of entity B is associated with one, zero or many instances
of entity A.

16/12/2023 11:38:23 CSC Alliance — 18


Relationships Between Entities
Many-to-Many

• For example, for a company in which all of its


employees work on multiple projects, each instance of an
employee (A) is associated with many instances of a
project (B), and at the same time, each instance of a
project (B) has multiple employees (A) associated with it.

16/12/2023 11:38:23 CSC Alliance — 19


Relationships Between Entities

Cardinality refers to the maximum number of times an


instance in one entity can relate to instances of another
entity.

Cardinality: Denotes the maximum number of possible


relationship occurrences in which a certain entity can
participate in (in simple terms: at most).

16/12/2023 11:38:23 CSC Alliance — 20


Relationships Between Entities

Participation: Denotes if all or only some entity


occurrences participate in a relationship (in simple terms:
at least).

Then multiplicity ?

Multiplicity = Cardinality + Participation

16/12/2023 11:38:23 CSC Alliance — 21


Sample Exercise

Create an ER diagram for each of the following descriptions:


•(a) Each company operates four departments, and each department
belongs to one company.
•(b) Each department in part (a) employs one or more employees,
and each employee works for one department.
•(c) Each of the employees in part (b) may or may not have one or
more dependents, and each dependent belongs to one employee.
•(d) Each employee in part (c) may or may not have an employment
history.
•(e) Represent all the ER diagrams described in (a), (b), (c), and (d) as
a single ER diagram.

16/12/2023 11:38:23 CSC Alliance — 22


Logical database design

Logical database designing is the process of deciding how


to arrange the attributes of the entities in a given business
environment into database structures such as the tables of
a relational database.

The goal of logical database design is to create well


structured entities that properly reflect the company's
business environment. The design continues to
demonstrate the relationships between entities using
foreign keys.
16/12/2023 11:38:23 CSC Alliance — 23
Logical database design

There are several software tools deployed to create


database logical designs in the process of database
modelling. These include MySQL Workbench, Lucidchart,
ER/studio Draw.io, erwin Data Modeler and others.

These have made it simpler to convert logical database


design into physical database designs.

16/12/2023 11:38:23 CSC Alliance — 24


Logical Database Modelling
from Business Requirements

• This is where the EER diagram comes into the scene ,which
helps us find relations between various different subjects.
The process involves understanding the business problem ,
finding an IT related solution towards the problem, decide
on how the solution will be developed(mostly software
products), identifying the core stakeholder (those who will
interact directly with the system), stating requirements for
each stakeholder and lastly modelling the logical database
design from the requirements.
• Note, core requirement in the logical database design are
the functional and non functional requirements of the
system.

16/12/2023 11:38:23 CSC Alliance — 25


Functional requirements

• A Functional Requirement (FR) is a description of the


service that the software must offer. It describes a software
system or its component.
• A function is nothing but inputs to the software system, its
behavior, and outputs. It can be a calculation, data
manipulation, business process, user interaction, or any
other specific functionality which defines what function a
system is likely to perform to its users.
• Functional Requirements of a system should include the
following things:

16/12/2023 11:38:23 CSC Alliance — 26


Functional requirements

• Details of operations conducted in every screen


• Data handling logic should be entered into the system
• It should have descriptions of system reports or other
outputs
• Complete information about the workflows performed by
the system
• It should clearly define who will be allowed to
create/modify/delete the data in the system
• How the system will fulfill applicable regulatory and
compliance needs should be captured in the functional
document
16/12/2023 11:38:23 CSC Alliance — 27
Examples of Functional Requirements

• Consider the development of a web based system for managing


staff information for sales organization. Example of functional
requirements are ;
– The admin shall be able to create and manage staff accounts
– The admin shall promote staff via the system
– The admin shall be able to view sales made by each staff member
– The system shall be able to calculate discounts based on the
products purchased by the client
– The system shall generate sales statistics and reports based on
different time frame i.e., daily, weekly, monthly, annual reports.
– The admin shall track attendance of staff members

16/12/2023 11:38:24 CSC Alliance — 28


Generating Models from requirements

• Consider a requirement like creation and managing of staff


accounts, you realize that a staff entity is needed with different
attributes like staff id , name, gender, login credentials. And also
to track attendance an entity attendance will be needed to store the
attendance records for the staff members. This therefore shows that
there will be relationship between the staff entity and the attendance
entity. As such a foreign key “staff_id” in the attendance table will
be required.

16/12/2023 11:38:24 CSC Alliance — 29


Non Functional requirements

• A non-functional requirement is a requirement that specifies


criteria that can be used to judge the operation of a system,
rather than specific behaviors. They are contrasted with
functional requirements that define specific behavior or
functions.
• Therefore, when we say a system shall/should be "secure",
"highly-available", "portable", "scalable" and so on, we are
talking about its quality attributes.
• For example most system enforce the first level of security
as authenticating user with their credentials. This means to
perform the user credentials must be stored. As such an
entity in the logical design is required to store them.

16/12/2023 11:38:24 CSC Alliance — 30


The Relational model and Normalization

Relational Model represents how data is stored in


Relational Databases. A relational database stores data in
the form of relations (tables) and also show the
relationship between relations.

Consider a relation STUDENT with attributes REG_NO,


NAME, ADDRESS, PHONE and AGE and a relation
PROGRAM with attributes PROGRAM_NAME,ID,
DURATION,SHORT_NAME.

16/12/2023 11:38:24 CSC Alliance — 31


The Relational model and Normalization

A relation model will clearly demonstrate the structure


of the two relations and also how one becomes a
reference of the other.

The goal of a relational model is to define the structure


and relationship of relations in a well normalized
environmental setting to eliminate data redundancy and
associated anomalies.

16/12/2023 11:38:24 CSC Alliance — 32


Normalization

Normalization is a systematic approach of decomposing


tables to eliminate data redundancy(repetition) and
undesirable characteristics like Insertion, Update and
Deletion Anomalies.

Database Normalization is a technique of organizing the


data in the database.

16/12/2023 11:38:24 CSC Alliance — 33


Normalization

It is a multi-step process that puts data into tabular form,


removing duplicated data from the relation tables.

Normalization is mainly used for two purposes i.e.


eliminating redundant data and ensuring that data
dependencies make sense (data is logically stored)

16/12/2023 11:38:24 CSC Alliance — 34


Anomalies and unnormalized Data
Unnormalized form (UNF), also known as an
unnormalized relation or non first normal form, is a simple
database data model (organization of data in a database)
lacking the efficiency of database normalization.
Unnormalized data is associated with the following
anomalies.

Insert, deletion, update anomalies

•Insertion, Update and Deletion Anomalies are very frequent


if database is not normalized.
16/12/2023 11:38:24 CSC Alliance — 35
Understanding Anomalies

Consider the table (STUDENT) below

16/12/2023 11:38:24 CSC Alliance — 36


Understanding Anomalies

Insertion Anomaly

if we have to insert data of 100 students of same branch,


then the branch information will be repeated for all those
100 students. These scenarios are nothing but Insertion
anomalies.

16/12/2023 11:38:24 CSC Alliance — 37


Understanding Anomalies

Update Anomaly

What if Mr. X leaves the college? or is no longer the HOD


of computer science department? In that case all the
student records will have to be updated, and if by mistake
we miss any record, it will lead to data inconsistency. This
is Update anomaly.

16/12/2023 11:38:24 CSC Alliance — 38


Understanding Anomalies

Deletion Anomaly

In our Student table, two different information's are kept


together, Student information and Branch information.
Hence, at the end of the academic year, if student records
are deleted, we will also lose the branch information. This
is Deletion anomaly.

16/12/2023 11:38:24 CSC Alliance — 39


Normalization Rule

Normalization rules are divided into the following


normal forms:

 First Normal Form

 Second Normal Form

 Third Normal Form

16/12/2023 11:38:24 CSC Alliance — 40


First Normal Form (1NF)

For a table to be in the First Normal Form, it should follow


the following 4 rules:

 It should only have single(atomic) valued


attributes/columns.

 Values stored in a column should be of the same


domain

 All the columns in a table should have unique names.

 And the order in which data is stored, does not matter.

16/12/2023 11:38:25 CSC Alliance — 41


Lets Workout this
Consider table below. Before Normalization

16/12/2023 11:38:25 CSC Alliance — 42


Lets Workout this
Consider table above. After Normalization

16/12/2023 11:38:25 CSC Alliance — 43


Second Normal Form (1NF)

For a table to be in the Second Normal Form,

It should be in the First Normal form.

And, it should not have Partial Dependency.

16/12/2023 11:38:25 CSC Alliance — 44


Data dependency

 Functional dependency is a constraint between two sets


of attributes in a relation from a database. In other
words, functional dependency is a constraint between
attributes in a relation.

Partial dependency, Where an attribute in a table


depends on only a part of the primary key and not on
the whole key.

16/12/2023 11:38:25 CSC Alliance — 45


Third Normal Form (3NF)

A table is said to be in the Third Normal Form when,

It is in the Second Normal form.

And, it doesn't have Transitive Dependency.

Transitive dependency

When a non-prime attribute depends on other non-


prime attributes rather than depending upon the prime
attributes or primary key.

16/12/2023 11:38:25 CSC Alliance — 46


Third Normal Form (3NF)

Advantage of removing Transitive Dependency

Amount of data duplication is reduced.

Data integrity achieved.

16/12/2023 11:38:25 CSC Alliance — 47


Normalization Question

• The following table is already in first normal form (1NF).


There is only one entry per field. Please convert this table to
the third normal form (3NF) using the techniques you learned
in this Unit. Write a short report about your solution

16/12/2023 11:38:25 CSC Alliance — 48


Physical Database Design

Physical database design represents the materialization of


a database into an actual system. It involves transforming
a data model into the physical data structure of a
particular database management system (DBMS).

16/12/2023 11:38:25 CSC Alliance — 49


Physical Database Design

Physical design is performed in two stages:

I. Conversion of the logical design into table definitions


(often performed by an application developer): includes
pre-deployment design, table definitions, normalization,
primary and foreign key relationships, and basic indexing.

II. Post deployment physical database design (often


performed by a database administrator): includes
improving performance, reducing I/O, and streamlining
administration tasks.
16/12/2023 11:38:25 CSC Alliance — 50
Conversion of Logical design to physical design

Forward Engineering to a Live Server in MySQL workbench

Select the model to forward engineer


Then choose the Database, Forward Engineer menu item
from the main menu.
Set Parameters to connect to DBMS and then click Next
Set Options for the database to created
Select objects to Forward Engineer
Review SQL statements to be created in the process creating
the schema
And Finally click Next.
16/12/2023 11:38:25 CSC Alliance — 51
SQL - A Standard Navigation Language for Relational
Databases

SQL is a domain-specific language used in programming


and designed for managing data held in a relational
database management system, or for stream processing in
a relational data stream management system.

SQL stands for Structured Query Language.

SQL is a standard language for accessing and


manipulating databases.

16/12/2023 11:38:25 CSC Alliance — 52


SQL - A Standard Navigation Language for Relational
Databases

SQL lets you access and manipulate databases.

SQL commands are instructions. It is used to


communicate with the database. It is also used to perform
specific tasks, functions, and queries of data

SQL can perform various tasks like create a table, add


data to tables, drop the table, modify the table, set
permission for users.

16/12/2023 11:38:25 CSC Alliance — 53


Types of SQL Commands

Data Definition Language (DDL)

These are SQL Commands used to define and change the


structure database and tables within a database. They
include commands used in creating a table, deleting a
table, altering a table, etc.

16/12/2023 11:38:25 CSC Alliance — 54


Types of SQL Commands

Data Definition Language (DDL)

All the command of DDL are auto-committed that means


it permanently save all the changes in the database. Some
examples of DDL commands:

CREATE
ALTER
DROP
TRUNCATE

16/12/2023 11:38:25 CSC Alliance — 55


Types of SQL Commands

Data Manipulation Language (DML)

These are SQL Commands used to modify the database.


They are responsible for all form of changes in the
database.

All the command of DDL are not auto-committed that


means it can't permanently save all the changes in the
database. They can be rollback.

16/12/2023 11:38:26 CSC Alliance — 56


Types of SQL Commands

Data Manipulation Language (DML)

Some examples of DML commands:

INSERT
UPDATE
DELETE

16/12/2023 11:38:26 CSC Alliance — 57


Types of SQL Commands

Data Control Language (DCL)

These are SQL Commands used to grant and take back


(REVOKE) authority from any database user. Some
examples of DCL commands:

GRANT
REVOKE

16/12/2023 11:38:26 CSC Alliance — 58


Types of SQL Commands

Data Query Language (DQL)

These are SQL Commands used to fetch the data from the
database. SQL uses only one command:

SELECT

16/12/2023 11:38:26 CSC Alliance — 59


Types of SQL Commands

Data Query Language (DQL)

Example
SELECT * from staff WHERE Group_Email=
[email protected]
The SELECT statement above will return all staff members
with a group email [email protected] in a result set.

16/12/2023 11:38:26 CSC Alliance — 60


Introduction to Two-Tier and Three-Tier Architectures,
and the Internet Database Environment:

A Database Architecture is a representation of DBMS design. It


helps to design, develop, implement, and maintain the database
management system. A DBMS architecture allows dividing the
database system into individual components that can be
independently modified, changed, replaced, and altered. It also
helps to understand the components of a database.

Since a database stores critical information and helps access data


quickly and securely, selecting the correct Architecture of DBMS
helps in easy and efficient data management.

16/12/2023 11:38:26 CSC Alliance — 61


Single-Tier Architectures

This is the simplest architecture of Database in which the


client, server, and database all reside on the same machine.
A simple one tier architecture example would be anytime
you install a Database in your system and access it to
practice SQL queries. But such architecture is rarely used in
production environment.

16/12/2023 11:38:26 CSC Alliance — 62


Two-Tier Architectures

This is the database architecture where the presentation


layer runs on a client (PC, Mobile, Tablet, etc.), and data is
stored on a server called the second tier. Two tier
architecture provides added security to the DBMS as it is
not exposed to the end-user directly. It also provides direct
and faster communication.

16/12/2023 11:38:26 CSC Alliance — 63


Three-Tier Architectures

This is the most popular client server architecture in DBMS


in which the development and maintenance of functional
processes, logic, data access, data storage, and user
interface is done independently as separate modules.
Three-Tier architecture contains a presentation layer, an
application layer, and a database server.

16/12/2023 11:38:26 CSC Alliance — 64


Three-Tier Architectures

Three-Tier database Architecture design is an extension of


the 2-tier client-server architecture. A Three-tier
architecture has the following layers:

1. Presentation layer (your PC, Tablet, Mobile, etc.)


2.Application layer (server)
3.Database Server

16/12/2023 11:38:26 CSC Alliance — 65


Three-Tier Architectures

The Application layer resides between the user and the


DBMS, which is responsible for communicating the user's
request to the DBMS system and send the response from
the DBMS to the user. The application layer(business logic
layer) also processes functional logic, constraint, and rules
before passing data to the user or down to the DBMS.

16/12/2023 11:38:26 CSC Alliance — 66


Three-Tier Architectures- Goals

To separate the user applications and physical database

To support DBMS characteristics

Program-data independence

Supporting multiple views of the data

16/12/2023 11:38:26 CSC Alliance — 67


Three-Tier Architectures- Demo

16/12/2023 11:38:26 CSC Alliance — 68


Introduction to Data Warehousing

Data Warehousing may be defined as a collection of


corporate information and data derived from operational
systems and external data sources.

A data warehouse is designed with the purpose of


inducing business decisions by allowing data
consolidation, analysis, and reporting at different
aggregate levels. Data is populated into the DW by
extraction, transformation, and loading.

16/12/2023 11:38:26 CSC Alliance — 69


Introduction to Data Warehousing

Data Warehousing is process for collecting and


managing data from varied sources to provide
meaningful business insights.

A Data warehouse is used to connect and analyze


business data from heterogeneous sources. The data
warehouse is the core of the BI system which is built for
data analysis and reporting.

16/12/2023 11:38:27 CSC Alliance — 70


Introduction to Data Warehousing

It is an electronic storage of a large amount of


information by a business which is designed for query
and analysis instead of transaction processing

16/12/2023 11:38:27 CSC Alliance — 71


Data Warehouse Features

Subject Oriented − A data warehouse is subject oriented


because it provides information around a subject rather than
the organization's ongoing operations. These subjects can be
product, customers, suppliers, sales, revenue, etc.

Integrated − A data warehouse is constructed by integrating


data from heterogeneous sources such as relational
databases, flat files, etc.

16/12/2023 11:38:27 CSC Alliance — 72


Data Warehouse Features

Time Variant − The data collected in a data warehouse is


identified with a particular time period. The data in a data
warehouse provides information from the historical point of
view.

Non-volatile − Non-volatile means the previous data is not


erased when new data is added to it. A data warehouse is kept
separate from the operational database and therefore frequent
changes in operational database is not reflected in the data
warehouse.
16/12/2023 11:38:27 CSC Alliance — 73
Data Warehouse Applications

Financial services

Banking services

Consumer goods

Retail sectors

Controlled manufacturing

16/12/2023 11:38:27 CSC Alliance — 74


How Datawarehouse works

A Data Warehouse works as a central repository where


information arrives from one or more data sources. Data
flows into a data warehouse from the transactional system
and other relational databases. Data may be structured, semi-
structured and unstructured.

The data is processed, transformed, and ingested so that


users can access the processed data in the Data Warehouse
through Business Intelligence tools, SQL clients, and
spreadsheets.

16/12/2023 11:38:27 CSC Alliance — 75


How Datawarehouse works

A data warehouse merges information coming from different


sources into one comprehensive database.

By merging all of this information in one place, an


organization can analyze its customers more holistically. This
helps to ensure that it has considered all the information
available. Data warehousing makes data mining possible. Data
mining is looking for patterns in the data that may lead to
higher sales and profits.

16/12/2023 11:38:27 CSC Alliance — 76


Datawarehouse Architecture

16/12/2023 11:38:27 CSC Alliance — 77


Datawarehouse Architecture

Operational System

An operational system is a method used in data warehousing to


refer to a system that is used to process the day-to-day
transactions of an organization.

Flat Files

A Flat file system is a system of files in which transactional data


is stored, and every file in the system must have a different
name.

16/12/2023 11:38:27 CSC Alliance — 78


Datawarehouse Architecture

Meta Data

A set of data that defines and gives information about other


data.

16/12/2023 11:38:27 CSC Alliance — 79


Online Analytical Processing Tools

OLAP tools enable users to analyze multidimensional data


interactively from multiple perspectives. OLAP involves
relational database, report writing, data mining.

16/12/2023 11:38:27 CSC Alliance — 80


Online Analytical Processing Tools

16/12/2023 11:38:27 CSC Alliance — 81


Data Quality and Database Administration

•Data quality

A measure of the condition of data based on factors such


as accuracy, completeness, consistency, reliability and
whether it's up to date.

Measuring data quality levels can help organizations


identify data errors that need to be resolved and assess
whether the data in their IT systems is fit to serve its
intended purpose.

16/12/2023 11:38:27 CSC Alliance — 82


Why Data Quality is important?

Bad data can have significant business consequences for


companies.

Poor-quality data is often pegged as the source of operational


snafus, inaccurate analytics and ill-conceived business strategies.

If poor data is based on, the organization is more likely to make


poor decisions which may have a significant negative impact to its
development.

16/12/2023 11:38:27 CSC Alliance — 83


Measuring data quality;

Data Consistency: Violation of semantic rules defined over the


dataset.

Data Accuracy: Data are accurate when data values stored in


the database correspond to real-world values.

Data Uniqueness: A measure of unwanted duplication existing


within or across systems for a particular field, record, or data set.

16/12/2023 11:38:28 CSC Alliance — 84


Measuring data quality

Data Completeness: The degree to which values are present in a


data collection.

Data Timeliness: The extent to which age of the data is


appropriated for the task at hand.

16/12/2023 11:38:28 CSC Alliance — 85


Data Integration

•Data integration involves combining data residing in


different sources and providing users with a unified view
of them.

•ETL is a type of data integration that refers to the three


steps (extract, transform, load) used to blend data from
multiple sources.

16/12/2023 11:38:28 CSC Alliance — 86


ETL Process

16/12/2023 11:38:28 CSC Alliance — 87


ETL Process

Data extraction involves extracting data from


homogeneous or heterogeneous sources.

Data transformation processes data by data cleaning and


transforming them into a proper storage format/structure
for the purposes of querying and analysis.

Data loading describes the insertion of data into the final


target database such as an operational data store, a data
mart, data lake or a data warehouse.

16/12/2023 11:38:28 CSC Alliance — 88


Data Administration – Logical Design
Perform business requirements gathering and analysis

Model business based on requirements (conceptual and logical)

Define and enforce standards and conventions (definition, naming,


abbreviation)

Conduct data definition sessions with users.

Manage and administer meta data repository and Data


Administration CASE (modeling) tools

Assist Database Administration in creating physical tables from logical


models
16/12/2023 11:38:28 CSC Alliance — 89
Database Administration – Physical Design

Define required parameters for database definition

Analyze data volume and space requirements

Perform database tuning and parameter enhancements

Execute database backups and recoveries

Monitor database space requirements

Verify integrity of data in databases

Coordinate the transformation of logical structures to properly


performing physical structures

16/12/2023 11:38:28 CSC Alliance — 90


Overview of Object-Oriented Databases:

An object-oriented database (OODBMS) or object


database management system (ODBMS) is a database that
is based on object-oriented programming (OOP).

The data is represented and stored in the form of


objects. OODBMS are also called object databases or
object-oriented database management systems.

16/12/2023 11:38:28 CSC Alliance — 91


Overview of Object-Oriented Databases:

Object databases are commonly used in applications that


require high performance, calculations, and faster results.
Some of the common applications that use object
databases are real-time systems, architectural &
engineering for 3D modeling, telecommunications, and
scientific products, molecular science, and astronomy.

16/12/2023 11:38:28 CSC Alliance — 92


Overview of Object-Oriented Databases:

In OOP, an entity is represented as an object and objects


are stored in memory. Objects have members such as
fields, properties, and methods. Objects also have a life
cycle that includes the creation of an object, use of an
object, and deletion of an object.

OOP has key characteristics, encapsulation, inheritance,


and polymorphism

16/12/2023 11:38:28 CSC Alliance — 93


Object Oriented Data Model- Components

An object is an abstraction of a real-world entity.

Attributes describe the properties of an object.

Objects that share similar characteristics are grouped in


classes.

Classes are organized in a class hierarchy. The class hierarchy


resembles an upside-down tree in which each class has only
one parent. For example, the CUSTOMER class and the
EMPLOYEE class share a parent PERSON class.

16/12/2023 11:38:28 CSC Alliance — 94


Object Oriented Data Model- Components

Inheritance is the ability of an object within the class


hierarchy to inherit the attributes and methods of the
classes above it. For example, two classes, CUSTOMER
and EMPLOYEE, can be created as subclasses from the
class PERSON. In this case, CUSTOMER and EMPLOYEE
will inherit all attributes and methods from PERSON.

16/12/2023 11:38:28 CSC Alliance — 95


OODM Vs RDM

16/12/2023 11:38:29 CSC Alliance — 96


Drawbacks of Object-Oriented Databases:

Object databases are not as popular as RDBMS. It is


difficult to find object DB developers.

Not many programming language support object


databases.

RDBMS have SQL as a standard query language. Object


databases do not have a standard.

Object databases are difficult to learn for non-


programmers.

16/12/2023 11:38:29 CSC Alliance — 97


Course work

JTS Tech Solution Uganda is an ICT company located in Mbarara town. The
company has 4 branches i.e. Mbarara, Sembabule, Lwengo, Masaka. Each
branch is assigned employees of different categories such as manager,
supervisors, coordinator and other operations workers. The company offers IT
services such Website design and development, Mobile application
Development, ICT Training and Consultations, Microsoft Package Training,
Internship Training, Digital Marketing, Research Development and others. The
company also has over 1000 clients for the different services provided. The
organization employees are responsible for attending to the client in different
areas. Assuming you have been hired at JTS as the database administrator;

16/12/2023 11:38:29 CSC Alliance — 98


Coursework questions

a. Explain why the organization need a database management system.


b. Explain what will be your roles as a database administrator at JTS.
c. Explain the database system that you will to design for JTS.
d. Discuss 4 functional and 4 non functional requirements of the
database system proposed
e. Explicate at least four techniques that will use to gather the database
system requirements
f. Design a well normalized ER Diagram for the database you have
selected with at least 12 tables with their relationships.
g. Discuss four reasons to why to will need a Relational database
system over an Object oriented database system.
h. Using MySQL workbench, convert the logical model designed in
part f into a physical database design

16/12/2023 11:38:29 CSC Alliance — 99


DATA DEFINITION LANGAUAGE
COMMANDS.

16/12/2023 11:38:29 CSC Alliance — 100


Data Definition Language commands

The DDL commands in SQL are used to create database


schema and to define the type and structure of the data that
will be stored in a database.

These commands are used to set up, change and remove


data structures such as tables. They are known as DDL or
Data Definition Language commands

16/12/2023 11:38:29 CSC Alliance — 101


Examples of DDL Commands

CREATE – is used to create the database or its objects


(like table, index, function, views, store procedure and
triggers).

DROP – is used to delete objects from the database.

ALTER-is used to alter the structure of the database.

TRUNCATE–is used to remove all records from a table,


including all spaces allocated for the records are removed.

16/12/2023 11:38:29 CSC Alliance — 102


DDL Commands. CREATE

Creating a Database: The syntax for creating a database is


as follows:

16/12/2023 11:38:29 CSC Alliance — 103


Example

CHANGING THE DATABASE TO USABLE STATE

16/12/2023 11:38:29 CSC Alliance — 104


Creating a table

• To begin with, the table creation command requires


the following details
• Name of the table
• Name of the fields
• Definitions for each field

•Syntax

16/12/2023 11:38:29 CSC Alliance — 105


Examples

16/12/2023 11:38:29 CSC Alliance — 106


Note

• Here, a few items need explanation −


• Field Attribute NOT NULL is being used because we
do not want this field to be NULL. So, if a user will try
to create a record with a NULL value, then MySQL will
raise an error.
• Field Attribute AUTO_INCREMENT tells MySQL to
go ahead and add the next available number to the id
field.
• Keyword PRIMARY KEY is used to define a column
as a primary key. You can use multiple columns
separated by a comma to define a primary key.

16/12/2023 11:38:29 CSC Alliance — 107


Foreign Key Creation

16/12/2023 11:38:29 CSC Alliance — 108


Describing a table

16/12/2023 11:38:29 CSC Alliance — 109


Using the ALTER Command

The MySQL ALTER command is very useful when you


want to change a name of your table, any table field or if
you want to add or delete an existing column in a table.

The SQL ALTER TABLE command is used to add, delete


or modify columns in an existing table. You should also use
the ALTER TABLE command to add and drop various
constraints on an existing table.

16/12/2023 11:38:29 CSC Alliance — 110


Usage of the Alter Command

• The basic syntax of an ALTER TABLE command to add a


New Column in an existing table is as follows.
ALTER TABLE table_name ADD column_name
datatype[size];

16/12/2023 11:38:30 CSC Alliance — 111


Adding multiple columns.

16/12/2023 11:38:30 CSC Alliance — 112


Changing Column Name

To change the column name in a table, we can use the


following Syntax
ALTER TABLE table_name CHANGE
old_column_name new_name datatype [size];

16/12/2023 11:38:30 CSC Alliance — 113


Changing Datatype and size

To change the column datatype or/and size in a table, we


can use the following Syntax
ALTER TABLE table_name MODIFY
column_name datatype [size];

16/12/2023 11:38:30 CSC Alliance — 114


Dropping the column

To drop the column from the table, we can use the
following Syntax
ALTER TABLE table_name DROP COLUMN
column_name

16/12/2023 11:38:30 CSC Alliance — 115


Remaining a table.

To change the name of the table, we can use the following
Syntax
ALTER TABLE table_name REMAME old__name
new_name
OR
ALTER TABLE table_name REMAME old_table_name
TO new_table_name

16/12/2023 11:38:30 CSC Alliance — 116


The Truncate Command

The TRUNCATE TABLE statement is a fast, efficient


method of deleting all rows in a table. TRUNCATE TABLE is
similar to the DELETE statement without a WHERE clause.
However, TRUNCATE TABLE is faster and uses fewer
system and transaction log resources. Note the TRUNCATE
resets the auto incrementing column. Use the following syntax
TRUNCATE TABLE table_name
TRUNCATE table_name

16/12/2023 11:38:30 CSC Alliance — 117


The DROP Command

The DROP command is a type of SQL DDL command,


that is used to delete an existing database or an object
within a database. An object can be a table, view, trigger,
stored procedure, even database. We can use the DROP
command following the syntax below.
DROP objectType objectName;

16/12/2023 11:38:30 CSC Alliance — 118


DATA MANIPULATION
LANGAUAGE COMMANDS.

16/12/2023 11:38:30 CSC Alliance — 119


Data Manipulation Language Commands

The SQL commands that deals with the manipulation of


data present in the database belong to DML or Data
Manipulation Language and this includes most of the SQL
statements

These commands are used to enter new rows, change


existing rows and remove unwanted rows from tables in the
database. They are known as DML or Data Manipulation
Language commands.

16/12/2023 11:38:30 CSC Alliance — 120


Data Manipulation Language Commands

Examples of DML:

 INSERT – is used to insert data into a table.

 UPDATE – is used to update existing data within a


table.

 DELETE – is used to delete records from a database


table

16/12/2023 11:38:30 CSC Alliance — 121


INSERT Command

DML Command used to insert records into the database.


Example.
Specify both the column names and the values to be
inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Columns not specified but the order of the values is in the


same order as the columns in the table.
INSERT INTO table_name
VALUES (value1, value2, value3, ...);

16/12/2023 11:38:30 CSC Alliance — 122


Inserting A single row

16/12/2023 11:38:30 CSC Alliance — 123


Inserting multiple records

16/12/2023 11:38:31 CSC Alliance — 124


UPDATE Command

This bases on a specified condition to change the


records/rows in the table. If no condition specified, all
records in the specified column will be updated. To use this
command we following the syntax below
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note:
If the condition is not specified, all the rows in the table
will be updated with the new values passed in the
UPDATE statement;

16/12/2023 11:38:31 CSC Alliance — 125


UPDATE with condition

16/12/2023 11:38:31 CSC Alliance — 126


UPDATE with not condition

16/12/2023 11:38:31 CSC Alliance — 127


DELETE Command

The DELETE command is used to remove records/rows


from the table. In most cases the command bases on the
specified conditions/criteria but if no condition specified, all
records will be deleted from the table. Unlike the
TRUNCATE command, when rows are deleted using the
delete command the AUTO INCREMENT is not reset. To
use this command the following syntax is followed.

DELETE FROM table_name WHERE condition;

16/12/2023 11:38:31 CSC Alliance — 128


Delete with condition

16/12/2023 11:38:31 CSC Alliance — 129


DELETE with no condition

16/12/2023 11:38:31 CSC Alliance — 130


DATA QUERY LANGAUAGE
COMMANDS.

16/12/2023 11:38:31 CSC Alliance — 131


Data Query Language Command

DQL statements are used for performing queries on the data


within schema objects. The purpose of the DQL Command is
to get some schema relation based on the query passed to it.

These commands are used to fetch the data from the database.
It uses only one command “SELECT”

 SELECT – is used to retrieve data from the database.

16/12/2023 11:38:31 CSC Alliance — 132


SELECT statement

The select statement is used in conjunction with the WHERE


clauses to specify the condition/criteria on which data is
fetched.

Each SQL query statement must contain both a SELECT and


FROM clause. The combination of these two clauses is to
determine the table columns that are searched by the query.

The WHERE clause and other advanced clauses further limit


data retrieval to specific table rows.

16/12/2023 11:38:31 CSC Alliance — 133


The SQL SELECT statement

Syntax.
SELECT column1, column2,… FROM table_name;

Following the syntax above, Column1, Column2,…. Are


the filed names of the table you want to select data from. If
you want to select all the available in the table, use the
following syntax:

SELECT * FROM table_name;

16/12/2023 11:38:31 CSC Alliance — 134


Example

16/12/2023 11:38:31 CSC Alliance — 135


The WHERE Clause

The WHERE Clause is used within the SELECT statement


to specify the criteria/condition on which data is returned.
The clause is used to specify a condition while fetching the
data from a single table or by joining with multiple tables.

The WHERE clause is not only used in the SELECT


statement, but it is also used in the UPDATE, DELETE
statements.

16/12/2023 11:38:31 CSC Alliance — 136


The WHERE Clause example

16/12/2023 11:38:31 CSC Alliance — 137


AND,OR Operator in WHERE Clause

An operator is a reserved word or character used primarily


in an SQL statement’s WHERE clause to perform
operations such as arithmetic and comparison operators.

These operators are used to specify conditions in an SQL


statement and to serve as conjunctions for multiple
conditions in a statement.

16/12/2023 11:38:31 CSC Alliance — 138


THE AND operator

The AND operator allows the existence of multiple


conditions in an SQL statement’s WHERE clause. It is
TRUE if all the conditions separated by the AND is TRUE.

16/12/2023 11:38:32 CSC Alliance — 139


THE OR operator

The OR operator is used to combine multiple conditions in


an SQL statement’s WHERE clause. It is TRUE if the
operand is equal to one of the list of expression.

16/12/2023 11:38:32 CSC Alliance — 140


THE BETWEEN operator

The BETWEEN operator is used to search for values that


are within a set of values given the maximum and minimum
values. It is TRUE if the operand is within the range of the
comparison.

16/12/2023 11:38:32 CSC Alliance — 141


THE LIMIT clause

The SQL LIMIT clause restricts how many rows are


returned from a query. The syntax for the LIMIT clause is:
SELECT * FROM table LIMIT X;. X represents how many
records you want to retrieve. For example, you can use the
LIMIT clause to retrieve the top 3 student records from the
table.

16/12/2023 11:38:32 CSC Alliance — 142


THE LIMIT clause and ORDER BY

Say you want to retrieve records from the bottom of the


list. You should use the SQL ORDER BY statement to
order them in descending order(DESC) instead of ascending
order (ASC). Then, you should use a LIMIT statement:

16/12/2023 11:38:32 CSC Alliance — 143


Offset the SQL LIMIT Clause

If you want to offset the LIMIT clause — change the


starting point —you can specify a second parameter. Here is
the syntax for an SQL LIMIT query that offsets a query:
SELECT column_name FROM table_name LIMIT
starting_point, rows_to_return;

The starting point is the offset for the query (where your
results will start). The “rows_to_return” is how many rows
you want your query to retrieve.

16/12/2023 11:38:32 CSC Alliance — 144


Offset the SQL LIMIT Clause. Example

16/12/2023 11:38:32 CSC Alliance — 145


SQL FUNCTIONS
(AGGREGATE AND SCALAR )

16/12/2023 11:38:32 CSC Alliance — 146


Functions

SQL has many built-in functions for performing


calculations on data. There are two types of functions in
SQL
Aggregate Functions
SQL aggregate functions return a single value, calculated
from values in a column.
Scalar Functions
SQL scalar functions return a single value, based on the input
value.

16/12/2023 11:38:32 CSC Alliance — 147


Examples of Aggregate Functions

AVG() - Returns the average value from the specified


column
COUNT() - Returns the number of rows
MAX() - Returns the largest value from the specified
column
MIN() - Returns the smallest value from the specified
column
SUM() - Returns the sum from the specified column

16/12/2023 11:38:32 CSC Alliance — 148


Aggregate Functions (AVG and COUNT)

16/12/2023 11:38:32 CSC Alliance — 149


Aggregate Functions (MAX and MIN)

16/12/2023 11:38:32 CSC Alliance — 150


Aggregate Functions (SUM and AVG with a sub query)

16/12/2023 11:38:32 CSC Alliance — 151


Examples of Scalar Functions

UCASE() - Converts a field to upper case


LCASE() - Converts a field to lower case
MID() - Extract characters from a text field
LENGTH() - Returns the length of a text field
ROUND() - Rounds a numeric field to the number of
decimals specified
CONCAT() – Joins specified strings
NOW() - Returns the current system date and time
FORMAT() - Formats how a field is to be displayed

16/12/2023 11:38:32 CSC Alliance — 152


Scalar Functions (UCASE)

16/12/2023 11:38:32 CSC Alliance — 153


Scalar Functions (LCASE)

16/12/2023 11:38:33 CSC Alliance — 154


Scalar Functions (MID)

16/12/2023 11:38:33 CSC Alliance — 155


Scalar Functions (CONCAT and LENGTH)

16/12/2023 11:38:33 CSC Alliance — 156


Scalar Functions (NOW and ROUND)

16/12/2023 11:38:33 CSC Alliance — 157


SQL JOINS
(INNER, RIGHT, LEFT JOINS)

16/12/2023 11:38:33 CSC Alliance — 158


SQL Joins

A JOIN clause is used to combine rows from two or more


tables, based on a related column between them.
Look at the “student" table and student address table in the
next slide.
Notice that the “student_id" column in the “student
address" table refers to the “ID" in the “student" table. The
relationship between the two tables above is the "student_id
" column.
Then, we can create SQL statements that selects records
from both tables in a single result set based on student_id.

16/12/2023 11:38:33 CSC Alliance — 159


Table descriptions

16/12/2023 11:38:33 CSC Alliance — 160


Types of Joins in SQL

(INNER) JOIN: Returns records that have matching values


in both tables

LEFT (OUTER) JOIN: Returns all records from the left


table, and the matched records from the right table

RIGHT (OUTER) JOIN: Returns all records from the right


table, and the matched records from the left table

FULL (OUTER) JOIN: Returns all records when there is a


match in either left or right table
16/12/2023 11:38:33 CSC Alliance — 161
INNER JOIN

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1, table2
WHERE table1.column_name = table2.column_name;

16/12/2023 11:38:33 CSC Alliance — 162


Inner Join Example

16/12/2023 11:38:33 CSC Alliance — 163


LEFT JOIN

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1 LEFT OUTER JOIN table2
ON table1.column_name = table2.column_name;

16/12/2023 11:38:33 CSC Alliance — 164


Alias Names

SQL aliases are used to give a table, or a column in a table,


a temporary name. Aliases are often used to make column
names more readable. An alias only exists for the duration
of that query.

16/12/2023 11:38:33 CSC Alliance — 165


LEFT JOIN

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1 LEFT OUTER JOIN table2
ON table1.column_name = table2.column_name;

16/12/2023 11:38:33 CSC Alliance — 166


Left Join Example

16/12/2023 11:38:33 CSC Alliance — 167


RIGHT JOIN

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1 RIGHT OUTER JOIN table2
ON table1.column_name = table2.column_name;

16/12/2023 11:38:33 CSC Alliance — 168


RIGHT JOIN example

16/12/2023 11:38:33 CSC Alliance — 169


SQL UNIONS
(UNION AND UNION ALL)

16/12/2023 11:38:33 CSC Alliance — 170


UNION vs UNION ALL

The UNION command combines the result set of two or


more SELECT statements (only distinct values)

The UNION ALL command combines the result set of two


or more SELECT statements (allows duplicate values).

To use either UNION or UNION ALL, there MUST be a


match in the number columns from the specified SELECT
statements.

16/12/2023 11:38:33 CSC Alliance — 171


UNION vs UNION ALL

The UNION command is used to select related information


from two queries, much like the JOIN command. However,
when using the UNION command all selected columns need
to be of the same number and same datatype.

The UNION ALL command is used much the same way


like the UNION command except that it returns all records
including duplicates:

16/12/2023 11:38:34 CSC Alliance — 172


Example. UNION ALL

16/12/2023 11:38:34 CSC Alliance — 173


Example. UNION

16/12/2023 11:38:34 CSC Alliance — 174


UNION vs UNION ALL

Analyzing the two examples above, you realize that the


name Grace appears in both webaccount table and account.
With the use of UNION, the name Grace is returned once
but with UNION ALL it’s returned twice.

16/12/2023 11:38:34 CSC Alliance — 175


SUB QUERIES

16/12/2023 11:38:34 CSC Alliance — 176


What is a sub query

A Nested/ Subquery is a SELECT statement nested inside a


SELECT, SELECT ...INTO, INSERT...INTO, DELETE, or
UPDATE statement or inside another query.

A Sub query or Inner query or Nested query is a query within


another SQL query and embedded within the WHERE clause.

A sub query is used to return data that will be used in the


main query as a

 condition to further restrict the data to be retrieved.


16/12/2023 11:38:34 CSC Alliance — 177
Basic Syntax in SELECT statement with subquery

16/12/2023 11:38:34 CSC Alliance — 178


Example

16/12/2023 11:38:34 CSC Alliance — 179


Sub query Rules

Subqueries must be enclosed within parentheses.


A subquery can have only one column in the SELECT
clause, unless multiple columns are in the main query
for the subquery to compare its selected columns.
An ORDER BY command cannot be used in a
subquery, although the main query can use an ORDER
BY. The GROUP BY command can be used to perform
the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be
used with multiple value operators such as the IN
operator.

16/12/2023 11:38:34 CSC Alliance — 180


Tables orders and order_details:

16/12/2023 11:38:34 CSC Alliance — 181


Nserting records in the orders Table

16/12/2023 11:38:34 CSC Alliance — 182


Inserting records in the order_details table

16/12/2023 11:38:34 CSC Alliance — 183


Using Order and Order_details to demonstrate
sub queries

Find the average order amount for each customer:

16/12/2023 11:38:34 CSC Alliance — 184


• Identify customers who placed orders above the average order
amount:

16/12/2023 11:38:34 CSC Alliance — 185


• List employees and the total number of orders they handled

16/12/2023 11:38:34 CSC Alliance — 186


VIEWS

16/12/2023 11:38:35 CSC Alliance — 187


What is a view?

In SQL, a view is a virtual table based on the result-set of


an SQL statement.
A view contains rows and columns, just like a real table.
The fields in a view are fields from one or more real tables
in the database.
You can add SQL statements and functions to a view and
present the data as if the data were coming from one single
table.
A view is created with the CREATE VIEW statement.

16/12/2023 11:38:35 CSC Alliance — 188


CREATE VIEW Syntax

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

16/12/2023 11:38:35 CSC Alliance — 189


Example

16/12/2023 11:38:35 CSC Alliance — 190


ALTERING VIEW Syntax

This involves the changing the structure of a view. This can


be achieved following the syntax below.
ALTER VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

16/12/2023 11:38:35 CSC Alliance — 191


ALTERING VIEW Example

16/12/2023 11:38:35 CSC Alliance — 192


Dropping A View

A view can be dropped from the database following


the syntax below

DROP VIEW view_name

Example

16/12/2023 11:38:35 CSC Alliance — 193


TRIGGERS

16/12/2023 11:38:35 CSC Alliance — 194


What are Triggers

A trigger is a prewritten script that automatically executes


when special event occurs with in a database.

A trigger is a procedural code that is automatically


executed in response to certain events on a particular table
with in a database

For example, a trigger can be invoked when a row is


inserted into a specified table or when certain table columns
are being updated or when a row is deleted.

16/12/2023 11:38:35 CSC Alliance — 195


What are Triggers

DML triggers execute when a user tries to modify data


through a data manipulation language (DML) Command.

DML Command are INSERT, UPDATE, or DELETE


statements on a table or view.

Note: MySQL support for triggers was only introduced in


version 5.0.2

16/12/2023 11:38:35 CSC Alliance — 196


Importance of Triggers

Triggers help the database designer ensure certain actions,


such as maintaining an audit file, are completed regardless
of which program or user makes changes to the data.

Prevention of invalid transactions− MySQL triggers are


very useful in the prevention of invalid transactions.

16/12/2023 11:38:35 CSC Alliance — 197


Importance of Triggers

Logging of event− MySQL triggers can log an event and


can also store the information on the access of table.

Alternative way to run scheduled tasks − Actually by using


MySQL triggers we do not have to wait to run the
scheduled tasks because the triggers are invoked
automatically ‘before’ or ‘after’ a modification is done to
the data in the table.

16/12/2023 11:38:35 CSC Alliance — 198


Trigger Events

The triggers can occur AFTER or BEFORE a DML action.


Triggers are associated with the database DML actions
INSERT, UPDATE, and DELETE. Triggers are defined to
run when these actions are executed on a specific table.

16/12/2023 11:38:35 CSC Alliance — 199


Trigger Action Event

INSERT – Use the INSERTED table to determine which


rows were added to the table.

DELETE – Use the DELETED table to see which rows


were removed from the table.

UPDATE – Use the UPDATED table to inspect the new or


updated values and the DELETED table to see the values
prior to update.

16/12/2023 11:38:35 CSC Alliance — 200


General Syntax for Creating A trigger

16/12/2023 11:38:35 CSC Alliance — 201


Syntax Explained

CREATE TRIGGER [trigger_name]: Creates or replaces


an existing trigger with the trigger_name.

trigger_event [BEFORE | AFTER]: This specifies when


the trigger will be executed.

Action_event [INSERT | UPDATE | DELETE]: This


specifies the DML operation that must take place for trigger
to fire.

16/12/2023 11:38:35 CSC Alliance — 202


Syntax Explained

ON [table_name]: This specifies the name of the


table associated with the trigger.

[FOR EACH ROW]: This specifies a row-level trigger,


i.e., the trigger will be executed for each row being affected.

trigger_body: This provides the operation to be performed


as trigger is fired.

16/12/2023 11:38:35 CSC Alliance — 203


Syntax Explained

Trigger_statement/s have the statements that executes


when the trigger fires

if you want to execute multiple statement there you have to


use the BEGIN…END compound statement

16/12/2023 11:38:36 CSC Alliance — 204


The OLD and NEW keyword

We can refer to the columns of the table that are associated
with trigger by using the OLD and NEW keywords.

OLD.column_name is used to refer the column of an


existing row before it is deleted or updated and

NEW.column_name is used to refer to the column of a


new row that is inserted or an after update existing row.

16/12/2023 11:38:36 CSC Alliance — 205


The OLD and NEW keyword

Insert -- :Old = NULL :New= Inserted new value

Update -- :Old = Value present in table before the Update


statement Triggered :New = Given new value to Update

Delete -- :Old = Value before deletion :New = NULL

16/12/2023 11:38:36 CSC Alliance — 206


UPDATE Event Example 1

Consider the table marks which is meant to store marks of


students.

16/12/2023 11:38:36 CSC Alliance — 207


UPDATE Event

Consider table edited_marks meant to capture the updated


student marks together with student details.

16/12/2023 11:38:36 CSC Alliance — 208


Update Trigger

For every updated record, the trigger below fires to capture


the new and old mark and other information and stored it in
the edited_marks table.

16/12/2023 11:38:36 CSC Alliance — 209


UPDATE statement and results

16/12/2023 11:38:36 CSC Alliance — 210


UPDATE Event. Example 2

Consider the table “student” and “student_edited_info”


which is defined to store updated student information when
a trigger fires.

16/12/2023 11:38:36 CSC Alliance — 211


Trigger Example. UPDATE Event

For every updated record, the trigger below fires to capture


the new and old email plus some other information and
stored it in the student_edited_info table.

16/12/2023 11:38:36 CSC Alliance — 212


UPDATE statement;

16/12/2023 11:38:36 CSC Alliance — 213


Trigger Example. INSERT Event

CREATE a table to handle sales. Following the


example below, the discounted_amount column value
is calculated whenever a new record is inserted basing
on the sale_amount entered.

16/12/2023 11:38:36 CSC Alliance — 214


Trigger Example. INSERT Event

For every new record, the trigger below fires to


compute the discounted price and saves the record.

16/12/2023 11:38:36 CSC Alliance — 215


Trigger Example. INSERT Event-Results

Results After new records inserted

16/12/2023 11:38:36 CSC Alliance — 216


DELETE event

A table below named sales_deletes was created to


handle data about deleted sales from the sales table.

16/12/2023 11:38:36 CSC Alliance — 217


DELETE event –Trigger Code

A Trigger named as handle_deletes was created to fire


whenever a transaction is deleted from the sales table.

16/12/2023 11:38:36 CSC Alliance — 218


DELETE event –Results

16/12/2023 11:38:37 CSC Alliance — 219


Dropping A Trigger

A Trigger can be dropped from the database following


the syntax below

DROP TRIGGER trigger_name

Example

16/12/2023 11:38:37 CSC Alliance — 220


STORED PROCEDURES

16/12/2023 11:38:37 CSC Alliance — 221


Stored procedures
A stored procedure can be defined as a named set of
logically written statements, stored in the database and are
executed when called, to perform a specific task.
NOTE:
A stored procedure is a prepared SQL code that you can
save, so the code can be reused over and over again.
Any stored procedure created, remains useless unless it is
called.
If you have SQL query that you write over and over again,
you can save it as a stored procedure and then simply call
the store procedure to execute the it.

16/12/2023 11:38:37 CSC Alliance — 222


Advantages of stored procedures

Importance of a stored Procedure

 Improves database performance, makes executions of data


queries quick and efficient. This is because multiple SQL
statements can be grouped and executed as a single call.
Maintains security, you can restrict access to the data by
allowing users to manipulate the data only through stored
procedure that execute with in their defined privileges.
Increase productivity, with stored procedures you can avoid
redundant coding and increase your productivity.

16/12/2023 11:38:37 CSC Alliance — 223


Advantages of stored procedures

Increase scalability, increase scalability by isolating


application processing on the server. Different applications
can be created and access the server via different stored
procedures
Provides reusability and avoids redundancy, The same
block of code for procedure or function can be called any
number of times for working on multiple data. A stored
procedure can also be used on different databases.

16/12/2023 11:38:37 CSC Alliance — 224


Store procedure syntax

CREATE PROCEDURE procedure_name(parameter list……)


BEGIN
//statements;
END
DELIMITER

16/12/2023 11:38:37 CSC Alliance — 225


Example

Assuming you have a table containing student details that you need to frequently reference
on a daily basis.

16/12/2023 11:38:37 CSC Alliance — 226


• We can create a stored procedure that can be efficiently invoked to
retrieve the desired result set whenever necessary.

16/12/2023 11:38:37 CSC Alliance — 227


Result set

16/12/2023 11:38:37 CSC Alliance — 228


Stored Procedures Types

• Stored procedures in a database system can have different


types of parameters, which are placeholders for values that
will be passed to the stored procedure when it is executed.
Following are the different types of stored procedure
parameters in SQL.
Input parameters: These parameters are used to pass
values from the calling statement to the stored procedure.
Output parameters: These parameters are used to return
values from the stored procedure
Input/output parameters: These parameters allow a stored
procedure to accept input values and return output values.

16/12/2023 11:38:37 CSC Alliance — 229


Procedure with IN parameter

• The 'IN' parameter serves as the default receiver for input values in
the procedure. Values can be passed as arguments during the
invocation of the stored procedure.

16/12/2023 11:38:37 CSC Alliance — 230


Procedure with OUT parameter

• The OUT parameter is used to return the output value


from the procedure.
• Note that when using an OUT parameter, we must
specify the keyword OUT before the parameter name
when passing it to the stored procedure. This tells the
SQL database that the parameter is an output parameter
and should be assigned with a value in the stored
procedure.

16/12/2023 11:38:37 CSC Alliance — 231


Example

16/12/2023 11:38:37 CSC Alliance — 232


Stored procedures parameter

A parameter can contain one of the following;

IN: INPUT parameter is used to pass value to Stored Procedures.


However it does not return any value.

INOUT: IN-OUT parameter is used to pass value to Stored


Procedures. And it can return any value too.

OUT: OUT Parameter is used to return some value from Stored


Procedure only.

16/12/2023 11:38:38 CSC Alliance — 233


Example

CREATE PROCEDURE register_customer(IN name


VARCHAR(45),IN age INT)
BEGIN
INSERT into customer(Name,Age)VALUES(name,age);
END#

16/12/2023 11:38:38 CSC Alliance — 234


DECLARING VARIABLES

Syntax
DECLARE variable_name datatype DEFAULT
defaultValue;

Assigning Values

SET variable_name = value;

16/12/2023 11:38:38 CSC Alliance — 235


Variable declaration example

Syntax
DECLARE amount INT DEFAULT 0;

Assigning Values
SET amount = 2000;

16/12/2023 11:38:38 CSC Alliance — 236


Screenshots for store procedures

• No parameter P1
procedure

• Parameterized P2
procedure

16/12/2023 11:38:38 CSC Alliance — 237


More screenshots

• Execute SQL
statement p3

• Declare variables
and assign values
p5

16/12/2023 11:38:38 CSC Alliance — 238


More screenshots

Execute Multiple SQL statements p4

 Perform calculation

16/12/2023 11:38:38 CSC Alliance — 239


Using an if statement

16/12/2023 11:38:38 CSC Alliance — 240


More operations

Syntax
DROP PROCEDURE procedure_name DELIMITER
Example
DROP PROCEDURE p1#
List all defined stored procedure
SHOW PROCEDURE STATUS;
Explaining structure of stored procedure
SHOW CREATE PROCEDURE procedure_name;

16/12/2023 11:38:38 CSC Alliance — 241


Reading assignment

INOUT
OUT

16/12/2023 11:38:38 CSC Alliance — 242


Database Connectivity with a Web
Application

16/12/2023 11:38:38 CSC Alliance — 243


Requirement

Web server (Local) Xampp or Wamp server


Source code editor Sublime Text Editor
Web client Google chrome (any
browser)
Database Modeling Tool MYSQL Workbench

16/12/2023 11:38:38 CSC Alliance — 244


Language

PHP Process data on the server


SQL Query data from the server
HTML Design User Interfaces
CSS Apply styling to the web
interfaces

16/12/2023 11:38:38 CSC Alliance — 245


Connection file. Config.php

16/12/2023 11:38:38 CSC Alliance — 246


Explanation of the connection file

The initialized variable at line 4-7 specify the connection


strings required to establish a connection to the server.
The server name specifies the address of the server you
want to connect to. For local connections, use localhost or
127.0.0.1 or the IP address of the computer where the
database is hosted.
The user account and password specifies the account on
which the database is managed. This account is a user on
the database server. And the database specifies the database
that you want to interact with using the connection variable
instantiated from the driver class (MYSQLI).

16/12/2023 11:38:38 CSC Alliance — 247


Login File index.php

16/12/2023 11:38:38 CSC Alliance — 248


Login file. login.ph

16/12/2023 11:38:38 CSC Alliance — 249


Fetch all students using a while loop

16/12/2023 11:38:38 CSC Alliance — 250


Inserting using Registration page

16/12/2023 11:38:39 CSC Alliance — 251


Inserting using Registration page

Line 9 in the code above indicated that there is a file


process.php where the code to process the form data is
located. The include (or require ) statement takes all the
text/code/markup that exists in the specified file and copies
it into the file that uses the include statement. This means
the code is copied in the html file. This explains why the
action is not specified reason the processing code is located
in the same file.
Every form field MUST be given unique names following
the variable naming standards. The name is to pick the field
value while processing the form data using the specified
method (POST/GET)

16/12/2023 11:38:39 CSC Alliance — 252


Code for process.php

16/12/2023 11:38:39 CSC Alliance — 253


Code for process.php Explanation

Line 4 means that if a user has clicked the save button which
indicates that the value of the button is posted. Then the code below
gets executed.
Line 5-10 show different value declared to capture the user input from
the form field using their names as passed in the square brackets
following the method specified to process form data.
Line 15-16 indicates an SQL statement being prepared to insert data.
Using prepared statement, each column value is specified using a
question mark “?” which are bound as parameters using the
bind_param() method. The binding method specified the number of
strings to be bound using s and the exact values for each column.
Specification character s indicates that the corresponding variable has
type string. Other are i for integers, d for double, b for blob etc.

16/12/2023 11:38:39 CSC Alliance — 254

You might also like