Académique Documents
Professionnel Documents
Culture Documents
CHAPTER EIGHT
DATABASE MANAGEMENT SYSTEM
Overview
Database Management System (DBMS) is a software that allows creation, definition and
manipulation of database. DBMS is actually a tool used to perform any kind of operation on data in
database. DBMS also provides protection and security to database. It maintains data consistency in case
of multiple users. This chapter covers database concepts, basic database terminology, how to
accomplish the basic database tasks and how to secure any database.
Learning Objectives
Page- 185
Chapter Eight Database Management System
Introduction
Database management system (DBMS) is a collection of interrelated data and a set of programs to
access those data. In a simple words data can be facts related to any object in consideration. For
example your name, age, height, weight etc are some data related to you. A picture, image, file, PDF
etc can also be considered data. And systematic collection of these data for one or more purposes
usually in digital form is known as database. The primary goal of a DBMS is to provide a way to store
and retrieve database information that is both convenient and efficient.
Database is the collection of schemes, tables, queries, reports, views and other objects. The data is
typically organized to model aspects of reality in a way that supports processes requiring information,
such as modeling the availability of rooms in hotels in a way that supports finding a hotel with
vacancies. If we consider a university database it might contain information such as students, faculties,
courses, classrooms etc. From these data we can find students enrollment in courses, faculty teaching
courses and the use of rooms for courses.
A database management system is a software that interacts with the user, other applications, and the
database itself to capture and analyze data. A general purpose DBMS is designed to allow the
definition, creation, querying, update, and administration of databases. Well known DBMSs include
MySQL, PostgreSQL, Microsoft SQL Server, Oracle, Sybase and IBM DB2. A database is not
generally portable across different DBMSs, but different DBMS can interoperate by using standards
such as SQL and ODBC or JDBC to allow a single application to work with more than one DBMS.
Database management systems are often classified according to the database model that they support.
The most popular database systems since the 1980s have all supported the relational model as
represented by the SQL language.
Existing DBMSs provide various functions that allow management of a database and its data which can
be classified into four main functional groups:
Data definition: Creation, modification and removal of definitions that define the organization
of the data.
Update: Insertion, modification, and deletion of the actual data.
Retrieval: Providing information in a form directly usable or for further processing by other
applications. The retrieved data may be made available in a form basically the same as it is
stored in the database or in a new form obtained by altering or combining existing data from
the database.
Page- 186
Chapter Eight Database Management System
Banking: For customer information, accounts, and loans, and banking transactions.
Airlines: For reservations and schedule information. Airlines were among the first to use
databases in a geographically distributed manner - terminals situated around the world
accessed the central database system through phone lines and other data networks.
Credit card transactions: For purchases on credit cards and generation of monthly statements.
Telecommunication: For keeping records of calls made, generating monthly bills, maintaining
balances on prepaid calling cards, and storing information about the communication networks.
Finance: For storing information about holdings, sales, and purchases of financial instruments
such as stocks and bonds.
Manufacturing: For management of supply chain and for tracking production of items in
factories, inventories of items in warehouses / stores, and orders for items.
Human resources: For information about employees, salaries, payroll taxes and benefits, and
for generation of paychecks.
Facebook: Use database to store, manipulate and present data related to members, their
friends, member activities, messages, advertisement and lot more.
Advantages of a DBMS
Using a DBMS to store and manage data comes with advantages, but also overhead. One of the biggest
advantages of using a DBMS is that it lets end users and application programmers access and use the
same data while managing data integrity. Data is better protected and maintained when it can be shared
using a DBMS instead of creating new iterations of the same data stored in new files for every new
application. The DBMS provides a central store of data that can be accessed by multiple users in a
controlled manner. Central storage and management of data within the DBMS provides:
Page- 187
Chapter Eight Database Management System
An efficient handler to balance the needs of multiple applications using the same data
The ability to swiftly recover from crashes and errors, including restart ability and
recoverability
Nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different tables and
relations are established using primary keys or other keys known as foreign keys.
RDBMS is a software that:
Enables you to implement a database with tables, columns and indexes.
Guarantees the Referential Integrity between rows of various tables
Updates the indexes automatically.
Interprets an SQL query and combines information from various tables.
RDBMS Terminology:
Few definitions related to database:
Column: One column (data element) contains data of one and the same kind, for example the
column postcode.
Row: A row is a group of related data, for example the data of one subscription.
Page- 188
Chapter Eight Database Management System
Referential Integrity: Referential Integrity makes sure that a foreign key value always points
to an existing row.
Properties of Relations
Keys
Superkey: An attribute, or set of attributes, that uniquely identifies a tuple within a relation.
CandidateKey: A superkey such that no proper subset is a superkey within the relation. A
candidate key, K, for a relation R has two properties:
Primary Key: The candidate key that is selected to identify tuples uniquely within the relation.
Foreign Key: An attribute or set of attributes within one relation that matches the candidate
key of some (possibly the same) relation.
Compound Key: A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
DDL
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records
are removed
COMMENT - add comments to the data dictionary
RENAME - rename an object
DML
Data Manipulation Language (DML) statements are used for managing data within schema objects.
Some examples:
DCL
Data Control Language (DCL) statements. Some examples:
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command
TCL
Transaction Control (TCL) statements are used to manage the changes made by DML statements. It
allows statements to be grouped together into logical transactions.
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like isolation level and what rollback
segment to use
Page- 190
Chapter Eight Database Management System
SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in relational database. SQL is the standard language for Relational Database
System. All relational database management systems like MySQL, MS Access, Oracle, Sybase,
Informix, Postgres and SQL Server use SQL as standard database language.
Creating Database
Let you want to store all the information in a database named studentdb. So to create studentdb you
have to execute the following statement.
Creating Table
The foundation of every Relational Database Management System is a database object called table.
Each table has its own unique name and consists of columns and rows. To form a table using SQL the
user needs to specify the four components:
Name of the table
Name of each of the columns in the table
Data type of each column
Maximum length of each column
These four items are formulated together in a CREATE TABLE command having the following basic
format:
Page- 191
Chapter Eight Database Management System
So, you can create a table named StudentInformation (It's not mandatory, you can choose whatever you
want) and add columns Id, FirstName, LastName, Email and Phone with their data types.
If you want to add another column name Batch after you created your table then you have to alter the
table. Execute the below statement.
You can also modify the column in your need by executing below statement
If you want to rename your Batch column into BatchId then you have to execute the following
statement.
Now if you want to delete the column BatchId then you have to execute the below statement
So you have created your final table. Now you have to store those information into the table. You have
to use the INSERT statement to store data into database table. Execute the following query.
Page- 192
Chapter Eight Database Management System
INSERT INTO studentinformation (Id, FirstName, LastName, Email, Phone) VALUES (38048,
'Amlan','Roy','amlan.roy@bu.edu.bd',014138048);
If you insert all the fields value then you can use the below statements.
So, all the student's data are on the database now. if you want to see all the information then you have to
use SELECT statement to fetch the data from the database.
If you execute the above statement then all the information from the database will be displayed. To
fetch specific data from the table you have to use the WHERE clause. For example if you want to fetch
the data whose Id is 38126 then you have to execute the following statement.
If you use * then all the column will display. For specific column you can specify it in the SELECT
statement.
Now, let you want to update an existing information. For example you want to change the email address
of id38054 from arafa.sathi@bu.edu.bd to sultana.arafa@bu.edu.bd. To do so you have to use the
UPDATE statement.
Ok, you can now change the existing data. To delete some information from the database you have to
use the DELETE statement. let you want to delete all the information whose id is 38126. So you have
to execute the following query.
If you want to delete all the information from the table then you have to use the following statement.
Page- 193
Chapter Eight Database Management System
TRUNCATE studentinformation;
DELETE
When you will use DELETE Command then the data deleted can be retrieved when you
ROLLBACK .
LIMIT clause can also be used to set a limit on the number of rows to be deleted.
A DELETE is issued with no WHERE clause, all rows are deleted.
ORDER BY clause can be used in DELETE statement. In this case, the rows are deleted in the
specified order.
TRUNCATE
TRUNCATE drops the table and re-create it. It is much faster than deleting rows one by one.
Once you use TRUNCATE command then you cannot retrieve the data again from the table.
TRUNCATE is not transaction-safe; an error occurs when attempting one in the course of an active
transaction or active table lock.
TRUNCATE removes all the rows from the Table and does not return number of deleted rows.
TRUNCATE is probably better thought of as a shortcut for DROP TABLE/CREATE TABLE
rather than a quirky kind of DELETE.
Let you have another table 'studentmarks' and from this table you got some students id and their
marks. But you want to know the first name of the student of each mark.
Id Mark
38048 90
38054 85
38126 80
38152 95
Table: studentmarks
So you have studentinformation and studentmarks table. You can get that by executing below
statement.
Page- 194
Chapter Eight Database Management System
Id Mark
Amlan 90
Sultana Arafa 85
Noman Al 80
Md. Rayhanuzzaman 95
Table: Query Result
You can also get the same result using JOIN. Run the following query.
Creating Views
View or a virtual table is nothing more than a SQL statement that is stored in the database with an
associated name. A view is actually a composition of a table in the form of a predefined SQL query. A
view can contain all rows and column or selected rows and column from single or multiple table or
view. You can use SELECT, INSERT, UPDATE and DELETE statement on view.
Let, you need name wise marks list from two table and you don't want to write that big query each time.
So there is a nice way to save your time. Create a view for that.
So the result from the SELECT statement saved as 'namewisemarks' view. If you want to see the result
of that big query, then you have to write only the following query.
Id Mark
Amlan 90
Page- 195
Chapter Eight Database Management System
Sultana Arafa 85
Noman Al 80
Md. Rayhanuzzaman 95
Table: Query Result of View
Stored Procedure
A stored procedure is simply a procedure that is stored on the database server. It is simply some SQL
statements. Almost any valid SQL can go inside a stored procedure. Oracle, MySQL, MSSQL all of
these support stored procedure.
You know that if you want to insert a value into database you have to use the INSERT statement. You
can create a procedure to make your inserting task easier. Lets create a procedure named
'insertResultProc' with two parameter.
CREATE PROCEDURE insertResultProc (id INT, mark INT) The insert statement is defined
inside the procedure. The
BEGIN procedure takes two parameter id
INSERT INTO studentmarks (Id, Mark) VALUES (id,mark); and mark. Using these value it
insert data into database.
END
Table: Procedure Example
So now you can call the procedure to insert your data into database. Execute the following query.
CALL insertResultProc(38055,75);
So the procedure will insert the mark into the studentmarks table.
Stored Function
The difference between a Stored Procedure and a Stored Function is not too much. A function always
returns a result, and can be called inside an SQL statement just like ordinary SQL functions. A function
parameter is the equivalent of the IN procedure parameter, as functions use the RETURN keyword to
determine what is passed back. Oracle, MySQL, MSSQL all of these support stored function.
Page- 196
Chapter Eight Database Management System
Like procedure we can also use function to make our query easy. Lets create a function named
'getResultFunc' which will take Id as a parameter and will return its Mark.
The function takes the id and it will return the mark of that id from database.
Trigger
A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is executed or
fired whenever an event associated with a table occurs e.g., insert, update or delete. It is a special type
of stored procedure because it is not called directly like a stored procedure. The main difference
between a trigger and a stored procedure is that a trigger is called automatically when a data
modification event is made against a table whereas a stored procedure must be called explicitly.
You have studentinformation and studentmarks tables. Now you want whenever you will insert any
new student's information into the studentinformation table automatically his or her default marks will
also insert into the studentmarks table. So let's create a Trigger which will invoke after insert statement
executed in studentinformation table.
Page- 197
Chapter Eight Database Management System
END
Table: Trigger Example
It will insert a row in the studentinformation table and also in a row in studentmarks table. This is
because when insert statement execution ended then the trigger after_studentinformation_insert fired.
Cursor
A cursor is a special kind of loop for traversing through an SQL result set one row at a time. That
allows you to perform operations on every record on a one-by-one basis. Just like loops, cursors are
only supported within stored procedures and functions.
Id Mark Id Mark
38055 90
38125 83
38131 80
Id Mark
38055 87
38131 74
Let, you have these three tables. You have two exams marks for same
students in two tables for a subject. Now you want to save each students
highest mark for that subject in your 38153 95 final table. For example Id 38055 get
90 and 87 in two exams of same subject. So in case of Id 38055 the highest mark 90 will be stored in
final table. So, let's create a procedure which will use two cursor to complete this task.
Page- 198
Chapter Eight Database Management System
CLOSE cur1;
CLOSE cur2;
END;
Table: Cursor Example
call cursorMarksProc();
Now you will get the result in the studentmarksfinal table like below:
Id Mark
38048 90
38054 85
38126 80
Page- 199
Chapter Eight Database Management System
38152 95
Table: studentmarksfinal
Primary Key
The Primary key constraint uniquely identifies each record in a database table. Every database table
should have one or more columns designated as the primary key. The value this key holds should be
unique for each record in the database. For example, assume you have a table called
studentinformation that contains personal information for every student in your class You need to
select an appropriate primary key that would uniquely identify each student. Your first thought might be
to use the student's name. This wouldn't work out very well because it is conceivable that you may find
two students with same name. A better choice might be to use a unique student ID number that is
assigned to each student when they’re admitted.
Page- 200
Chapter Eight Database Management System
So, you have to make Id column as a primary key to identify each student uniquely. Id is seleccted
because it is impossible to have two students with same Id.
Once you have decided upon a primary key and set it up in the database, the database management
system will enforce the uniqueness of the key. If you try to insert a record into a table with a primary
key that duplicates an existing record, the insert will fail.
Foreign Key
In context of relational databases, a foreign key is a field (or collection of fields) in one table that
uniquely identifies a row of another table. In simpler words, the foreign key is defined in a second table,
but it refers to the primary key in the first table.
Foreign keys are used to create relationships between tables. Natural relationships exist between tables
in most database structures. Returning to your database, remember that you have studentinformation
and studentmarks tables. You want that the studentmarks table will contain only those student's marks
whose information are in the studentinformation table.
Page- 201
Chapter Eight Database Management System
With this foreign key it is restricted that the id of studentmarks must be in studentinformation list.
Execute the following two statements.
So now studentinformation table contains two ID 38126 and 33152. Now if you execute
It will create error as 38048 is not in studentinformation table. But these two statement will execute
successfully.
Again if you want to delete the mark of Id 38126 from studentmarks table it will create error. Because
you have to delete 38126 id from studentinformation table. And as there is on delete cascade integrity
constraint it will be automatically removed from studentmarks table.
Page- 202
Chapter Eight Database Management System
Data Model
A data model in software engineering is an abstract model, that documents and organizes the business
data for communication between team members and is used as a plan for developing applications,
specifically how data is stored and accessed.
According to Hoberman (2009), "A data model is a wayfinding tool for both business and IT
professionals, which uses a set of symbols and text to precisely explain a subset of real information to
improve communication within the organization and thereby lead to a more flexible and stable
application environment."
A data model explicitly determines the structure of data or structured data. Typical applications of data
models include database models, design of information systems, and enabling exchange of data.
Usually data models are specified in a data modeling language.
Communication and precision are the two key benefits that make a data model important to applications
that use and exchange data. A data model is the medium which project team members from different
backgrounds and with different levels of experience can communicate with one another. Precision
means that the terms and rules on a data model can be interpreted only one way and are not ambiguous.
A data model can be sometimes referred to as a data structure, especially in the context of programming
languages. Data models are often complemented by function models, especially in the context of
enterprise models.
Page- 203
Chapter Eight Database Management System
Database Administrator
A database administrator (short form DBA) is a person responsible for the design, implementation,
maintenance and repair of an organization's database. They are also known by the titles Database
Coordinator or Database Programmer, and is closely related to the Database Analyst, Database
Modeller, Programmer Analyst, and Systems Manager. The role includes the development and design
Page- 204
Chapter Eight Database Management System
of database strategies, monitoring and improving database performance and capacity, and planning for
future expansion requirements. They may also plan, co-ordinate and implement security measures to
safeguard the database. Employing organizations may require that a database administrator have a
certification or degree for database systems (for example, the Microsoft Certified Database
Administrator). Some organizations have a hierarchical level of database administrators, generally:
Data Analysts/Query designers
Junior DBAs
Midlevel DBAs
Senior DBAs
DBA consultants
Manager/Director of Database Administration/Information Technology
Page- 205
Chapter Eight Database Management System
Data Warehouse
In computing, a data warehouse (DW) is a database used for reporting and analysis. The data stored in
the warehouse is uploaded from the operational systems. The data may pass through an operational data
store for additional operations before it is used in the DW for reporting.
A data warehouse maintains its functions in three layers: staging, integration, and access. Staging is
used to store raw data for use by developers. The integration layer is used to integrate data and to have
a level of abstraction from users. The access layer is for getting data out for users.
This definition of the data warehouse focuses on data storage. The main source of the data is cleaned,
transformed, catalogued and made available for use by managers and other business professionals for
data mining, online analytical processing, market research and decision support (Marakas & O'Brien
2009). However, the means to retrieve and analyze data, to extract, transform and load data, and to
manage the data dictionary are also considered essential components of a data warehousing system.
Many references to data warehousing use this broader context. Thus, an expanded definition for data
warehousing includes business intelligence tools, tools to extract, transform and load data into the
repository, and tools to manage and retrieve metadata.
Data Mining
Generally, data mining (sometimes called data or knowledge discovery) is the process of analyzing data
from different perspectives and summarizing it into useful information - information that can be used to
increase revenue, cuts costs, or both. Data mining software is one of a number of analytical tools for
analyzing data. It allows users to analyze data from many different dimensions or angles, categorize it,
and summarize the relationships identified. Technically, data mining is the process of finding
correlations or patterns among dozens of fields in large relational databases.
Data mining consists of five major elements:
Extract, transform, and load transaction data onto the data warehouse system.
Store and manage the data in a multidimensional database system.
Provide data access to business analysts and information technology professionals.
Analyze the data by application software.
Present the data in a useful format, such as a graph or table.
Page- 206
Chapter Eight Database Management System
Database Security
Database security concerns the use of a broad range of information security controls to protect
databases (potentially including the data, the database applications or stored functions, the database
systems, the database servers and the associated network links) against compromises of their
confidentiality, integrity and availability. It involves various types or categories of controls, such as
technical, procedural/administrative and physical. Database security is a specialist topic within the
broader realms of computer security, information security and risk management.
Security risks to database systems include, for example:
Unauthorized or unintended activity or misuse by authorized database users, database
administrators, or network/systems managers, or by unauthorized users or hackers (e.g.
inappropriate access to sensitive data, metadata or functions within databases, or inappropriate
changes to the database programs, structures or security configurations);
Malware infections causing incidents such as unauthorized access, leakage or disclosure of
personal or proprietary data, deletion of or damage to the data or programs, interruption or
denial of authorized access to the database, attacks on other systems and the unanticipated
failure of database services;
Overloads, performance constraints and capacity issues resulting in the inability of authorized
users to use databases as intended;
Physical damage to database servers caused by computer room fires or floods, overheating,
lightning, accidental liquid spills, static discharge, electronic breakdowns/equipment failures
and obsolescence;
Design flaws and programming bugs in databases and the associated programs and systems,
creating various security vulnerabilities (e.g. unauthorized privilege escalation), data
loss/corruption, performance degradation etc.;
Data corruption and/or loss caused by the entry of invalid data or commands, mistakes in
database or system administration processes, sabotage/criminal damage etc.
Page- 207
Chapter Eight Database Management System
Practice Example
create table zipcodes (
zip integer(5) primary key,
city varchar(30),
State varchar(20));
Page- 208
Chapter Eight Database Management System
insert into customers values (23511, 'Michelle Kuan', '123 Main St.',98225, '360-636-5555');
insert into customers values (23512, 'George Myer', '237 Ash Ave.',95124, '312-678-5555');
insert into customers values (23513, 'Richard Gold', '111 Inwood St.',95124, '312-883-7337');
insert into customers values (23514, 'Robert Smith', '54 Gate Dr.',95388, '206-832-1221');
insert into customers values (23515, 'Christopher David', '777 Loto St.',98225, '360-458-9878');
insert into customers values (23516, 'Adam Beethoven', '234 Park Rd..',95380, '209-546-7299');
insert into customers values (23517, 'Lidwig Bach', '5790 Walnut St.',95382, '209-638-2712');
insert into odetails values (1020, 10506,1); insert into odetails values (1020, 10507,2);
insert into odetails values (1020, 10508,2); insert into odetails values (1020, 10509,3);
insert into odetails values (1021, 10601,4); insert into odetails values (1022, 10601,1);
insert into odetails values (1022, 10701,2); insert into odetails values (1023, 10800,4);
insert into odetails values (1023, 10900,1); insert into odetails values (1024, 10900,7);
Page- 209
Chapter Eight Database Management System
Practical Exercise
1. Suppose you have created a table named cars. Now change the table using SQL query
following the instructions given below:
create table cars a) Add another column named 'tyre' to the table which can
( contain maximum 20 characters.
md_num integer, b) Modify 'md_name' and 'style' columns so that they can
md_name varchar(10), contain 30 characters instead of 10.
style varchar(10), c) Rename column name 'year' to 'made_year'.
year integer d) Drop column 'tyre' from the table.
); e) Drop the table.
2. Read the table 'StudentInfo' and answer the following questions using SQL query:
a) Insert marks of Alamin, Samia and Shafik into the table StudentInfo.
b) Update student's name to Nusrat, Mardia and Laila where student id is 12,13 and 14
respectably.
c) Delete information from the table whose StudentId is 16.
3. Read the 'Students' table and answer the following questions using SQL query:
a) Let you want to hide mobile number of SAD students. So create a view of SAD students
named 'sadstudent' excluding 'Mobile' column from the above Students table.
b) Find the student's name whose student id is 13 using the created view.
Page- 210
Chapter Eight Database Management System
4. Read the 'Order' table and answer the following questions using SQL query:
a) Count the number of orders from customer 'Rinky' [hint: use count()].
b) Find the total order of each customer [hint: use sum() and group by].
c) Find if any of the customers have a total order of less than 200 [hint: use sum(), group by
and having].
Exercise
1. What is Data, Database and Database Management System.
2. What is Relational Database? What are the Properties of Relation.
3. Briefly describe Primary and Foreign Key with example.
4. Describe Data Models with figure.
5. Write short note on DML, DCL and TCL.
6. What are the Signs of Good Database Design.
7. What is Database administrator? What are the duties of Database Administrator.
8. What is data Warehouse. Write some Benefits of Data Warehouse
9. Write short note on Database Security.
Page- 211