Vous êtes sur la page 1sur 27

Chapter Eight Database Management System

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

In this chapter you will learn about:

 Data, Database and Database Management System(DBMS)


 Application Areas of DBMS
 Advantages of DBMS
 RDMS Terminology
 Relational Data Structure
 Properties of Relation
 DDL, DML, DCL, TCL
 Structured Query Language
 Procedure, Function, Trigger, Cursor
 Primary and Foreign Key
 Data Model
 Database Security

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.

 Administration: Registering and monitoring users, enforcing data security, monitoring


performance, maintaining data integrity, dealing with concurrency control, and recovering
information that has been corrupted by some event such as an unexpected system failure

Page- 186
Chapter Eight Database Management System

Application areas of DBMS

 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.

 Universities: For student information, course registrations, and grades.

 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.

 Sales: For customer, product, and purchase information.

 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:

 Data abstraction and independence


 Data security

Page- 187
Chapter Eight Database Management System

 A locking mechanism for concurrent access

 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

 Robust data integrity capabilities

 Logging and auditing of activity

 Simple access using a standard application programming interface (API)

 Uniform administration procedures for data

Relational Database Management System

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:

 Database: A database is a collection of tables, with related data.


 Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.

 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

 Redundancy: Storing data twice, redundantly to make the system faster.

 Index: An index in a database resembles an index at the back of a book.

 Referential Integrity: Referential Integrity makes sure that a foreign key value always points
to an existing row.

Relational Data Structure

 Relation: A relation is a table with columns and rows.


 Attribute: An attribute is a named column of a relation.
 Tuple: A tuple is a row of a relation.
 Domain: A domain is the set of allowable values for one or more attributes.
 Degree: The degree of a relation is the number of attributes it contains.
 Cardinality: The cardinality of a relation is the number of tuples it contains.
 Relational database: A collection of normalized relations with distinct relation names.

Properties of Relations

A relation has the following properties:


 The relation has a name that is distinct from all other relation names in the relational schema.
 Each cell of the relation contains exactly one atomic (single) value.

 Each attribute has a distinct name.

 The values of an attribute are all from the same domain.

 Each tuple is distinct; there are no duplicate tuples.

 The order of attributes has no significance.

 The order of tuples has no significance, theoretically.

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:

o uniqueness – in each tuple of R, the values of K uniquely identify that tuple.

o irreducibility – no proper subset of K has the uniqueness property.


Page- 189
Chapter Eight Database Management System

 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:

INSERT - insert data into a table


SELECT - retrieve data from the a database
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
CALL - used to call a procedure

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

Structured query language

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.

CREATE DATABASE studentdb;

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:

The column_name parameters specify the names


CREATE TABLE table_name of the columns of the table.
(
column_name1 data_type(size), The data_type parameter specifies what type of
column_name2 data_type(size), data the column can hold (e.g. varchar, integer,
column_name3 data_type(size), decimal, date, etc.).
....
); The size parameter specifies the maximum length
of the column of the table.
Suppose, you want to store the following students information in your database. You have each
student's id, first name, last name, email address and phone number.

Id FirstName LastName Email Phone

38048 Amlan Roy amlan.roy@bu.edu.bd 014138048

Page- 191
Chapter Eight Database Management System

38054 Sultana Arafa Sathi arafa.sathi@bu.edu.bd 014138054

38126 Noman Al Rabbi noman.rabbi@bu.edu.bd 014138126

38152 Md. Rayhanuzzaman Roky md.roky@bu.edu.bd 014138152

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.

Data type of Id and Phone are set to integer as


CREATE TABLE StudentInformation they will store numbers and their size set to 12.
(
Id integer(12), Other columns data type are set to varchar as
FirstName varchar(100), they will contain strings and their size set to 100.
LastName varchar(100),
Email varchar(100), Lots of data type are there like tinyint, bit, real,
Phone integer(12) double, char, date, time, year, timestamp,
); datetime, blob etc.

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.

ALTER TABLE StudentInformation ADD COLUMN Batch integer(12);

You can also modify the column in your need by executing below statement

ALTER TABLE StudentInformation MODIFY COLUMN Batch integer(30);

If you want to rename your Batch column into BatchId then you have to execute the following
statement.

ALTER TABLE StudentInformation CHANGE BatchId batchid integer;

Now if you want to delete the column BatchId then you have to execute the below statement

ALTER TABLE StudentInformation drop COLUMN BatchId;

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.

INSERT INTO studentinformation VALUES (38054,'Sultana Arafa', 'Sathi',


'arafa.sathi@bu.edu.bd', 014138054);

INSERT INTO studentinformation VALUES (38126,'Noman Al', 'Rabbi',


'noman.rabbi@bu.edu.bd', 014138126);

INSERT INTO studentinformation VALUES (38152,'Md. Rayhanuzzaman', 'Roky',


'md.roky@bu.edu.bd', 014138152);

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.

SELECT * FROM studentinformation;

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.

SELECT * FROM studentinformation WHERE Id=38126;

If you use * then all the column will display. For specific column you can specify it in the SELECT
statement.

SELECT FirstName, Email FROM studentinformation WHERE Id=38152;

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.

UPDATE studentinformation SET Email='sultana.arafa@bu.edu.bd' WHERE Id=38054;

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.

DELETE FROM studentinformation WHERE Id=38126;

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

DELETE FROM studentinformation;

You can also use TRUNCATE to delete data from table.

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

SELECT studentinformation.FirstName, studentmarks.Mark FROM studentinformation,


studentmarks WHERE studentinformation.id = studentmarks.id;

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.

SELECT studentinformation.FirstName, studentmarks.Mark FROM studentinformation JOIN


studentmarks ON studentinformation.id = studentmarks.id;

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.

CREATE view namewisemarks AS


SELECT studentinformation.FirstName, studentmarks.Mark FROM studentinformation JOIN
studentmarks ON studentinformation.id = studentmarks.id;

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.

SELECT * FROM namewisemarks;

And the above query produce same output as previous.

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.

There are three types of parameter:


 IN: The default. This parameter is passed to the procedure, and can change inside the
procedure, but remains unchanged outside.
 OUT: No value is supplied to the procedure (it is assumed to be NULL), but it can be modified
inside the procedure, and is available outside the procedure.
 INOUT: The characteristics of both IN and OUT parameters. A value can be passed to the
procedure, modified there as well as passed back again.

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.

CREATE FUNCTION getResultFunc(uid INT) The select statement is


RETURNS INT defined inside the
BEGIN function. This function
DECLARE umark INT; takes one parameter and
SELECT Mark INTO umark FROM studentmarks WHERE Id=uid; using this it fetches mark
from the table and return
RETURN umark; the result.
END
Table: Function Example

Now execute the statement SELECT getResultFunc(38126);

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.

A trigger can be defined to be invoked in the following scenario:


 BEFORE INSERT – activated before data is inserted into the table.
 AFTER INSERT– activated after data is inserted into the table.
 BEFORE UPDATE – activated before data in the table is updated.
 AFTER UPDATE – activated after data in the table is updated.
 BEFORE DELETE – activated before data is removed from the table.
 AFTER DELETE – activated after data is removed from the table.

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.

CREATE TRIGGER after_studentinformation_insert This trigger will invoke


AFTER INSERT ON studentinformation after insert statement
FOR EACH ROW BEGIN execution in
INSERT INTO studentmarks (Id, Mark) VALUES (NEW.Id,40); studentinformation table.

Page- 197
Chapter Eight Database Management System

END
Table: Trigger Example

So, execute the following statement now.

INSERT INTO studentinformation VALUES (38125,'Sharmin Sultana', 'Poly',


'sharmin.poly@bu.edu.bd', 014138125);

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

38153 92 Table: studentmarksalt

Id Mark

38055 87

Table: studentmarks 38125 85 Table: studentmarksfinal

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.

CREATE PROCEDURE cursorMarksProc() This procedure

Page- 198
Chapter Eight Database Management System

BEGIN fetch data both


DECLARE done INT DEFAULT FALSE; from tables
DECLARE id1,mark1 INT; studentmarks
DECLARE id2,mark2 INT; and
DECLARE cur1 CURSOR FOR SELECT Id,Mark FROM studentmarks; studnetmarksalt
DECLARE cur2 CURSOR FOR SELECT Id,Mark FROM studentmarksalt; and using
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = cursors and loop
TRUE; compare the
marks and store
OPEN cur1; the highest mark
OPEN cur2; in
studentmarksfina
read_loop: LOOP l table.
FETCH cur1 INTO id1,mark1;
FETCH cur2 INTO id2,mark2;
IF done THEN
LEAVE read_loop;
END IF;
IF mark1 < mark2 THEN
INSERT INTO studentmarksfinal VALUES (id2,mark2);
ELSE
INSERT INTO studentmarksfinal VALUES (id1,mark1);
END IF;
END LOOP;

CLOSE cur1;
CLOSE cur2;
END;
Table: Cursor Example

Your procedure is ready. Now execute the following statement.

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

Deleting From Database

Use the following queries to complete your desired task.

DROP DATABASE dropdb; // here dropdb is the name of the database;

DROP TABLE droptable; // here droptable is the name of the table

DROP VIEW dropview; // here dropview is the name of the view

DROP PROCEDURE dropproc; // here dropproc is the name of the procedure

DROP FUNCTION dropfunc; // here dropfunc is the name of the function

DROP TRIGGER droptrig; // here droptrig is the name of the trigger

More about Database Keys


You already know that databases use tables to organize information. Each table consists of a number of
rows, each of which corresponds to a single database record. So, how do databases keep all of these
records straight? Then the idea came of using keys.

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.

Id FirstName LastName Email Phone

Page- 200
Chapter Eight Database Management System

38055 Sanjida Chowdhuri sanjida.chowdhuri@bu.edu.bd 014138055

38125 Sharmin Sultana Poly sultana.poly@bu.edu.bd 014138125

38131 Mir Tasmima Awol tasmima.awal@bu.edu.bd 014138131

38153 Mst. Najnin Akter najnin.akter@bu.edu.bd 014138153


Table: studentinformation

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.

CREATE TABLE studentinformation INSERT INTO studentinformation VALUES (38125,


( 'Sharmin Sultana ','Poly', sharmin.sultana@bu.edu.bd',
Id integer(12), 014138054);
FirstName varchar(100),
LastName varchar(100), Will insert a row. But if you try again
Email varchar(100),
Phone integer(12), INSERT INTO studentinformation VALUES (38125,
'Sharmin Sultana ','Poly', sharmin.sultana@bu.edu.bd',
PRIMARY KEY (Id) 014138054);
);
It will fail because it will find duplicate value in Id column.

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

CREATE TABLE studentmarks(


Id integer(12), Here Id is defined as
Mark integer(12), foreign key and
referenced with the Id
PRIMARY KEY (Id), of the table
studentinformation.
FOREIGN KEY (Id) Also on delete
REFERENCES cascade ensures that
StudentInformation(Id) ON DELETE if parent Id is deleted
CASCADE then all its references
); will be deleted
automatically.

With this foreign key it is restricted that the id of studentmarks must be in studentinformation list.
Execute the following two statements.

INSERT INTO studentinformation VALUES (38126,'Noman Al','Rabbi',


'noman.rabbi@bu.edu.bd',014138126);

INSERT INTO studentinformation VALUES (38152,'Md. Rayhanuzzaman', 'Roky',


'md.roky@bu.edu.bd',014138152);

So now studentinformation table contains two ID 38126 and 33152. Now if you execute

INSERT INTO studentmarks (Id, Mark) VALUES (38048,90);

It will create error as 38048 is not in studentinformation table. But these two statement will execute
successfully.

INSERT INTO studentmarks VALUES (38126,80);

INSERT INTO studentmarks VALUES (38152,95);

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.

Types of Data Models


1. Database model
A database model is a theory or specification describing how a database is structured and used.
Several such models have been suggested.

Figure 8.1: Flat Model Figure 8.2: Hierarchical Model

Page- 203
Chapter Eight Database Management System

Figure 8.3: Network Model Figure 8.4: Relational Model


 Flat model: This may not strictly qualify as a data model. The flat (or table) model consists of
a single, two-dimensional array of data elements, where all members of a given column are
assumed to be similar values, and all members of a row are assumed to be related to one another.
 Hierarchical model: In this model data is organized into a tree-like structure, implying a
single upward link in each record to describe the nesting, and a sort field to keep the records in a
particular order in each same-level list.
 Network model: This model organizes data using two fundamental constructs, called records
and sets. Records contain fields, and sets define one-to-many relationships between records: one
owner, many members.
 Relational model: is a database model based on first-order predicate logic. Its core idea is to
describe a database as a collection of predicates over a finite set of predicate variables, describing
constraints on the possible values and combinations of values.
 Object-relational model: Similar to a relational database model, but objects, classes and
inheritance are directly supported in database schemas and in the query language.
 Star schema is the simplest style of data warehouse schema. The star schema consists of a few
"fact tables" (possibly only one, justifying the name) referencing any number of "dimension
tables". The star schema is considered an important special case of the snowflake schema.

Fig 8.11: Object Relational Model

Figure 8.5: Star Schema

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

Duties of Database Administrator


A database administrator's activities can be listed as below:
 Transferring Data
 Replicating Data
 Maintaining database and ensuring its availability to users
 Maintaining the data dictionary
 Controlling privileges and permissions to database users
 Monitoring database performance
 Database backup and recovery
 Database security

Signs of Good Database Design


 Works for the intended situation and purpose
 Streamlines a process
 Shows consistency among data (Fall 05 vs. fall 2005)
 Eliminates redundancy as much as possible, i.e. tables are normalized
 Provides users with an easy way to enter, store, and retrieve data
 Does NOT promote deleting data, but rather making designations or archiving it
 Provides unique identifiers (primary keys) for records
 Grows, changes, and improves as needed

Considerations for Implementation in a Multi-User Environment


 Who will administer the database? An individual? A group or committee?
 Are shared folders being used?
 Is server space needed? If so, is it available and where?
 Are web capabilities required (intranet and/or internet)? If so, is Web space
available?
 Is security an issue? If so, how will that be handled?

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.

Benefits of a Data Warehouse


A data warehouse maintains a copy of information from the source transaction systems. This
architectural complexity provides the opportunity to:
 Maintain data history, even if the source transaction systems do not.
 Integrate data from multiple source systems, enabling a central view across the enterprise. This
benefit is always valuable, but particularly so when the organization has grown by merger.
 Improve data, by providing consistent codes and descriptions, flagging or even fixing bad data.
 Present the organization's information consistently.
 Provide a single common data model for all data of interest regardless of the data's source.
 Restructure the data so that it makes sense to the business users.
 Restructure the data so that it delivers excellent query performance, even for complex analytic
queries, without impacting the operational systems.
 Add value to operational business applications, notably customer relationship management
(CRM) systems.

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));

insert into zipcodes values (98225, 'Bellingham', 'WA');


insert into zipcodes values (95388, 'Winton', 'CA');
insert into zipcodes values (44242, 'Stow', 'OH');
insert into zipcodes values (61536, 'Hanna city', 'IL');
insert into zipcodes values (01254, 'Richmond', 'MA');
insert into zipcodes values (95124, 'San Jose', 'CA');
insert into zipcodes values (95382, 'Turlock', 'MA');
insert into zipcodes values (95380, 'Turlock', 'CA');

create table employees (


eno varchar(10) primary key,
ename varchar(30),
zip integer(5) references zipcodes,
hire_date date);

insert into employees values ('P0239400', 'Jones Hoffer',98225, '2000-12-12');


insert into employees values ('P0239401', 'Jeffrey Prescott',95388, '2006-01-01');
insert into employees values ('P0239402', 'Fred NcFaddeb',95124, '2008-09-01');

create table books (


bno integer(5) primary key,
bname varchar(30),
qoh integer(5) not null,
price dec(6,2) not null);

insert into books values (10506, 'Accounting 101',200, 129.99);


insert into books values (10507, 'Management 101',159, 109.99);
insert into books values (10508, 'Fraud Cases',190, 179.99);
insert into books values (10509, 'CPA Review',65, 299.99);
insert into books values (10601, 'Peachtree for Dummies',322, 49.99);
insert into books values (10701, 'Financial Accounting',129, 164.99);
insert into books values (10800, 'Managerial Accounting',155, 114.99);
insert into books values (10900, 'Cost Accounting',122, 119.99);
insert into books values (10901, 'Intermediate Accounting',123, 164.99);
insert into books values (10902, 'XBRL in Nutshell',124, 109.99);

Page- 208
Chapter Eight Database Management System

create table customers (


cno integer(5) primary key,
cname varchar(30),
street varchar(30),
zip integer(5) references zipcodes,
phone char(12));

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');

create table orders (


ono integer(5) primary key,
cno integer(5) references customers,
eno varchar(10) references employees,
received date,
shipped date
);

insert into orders values (1020, 23511, 'P0239400', '2009-10-18', '2009-10-20');


insert into orders values (1021, 23511, 'P0239400', '2009-10-29', '2009-10-31');
insert into orders values (1022, 23512, 'P0239401', '2009-11-10', '2009-11-13');
insert into orders (ONO, CNO, ENO, RECEIVED) values (1023, 23513, 'P0239402', '2009-11-15');
insert into orders (ONO, CNO, ENO, RECEIVED) values (1024, 23511, 'P0239400', '2009-11-16');

create table odetails (


ono integer(5) references orders,
bno integer(5) references books,
quantity integer(10) not null,
primary key (ono, bno));

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:

StudentId StudentName Marks Grade


11 Hemel 80 A
12 Azam 70 B
13 Tamal 60 C
14 Soheli 50 D
15 Istiak 40 E
16 Amrika 30 F

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:

StudentId StudentName Mobile CourseId


12 Sagor 01123 SAD
13 Sadia 01745 SAD
14 Runa 01567 SAD
15 Shamol 01689 SE
16 Shuvo 01810 SE
17 Farhana 01911 SE

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:

OId OrderDate OrderPrice Customer


1 2014/6/11 40 Rinky
2 2014/7/14 100 Pinky
3 2014/7/16 300 Rinky
4 2014/7/21 500 Sabet
5 2014/8/10 60 Rinky
6 2014/9/10 60 Nazmul
7 2014/9/16 40 Joy

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.

---- The End ---

Page- 211

Vous aimerez peut-être aussi