DBMS Hints Final

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

I YEAR

II SEM
DATA BASE MANAGEMENT SYSTEM

S. SURESH , M.COM., B.Ed.,


ASSISTANT PROFESSOR IN COMMERCE (CA)
AVS ARTS & SCIENCE COLLEGE, OMALUR
B.COM. (COMPUTER

APPLICATION) SEMESTER – II

ALLIED II - DATABASE MANAGEMENT SYSTEM

UNIT –I

Introduction: Database System Application – Purpose of Database System – View of Data – Data Model – Database
Language – Relational Database – Database Design – Data Storage and Query – Transaction Management – Database
Architecture - Database User and Administrator. – History of DatabaseSystem.

UNIT–II:

Relational Database: Structure of Relational Databases – Database Schemas – Keys – Schema Diagrams - Relational Query
Language. SQL: Overview of the SQL Query Language – SQL Data Definition –Basic Structure of SQL Queries- Set
operations – Null Values –Aggregate Functions – Nested Sub queries –Modification of the Database.

UNIT– III:

Intermediate SQL: Join Expressions – View – Transactions-Authorization. Advance SQL: Functions and Procedures –
Triggers - Formal Relational Queries Languages: The Relational Algebra – The TupleRelational Calculus –The Domain
Relational Calculus.

UNIT– IV:

Database Design and the E-R Model: Overview of the Data Process – The Entity-Relationship Model – Constraints - Entity-
Relationship Diagram - Entity-Relationship Design Issues – Extended E-R Features.Relational Database Design: Atomic
Domain and First Normal Form –Decomposition using Functional Dependency - Functional Dependency Theory -
Decomposition using Multivalued Dependencies – More Normal Form.

UNIT-V:

Database System Architectures: Centralized and Client-System Architectures – Server System Architectures – Parallel
Systems – Distributed Systems – Network Types. Distributed Databases: Homogeneous and Heterogeneous Databases -
Distributed Data Storage - Distributed Transaction - CommitProtocols –Cloud Based Databases – Directory Systems.

TEXTBOOK:

1. ―Database System Concepts‖ -Abraham Sliberschatz, Henery F.Korth, S.Sudarshan, 6th Edition. MC Graw Hill
International Edition

1
UNIT- I
INTRODUCTION:

 A Data base management system (DBMS) is a collection of interrelated data and a set of programs to
access those data.
 The collection of data usually referred to of as the database, contains information to an enterprise.

GOALS:

 To provide a way to store and retrieve database information that is both convenient and efficient.

DATABASE –SYSTEM APPLICATIONS:

Enterprise information (sales, Accounting, HR, Manufacturing0

Banking and Finance

Universities

Airlines and telecommunication

PURPOSE OF DATABASE SYSTEM:

 Database systems arose in response to early methods of computerized management of commercial


data.
Example: University Organization
 Add new students, instructors, and courses
 Register students for courses and generate class rosters
 Assign grades to students, compute grade point average (GPA)

MAJOR DISADVANTAGES:
Difficulty in
accessing data

Data redundancy
data isolation
and inconsistency

Concurrent-
security problems
access anomalies

2
VIEW OF DATA:

Examples: type instructor=record


ID: Char (5):
name: char (20);
dept_name: char (20);
salary: numeric (8,2):
end;

STORY TIME

Edmund Thomas Clint was an Indian child prodigy known for having
drawn over 25,000 painting during his life of less seven years.

DATA MODEL:

 A data model provides a way to describe the design of a database at the physical, logical and view
levels.

3
Relational Model

Entity-Relationship
Model

Object-Based Data
Model

Semistructured Data
Model

DATABASE LANGUAGE:

1. Data-Manipulation Language
It is language that enables users to access or manipulate data as
organized by the approprite data model
There are basically two types
ex: select instructor. ID, department.dept_name
from instructor, department 1. Procedural DML's
where instructor. dept_name=department.dept_name and 2. Declarative DML's
department.budget>95000;

2. Data-Definition Language
We specify a database schema by a set of definitions expressed
by a special language called it
They are Four types
example: create table department
(dept_name char(20), 1. Domain Constraints 3. Assertions.
building char)15), 2. Referential Integrity 4. Authorization
budget char(12,2);

4
RELATIONAL DATABASE:

 A relational database is based on the relational model and uses a collection of tables of represent both
data the relationship among those data.
 Each table has multiple columns and each column has a unique name.

ID name salary
10001 Santhosh 100000
10002 Vijay 90000
10003 Selvaraj 85000
10004 Bharani 120000
10005 Guberan 50000
10006 Kamalraj 70000
10007 kannan 50000

DATABASE DESIGN:

 Database systems are designed to manage large bodies of information


 Database design mainly involves the design of the database schema
 The design of a complete database application environment that meets the needs of enterprise
being modelled requires attention to a set of issues.

Database The Entity-


Design Desing for a Relationship
Process University Model
Org.

Instructor Department
ID Dept_name
Member Building
Name
Salary budget
A sample E-R diagram
DATA STORAGE AND QUERYING:

 A database system is partitioned into modules that deal with each of the responsibilities of
the overall system.
 It can be broadly divided into the Storage manager and the query processor.

1. Storage manger:
 The component of a database system that provides the interface between the
low-level data stored in database and the application programs and queries
submitted to the system.
 SM is responsible for interaction
5
 The Raw data are stored on the disk using OS
 The SM translates the various DML statement into low-level file system
commends

Authorization and integrity manager

Transaction manager

File manager

Buffer manager

2. The Query Processor:

Query
DDL DML
evaluation
interpreter compiler
engine

TRANSACTION MANAGEMENT:

 Several operations on the database form a single logical unit of work.


 Example: Fund transfer
 Which one department a/c (A) is debited another department a/c (B) is credited
 Atomicity – all or none requirement
 Consistency – correctness requirements
 Durability – persistence requirements

DATABASE ARCHITECTURE:

 The architecture of a database system is greatly influenced by the underlying computer system on
which the database system runs.
 It can be centralized, or client-server, where one server machine executes work on behalf of multiple
machines.
 It’s usually partitioned into two or three parts.

1. Two-tier architecture
6
 The application resides at the client machine, where in invokes database system
functionally at the server machine through query language statements.

2. Three-tier architecture
 The client machine acts as merely a front end and does not contain any direct database
calls.
 Instead, the client end communicates with an application server, usually through a forms
interface.

STORY TIME:

Babar Ali is a teacher from Murshidabad is west Bengal. He was called the
“Youngest Headmaster” in the world”.

DATABASE USERS AND ARMINISTRATORS:

 People who work with a database can be categorized as database users or database administrators.
1. Database users and user interfaces
It’s differentiated by the way they expect to interact with system.
Different types of user interfaces have been designed for the different types of users.

7
•It's unsophisticated users who interact with the system by invoking one of the application programs that have
been writtent previously
Naive users

•Are computer professionals who write application programs.


Application
progrmmers

•It intract with the system without writing programs.


Sophisticated
users

•They are sophisticated users who write specialized database applications that do not fit into the tradtional data-
Specialized processing framework Ex: graphics data and audio data
users

2. Database Administrator
A person who has such central control over the system is called a database administrator
(DBA).

Schema definition

Storage structure and access-method definition

Schema and Physical-orgnization modification.

Granting of quthorization for data access

Routine maintenance

8
HISTORY OF DATABASE SYSTEMS:

Magnetic Widespread Relational SQl language XML and


tapes were use of hard and was designed query
developed for disk Hierarchical and WWW language
data storage. database (worl wide XQuery
1950s & 1960s

Early 1990s
1980s

2000s
Late 1960s & 1970s

web)

UNIT – I Completed

9
UNIT – II
RELATIONAL MODEL:
INTRODUCTION:

 The relational model in DBMS is an abstract model used to organize and manage the data stored in
database.
 It stores data in two-dimensional inter-related tables
 Row - each represents an entity
 Column – each represents the properties of the entity

MEANING:

 It is an approach to logically represent and manage the data stored in a database.


 In this model, the data is organized into a collection of two dimensional inter-related tables, also
known as relations.
 Each relation is a collection of columns and rows
 Where the column represents the attributes of an entity and the row (or tuple) resents the record.

Highlights:

1. Relational model stores the data into tables (relations)


2. It makes data sorting and data access easier
3. Provides a standard way to organize data in database.

10
RELATIONAL MODEL CONCEPTS:

 This database consists of various components based on the relational model. These include.

• Two dimensional used to stored a collection of data


1.Relation element

• Row of the relation


2. Tuple

• Column of the relation


3. Attribute/Field

• Set of pre-defined atomic value that an attribute can


4. Attribute Domain take

• It is the total No of attributes present in the relation


5. Degree

• It specifies the No of entities invovled in the relation


6.Cardinality

• It is logical blueprint of the relation


7. Relational Schema • i.e., it descripes the design and the structure of the
relation

• It is the collection of records present in the relation at a


8. Relation Instance given time

• It is an attribute or a group of attributes that can be used


9. Relation Key to uniquely identify and entity in a table

11
1.Candidate Key

Types of Relation Key


2. Super Key

3. Composite
Key

4. Primary Key

5. Alternate Key

6. Foreign Key

STORY TIME:

Thamos Alva Edison was an American inventor and business man.

DATABASE SCHEMA:
A database schema is the skeleton structure that represents the logical view of the entire
database.
It defines how the data is organized and how the relations among them are associate.
It’s the database designers who design the schema to help programmers understand the
database and make it useful.

12
CATEGORIES:
 A database schema can be divided broadly into two categories

1. Physical Database 2. Logical Database


Schema Schema
•It difines how the data will •It's difnes all the logical
be stored in a secondary constraints that need to be
storage. applied on the data stored.

DATABASE INSTANCE:
 A database instance is a state of operational database with data at any given time.
 It contains a snapshot of the database.
 Database instance tend to change with time

SCHEMA DIAGRAMS:

 A database schema, along with primary key and foreign key dependencies, can be depicted by
schema diagram.

13
 Primary Key attributes are shown underline.
 Foreign key dependencies appear as arrow

RELATIONAL QUERY LANGUAGES:


 Relational algebra is used to break the user and instruct the DBMS to execute them.
 Relational query language is used by the to communicate with the database.
 This is further divide into two types

Non-Procedural
Language
Procedural Query • The user outline the
desired information
Language without giving a specific
• The user instructs the procedure for attaining
system to perform a set the information.
of operations on the
database to determine
the desired results.

14
STORY TIME:

SQL QUERY LANGUAGES:


INTRODUCTION:
 SQL stands for Structure Query Languages.
 It is used for storing and management data in relational database management system (RDBMS)
 It is a standard language for RDBMS.
 It enables a user to create, read, update and delete RDBMS.

DEFINITION:
 The set of relations in a database must be specified to the system by means of a DDL.
 It’s allows specification of not only a set of relations, but also information about each relation.

SQL DATA TYPE:

 SQL data type is used to define the value that a column can contain.
 Every column is required to have name and data type in DB tables

1. Binary Datatype

2. Approximate Numeric Datatype


Binary (max 8000
bytes FL)
3. Exact Numeric Datatype
Varbinary (max 8000 float (F -1.79E+308 T
bytes VL) 1.79E+308) - Sepecific
a FP num) 4. Character String Datatype
Image (max int
2,147,483,647 bytes real (it specific a smallint 5. Data and Time
VL) single precision FP char Datatype
num) bit
decimal varcher
text date
numeric
time
timestamp

15
SQL COMMENDS:
 SQL commends are instructions. It is used to communicate with the database.
 It is also used to perform specific tasks, functions, and queries of data.

Types of SQL Commends:

Create
1. DDL (Data Definition Language)

Drop
Alter Insert
2. DML (Data Manipulation Language)

Truncate Update
Delete Grant

3.DCL (Data Control Language)


Revoke
Commit

Language)
4. TCL (Transaction Control
Rollback
Savepoint Select

Language)
5. DQL (Data Query

BASIC STRUCTURE OF SQL:


 Consists of these clauses:
1. Select (Projection operation)
o Used to list the attributes desired in the result of a query.
2. From (Cartesian-product operation)
o Lists the relations to scanned in the evaluation of the expression.
3. Where (Selection predicate)
o Consists of a predicate involving attributes of the relations that appear in the from clause.

16
Example: Select name from students where GPA = ‘4.0’

Attribute relation condition

 A typical SQL query form


o Select: A1, A2,…….. An. – Ai represents an attribute.
o From: r1, r2,………..rm – ri is a relation
o Where: P – P represents a predicate.

SQL SYNTAX THROUGH EXAMPLE:

1. Queris on a Single 2. Queris on Multiple


Relation Relations 3. The Natural Join
i.e., i.e., i.e.,
Select name Select name, instructor.dept_name, select name, title
building
from instructor from (instructor natural join teaches)
from instructor, depatment join course using (course_id);
where dept_name='Comp.Sci' and
salary > 70000; where instructor.dept_name=
department.dept_name

SQL SET OPERATION:

 The SQL Set Operation is used to combine the two or more SQL SELECT statement.

Types of Set Operation:

17
Types of Set Operation
1. Union

2. UnionAll

3. Intersect

4. Minus

STORY TIME:

1. Union:
The SQL union operation is used to combine the result of two or more SQL SELECT queries
All the number of data type and column must be same in both the tables on which UNION
operation is being applied
The union operation eliminates the duplicate rows from its result set.

Syntax:
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2
SELECT * FROM First
UNION
SELECT * FROM Second;

RESULT:

ID NAME
1 Jack
2 Harry
3 Jackson
4 Kannan
5 David
2. Union All:
18
Union All operation is equal to the union operation it returns the set without removing
duplication and sorting the data.
Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2
SELECT * FROM First
UNION ALL
SELECT * FROM Second;

RESULT:

ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Kannan
5 David

3. Intersect :
It is used to combine two SELECT statements and return the common rows from SELECT.
In the intersect operation, the No of data type and column must be the same.
It has no duplicates and it arranges the data in ascending order by default.
Syntax:
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2
SELECT * FROM First
INTERSECT
SELECT * FROM Second;

RESULT:

ID NAME
3 Jackson

4. Minus:
19
Minus operator is used to display the rows which are present in the first query but absent in
the second query.
Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2
SELECT * FROM First
MINUS
SELECT * FROM Second;

RESULT:

ID NAME
1 Jack
2 Harry
NULL VALUE:
 A field with a NULL value is a field with no value.
 It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
 We will have to use the IS NULL and IS NOT NULL operator Instead.

Example:

ID NAME SALARY
1 Jack 2000
2 Harry 1500
3 Jackson 2000
4 Kannan -
5 David -

Syntax:
SELECT Id, name, salary
FROM Customers
WHERE salary IS NOT NULL;

RESULT:

20
ID NAME SALARY
1 Jack 2000
2 Harry 1500
3 Jackson 2000

Syntax:
SELECT Id, name, salary
FROM Customers
WHERE salary IS NULL;

RESULT:

ID NAME SALARY
4 Kannan -
5 David -

SQL AGGREGATE FUNCTIONS:


SQL aggregation function is used to perform the calculations on multiple rows of single
column of a table.
It is also used to summarize the data.

Types of SQL Aggregation Function:

1.
COUNT

5. MIN 2. SUM

Funtions

4. MAX 3. AVG

1. COUNT function:
This is used to count the Number of rows in a database table.
COUNT (*) considers duplicate and Null.
21
Example: Customer_det

ID NAME SALARY
1 Jack 2500
2 Harry 1000
3 Jackson 2000
4 Kannan -
5 David -

Syntax:
SELECT COUNT(*)
FROM Customer_det;
RESULT:
5

2. SUM Function:
Sum function is used to calculate the sum of all selected columns

Syntax:
SELECT SUM(salary)
FROM Customer_det;
RESULT:
5500

3. AVG function:
It is used to calculate average value
Syntax:
SELECT AVG(salary)
FROM Customer_det;
RESULT:
1833.33

4. MAX function:
It is used to find the maximum value of a certain column
22
Syntax:
SELECT MAX(salary)
FROM Customer_det;
RESULT:
2500

5. MIN function:
It is used to find the minimum value in the column

Syntax:
SELECT MIN(salary)
FROM Customer_det;
RESULT:
1000

NESTED SUBQUERIES:
 A sub query can be nested inside other sub queries.
 SQL has an ability to nest queries within one another.
 A sub query is a SELECT statement that is nested within another SELECT statement and which
return intermediate results.

23
 This nested sub query retrieves the job_id(s) from Job_history table which is within the
department_id 50 to 100.

MODIFICATION OF THE DATABASE:

STORY TIME:

24
DELETE INSERT UPDATE
It helps us to It is helps us to It helps us to
remove rows from insert rows into modify column in
the table the table table rows

Syntax:
Syntax:
Syntax: update (relation
INSERT into
DELETE from r name>
relation name
where P set <assignment>
value(...)
where <condition>

UNIT- II COMPLETED

25
UNIT – III
INTERMEDIATE SQL:
In a DBMS, the use of various data types, aggregation functions, aggregation queries, unions,
triggers, events, the and creation of an index, etc., are done using intermediate SQL.

JOIN EXPRESSION:
JOIN means to combine something. In case of SQL, JOIN means ‘to combine two or more
table’.

Types of SQL Join:

INNER JOIN

LEFT OUTER
JOIN

RIGHT JOIN

FULL JOIN

Sample Tables:
1. EMPLOYEE:
EMP_ID EMP_NAME CITY SALARY AGE
1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Marry Las angels 200000 36

2. PROJECT:
PROJECT_NO EMP_ID DEPARMENT
101 1 Testing
102 2 Development
103 3 Designing

26
104 4 Development

i) INNER JOIN:
It is select records that have matching values in both tables as long as the condition is
satisfied
It returns the combination of all rows from both tables.

Syntax:
SELECT table1.column1, table.column2, table2.column1,…
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Query:
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID=EMPLOYEE.EMP_ID
RESULT:

EMP_NAME DEPARMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development

ii) LEFT JOIN:


LEFT JOIN all the values from left table and the matching values from the right table,
If there is no matching join value, it will return NULL.

Query:
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID=EMPLOYEE.EMP_ID
RESULT:

27
EMP_NAME DEPARMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Marry NULL

iii) RIGHT JOIN:


RIGHT JOIN returns all the values from the values from the rows of right table and the
matches values from left table.
If there is no matching in both tables, it will return NULL.

Query:
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID=EMPLOYEE.EMP_ID
RESULT:

EMP_NAME DEPARMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development

iv) FULL JOIN:


FULL JOIN is the result of a combination of both left and right outer join.
Join tables have all the record from the both tables.
It puts NULL on the place of matches not found.

Query:
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID=EMPLOYEE.EMP_ID
RESULT:

28
EMP_NAME DEPARMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Marry NULL

STORY TIME:

SQL VIEWS:
In SQL, a view is a virtual table based on the result-set of an SQL statement.
The fields in a view are fields from one or more real tables in the database.

1. CREATE VIEW
A view is created with the CREATE VIEW statement.
A view always shows up-to-date data.

Syntax:
CREATE VIEW view_name AS
SELECT column1, column2,…
FROM table_name
WHERE condition;

Queries:
CREATE VIEW (Chicago EMPLOYEE) AS
SELECT EMP_ID, EMP_NAME
FROM EMPLOYEE
WHERE CITY = ‘Chicago’;

RESULT:

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30

29
2. SQL Updating a View:
A view can be updated with the CREATE OR REPLACE VIEW statement.

Queries:
CREATE OR REPLACE VIEW (CHICAGO EMPLOYEE) AS
SELECT EMP_ID, EMP_NAME, CITY
FROM EMPLOYEE
WHERE CITY = ‘Chicago’;

RESULT:
EMP_ID EMP_NAME CITY SALARY AGE
1 Angelina Chicago 200000 30
2 Robert Chicago 300000 26

3. SQL DROP A VIEW:


A view is deleted with the DROP VIEW statement

Queries:
DROP VIEW (EMP_ID, EMP_NAME, SALARY);

RESULT:
EMP_ID EMP_NAME SALARY
1 Angelina 200000
2 Robert 300000
3 Christian 100000
4 Kristen 500000
5 Marry 200000

TRANSACTIONS:
A transaction is a unit of work that is performed against a database.
A transaction is the propagation of one or more changes to the database.

PROPERTIES OF TRANSACTIONS:

30
•Ensures that all operations within the work unit are

Atomicity completed.
•Otherwise, the transaction is aborted at the point of failure

•Ensures that the database properly changes states upon a

Consistency successfully committed transaction.

•Enables transactions to operate independently of and

Isolation transparent to each other.

•Ensures that the result or effect of a committed transaction

Durability persists in case of a system failure.

TRANSACTIONAL CONTROL:

1. COMMIT 2. ROLLBACK
• To save the change • To roll back the
changes

4. SET 3. SAVEPOINT
TRANSACTION • Create points wihin the
• Places a name on a groups of transactions
transaction. in which to ROLLBACK.

31
AUTHORIZATION:

 Authorization is finding out if the person, once identified, is permitted to have the resource.
 It’s explains that what you can do.

Forms of Authorization:
i) Resource Authorization:
Authorization to access any system resource. E.g. sharing of database.
ii) Alternation Authorization:
Authorization to add attributes or delete attributes from relations.
iii) Drop Authorization:
To drop a relation.

STORY TIME:

TYPES OF FORMS OF PRIVILEGE AUTHORIZATION:


1. Granting of privileges:
 A system privilege is the right to perform a particular action, or to perform an action on any
schema objects of a particular type.
 An authorization user may pass on this authorization to other users.

Syntax:
GRANT <privilege list>
ON<relation name or view name>
TO<user/role list>

2. Revoking of privileges:
 We can reject the privileges given to particular user with help of revoke statement.

Syntax:
REVOKE <privilege list>
ON<relation name or view name>
FROM<user/role list> [restrict/cascade];
3. Reference privileges:
 It’s permits a user to declare foreign keys while creating relations.

Example:

GRANT REFERENCE (EMP_ID)


ON EMP_SALARY
TO 1;
32
4. Executive privileges:
 This privileges authorizes a user to execute a function or procedure.

Example:

GRANT EXECUTE
ON Create_Acc
TO 1;

PROCEDURE AND FUNCTIONS:


A procedure or function is group or set of SQL and PL/SQL statement that perform a specific
task.

PROCEDURE:
A procedure is a named PL/SQL bock which performs one or more specific task.
A procedure has a header and a body.
A header consists of the name of the procedure and parameters.
The body consists or declaration section (Execution section and Exception section)
Parameters Description
IN type These types of parameters are used to send
value to stored procedures.
OUT type These types of parameters are used to get
values from stored procedures
IN OUT type These types of parameters are used to send
value and get values from stored procedures.

Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name 9,Arguments. {IN, OUT, IN OUT}
<Datatype>,…)
IS
Declaration section<variable, constant>;
BEGIN
Execution section
EXCEPTION
Exception section
END

Examples: (create table named emp have two column id and salary)
CREATE OR REPLACE PROCEDURE p1 (id IN NUMBER, sal IN NUMBER)
AS
BEGIN
INSERT INTO emp VALUES (id, sal)
END;
/

33
Output:

ID SALARY

FUNCTIONS:
A function is a named PL/SQL Block which is similar to a procedure.
A function must always return a value, but a procedure may or may not return a value.

Syntax:
CREATE [OR REPLACE] FUNTION function_name [parameters]
RETURN return_datatype; {IS, AS}
Declaration_section <variable, constant>;
BEGIN
Excution_section
Return return_variable;
EXECEPTION
Exception section
Return return_variable;
END;

Example:
Create or replace function getsal (no IN number) return number
Is
Sal number (5);
Begin
Select salary into sal from emp where id=no;
Return sal;
End;
/
Output:
ID SALARY
2 5000
DIFFERENT BETWEEN PROCEDURE VS FUNTIONS:

SNO PROCEDURE FUNCTION


1 A procedure cannot return a value A function MUST return a value
2 Procedure can return data in OUT and IN Also function can return data in OUT and IN
out parameter out parameter
3 The return statement in a procedure return The return statement in a function return

TRIGGER IN S QL:
A trigger n structured query language is a set of procedural statement which are executed
automatically when there is any response to certain events on the particular table in the
database.
Triggers are used to protect the data integrity in the database.

34
TRIGGER EVENT:

UPDATE DELETE
INSERT Event
Event Event

STORY TIME:

TYPES OF TRIGGERS:

• This trigger is invoked after the insertion of data in the


1. AFTER INSERT Trigger table

• This trigger is invoked in SQL after the modification of


2. AFTER UPDATE Trigger the data in the table.

• This trigger is invoked after deleting the data from the


3. AFTER DELETE Trigger table.

4. BEFORE INSERT • This trigger is invoked before the insertion of data in the
Trigger table

5. BEFORE UPDATE • This trigger is invoked before the updating of data in the
Trigger table

6. BEFORE DELETE • This trigger is invoked before delete of data in the table
Trigger

35
Syntax:
CREATE TRIGGER Trigger_Name
[Before/ AFTER] [insert/ Update/ Delate]
ON [Table_Name]
[FOR EACH ROW/ FOR EACH COLUMN]
AS
Set of SQL Statement

Example:
CREATE TABLE student_trigger
(
Student_RollNo INT NOT NUL PRIMARY KEY,
Student_firstName Varchar (100)
Student_EnglishMark INT,
Student_AccountsMark INT,
Student_Percentage );
Output:
Field Type NULL KEY DEFAULT Extra
Student_RollNo INT NO PRI NULL
Student_firstName Varchar(100) YES NULL
Student_EnglishMark INT YES NULL
Student_AccountsMark INT YES NULL
Student_Percentage INT YES NULL

MERITS:
SQL provides an alternate way for maintain the data and referential integrity in the tables
They catch the errors in the database layer of various businesses.

DEMERITS:
They are not complied.
Trigger increase the high load on the database system.

RELATIONAL ALGEBRA:
MEANING:
36
 Relational algebra refer to a procedural query language that takes relation instances as input and
returns relation instances as output.
 It performs queries with the help of operators.
 A binary or unary operator can be used.

RELATIONAL ALGEBRA OPERATION:

Select
Operation

Rename Project
Operation Operation

Cartesian
Union
Product
Operation
Operation

Set Different
Operation

1. Select Operation (or Ơ)


 It selects tuples from a relation that satisfy the provided predicate.
 The notation is _ Ơp(r)
 Here, Ơ – stands for the selection predicate while r – relation.
 Also, these terms may make use of relational operators such as - = , ≠, ≥, ≤, <, >

Example:
Ơsubject = “information”(Novels)
2. Project operation (or ᴨ)
 It projects those columns that satisfy any given predicate.
 Here B1, B2, an refer to the attribute names of the relation r.
 The notation is - ᴨB1, B2, Bn (r)
 Remember that duplicate rows are eliminated automatically.
3. Union Operation or ( U)
 It would perform binary union between two relations.
 The notion is – r U s
 r U s = {t/ t € r or t € s}
 Examples: ᴨ writer (Novels) U ᴨ writer (articles)
37
 Output : providing the writer names who might have written novels and articles
4. Set operation (or -)
 Tuples refers to result of the set difference operation. These are present in just one of the
relations but not at in the second one
 The notion is – r-s
 Examples: : ᴨ writer (Novels) - ᴨ writer (articles)
 Output : providing the writer names who might have written novels but not write
articles
5. Cartesian Product operation (or X)
 It helps in combining data and info of two differing relations into a single one.
 The notion is – r X s
 Example: Ơwriter = ‘mahesh’(Novels X articles)
 Output: yielding a relation that shows all the articles and novels written by Mahesh.
6. Rename operation or (p)
 Relation are the result of the relational algebra, but without any name.
 Thus, the rename operation would allow us to rename the relation output.
 The notion is – p X (E)
RELATIONAL CALCULUS:
It is refers to a non-procedural type of query language. It means that it would tell you what to do but
would never explain how to do it.

TYPES OF RELATIONAL CALCULUS:

Domain
Tuple Relational
Relationa
Calculus or (
Calculus or
TRC)
(DRC)

1. Tuple Relational Calculus or TRC:


o These filter the variable ranges over the tuples
o The notion is – {T/ Condition}
o Examples: {T.name / writer (T) AND T.blog = ‘information’}
o Output : it would return tuples with the ‘name’ from the writer that has written a blog on the
‘information’
2. Domain Relational Calculus or DRC
o The filtering variable in DRC makes use of the attributes domain instead of the values of an
entire tuple
o The notion is – {b1, b2, b3, ….,an / P (b1, b2, b3, …, bn)}
o Examples: {<page, article, subject> / € chocolate ∆ subject = ‘information’}
o Output: yielding page, article, as well as subject from the relation chocolate

UNIT-III COMPLETED

38
UNIT – IV
OVERVIEW OF DATABSE DESING PROCESS:
INTRODUCTION:
 Database design can be generally as a collection of tasks or processes that enhance the designing,
development, implementation, and maintenance of enterprise data management system.

IMPORTANCE:
a) It is provide the blueprint of how the data is going to be stored in a system
b) It’s principles defined for a database give a clear idea of the behavior of application.
c) It’s give and meets all the requirements of users.
d) It’s reduced processing time.

LIFE CYCLE:

1. Requirement Analysis:
o The planning hat to be done on what are the requirements of the project under which the
design of the database.
a) Planning – this stage is concerned with planning the entire DDLC (Database
Development Life Cycle).
b) System definition – this stage covers the boundaries and scopes of the database.
2. Database Designing:
o It’s considering the user-based requirements and splitting them out into various models.
a) Physical Model – It’s concerned with the practice and implementations of the logical
model.
b) Logical Model- It’s concerned with developing a model based on the proposed
requirements.
3. Implementation:
o The implementation methods and checking out the behavior that matches our requirements.
o It is ensured with continuous integration testing of the database with data set and conversion
of data.
a) Data conversion and loading – this section is used to import and convert data from the
old to new system.
b) Testing – this is concerned with error identification in the newly implemented system.

39
STORY TIME:

ER (Entity Relationship) MODEL:

 The entity-relationship (E-R) data model was developed to facilitate database design by allowing
specification of enterprise schema that represents the overall logical structure.
 In ER modeling, the database structure is portrayed as a diagram called an entity relationship
diagram.

COMPONENTS OF ER MODELS OR DIAGRAM:

40
1. Entity:
 An entity may any object, class, person or place.
a. Weak Entity- It’d doesn’t contain any key attribute of its own and it is represented by a
double rectangle. Ex: loan and installment.
2. Attribute:
 The attribute is used to describe the property of an entity.
 Ex: id, age, contact number,…
a. Key attribute – it is used to represent the main characteristics of an entity.
b. Composite attribute – It is represented by an ellipse and those ellipses are connected
with an ellipse Ex: First_name, Middle_name, Last_name.
c. Multivalued attribute – It can have more than one value. Ex: a student can have more
than one PH.NO.
3. Relationship:
A relationship is used to describe the relation between entities.
a) One to one Relationship –when only one instance of an entity is associated with the
relationship. Ex: a students have one teacher in one subject
b) One to many Relationship –it is more than one instance of an entity on the right
associates with the relationship Ex: scientist can invent many invention.
c) Many to one relationship – when more than one instance of the entity on the left, and
only one instance of an entity on the right associated with the relationship. Ex: students
enroll only one course but a course can have many students.

CONSTRAINTS:

Constraints enforce limits to the data or type of data that can be inserted/ updated/ deleted
from a table.

41
TYPES OF CONSTRAINTS:

1.NOT
4. CHECK
NULL

1. NOT NULL – This constraint makes sure that a column does not hold NULL value.
2. UNIQUE - This constraint enforces a column or set of columns to have unique values.
3. DEFAULT –This constraint provides a default value to a column when there is no value provided
while inserting a record into a table.
4. CHECK – It’s used for specifying range of values for a particular column of a table.
5. KEY Constraint:
a) PRIMARY KEY:
It’s uniquely identification each record in a table.
b) FOREIGN KEY:
They are the column of a table that points to the primary key of another table. They act as a
cross-reference b/w table.
6. Domain Constraints:
Each table has certain set of columns and each column allows a same type of data, based on
its data type.
Domain constraint = data type + constraints (NOT NULL/ UNIQUE/ CHECK)
7. Mapping Constraints:
a) One to one Relationship –when only one instance of an entity is associated with the
relationship. Ex: a students have one teacher in one subject
b) One to many Relationship –it is more than one instance of an entity on the right
associates with the relationship Ex: scientist can invent many invention.
c) Many to one relationship – when more than one instance of the entity on the left,
and only one instance of an entity on the right associated with the relationship. Ex:
students enroll only one course but a course can have many students.
d) Many to Many – an entity set a can be associated with any number of entities.

42
STORY TIME:

ER – DESING ISSUES:

ER-Design Issues
Use of Entity Set vs
Attributes

Use of Entity Set vs


Relationship Sets

Use of Binary vs n-
ary Relationship sets

Placing Relationship
Attributes

EXTENDED E-R FEATURE:

Attribute Constriants on
Specialization Generalization
inheritance Generalization

1. SPECIALIZATION:
An entity set may include sub-groupings of entities that are distinct in some way from other
entities in the set.
Types of Specialization
43
a) Overlapping – an entity may belong to multiple specialized entity sets.
b) Disjoint specialization – an entity may belong to at most one special entity.

2. GENERALIZATION:
In which multiple entity set are synthesized into a higher-level entity set on the basic of
common features.
3. ATTRIBUTE INHERITANCE:
A crucial property of the higher
The attributes of higher level to be inherited by the lower level
4. CONSTRAINTS ON GENERALIZATIONS:
Condition-defined – membership is evaluated on the basis of whether or not an entity.
User- define – it to be classified sub classes with relation
Coverage based – it is maintain no more than one lower level entity set.
Completeness based – each higher level entity must belongs to lower level entity

FIRST NORMAL FORM (1NF):


 A relation will be 1NF if it contains an atomic value.
 It states that an attribute of a table cannot hold multiple values. It must hold only single valued
attributes.
 This form disallows the multi valued attributes, composite attribute, and their combinations.
Example: relation EMPLOYEE is not in 1NF because of multi-valued attributes
EMP_PHONE.
DECOMPOSITION USING FRUNCTIONAL DEPENDENCIES:
 The formal methodology for evaluating whether a relational schema should be decomposed.
 This methodology is based upon the concepts of keys and functional dependencies
 When a set of attributes is a super key, we denote it by K.
 We use a lowercase name for relations.
 A relation, of course, has a particular value at any time.

CATEGORY OF FD:
1. Keys and functional dependencies:
44
 Functional dependencies play key role in differentiating good database design from bad
designs.
 Let R be a relation schema
α ⸦ R and β ⸦ R

 The functional dependency α -------) R


 Holds on R if and only if for any legal relations r(R), whenever any two tuples t1 and t2 of R
agree on the attributes α, they also agree on the attributes β. That is ,
 T1[α] = t2[α ]----------)t1[β] = t2[β]
2. Boys- Codd Normal Form:
 It eliminates all redundancy that can be discovered based on functional dependencies.
 α---------)β is a trivial functional dependency (that is, α⸦ β)
 α is a super key for schema R.
 Example : Inst_dept (ID, name, salary, dept_name) -------- ID(fd) -------) name, dept_name,
salary.
3. Third Normal Form:
 Third normal form (3NF) relaxes this constraint slightly by allowing certain nontrivial
functional dependencies whose left side is not a superkey.
 α---------)β is a trivial FD.
 α is a superkey for R.
 Each attribute A in β – α is contained in a candidate key for R.
4. Higher Normal Forms:
 Using FD to decompose schemas may not be sufficient to avoid unnecessary repetition of
information in certain cases.
 Examples: which we record with each instructor a set of children’s name and a set of phone
numbers.

FUNCTIONAL DEPENDENCY THEORY:


 The FD is a relationship that exist between two attributes. It typically exists between the primary and
non-key attributes within table.

TYPES OF EXAMPLES:
1. Closure of a set of FD:
 It’s means the complete set of all possible attributes that can be functionally derived from give
functional dependency using the inference rules.
 If ‘F’ is a FD then closure of FD can be denote using “{F}+”.

Step1: add the attributes which are present on left hand side in the original FD.
Step2: add the attributes present on the right hand side of the FD.
Step3: report this process until all the possible attributes which can be derived are added in the
closure
2. Closure of Attributes sets:
 Closure of an attribute X is the se of all attributes that are functional dependencies on X with
respect to F. it is denoted by X+ which means which means what X can determine.
Algorithm:
Let’s see the algorithm to compute X+
45
Step 1: X+ = X
Step2: repeat until X+ does not change
For each FD YZ in F
If Y ⸦ X+ then X+ = X+ U Z
3. Canonical cover:
 In the case of updating the database, the responsibility of the system is to check whether the
existing FD are getting violated during the process of updating.
 Extraneous attributes: we can remove it without changing the closure of the set of FD.
 Consider a set F of FD and the FD α β in F.
4. Lossless Decomposition :
 Lossless join decomposition is a decomposition of a relation R into relations R1, R2 such that
if we perform a natural join of relation R1and R2, it will return the original relation R.
5. Dependency preserving:
 If we decompose a relation R into relations R1 and R2, all dependencies of r must be part of
either R1 or R2 or must be drivable from combination of FD of R1 and R2
 Suppose a relation R(A,B,C,D with FD set {A - BC} is decomposed into R1(ABC) and R2
(AD) which is dependency preserving because FD A  BC is a part of R1 (ABC)

DECOMPOSITION USING MULTIVALUED DEPENDENCIES:


o We use multivalued dependencies to define a normal form for relation schemas
o Fourth normal form (4NF) is more restrictive than BCNF
o Every 4NF schema is in BCNF but not every BCNF schema is in 4NF.
o If AB we can have two tuples with same A value but different B values.

FOURTH NORMAL FORM (4NF):


o The relation is in BCNF and has multi valued dependencies.
o Multi valued dependency for a relation A B exists when for a single value of A,
multiple values of B exist.
Rule for 4NF:
1. The table is in Boyce-Codd Normal Form (BCNF)
2. The table is not any having multi valued dependency.

MORE NORMAL FORMS:


1. Project – join normal form (PJNF)- this is lead to join dependencies
2. Domain – key normal form (DKNF)- this is a class of even more general constraints that leads to
normal form.

UNIT- IV COMPLETED

46
UNIT – V
SYSTEM ARCHITECTURE:
INTRODUCTION:
o The architecture of a database system is greatly influenced by the underlying computer system on
which it runs, in particular by such aspects of computer architecture as networking, parallelism, and
distribution.

CENTRALIZED AND CLIENT-SERVER ARCHITECTURES:


o Merge everything into single system including hardware, DBMS software, application programs, and
user interface processing software.
o User can still connect by a remote terminal-but all processing is done at centralized site.

CLIENT SERVER:
o Offer appropriate interface through a client software module to access as well as utilize the various
server resource.
o Clients perhaps diskless machines or PCs or workstations with disks with only the client software
installed.
o Connected to the servers by means of some form of a network.

Types of architecture:
1. 1 tier architecture :
o Where data does not change frequently and where no multiple user is accessing the system.
o This is generally use for development of the local application.
o It is rarely used in production.
2. 2- Tier architecture:
o In this architecture client can directly communicate with database at server side easily.
o An application programming interface like ODBC & JDBC.

47
o User interface to client site and client side connect to server side and finally server side
responsible to provide the function.
o It is used inside any organization.

3. Three tier architecture:


o Client machines will contact application server which in turn processes our application
programs server itself.
o It different from two-tier architecture where queries are processed in the database server.

Merits:
o Direct and faster communication
o Maintenance and understanding is easier
o Compatible with existing systems.

Demerits:
o Scalability i.e. it gives poor performance when there are a large No of users.
o Less secure as client can access the server directly.

SERVER SYSTEM ARCHITECTURE:

STORY TIME:

48
Transaction- Cloud based
Data server
Server server

Serve process page shipping

Lock Manager Adaptive lock


process granularity

Database
Data caching
writer Process

Log writer
Lock caching
process

check point
process

process
monitor

PARALLEL SYSTEM:
1. SPEEDUP AND SCALEUP:
Speedup:-
o Running a given task in less time by increasing the degree of parallelism is called speed
up
o N>speedup is called linear
o N<speedup is called sub linear

Scale up:-
o Handling larger tasks by increasing the degree of parallelism is called scale up.
49
o The scale up is then defined as TS/TL.
o ML  is called linear scale up
o TL>TS is called sub linear scale up

2. INTERCONNECTION NETWORKS:

Bus

NETWORKS

Hypercube Mesh

3. PARALLEL DATABASE ARCHITECTURE:

50
Shared Memory

Shared Disk

Shared nothing

Hierarchical

DISTRIBUTED SYSTEMS:
o The database is stored on several computers.
o The computer in a distributed system communicate with one another through various communication
media.
o This system may vary in size and function, ranging from workstations up to mainframe systems.

51
Reasons

Sharing data Autonomy Availability

An Example of a Distributed Database

Implementation issues
Software-development Greater potential for Increased processing
cost Bugs. overhead.

TYPES OF NETWORKS:
o There are five main types of computer
1. LAN (Local Area Network)
 Systems connected in a small network like in a building or a small office
 In is inexpensive
 Fast and is highly score

52
2. PAN (Personal Area Network)
 The smallest computer network
 Devices may be connected through Bluetooth
 It has connectivity range of upto 10 mtr.

3. MAN (Metropolitan Area Network)


 A network that can be connected within a city, for example cable TV connection, ATM
 It has a higher range

4. WAN (Wide Area Network)


 A network which covers over a country or a large of people
 Telephonic lines, internet
 It is used mostly in govt. organization

53
5. VPN (Virtual Private networks)
 A network which is constructed by using public wires to connect to a private networks.

STORY TIME:

HOMOGENEOUS AND HETEROGENEOUS DATABASE :


 All sites have identical DBMS software, are aware of one another, and agree to co-operate
in processing user’s request.
 It must also co-operate with other sites in exchanging information about transactions
 To make transaction processing possible across multiple sites.

DISTRIBUTED DATA STORAGE:

54
Data Data
Transparency
Replication Fragmentation

Horizontal Frangmentation
Availability
Fragmentation transparency

Increased Vertical Replication


parallelism Fragmentation transparency

Increased
Location
overhead on
transparency
update

 Horizontal fragmentation splits the relation by assigning each tuple of r to


one or more fragments.
 Vertical fragmentation splits the relation by decomposing the scheme R of
relation r.

DISTRIBUTED TRANSACTIONS:

 Access to the various data items in a distributed system is usually accomplished through
transactions.

Types of transaction:
1. The local transactions are those that access and update data in only one local database.
2. The global transactions are those that access and updated data in several local database.

SYSTEM STRUCTURE:

 The transaction manager manages the execution of those transactions that access data stored in a
local site.
 The transaction co-ordinator coordinates the execution of the various transactions initiated at that
site.
 Maintaining a log for recovery purpose
 Starting the execution of the transaction
 Breaking the transaction into a No of sub transactions
 Distribution the sites
 Coordinating the termination of the transaction.

55
SYSTEM FAILUR MODES:

 Failure of a site
 Loss of messages
 Failure of a communication link
 Networks partition.

COMMIT PROTOCOLS:

 If we are ensure atomicity, all the sites in which a transaction T executed must agree on the final
outcomes of the execution.
 T must either commit at all sites, or it must abort at all sites.
 To ensure this property, the transaction coordinator of T must execute a commit protocol.

Alternative Models
Recovery and
Two-Phase commit Handling of failures Three Phase Commit of Transaction
Concurrency control
Processing

The commit Failure of a


Sending site
protocal (Ci--> participating
protocal
T) site

Phase 1 Failure of the Receiving


(<prepare T>) coordinator site protocol

Phase 2(
<abort T>,
<commit T>)

HETEROGENEOUS DISTRIBUTION DATABASE:


56
 Many new database applications require data from a variety of preexisting database located in a
heterogeneous collection of hardware and software environment.
 Manipulation of information located in a heterogeneous distributed database requires an additional
software layer on top of the existing DB system. It’ s called multi database system.

Unified
Difficulties
View of data

Transaction
Techinical organizational Query Management
difficulties Difficulties Processing in
Multidatabase

CLOUD-BASED DATABASE

Data Storage Systems


on the Cloud

Data Representation
Process

Partitioning and
Retrieving Data

Transaction and
Replication

Traditional database on
the cloud Cha

Challenges with Cloud-


Based Database.

57
DIRECTORY SYSTEMS:

Distributed
Directory Trees
Data Manipulation

LDPA Data Model

LDPAP:Lightweight
Directory Acess
Directoey Access Protocol
Protocal

UNIT- V COMPLETED

58

You might also like