0% found this document useful (0 votes)
51 views121 pages

Database Management System Overview

The document is a comprehensive overview of Database Management Systems (DBMS), covering key concepts such as data, information, and the structure of databases. It discusses various models, including the Entity-Relationship model and the Relational model, as well as SQL and PL/SQL programming. Additionally, it highlights the advantages of DBMS over file-based systems, the importance of database design, and the components of a database system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views121 pages

Database Management System Overview

The document is a comprehensive overview of Database Management Systems (DBMS), covering key concepts such as data, information, and the structure of databases. It discusses various models, including the Entity-Relationship model and the Relational model, as well as SQL and PL/SQL programming. Additionally, it highlights the advantages of DBMS over file-based systems, the importance of database design, and the components of a database system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

B.

Sc
DATA BASE MANAGEMENT SYSTEM
[Link]

[ABHYUDAYA MAHILA DEGREE COLLEGE]


Andhra Pradesh State Council of Higher Education
[Link]. Computer Science
Paper-: Data Base Management System

UNIT I

Overview of Database Management System: Introduction to data, information,


database, database management systems, file-based system, Drawbacks of file-
Based System, database approach, Classification of Database Management Systems,
advantages of database approach, Various Data Models, Components of Database
Management System, three schema architecture of data base, costs and risks of
database approach.
UNIT – II
Entity-Relationship Model: Introduction, the building blocks of an entity relationship
diagram, classification of entity sets, attribute classification, relationship degree,
relationship classification, reducing ER diagram to tables, enhanced entity-
relationship model (EER model), generalization and specialization, IS A relationship
and attribute inheritance, multiple inheritance, constraints on specialization and
generalization, advantages of ER modeling.
UNIT - III
Relational Model: Introduction, CODD Rules, relational data model, concept of key,
relational integrity, relational algebra, relational algebra operations, advantages of
relational algebra, limitations of relational algebra, relational calculus, tuple
relational calculus, domain relational Calculus (DRC), Functional dependencies and
normal forms upto 3rd normal form.
UNIT - IV
Structured Query Language: Introduction, Commands in SQL, Data Types in SQL, Data
Definition Language, Selection Operation, Projection Operation, Aggregate functions,
Data Manipulation Language, Table Modification Commands, Join Operation, Set
Operations, View, Sub Query.
UNIT – V
PL/SQL: Introduction, Shortcomings of SQL, Structure of PL/SQL, PL/SQL Language
Elements,Data Types, Operators Precedence, Control Structure, Steps to Create a
PL/SQL, Program, Iterative Control, Procedure, Function, Database Triggers, Types of
Triggers.

[Link] M.C.A,[Link],[Link].., Page 2


Database Management Systems

Design, Implementation and Management

P. Y. Kumar M.C.A, [Link], [Link]..,

Head of the Department

Computer Science

This Book is dedicated to my Daughter. May God Bless you and be with you
little one!

[Link] M.C.A,[Link],[Link].., Page 3


UNIT – I
DATABASE SYSTEMS
Data:
Data are raw facts. The word raw indicates that the facts have not yet been
processed to reveal their meaning.
Or
The term data referred to known raw facts. Text, graphics, images and video
segments that have meaning in the user’s environment

Information:
Information is the result of processing raw data to reveal ors meaning. Data
processing can be as simple as organizing data to reveal patterns or as complex as
making forecasts or drawing inferences using statistical modeling.
Or
Data that have been processed in such a way as to increase the knowledge of the
person who use the data
Information is produced by processing data.
Information is used to reveal the meaning of data.
Accurate, relevant, and timely information os the key

Database: The database consists of logically related data stored in a single data
repository.

Metadata: The metadata provide a description of data characteristics and the set of
relationships that link the data found with in the database.

Ex:

Name Type Length Min Max Description

Course Alphanumeric 30characters - - Course ID and


name

Database management system (DBMS): DBMS is collection of programs that


manages the database structure and control access to the data stored in the database.

Field: A character or group of characters that has a specific meaning. A field is used to
define and store data.

Record: A logically connected a set of one or more fields that describes a person, place
or thing.

File: A collection of related records.

[Link] M.C.A,[Link],[Link].., Page 4


Q) Drawbacks of file-Based System ?

Drawbacks of a File-Based System

1. Data Redundancy
o The same data may be duplicated in multiple files, leading to increased storage requirements
and potential inconsistencies.
2. Data Inconsistency
o Due to redundancy, changes made in one file might not reflect in others, causing mismatched
data across the system.
3. Limited Security
o File-based systems lack robust access controls, making it hard to restrict or monitor
unauthorized access.
4. Concurrency Problems
o Managing access by multiple users simultaneously can result in data corruption or access
conflicts.
5. Lack of Flexibility
o Modifications or adding new types of data often require significant effort and changes to the
system.
6. No Centralized Management
o Files are usually managed independently, making it challenging to maintain a unified view or
control.
7. Poor Data Sharing
o Sharing data between users or applications is cumbersome due to the absence of standard
interfaces or integration mechanisms.
8. Difficulty in Querying and Searching
o Complex data queries are not supported; users must often write custom programs or manually
search files.
9. Backup and Recovery Issues
o Backups must be handled manually, and recovery after failure can be time-consuming and
prone to errors.
10. Lack of Data Integrity
o Constraints like relationships between data are not inherently enforced, leading to potential
errors in data representation.
11. Scalability Challenges
o As the volume of data grows, file-based systems struggle with performance and management.
12. Limited Support for Complex Relationships
o Establishing and maintaining relationships between different data sets is difficult without a
database management system.

 Q) Classification of Database Management Systems OR TYPES OF DBMS?


Database Management Systems (DBMS) can be classified based on various criteria such as their data
model, architecture, or intended use. Here’s a detailed classification:

[Link] M.C.A,[Link],[Link].., Page 5


1. Based on Data Model

• Relational DBMS (RDBMS):


o Uses tables (relations) to represent data and relationships.
o Example: MySQL, PostgreSQL, Oracle Database.
• Hierarchical DBMS:
o Organizes data in a tree-like structure with parent-child relationships.
o Example: IBM Information Management System (IMS).
• Network DBMS:
o Represents data using a graph structure, allowing many-to-many relationships.
o Example: Integrated Data Store (IDS).
• Object-Oriented DBMS (OODBMS):
o Stores data as objects, similar to object-oriented programming.
o Example: db4o, ObjectDB.
• Document-Oriented DBMS:
o Focuses on storing, retrieving, and managing document-oriented data.
o Example: MongoDB, CouchDB.
• Key-Value Store DBMS:
o Uses key-value pairs for data storage.
o Example: Redis, DynamoDB.
• Column-Oriented DBMS:
o Stores data by columns instead of rows, optimized for analytical queries.
o Example: Apache Cassandra, HBase.
• Graph DBMS:
o Specializes in managing graph-based data for interconnected structures.
o Example: Neo4j, ArangoDB.

2. Based on Architecture

• Centralized DBMS:
o All data is stored and managed in a single location.
o Example: Mainframe-based databases.
• Distributed DBMS:
o Data is distributed across multiple locations, connected via a network.
o Example: Google Spanner, Amazon Aurora.
• Cloud-Based DBMS:
o Hosted in the cloud, offering scalability and remote access.
o Example: Google BigQuery, AWS RDS.

3. Based on Purpose

• OLTP (Online Transaction Processing) DBMS:


o Optimized for handling transactional data with frequent reads and writes.
o Example: MySQL, SQL Server.
• OLAP (Online Analytical Processing) DBMS:
o Designed for analytical queries and data warehousing.
o Example: Snowflake, SAP HANA.

4. Based on User Interaction

• Single-User DBMS:
o Supports one user at a time.
o Example: Microsoft Access.

[Link] M.C.A,[Link],[Link].., Page 6


• Multi-User DBMS:
o Allows multiple users to access the database simultaneously.
o Example: Oracle Database, PostgreSQL.

5. Based on Access Type

• Read-Only DBMS:
o Primarily for querying and viewing data.
o Example: Data warehouses.
• Read-Write DBMS:
o Allows both querying and modification of data.
o Example: Standard transactional databases.

6. Based on Scalability

• Vertical Scaling DBMS:


o Relies on increasing the power of a single server.
o Example: Traditional RDBMS like Oracle, SQL Server.
• Horizontal Scaling DBMS:
o Distributes data across multiple servers.
o Example: NoSQL databases like MongoDB, Cassandra.

7. Based on Data Storage Type

• In-Memory DBMS:
o Stores data in RAM for fast access.
o Example: SAP HANA, Redis.
• Disk-Based DBMS:
o Stores data on disk for durability and larger capacity.
o Example: Oracle, PostgreSQL.

 Q) ROLE AND ADVANTAGES OF THE DBMS(functions of dbms)

Database systems offer several advantages that make them an essential component of modern
applications and businesses. Here are the key benefits:

1. Data Integrity and Accuracy

• Ensures consistency and correctness of data through constraints and rules.


• Prevents duplication and inconsistencies by enforcing normalization.

2. Data Security:Allows administrators to control access to the database.

• Protects sensitive information through authentication and authorization mechanisms.


• Provides encryption and auditing to safeguard data from unauthorized access.

3. Efficient Data Management

• Centralizes data storage, making it easier to manage and retrieve.

[Link] M.C.A,[Link],[Link].., Page 7


• Handles large volumes of data with optimized storage and indexing techniques.
• Supports efficient querying and transactions.

4. Data Redundancy Minimization

• Reduces duplication by storing data in a normalized structure.


• Ensures updates are reflected throughout the system, maintaining consistency.

5. Data Sharing

• Facilitates data sharing across multiple users and applications in a controlled manner.
• Supports concurrent access, allowing multiple users to work simultaneously without conflicts.

6. Backup and Recovery

• Provides mechanisms for automated backups and data recovery.


• Ensures data is not lost during system failures or disasters.

7. Scalability

• Supports the growth of data and users by allowing the system to expand without significant rework.
• Can handle distributed databases and cloud-based solutions.

8. Flexibility and Adaptability

• Allows easy modification of the database structure to accommodate changing requirements.


• Supports complex queries and reports for varied business needs.

9. Improved Decision Making

• Enables advanced data analytics and reporting.


• Provides accurate and up-to-date information for informed decisions.

10. Data Independence

• Separates data structure from application logic, allowing changes to the database without affecting
applications.
• Promotes reusability and portability of applications.

11. Transaction Management

• Ensures atomicity, consistency, isolation, and durability (ACID properties) of transactions.


• Prevents data corruption and maintains integrity during concurrent access.

12. Cost Efficiency

• Reduces long-term operational costs by improving data management efficiency.


• Minimizes hardware requirements due to optimized storage.

13. Standardization

• Follows industry standards (e.g., SQL) for querying and managing data.
• Facilitates integration with other systems and technologies.

[Link] M.C.A,[Link],[Link].., Page 8


14. Support for Advanced Applications

• Enables use in diverse fields like e-commerce, banking, healthcare, and AI.
• Supports modern technologies like data warehousing, big data, and machine learning.

8)WHY DATABASE DESIGN IS IMPORTANT

Database design refers to the activities that focus on the design of the database
structure that will be used to store and manage end-user data. A database that meets all
user requirements does not just happen; its structure must be designed carefully. In
fact, database design is such a crucial aspect of working with database.
Proper database design requires the designer to identify precisely the database’s
expected use. Designing a transactional database emphasizes accurate and consistent
data and operational speed. Designing a database to be used in a centralized, single-
user environment requires a different approach from that used in the design of a
distributed, multiuser database.
A well-designed database facilitated data management and generates accurate
and valuable information.
A database contains redundant data when the same data about the same entity
are kept in different locations. Therefore, the existence of redundant data can produce
uncorrected data entries and you probably won’t know which value is the correct one.

9 ) D a t a b a s e S y s te m v e r s u s F i l e S y s t e m

DBMS File Processing System

Minimal data redundancy problem in


Data Redundancy problem exits
DBMS

Data Inconsistency does not exist Data Inconsistency exist here

Accessing database is easier Accessing is comparatively difficult

Data is scattered in various files and files may be


The problem of data isolation is not found
of different format, so data isolation problem
in database
exists

Transactions like insert, delete, view,


In file system, transactions are not possible
updating, etc are possible in database

Concurrent access and recovery is


Concurrent access and recovery is not possible
possible in database

Security of data Security of data is not good

A database manager (administrator)


A file manager is used to store all relationships in
stores the relationship in form of
directories in file systems.
structural tables

[Link] M.C.A,[Link],[Link].., Page 9


10)DATABASE SYSTEMS (OR)
THE DATABASE SYSTEM ENVIRONMENT (OR)
COMPONENTS AND INTERFACES OF DATABASE MANAGEMENT SYSTEM (OR)
COMPONENTS OF DATABASESYSTEM

1. The database consists of logically related data stored in a single data


repository (Storage area).
2. It is possible to remove most of the file system’s problems.
3. Like data inconsistency, data anomalies, data dependency and structural
dependency.
4. DBMS software not only the data structures, but it also the relationship
between those structures and the access structures path, in a central location.

[Link] M.C.A,[Link],[Link].., Page 10


The term database system refers to an organization of components that define
and regulate the collection storage, management and use of data within a database
environment. The database system is composed of the five major ports
1. Hardware
2. Software
3. People
4. Procedures
5. Data

1. Hardware:
Hardware refers to all the system’s physical devices. The database system’s main
and most easily identified hardware component is the computer. Hardware also
includes all of the computer peripherals. Peripherals include keyboards, nice,
modems and printers. Peripherals also included any electronic devices that are used
to connect two or more computers.
2. Software:
Software refers to the collection of programs used by the computer within the
database system. Three types of software to make the database system function
fully operating system software, DBMS software and application programs and
utilities

• OS software manages all hardware components and makes its possible for all
other software to run the computers.
• DBMS software manages the database within the database system. Microsoft’s
Access and SQL server, oracle.
• Application programs and utility software’s are used to access and
manipulated the data in the DBMS. Application programs are most commonly
used to access the data found within the database to generate reports,
tabulations and other information to facilitate decision making. Utilities are the
software tools used to help manage the database system’s computer
components.

3. People:

.
Database Administrator

Database Administrator is a person having central control over data and programs
accessing that data. The database administrator is a manager whose responsibilities are
focused on management of technical aspects of the database system.

Database Designer

Database designer can be either logical database designer or physical database designer.
Logical database designer is concerned with identifying the data, the relationships

[Link] M.C.A,[Link],[Link].., Page 11


between the data, and the constraints on the data that is to be stored in the database.
The logical database designer must have thorough understanding of the organizations
data and its business rule.

Database Manager

Database manager is a program module which provides the interface between the low
level data stored in the database and the application programs and queries submitted to
the system:

– The database manager would translate DML statement into low level

file system commands for storing, retrieving, and updating data in the

database.

– Integrity enforcement. Database manager enforces integrity by checking

consistency constraints like the bank balance of customer must be maintained

to a minimum of Rs. 300, etc.

– Security enforcement. Unauthorized users are prohibited to view the information

stored in the data base.

– Backup and recovery. Backup and recovery of database is necessary to ensure

that the database must remain consistent despite the fact of failures.

Database Users

Database users are the people who need information from the database to carry out
their business responsibility. The database users can be broadly classified into two
categories like application programmers and end users.

Sophisticated End Users

Sophisticated end users interact with the system without writing programs. They form
requests by writing queries in a database query language. These are submitted to query
processor. Analysts who submit queries to explore data in the database fall in this
category.

Specialized End Users

Specialized end users write specialized database application that does not fit into data-
processing frame work. Application involves knowledge base and expert system,
environment modeling system, etc.

Naive End Users

Na¨ıve end user interact with the system by using permanent application program
Example: Query made by the student, namely number of books borrowed in library
database.

System Analysts

[Link] M.C.A,[Link],[Link].., Page 12


System analysts determine the requirements of end user, and develop specification for
canned transaction that meets this requirement.

Canned Transaction

Ready made programs through which na¨ıve end users interact with the database is
called canned transaction.

4. Procedures
Procedures are the instructions and rules that govern the design and use of
the database system. Procedures play an important role in a company, they
enforced the standards procedures also are used to ensure that there is an
organized way to monitor and audit both the data that enter the database and the
information that is generated through the use of such data.

5. Data:
The word ‘Data’ covers the collection of facts stored in the database data are
the raw material from which information is generated.
Integrated Data

A data can be considered to be a unification of several distinct data files and when any
redundancy among those files is eliminated, the data are said to be integrated data.

Shared Data

A database contains data that can be shared by different users for different application
simultaneously. It is important to note that in this way of sharing of data, the
redundancy of data are reduced, since repetitions are avoided, the possibility of
inconsistencies is reduced.

Persistent Data

Persistent data are one, which cannot be removed from the database as a side effect of
some other process. Persistent data have a life span that is not limited to single
execution of the programs that use them.

11) Functional Components of Database System Structure ?

The functional components of database system structure are:

1. Storage manager.

2. Query processor.

Storage Manager

Storage manager is responsible for storing, retrieving, and updating data in the
database. Storage manager components are:

1. Authorization and integrity manager.

2. Transaction manager.

3. File manager.

4. Buffer manager.

[Link] M.C.A,[Link],[Link].., Page 13


Transaction Management

– A transaction is a collection of operations that performs a single logical

function in a database application.

– Transaction-management component ensures that the database remains in a


consistent state despite system failures and transaction failure.

– Concurrency control manager controls the interaction among the concurrent


transactions, to ensure the consistency of the database.

Authorization and Integrity Manager

Checks the integrity constraints and authority of users to access data.

Transaction Manager

It ensures that the database remains in a consistent state despite system failures. The
transaction manager manages the execution of database manipulation requests. The
transaction manager function is to ensure that concurrent access to data does not result
in conflict.

File Manager

File manager manages the allocation of space on disk storage. Files are

used to store collections of similar data. A file management system manages

independent files, helping to enter and retrieve information records.

File manager establishes and maintains the list of structure and indexes

defined in the internal schema. The file manager can:

– Create a file

– Delete a file

– Update the record in the file

– Retrieve a record from a file

Buffer

The area into which a block from the file is read is termed a buffer

Buffer Manager

Buffer manager is responsible for fetching data from disk storage into main memory.
Programs call on the buffer manager when they need a block from disk. The requesting
program is given the address of the block in main memory, if it is already present in the
buffer. If the block is not in the buffer, the buffer manager allocates space in the buffer
for the block, replacing some other block

Query Processing

[Link] M.C.A,[Link],[Link].., Page 14


is the activity performed in extracting data from the database. In query processing, it
takes various steps for fetching the data from the database. The steps involved are:

1. Parsing and translation


2. Optimization
3. Evaluation

Parsing and Translation

As query processing includes certain activities for data retrieval. Initially, the
given user queries get translated in high-level database languages such as SQL. It
gets translated into expressions that can be further used at the physical level of
the file system. After this, the actual evaluation of the queries and a variety of
query -optimizing transformations and takes place. Thus before processing a
query, a computer system needs to translate the query into a human-readable
and understandable language

Relational algebra is well suited for the internal representation of a query. The
translation process in query processing is similar to the parser of a query. When a
user executes any query, for generating the internal form of the query, the parser
in the system checks the syntax of the query, verifies the name of the relation in
the database, the tuple, and finally the required attribute value. The parser
creates a tree of the query, known as 'parse-tree.' Further, translate it into the
form of relational algebra. With this, it evenly replaces all the use of the views
when used in the query.

query processing in the below-described diagram:

Suppose a user executes a query. As we have learned that there are various methods of
extracting the data from the database. In SQL, a user wants to fetch the records of the
employees whose salary is greater than or equal to 10000. For doing this, the following
query is undertaken:

[Link] M.C.A,[Link],[Link].., Page 15


select emp_name from Employee where salary>10000;

Thus, to make the system understand the user query, it needs to be translated in the
form of relational algebra. We can bring this query in the relational algebra form as:

• σsalary>10000 (πsalary (Employee))


• πsalary (σsalary>10000 (Employee))

After translating the given query, we can execute each relational algebra operation by
using different algorithms. So, in this way, a query processing begins its working.

Evaluation

For this, with addition to the relational algebra translation, it is required to annotate the
translated relational algebra expression with the instructions used for specifying and
evaluating each operation. Thus, after translating the user query, the system executes a
query evaluation plan.

Query Evaluation Plan

• In order to fully evaluate a query, the system needs to construct a query


evaluation plan.
• The annotations in the evaluation plan may refer to the algorithms to be used for
the particular index or the specific operations.
• Such relational algebra with annotations is referred to as Evaluation Primitives.
The evaluation primitives carry the instructions needed for the evaluation of the
operation.
• Thus, a query evaluation plan defines a sequence of primitive operations used for
evaluating a query. The query evaluation plan is also referred to as the query
execution plan.
• A query execution engine is responsible for generating the output of the given
query. It takes the query execution plan, executes it, and finally makes the output
for the user query.

Optimization

• The cost of the query evaluation can vary for different types of queries. Although
the system is responsible for constructing the evaluation plan, the user does need
not to write their query efficiently.
• Usually, a database system generates an efficient query evaluation plan, which
minimizes its cost. This type of task performed by the database system and is
known as Query Optimization.
• For optimizing a query, the query optimizer should have an estimated cost
analysis of each operation. It is because the overall operation cost depends on the
memory allocations to several operations, execution costs, and so on.

 Q)DATABASE SYSTEM DISADVANTAGES: 0R COSTS AND RISKS OF DATABASE


APPROACH.

Database systems main disadvantages are


1. Increased costs
2. Management complexity
3. Maintaining currency
4. Vendor dependence

[Link] M.C.A,[Link],[Link].., Page 16


5. Frequent upgrade/replacement cycles

1. Increased costs:
a. Database System required sophisticated hardware and software and highly skilled
personnel.
b. The cost of maintain the hardware, software and personnel required to operate
and manage a database system can be large.

2. Management Complexity:
1. Database Systems interface with many different technologies
2. And have a significant impact on a company’s resources and culture.
3. Database systems hold crucial company data
4. That are accessed from multiple sources, security issues must be assessed
constantly.

3. Maintaining currency:
1. To maximize the efficiency of the database system, you must key your system
current.
2. User must perform frequent updates and apply
3. The latest patches and security measures to all components.
4. Because database technologies advances rapidly, personnel training cost tend to
be significant.

4. Vendor dependence:
1. Given the heavy investment in technology and personnel training, companies
might be reluctant to change database vendors.

5. Frequent upgrade / replacement cycles:


1. DBMS vendors (seller) frequently upgrade their products by adding new
functionality.
2. Such new features often the software. Some of these versions require hardware
upgrades.

 Q)DATA MODEL BASIC BUILDING BLOCKS

1. The basic building blocks of all data models are entities attributes, relationships and
constraints.
2. An entity is any thing (a person, a place, a thing or an event) about which data to
be collected and stored.
3. An attribute is a character of an entity. Attributes are the equivalent of fields in file
systems.
4. A relationship describes an association among entities.
5. Data models are used three types of relationships.

One – to – Many (1: M)


Many – to – Many (M: M)
One – to – One (1: 1)

6. A constraint is a restrictions placed on the data constraints are important


7. Because they help to ensure data integrity.
8. Constraints are normally expressed in the form of rules.

Eg: Employee salary must have values that are between 6,000 and 3,50,000

Q)DATA MODELING AND DATA MODELS

[Link] M.C.A,[Link],[Link].., Page 17


Data model: Data models define how the logical structure of a database is modeled. Data Models are
fundamental entities to introduce abstraction in a DBMS. Data models define how data is connected to each
other and how they are processed and stored inside the system.
There are several types of data models are available in DBMS. They are:
[Link] Based Model
[Link]
[Link]
Model [Link]
Model
[Link] Oriented Database Model
[Link] Dimensional Database
[Link] Relationship Model
The generations of above data models is as follows:

First Generation (1960-70): In this year File System is much dominated. It is used mainly on IBM
mainframe systems. It managed records only. It does not support relationships.

1. File-Based System: A file based system is a collection of application programs that perform
services for the users wishing to access information. Each program within a file based system
defines and manages its own data. Because of this, there are limits as to how that data can be used
or transported.
File based systems were developed as better alternatives to paper based filing systems. By havingfiles stored
on computers, the data could be accessed more efficiently. It was common practice for larger companies to
have each of its departments looking after its own data.

Second Generation (1970’s): In second generation hierarchical and Network models are
used.

2. Hierarchical Model: In Hierarchical model data is represented by an upside down tree. The
top layer (root) is preserved as the parent of the segment directly under it. The hierarchical model
supports One-to-many relationships.
Ex: parent and its children.

[Link] M.C.A,[Link],[Link].., Page 18


3. Network Model: It creates to represent complex data relationships more effectively than
hierarchical model, to improve database performance, and to impose database standards.

To help establish database standards CODASYL (Conference on Data System Language) create theDBTG
(Database Task Group). The DBTG report contains three crucial database components. i)Network schema
– In this schema includes definition of database name, record type for eachrecord, and the components
that make up of those records.
ii) Network Sub Schema – Which defines the portion of the database, seen by the application
programs that actually produce the desired information from the data contained within the
database.
iii) Data Management Language – It defines the environment in which data can be managed. In
network model allows a record to have more than one parent. In network database terminology,
relationship is called a set.
Third Generation (Mid of 1970’s): In this generation Relational model is used.
[Link] Model: The relational model was introduced by [Link] in 1970’s. In this
model the data is representing in the form of tables each table will contain set of rows andcolumns.
A relational model is support many to many relationships. Primary and Secondary Keysare used in this
model. A Foreign Key is used to establish the relation between the tables.

EMP_ID EMP_NAME EMP_SAL EMP_DEPT


1001 Kumar 2000 Sales
1002 Ravi 3000 Marketing
1003 Subbu 2356 Sales
1004 Karthik 4523 Insurance
The RDBMS performs the same basic functions provided by the hierarchical and network DBMS
systems. Most relational database software’s, the query language is SQL is a 4GL that allowsthe user to specify
what must be done without specifying how it must be done.

Fourth Generation (Mid of 1980’s): In this generation Object Oriented Database model ,
Multi Dimensional Database and Entity Relationship models are used.

[Link] M.C.A,[Link],[Link].., Page 19


5. Object Oriented Database model: An object is an entity which contains set of data
members & member functions. The data members are also called as attributes. The member
function is also called as methods. An instance of type class as object. This database model is used
to support complex data models such as graphics. Video and Audio.

6. Multi Dimensional Database Model: This database model is used in data ware housing
applications. There are 2 methods to represent the multi dimensional data base model. The 1st
method is cube method. The 2nd method is star View.
In multidimensional cube method each cell contains 1 or more simple attributes and the dimensions
of the raw data. These dimensions are factors on which the user wants to segment the data such as time
period, Geography, lines of business or people.
In star representation a fact table is located at center. This table will contains the entire row attribute
and the composite key made with the primary key of all its surrounding dimension tables

.[Link] MODEL: This model was developed by “CHEN”. ER Model is the logical representation of
the data for an organization. This model represents in terms of

1. Entity
2. Attributes
3. Relationship sets among
entitiesExmaple:

 Q)Ansi/Spark Data Model (American National Standard Institute/ Standards


Planning and Requirements Committee)
(Or)
 Explain Degree of Data abstraction.
(Or)
 Explain the levels of Data abstraction.
(Or)
 Explain three schema architecture

1. In the early 1970s the (American National Standards Institute) ANSI (standards
planning and Requirements committee) SPARC defined a framework for data
modeling based on degrees of data abstraction.
2. The ANSI/SPARC architecture defines three levels of data abstractions:
a. External,
b. conceptual and

[Link] M.C.A,[Link],[Link].., Page 20


c. Internal.
3. The ANSI/SPARC framework has been expanded with the addition of a physical
model to explicitly address physical level implementation address physical level
implementation details of the internal model.

Need for Abstraction

The main objective of DBMS is to store and retrieve information efficiently; all the users
should be able to access same data. The designers use complex data structure to
represent the data, so that data can be efficiently stored and retrieved, but it is not
necessary for the users to know physical database storage details. The developers hide
the complexity from users through several levels of abstraction.

The Three-Schema Architecture is a framework for database systems that separates the database into
three distinct levels. This separation ensures abstraction, making the database system more flexible,
adaptable, and easier to use. Here’s an explanation:

1. External Schema (User View)

• Definition:
o Represents the user-specific views of the database. It defines how individual users or
applications interact with the data.
• Purpose:
o Allows different users to see only the data they need, hiding irrelevant details.
o Provides security by restricting access to certain data.
• Example:
o An employee may see their personal details, while a manager sees a summary of all
employees' work hours.
• Key Features:
o Multiple external schemas can exist for the same database.
o Tailored to meet specific requirements of different user groups.

2. Conceptual Schema (Logical View)

• Definition:
o Provides a unified view of the entire database. It describes the logical structure of the data and
relationships, independent of physical storage details.
• Purpose:
o Serves as a bridge between the external and internal schemas.
o Ensures data consistency across different external schemas.
• Example:

[Link] M.C.A,[Link],[Link].., Page 21


o Defines entities like "Employee" and "Department" along with their attributes and
relationships, e.g., "Each employee belongs to a department."
• Key Features:
o Focuses on what data is stored and the relationships between data.
o Independent of hardware and software considerations.

3. Internal Schema (Physical View)

• Definition:
o Describes the physical storage of data on hardware. It deals with how data is actually stored,
retrieved, and optimized for performance.
• Purpose:
o Manages storage details, indexing, and file organization to ensure efficient data access and
retrieval.
• Example:
o Data is stored in a table format, with indexing on specific columns for faster search operations.
• Key Features:
o Concerned with storage structures like B-trees, hashing, or data clustering.
o Handles performance tuning, storage allocation, and data compression.

Benefits of Three-Schema Architecture

1. Data Abstraction:
o Users do not need to understand the physical storage details; they work with higher levels of
abstraction.
2. Data Independence:
o Changes in one schema do not affect the others:
▪ Logical Data Independence: Conceptual schema changes do not affect external
schemas.
▪ Physical Data Independence: Internal schema changes do not affect the conceptual
schema.
3. Enhanced Security and Flexibility:
o Different users can access tailored views without exposing sensitive information or complex
database details.

 Q)Which Situations where DBMS is not Necessary


1. It is also necessary to specify situations where it is not necessary to use a DBMS.
2. If traditional file processing system is working well
3. It takes more money and time to design a database,
4. But it is better not to go for the DBMS.
5. If only one person maintains the data and that person is not skilled in designing a
database [as well as not comfortable in using the DBMS]
6. Then it is not advisable to go for DBMS.
DBMS is undesirable (unwanted) under following situations:
1. DBMS is undesirable if the application is simple, well-defined, and not expected to
change
2. Runtime overheads are not feasible because of real-time requirements.
3. Multiple accesses to data are not required.

Q)Compared with file systems, databases have some disadvantages:

1. Higher hardware costs


2. Higher programming costs
3. High conversion costs
4. Slower processing of some applications
5. Increased vulnerability

[Link] M.C.A,[Link],[Link].., Page 22


6. More difficult recovery

Q)Vendor dependency:
1. Give the heavy investment in the technology
2. And personnel training, companies may be unwilling to change database vendors.

Vendor products
IBM DB2/MVS
DB2/UDB
DB2/400
Informix Dynamic
Server(IDS)
Microsoft Access
SQL Server
DesktopEdition(MSDE)
Open Source MySQL
PostgreSQL
Oracle Oralce DBMS
RDB
Sybase Adaptive Server Enterprise (ASE)
Adaptive Server Anywhere (ASA)
Watcom

Unit – II
Entity-Relationship Model: Introduction, the building blocks of an entity relationship
diagram, classification of entity sets, attribute classification, relationship degree,
relationship classification, reducing ER diagram to tables, enhanced entity-relationship
model (EER model), generalization and specialization, IS A relationship and attribute
inheritance, multiple inheritance, constraints on specialization and generalization,
aggregation and composition, entity clusters, connection types, advantages of ER
modeling.
1)ENTITY RELATIONSHIP(ER) MODELING

The E-R Models [ERM]:


1. An entity relationship model [E-R Model] is a defiled logical representation of
the data for an organization or for a business area.
2. The E–R Model is expressed in terms of entities.
3. A E-R Model is normally expressed as an entity relationship diagram
4. It is a graphical representation of an E-R model.
The components in E-R Model
1. Entities
2. Attributes
3. Relationships

 ENTITIES:
EMPLOYEE

1. An entity is an object of interest to the end user.


2. An entity is represented by a rectangle containing the entity’s name.
3. The entity name, a noun, is usually written in all capital letters.
4. An entity is anything a place, a person, a thing, an event about which data are
collected and store.

[Link] M.C.A,[Link],[Link].., Page 23


5. A collection of entities known as entity set or entity type.
6. Each row in the relational table is known as an entity instance or entity occurrence
(event).
The examples of entities are:

A particular person, for example Dr. A.P.J. Abdul Kalam is an entity.


A particular department, for example Electronics and Communication
Engineering Department.
A particular place, for example Coimbatore city can be an entity.

There are different types of entities


1. Strong entity.
2. Weak entity.
3. Associative entity (or) Composite entity (or) bridge entity

Strong Entities
1. A strong entity type is an entity that exists independently of other entity types.
2. Strong entity type always has a unique characteristic called an identifier.
3. That is an attribute or combination of attribute
4. That uniquely identified each occurrence (incidence) of that entity type.
5. It can be denoted as single line rectangle.

Syntax: [[ ENTITY NAME Ex: STUDENT

Example:
1. Consider the example, student takes course.
2. Here student is a strong entity

Weak Entities

1. A weak entity is an entity type whose existence depends on some other entity
type.
2. The entity has a primary key
3. That is partially or totally derived from the parent entity in the relationship.
4. It is represented by double line rectangle.

Syntax: ENTITY NAME Ex: BANK LOAN

Example:
1. Consider the example, customer borrows loan.
2. Here loan is a weak entity.

ASSOCIATIVE ENTITY

1. An associative entity is an entity type that associates the instances of one or


more entity type.
2. It means a many to many relationship exits
3. It is also called composite entity or bridge entity
4. And it contains attributes that are peculiar to the relationship between those entity
instances.
5. It is represented by a diamond shape with in a rectangle.

EMTITY NMAE

[Link] M.C.A,[Link],[Link].., Page 24


 ATTRIBUTES: (Attribute Classification or Different types of attributes)

1. An attribute is a property or characteristics of an entity.


2. Attributes are represented by ovals and are connected to the entity rectangle with
a line.

Ename

Eno ESal

EMPLOYEE

Entity type: EMPLOYEE

Attributes: Ename
Eno
Esal

Note: The naming attributes we use an initial capital letter followed by lower case letter.

There are different types of attributes

1. Domain
2. Composite and simple attributes
3. Single-valued attribute
4. Multivalued attribute
5. Derived attribute
6. Identifiers
7. Composite primary keys
Domains
1. Attribute have a domain.
2. A domain is the ser of possible values for a given attribute.
3. For example the domain for the gender attribute consists of only two possible: M
or F.

Male Female

[Link] M.C.A,[Link],[Link].., Gender Page 25


Required and optional attributes
1. A required attribute is an attribute that must have a value.
2. It cannot be left empty.
3. An optional attribute is an attribute that does not require a value;
4. It can be left empty.

36

Age facebook

Required attribute optional attribute

Composite and simple attributes:


1. A composite attribute is an attribute that can be further subdivided to yield (give
up) additional attributes.
2. For example the attribute address is subdivided into street, city, state and zip
code.
Door_no
street City
Male/Female
Address

Composite attribute simple attribute

3. A simple attribute is an attribute that cannot be subdivided.


4. For example age, sex and marital status would be classified as simple attributes.

Single- valued attributes


1. A single-valued attribute is an attribute that can have only a single value.
2. For example a person can have only one social security number
3. A single valued attribute is not necessarily a simple attribute.

Pin No

ATM card
card
Single valued attribute
Multivalued attribute

1. Multivalve attributes are attributes that may take on more than one value for a
given entity instance.
2. A multi value attribute with an ellipse with double lines.

Ename
skill
Eno

EMPLOYEE
[Link] M.C.A,[Link],[Link].., Page 26
Derived attributes

1. A derived attribute is an attribute whose value is calculated (derived) from other


attributes.
2. The derived attributes need not be physically stored within the database.
3. Derived attributes are sometimes referred to as computed attributes.
4. Indicate a derived attribute using an ellipse with a dashed line.

Ename
skill
Eno

EMPLOYEE Join_date
Experience

Identifiers (Primary keys)


1. One or more attributes that uniquely identify each entity instance.
2. In the relational model, such identifiers are mapped to primary keys (PKs) in
table.
3. Identifiers are underlined I n the ERD.

Ex:
Jdc(Eno, ename, salary);
Null Value Attribute

In some cases, a particular entity may not have any applicable value for an attribute. For
such situation, a special value called null value is created. Null value situations Not
applicable Not known

Example

In application forms, there is one column called phone no. if a person do not have phone
then a null value is entered in that column

Composite identifiers

A composite identifier is a primary key composed of more than one attribute.

JDC( Eno, Deptno, Ename, Salary )


 RELATIONSHIPS

1. Relationship is an association between entities.


2. The entities that participate each relationship is identified by a name that
describes the relationship

3. The relationship represents diamond symbol.

[Link] M.C.A,[Link],[Link].., Page 27


4. Relationships between entities always operate in both directions.
5. For example: the relationship between the entities named EMPLOYEE and SKILL
6. An EMPLOYEE may learn many SKILLS. Each SKILL may learn by many EMPLOYEE
7.

M N
CITY Vehicle ROOTS

CONNECTOVITY AND CARDONALITY


1. The term connectivity is used to describe the relationship classification.
2. The entity relationships may be classified as

a. one-to-one,
1 1
Principal Manages Department

b. one-to many
1 M
Subject has Lectures

c. many to many
M N
Lectures Teach Subjects

3. Cardinality expresses the minimum and maximum number of entity occurrence


(incidence) associated with one occurrence of the related entity.
4.
M N
Lectures Teach Subjects

EXISTENCE DEPENDENCE
1. An entity is said to be existence-dependent
2. If it can exist in the database only when it is associated with another related
entity occurrence.
3. In entity can exist apart from one or more related entities, it is said to be
existence-independent.
Author Book

1. For example, there are two entities named Author and Book.
2. A writer to take an advance to write a book for a publisher,
3. But the first book written by the writer for this publisher,
4. There will be no entry in the Book entity until the contracted book has been written and
published
5. In this case, the relationship between Author and Book is 1:0, indicating that the
existence of an instance of Book is optional
2) RELATIONSHIP STRENGTH
1. Relationship strength is based on how the primary key of a related entity is
demined.
2. To implement a relationship, the primary key of one entity connects as a foreign
key in the related entity.
Ex:
College (SNO, SNAME, SSECTION)
Hostel (SNO, SNAME, ROOMECODE,)

[Link] M.C.A,[Link],[Link].., Page 28


1. Hear Hostel student no is dependent on college sno
2. student don’t have sno in college that student sno not to store in hostel

Weak (Non-identifying) Relationships


1. A weak relationship, also known as a non-identifying relationship,
2. It exists if the PK of the related entity does not contain a PK component of the
parent entity.

College (SNO, SNAME, SSECTION)


Hostel (SNO, SNAME, ROOMECODE,)

Strong (Identifying) Relationships


1. A strong relationship, also known as identifying relationship
2. It exists when the PK of the related entity contains a PK component of the parent
entity.

College (SNO, SNAME, SSECTION)


Hostel (SNO, SNAME, ROOMECODE,)

3)RELATIONSHIP PARTICIPATION
Participation in an entity relationship is either optional or mandatory.

Optional:
1. Optional participation means that one entity occurrence does not require a
corresponding entity occurrence in a particular relationship.
2. Ex: Some Lecturers may Teach any Students I Each Student must be taught by at
least one Lecturer

M N
Lectures Teaches Student

Mandatory:

1. Mandatory participation means that one entity occurrence requires a


corresponding entity occurrence in a particular relationship.
2. Some Lecturers may not Teach any Students I Each Student must be taught by at
least one Lecturer
M N
Lecturer Teaches Student

 4)REATIONSHIP DEGREE (DEGREES OF RELATIONSHIP)


The degree of relationship is number of entities or participates associated with a
relationship. The most common relationship degrees in E-R models are

1. Unary (Degree I)
2. Binary (Degree II)
3. Ternary (Degree III)
Higher relationship degrees are also possible but they are rear in use.
UNARY RELATIONSHIP:
1. A unary relationship is a relationship between the instances of a single entity
type.
2. These relationships are also called a recursive relationship.
One-to-one relationship (1-1):
One instant of entity type
associated one instant of the PERSON Is-married_to

same entity
[Link] then it is called
M.C.A,[Link],[Link].., Page 29
In this Eg is_married_to is shown as a 1-1 relationship between instances of the
person entity type.

EMPLOYEE Manages

One_to_many (1 – N):

One instant of entity type


associated more than one instant of
the same entity then it is called one-
to-many relationship
In this Eg manages is shown as 1 to many relationship between the instances of the
employee entity type.

Some organizations it may be possible for one employee to be managed by many other
employees.

Many_to_many (N – N)

More than one instant of entity type


associated with more than one
Has-
instant of the same entity then it is ITEM components
called many-to-many relationship

1. In this eg we represent many to many relationships.


2. The entity type item is used to represent all types of components.
3. Components for the name of the relationship that associated lower level item and
higher level items.

BINARY RELATIONSHIP:
A binary relationship is relationship between the instances of two entity types.

One_to_one(1-1): One instance of the one entity type can be associated with one
instances of other entity type.

EMPLOYEE Is_assigned PARKING PLACE

This eg indicates that an employee is assigned one parking place and each parking
place is assigned to only one employee.

One to many (1-N): One instance of the one entity type can be associated with
number of instances of other entity type.

[Link] M.C.A,[Link],[Link].., Page 30


Eg: Contains PRODUCT
PRODUCT LINE

In this eg has is the relation between product groups and products many no. of
products are related to only one product group.

Many-to-many: The number of instances of one entity type can associated with
number of instances of other entity type.

Eg: STUDENT Registers-


_for COURSE

This eg indicated that an employee may complete more than one course and then
each course may have many employees.

TERNARY RELATIONSHIP

1. A ternary relationship is a simultaneous relationship among the instances of three


entity types.
PART

VENDOR Supplies WAREHOUSE

Shipping mode unitcost

1. In this eg vendor can supply various parts to warehouse.


2. The relationship supply is used to record to specific parts that are supplied by a
given vendor to a particular warehouse.
3. Thus there is three-entity type VENDOR, PARTS, WAREHOUSE.
4. There are two attributes are relationship is shipping code and unit-cost.

Quaternary Relationships

Quaternary relationships involve four entities. The example of quaternary

relationship is “A professor teaches a course to students using slides.” Here the four
entities are PROFESSOR, SLIDES, COURSE, and STUDENT. The relationships between
the entities are “Teaches.”

[Link] M.C.A,[Link],[Link].., Page 31


5)RELATIONSHIPS WITHIN THE RELATIONAL DATABASE
A relationship is an association among the instance of one or more entity types. The
relationship are classified as one-to-one (1: 1), one-to-many (1: M), and many to many
(M: N or M: M)

The 1:M Relationship:

The 1: M relationship is the relational database norm. consider the PAINTER paints
PAINTING example.

PAINTER paints PAINTING

The 1:M relationship between PAINTER and PAINTING

1. Each painting is painted by one and only one painter, but each painter could
have painted many paintings.
2. There is only one row in the PAINTER table for any given row in the painting
table, but there may be many rows in the PAINTER table for any given row in
the PAINTER table.
3. The 1:M relationship is found in any database environment.

The 1: 1 Relationship:

As the 1: 1 table implies, in this relationship, one entity can be related to only one
other entity, and vice-versa. For example, one department chair – a professor – can
chair only one department can have only one department chair. The entities PROFESSOR
and DEPARTMENT thus exhibit a 1: 1 relationship.

The preceding “PROFESSOR chairs DEPARTMENT” example illustrates a proper 1:


1 relationship. In fact, the use of a 1:1 relationship ensures that two entity sets are not
placed in the same table when they should not be.

PROFESS DEPARTMENT
Chairs

The 1:1 relationship between PROFESSOR and DEPARTMENT

[Link] M.C.A,[Link],[Link].., Page 32


The M : N Relationship
A many-to-many (M:N) relationship is not supported directly in the relational
environment. To explore the many-to-many (M:N) relationship, consider a rather typical
college environment in which each STUDENT can take many CLASSes, and each CLASS
can contain many STUDEMTs.

STUDENT CLASS
has

The ERM’s M:N relationship between STUDENT and CLASS


6)INDEXS:
An index is an orderly arrangement used to logically access rows in a table.

Indexes in the relational database environment work like the indexes described in
the preceding paragraphs. From a conceptual point of view, an index is composed of an
index key and a set of pointers.

DBMS use index for many different purposes. An index can be used to retrieve
data more efficiently. But indexes can also be used by a DBMS to retrieve data ordered
by a specific attribute or attributes.

For example, creating an index on a customer’s last name will allow you to
retrieve the customer data alphabetically by the customer’s last name.

Index play an important role in DBMSs for the implementation of primary keys,
when you define a table’s primary key column(s). The DBMS automatically creates a
unique index on that attribute. A unique index as its name implies, is an index in which
the index key can have only one0020pointer value (row) associated with it.

Create index <index name>on <tablename>(colum name);

CREATE INDEX idx_lastname ON Persons (LastName);

 7)Symbols Used in ER Diagram


1. The elements in ER diagram are Entity, Attribute, and Relationship.
2. The different types of entities like strong, weak, and associative entity,
3. Different types of attributes like multivalued and derived attributes and identifying
relationship and their corresponding symbols

Strong entity Associate entity

Week entity Attribute

Relation ship Multivalue attri.

Identify [Link] Derive Attribute

[Link] M.C.A,[Link],[Link].., Page 33


8)Converting Composite Attribute in an ER Diagram to Tables

Example

In this example the composite attribute is the Customer address, which consists of
Street, City, State, and Zip.

The first relation contains all of the attributes of the entity type except

the multivalued attribute.

The second relation contains two attributes that form the primary key of

the second relation. The first of these attributes is the primary key from the first
relation, which becomes a foreign key in the second relation. The second is the
multivalued attribute.

Mapping Multivalued Attributes in ER Diagram to Tables

[Link] M.C.A,[Link],[Link].., Page 34


Converting “Weak Entities” in ER Diagram to Tables

Converting Binary Relationship to Table

A relationship which involves two entities can be termed as binary relationship.

This binary relationship can be one-to-one, one-to-many, many-to-one,

[Link] M.C.A,[Link],[Link].., Page 35


and many-to-many.

Mapping one-to-Many Relationship

Mapping Associative Entity to Tables

Many-to-many relationship can be modeled as an associative entity in the ER diagram.

[Link] M.C.A,[Link],[Link].., Page 36


Converting Ternary Relationship to Tables

[Link] M.C.A,[Link],[Link].., Page 37


[Link] M.C.A,[Link],[Link].., Page 38
ADVANCED DATA MODELING

 1)What is an extended entity relationship model? Explain entity super types


and sub types? Or THE EXTENDED ENTITY RELATONSHIP MODEL (EER model)

EER Models:

As the complexity of the data structures being modeled has increased and as application
software requirements, there has been as increasing more information in the data
model. In this model represent some business rules also This model that has
resulted from extending the original ER model with new modeling constructs is called
EER model

ENTITY SUPERTYPES AND SUBTYPES

❖ SUPERTYPE:
1. An entity super-type is a generic entity type
2. That is related to one or more entity subtypes
3. Where the entity super-type contains the common characteristics,
4. And the entity subtypes contain the unique characteristics of each entity
subtype
.
❖ SUBTYPE:
1. A subtype is a subgroup of the entities in an entity type

[Link] M.C.A,[Link],[Link].., Page 39


2. That is meaningful of the organization shares common attributes or
relationships distinct from other sub-grouping.

INHERITANCE
1. The property of inheritance enables (allow) an entity subtype to inherit the
attributes and relationships of the super type.
2. A super type contains those attributes that are common to all of its subtype.
3. In contrast, subtypes contain only the attributes that are unique to the
subtype.
4. One important inheritance characteristic is that all entity subtype inherit their
primary key attribute from their super type.

SUBTYPE DISCRIMINATOR
1. A subtype discriminator is the attribute in the super type entity that
determines to which subtype the super type occurrence is related.

2)Explain Specialization and Generalization

Generalization:

Generalization is the process of minimizing the differences between entities by


identifying common features. It can also be defined as the process of defining a
generalized entity type from a set of entity types.

Specialization is a process of identifying subsets of an entity set (the

superset) that share some distinguishing characteristics. In specialization

the super class is defined first and the subclasses are defined next. Specialization is the
process of viewing an object as a more refined, specialized object.

[Link] M.C.A,[Link],[Link].., Page 40


The process of defining a more general entity type from a set of more specialized entity
types. Thus generalization is a “Bottom up process”.

Ex:

In the above diagrams car, truck and motor cycle contains a no. of attributes in
common, vehicle-ID, v-name, and price and engine displacement.

This fact suggests that each of the three entity types is really a version of a more
general entity types. This more general entity type (vehicle) together with the resulting
supertype / subtype relationships is shown in above fig b.

The entity car has the specific attribute, no. of passengers, while truck has 2
specific attributes capacity and cab type. Thus generalization has allowed us to group
entity types along with their common attributes and at the same time preserve specific
attribute that are peculiar to each subtype.

In the above examples, motorcycle is not included in the relationship because all
attributes of motor cycle are those that are common to all vehicles.

Specialization:

The process of defining one or more subtypes of the supertype and forming
supertype/subtype relationships.

[Link] M.C.A,[Link],[Link].., Page 41


Description Location

Part-no Quantity
Part S-ID
on Hand

Routing-No Supplier
Unit
Price
Manufactur Purchased
Supplies
ed Part Part

In the above ex entity type part having attributes partno, description, unit price,
location, quality on hand, routing no and supplier.(a supplier attribute is Multivalued
attribute. since there may be more than one supplier with associated unit price, for a
part).there are 2 possible source for parts. Some are manufactured internally, while
others are purchased from outside suppliers. In this case, the choice depends on factors
such as manufacturing capacity, unit price of the parts. Thus routing_no applies only to
manufactured parts, while supplier_id and unit price apply only to purchase parts.

3) ISA Relationship and Attribute Inheritance

IS A relationship supports attribute inheritance and relationship participation.

In the EER diagram, the subclass relationship is represented by ISA

relationship. Attribute inheritance is the property by which subclass entities

inherit values for all attributes of the superclass.

Consider the example ofEMPLOYEEentity set in a bank. TheEMPLOYEE

[Link] M.C.A,[Link],[Link].., Page 42


in a bank can be CLERK, MANAGER, CASHIER, ACCOUNTANT, etc. It

is to be observed that the CLERK, MANAGER, CASHIER, ACCOUNTANT

inherit some of the attributes of the EMPLOYEE.

In this example the superclass is EMPLOYEE and the subclasses are

CLERK, MANAGER, and CASHIER. The subclasses inherit the attributes

of the superclass. Since each member of the subclass is an ISA member of the
superclass, the circle below the EMPLOYEE entity set represents ISA relationship.

4)Multiple Inheritance

A subclass with more than one superclass is called a shared subclass. A subclass inherits
attributes not only of its direct superclass, but also of all its predecessor superclass, that
is it has multiple inheritance from its superclasses. In multiple inheritance a subclass can
be subclass of more than one superclass.

[Link] M.C.A,[Link],[Link].., Page 43


 5)Constraints on Specialization and Generalization
The constraints on specialization and generalization can be broadly classified into
disjointness and completeness. The dis jointness constraint allows us to specify
whether an instance of a super type may simultaneously be a member of two or
more subtypes. In dis jointness we have two categories (1) Overlap and
(2) Disjoint. In completeness we have two categories

(1) Total and (2) Partial

Overlap Constraint
Overlap refers to the fact that the same entity instance may be a member of more
than one subclass of the specialization
Example of Overlap Constraint
Consider the example of ANIMAL entity, which can be further subdivided
into LAND ANIMAL and WATER ANIMAL. Consider the example of Frog
and Crocodile which can live in both land and water hence the division of
ANIMAL into LAND and WATER animals is an example of overlap constraint.

Disjoint Constraint

Disjoint refers to the fact that the same entity instance may be a member of only
one subclass of the specialization.
Example of Disjointness Constraint

Consider the example of CATALOGUE. The CATALOGUE is a superclass,

which can be further subdivided into BOOKS, JOURNALS, and [Link]


falls under disjointness because a BOOK entity can be neither JOURNAL nor
PERIODICAL.

Total Specialization

 Total completeness refers to the fact that every entity instance in the
superclass must be a member of some subclass in the specialization.

[Link] M.C.A,[Link],[Link].., Page 44


With total specialization, an instance of the supertype must be a
member of at least one subtype.

Partial Specialization
Partial completeness refers to the fact that an entity instance in the superclass
need not be a member of any subclass in the specialization. With partial
specialization, an instance of a supertype may or may not be a member of any
subtype.
Example of Partial Specialization
Consider the PERSON specialization into EMPLOYEE and STUDENT. This
is an example of partial specialization because there can be a person who is
unemployed and does not study.

6) Aggregation and Composition

Relationships among relationships are not supported by the ER model. Groups of


entities and relationships can be abstracted into higher level entities using
aggregation. Aggregation represents a “HAS-A” or “IS-PART-OF” relationship
between entity types. One entity type is the whole, the other is the part.
Aggregation allows us to indicate that a relationship set participates in another
relationship set. Consider the example of a driver driving a car. The car has
various components like tires, doors, engine, seat, etc., which varies from one car
to another. Relationship drives is insufficient to model the complexity of this
system. Part of relationships allow abstraction into higher level entities.
In this example
engine, tires, doors, and seats are aggregated into car.

[Link] M.C.A,[Link],[Link].., Page 45


Composition is a stronger form of aggregation where the part cannot exist
without its containing whole entity type and the part can only be part of one entity
[Link] the example of DEPARTMENT has PROJECT. Each project is
associated with a particular DEPARTMENT. There cannot be a PROJECT without
DEPARTMENT. Hence DEPARTMENT has PROJECT is an example of composition.

.Q) EER DIAGRAM OF HOSPITAL MANAGEMENT?

Q) Advantages of ER Modeling
An ER model is derived from business specifications. ER models separate

the information required by a business from the activities performed within a

[Link] M.C.A,[Link],[Link].., Page 46


business. Although business can change their activities, the type of information
tends to remain constant. Therefore, the data structures also tend to be
constant. The advantages of ER modeling are summarized later:
1. The ER modeling provides an easily understood pictorial map for the
database design.
2. It is possible to represent the real world problems in a better manner in
ER modeling.
3. The conversion of ER model to relational model is straightforward.
4. The enhanced ER model provides more flexibility in modeling real world
problems.
5. The symbols used to represent entity and relationships between entities are
simple and easy to follow.

UNIT III

Relational Model: Introduction, CODD Rules, relational data model, concept of key,
relational integrity, relational algebra, relational algebra operations, advantages of
relational algebra, limitations of relational algebra, relational calculus, tuple relational
calculus, domain relational Calculus (DRC). QBE

 1) What is a Relational Data Model


1. The relational model uses a collection of tables to represent both data and
relationships.
2. Tables are logical structures maintained by the database manager.
3. The relational model is a combination of three components,
a. Structural
b. Integrity and
c. Manipulative parts.

a. Structural Part
1. The structural part defines the database as a collection of relations.

b. Integrity Part
1. The database integrity is maintained in the relational model using primary
and foreign keys.

c. Manipulative Part
1. The relational algebra and relational calculus are the tools
2. It used to manipulate data in the database.
3. Thus relational model has a strong mathematical background.

Table: (Characteristics of a relational table)


A table is perceived as a two-dimensional structure composed of rows and columns.
1. A table is also called relation.
2. Each row in the table is called tuple.
3. Each column in the table is called attribute.
4. Each column represents an attribute, and each column has a distinct name
5. Each rows and columns can be exactly the same
6. The column will have data value.
7. All values in a column must conform to the same data format
8. The order of the rows and columns is unimportant to the DBMS.
9. In relational model attributes can be in any order.

[Link] M.C.A,[Link],[Link].., Page 47


[Link] relational model rows can be in any order.
[Link] must have a key.
[Link] can be a set of attributes.
[Link] column has a specific range of values known as the attribute domain
[Link] is the set of valid values for an attribute.
[Link] of the relation is the number of attributes (columns) in the relation.
[Link] of the relation is the number of tuples (rows) in the relation

2) What is a Functional dependence Key:


1. A key is a one or more attributes that determine (decide) other attributes.
2. For example sno identifies all of the student attributes
3. Such as sfname, slname, sintial, dob, class and phno.
4. The one attribute determines other attribute is called determination.
A→ B
In the above A determines B. A is called determination.

Functional dependence:

1) Functional dependency is a relationship that exists when one attribute uniquely


determines another attribute.
2) The attribute B is functionally dependent on the attribute A
3) If each value in column A determines one and only one value in column B.
4) Attribute A determines attribute B (that is, B is functionally dependent on A) if all
of the rows in the table that agree in value for attribute.
5) A also agree in value for attribute B

Functional Dependencies and Keys


A functional dependency is a constraint between two attributes or two sets of
attributes.
If the attribute (B) is functionally dependent on a composite key(A) but not on any
subset of that composite key, the attribute (B) is fully functionally dependent on (A).
For any relation R. attribute B is functionally dependent on attribute A if, for every
valued instance of A, that value of a uniquely determines that value of B.
The functional dependency of B on A is represented by an arrow as follows.
A→B
Eg: Consider the relation EMP-COURSE

EMP-COURSE (Eno, Course_title, Date_completed);


Eno, Course_title → Date_completed.

Determinants:
The attribute on the left-hand side of the arrow in a functional dependency is
called a determinant.
Eg: In the EMP-COURSE relation the combination of eno, course_tittle is a
determinant.

 3)Types of SQL Keys

There are different types keys relation data model. They are
1. Composite key
2. Candidate key
3. Super key
4. Alternate key
5. Secondary key

[Link] M.C.A,[Link],[Link].., Page 48


6. Primary key
7. Foreign key
1. Composite key:
a. It is a combination of two or more columns in a table
b. That can be used to uniquely identify each row in the table.
c. Such a multi attribute key is known as composite key.
Ex:
CREATE TABLE BABA
(Sno integer, deptno
integer, address varchar(50), PRIMARY KEY (sno, deptno));

Explanation:

2. Candidate key:
a. A Candidate Key can be any column or a combination of columns
b. That can qualify as unique key in database.
c. There can be multiple Candidate Keys in one table.
d. Each Candidate Key can qualify as Primary Key.
e. [A Primary Key is a column or a combination of columns that uniquely identify a
record
f. A minimal super key. A super key that does not contain a subset of attributes
that is itself a super key. ]

For example: In the EMPLOYEE table, id is best suited for the primary key. Rest of the
attributes like SSN, Passport_Number, and License_Number, etc. are considered as a
candidate key.

3. Super key:
a. Super key is a combination of columns
b. That uniquely identifies any row within a RDBMS table.
c. It is reduced to the minimum number of columns required to uniquely identify each
row.
d. An attribute or combination of attributes that uniquely identifies each row in a
table is called super key.

[Link] M.C.A,[Link],[Link].., Page 49


For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME) the name of two
employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this combination can
also be a key. The super key would be EMPLOYEE-ID, (EMPLOYEE_ID, EMPLOYEE-NAME),

4. Alternate key:
a. A Alternate key is a key that can be work as a primary key.
b. Basically it is a candidate key that currently is not primary key.
Or
a. Among of candidate keys if any single key or combination of keys made as
primary key then rest candidate key called as alternate key.
Exp:
1. Suppose in employee table EmpID is primary key
2. Then Emailid and SSN are called as alternate key
3. It mean later on these key can be act as primary key without affecting existing data in
table.

Secondary key:
1. An attribute (or combination of attributes) used strictly for data retrieval
purpose is called secondary key.
Exp :
create table tnam(ano number, bno number, bname char(12), primary
key(ano,bno))
In this bno is secondary key.

Primary key:
1. An attribute that uniquely identifies each row in a relation is called primary
key.
2. The combination of unique and not null
3. It cannot support duplicate value and also empty value in attribute

Ex: CREATE TABLE BABA


(Sno integer, deptno integer, address varchar(50), PRIMARY KEY (sno));
Or
CREATE TABLE BABA
(Sno integer primary key, sna varchar2(20));

Foreign key:
1. It is used to create relation between two tables using with primary key.
2. A FOREIGN KEY is a key used to link two tables together
3. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
4. The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.

CREATE TABLE BABA1 (


dno int PRIMARY KEY,
dname varchar2(20) NOT NULL,
Sno integer FOREIGN KEY REFERENCES BABA(Sno)
);

 4) Explain Dr. [Link] Rules


[For any RDBMS to be accepted as full fledged RDBMS it has to follow the 12 CODD
rules . The rules are] There are 12 CODD rules.

1. The information Rule: it is used to be represented all information as a data values


in the rows and columns of tables. This is the basis of the relational model.

[Link] M.C.A,[Link],[Link].., Page 50


2. The guaranteed access Rule: Every data value in a relational database should be
logically accessible by specifying a combination of the table name, the primary key
value on column name.

3. Systematic Treatment of NULL values: DBMS must support NULL values to


represent missing or inapplicable information. They must be distinct from zero or
spaces.

4. Active Online Catalog Based on the Relational model: The system list is a
collection of tables that the DBMS maintains for its own use. These tables hold the
description of the structure of the database.

5. The Comprehensive Data Sub-language Rule: This Rule states that the system
must support at least one language that performs data definition, View Definition,
data manipulation operations, security and integrity constraints and transaction
management operations.

6. The View Updation Rule: It used to All views that are theoretically updateable must
be updateable by the system.

7. High Level insert, update, and Delete: it used to rows should be treated as sets in
insert, delete and update operations.

8. Physical data independence: Application Program must remain un impaired


(undamaged) when any changes are made in storage representation or access
method.

9. Logical Data Independence :Users and user Programs should be independent of


the logical structure of the database.

10. Integrity independence: Integrity constraints must be storable in System catalog.

11. Distribution independence: Database must allow manipulation of Distributed data


located on other computer systems.

12. Non – Subversion Rule: This rule states that different levels of the language can
not subvert or bypass the integrity rules and constraints.

 5) Integrity rules or relational integrity:


1. Relational database integrity rules are very important to good database design.
2. Many (but by no means all) RDBMSs enforce integrity rules automatically.
3. The set of rules which are used to maintain the accuracy of the data and to
integrate (add) the data in database is called as integrity constraints.
1. Domain Integrity.
2. Entity Integrity.
3. Referential Integrity.

1. Domain Integrity:
1. A domain is a set of values which is assigned to an attribute.
2. The components of the domain are domain name, meaning, data type, size and
range of the values.

Ex: student relation the domains are regdno, name.

2. Entity Integrity :

[Link] M.C.A,[Link],[Link].., Page 51


1. All primary key entries are unique, and no part of a primary key may be null.
2. Each row will have a unique identity, and foreign key values can properly
reference primary key values.
3. A primary key is an attribute in a relation which is used to identify each row in a
relation.
4. No. of components of a primary key value may be NULL.
5. This is called as entity integrity.
6. A NULL is an undefined value. One NULL is not equal to another NULL.

3. Referential Integrity :
1. A referential integrity is used to implement the foreign key.
2. A foreign key is a non key attribute in the relation R and it is a primary key in
relation R2.
3. This key is called as foreign key. The value of the foreign key is either NULL or primary
key.
4. Another integrity rules that can be enforced in the relational model are the
NOT NULL and UNIQUE constraints.

NOT NULL: its not supports empty value in attribute. The NOT NULL constraint
can be placed a value for that column.

UNIQUE: The UNIQUE constraint is used to not support duplicate values exists
column.

 6) What is a Relational Algebra


1. The relational algebra is a notional language with operations
2. That work on one or more relations to define another relation without changing
the original relation.
3. The both the operands and the results are relations;
4. The output from one operation can become the input to another operation.
5. This allows expressions to be nested in the relational algebra. This property is called
closure.
6. Relational algebra is an abstract language,
7. It means that the queries formulated in relational algebra are not intended to be
executed on a computer.
8. Relational algebra consists of group of relational operators that can be used to
manipulate relations to obtain a desired result.
9. Knowledge about relational algebra allows us to understand query execution and
optimization in relational database management system.

 7)Explain Relational Algebra Operations (Relational Set operators)


Operations in relational algebra can be classified into set operation and database
operations.
1. Unary and Binary Operations
1. Unary operation involves one operand,
a. selection
b. Projection
2. Binary operation involves two operands.
a. Union operation
b. Difference operation
c. Cartesian product operation
d. Intersection operation
e. Division operation
f. Join operations operation
2. Relational algebra operations

[Link] M.C.A,[Link],[Link].., Page 52


3. Set Operations Database operations

Three main database operations are SELECTION, PROJECTION, and JOIN.

1. a. Selection Operation
1. The selection operation works on a single relation R
2. And it defines a relation that contains only those tuples of R
3. That satisfies the specified condition (Predicate).
4. Selection operation can be considered as row wise filtering.
5. This is pictorially represented also known as RESTRICT
6. It creates values for all rows found in a table that satisfy a given
condition.
7. Select can be used to list all of the row values, or it can create only those
row values
8. That matches a specified criterion.
9. Select create a horizontal subset of a table.
Syntax
σ Predicate (R).

ex: σ subject = "database"(Books)

P_CODE P_DESCRIPT PRICE


123456 Flash light 5.26
123457 Lamp 25.15
123458 Box Fan 10.99
123459 9v battery 1.92
123455 100W bulb 1.47
123454 Powerdrill 34.99

SELECT only PRICE less than Rs. 2.00 yields P_CODE P_DESCRIPT PRICE
123459 9v battery 1.92
123455 100W bulb 1.47
1. b. Projection Operation
2. The projection operation works on a single relation R
3. And defines a relation that contains a vertical subject of R,
4. And extracting the values of specified attributes and elimination duplicates.
5. The projection operation can be considered as column wise filtering.
It’s creates all values for selected attributes. In other words, project creates
a vertical subset of a table.

Syntax
a1,a2,......an (R).
[Where a1, a2, . . . . . . an are attributes and R stands for relation To illustrate
projection operation consider the relation STAFF, with the attributes Staff number,
Name, Gender, Date of birth, and Salary.]

[Link] M.C.A,[Link],[Link].., Page 53


SALES:

P_CODE PRICE
P_DESCRIPT PRICE
123456 Flashlight 5.26 PROJECT PRICE yields
5.26
123457 Lamp 25.15 25.15
123458 Box Fan 10.99 10.99
123459 9v battery 1.92 Select price from sales; 1.92
123455 100w bulb 1.47 1.47
123454 Power drill 34.99 34.99
PRICE
P_DESCRIPT
Flashlight 5.26
PROJECT P_DESCRIPTand PRICE yields Lamp 25.15
Box Fan 10.99
9v battery 1.92
100w bulb 1.47
Select components, price, from sales; Power drill 34.99

2. a. Union Operation
1. Union combines all rows from two tables, excluding (without) duplicate
rows.
2. The tables must have the same attribute characteristics to be used in the
UNION.
Or
3. The union of two relations R and S defines a relation
4. That contains all the tuples of R or S or both R and S,
5. Duplicate tuples being eliminated.

Relational Algebra Expression

The union of two relations R and S are denoted by R ∪ S. R ∪ S is pictorially


represented

P_CODE PRICE
P_DESCRIPT
123456 Flashlight 5.26 PRICE
123457 Lamp 25.15 P_CODE P_DESCRIPT
UNION
123458 Box Fan 10.99 345678 Microwave 160.00
123459 9v battery 1.92 345679 Dishwasher 500.00
123455 100w bulb 1.47
123454 Powerdrill 34.99

P_CODE P_CESCRIPT PRICE


123456 Flashlight 5.26
123457 Lamp 25.15
OUTPUT 123458 Box Fan 10.99
123459 9v battery 1.92
123455 100w bulb 1.47
123454 Powerdrill 34.99
345678 Microwave 160
345679 Dishwasher 500

[Link] M.C.A,[Link],[Link].., Page 54


b. Difference Operation
1. The set difference operation defines a relation consisting of the tuples
2. That is in relation R but not in S.
3. It create all rows in one table that are not found in the other table
4. That is, it subtracts one table from the other.
5. The effect of a DIFFERENCE is shown in follow in example.
6. That subtracting the first table from the second table is not the same as
subtracting the second table from the first table.

Relational Algebra Expression


The difference between two relations R and S is denoted by R–S.
F_NAME F_Name F_Name
Yields
Krishna Sree Krishna
sree DIFFERENCE Kumar Sridhar
Sridhar Hari Sheshu
Sheshu Kiran
Hari

c. Cartesian Product Operation


1. The Cartesian product operation defines a relation
2. That is the concatenation of every tuples of relation R with every tuples of relation
S.
3. The result of Cartesian product contains all attributes from both relations R and S.
4. It’s creates all possible pairs of rows from two tables
5. It is also known as the Cartesian product.
6. For example one table has six rows and the other table has three rows,
7. The PRODUCT creates a list composed of 6 X 3 = 18 rows.

Relational Algebra Symbol for Cartesian product:


The Cartesian product between the two relations R and S is denoted by R ×
S.

Example
If there are 5 tuples in relation “R” and 2 tuples in relation “S” then the
number of tuples in R × S is 5 ∗ 2 = 10.
R S
R S
A 1 A 1
A 2
B 2 A 3
Note:
B 1
No. of tuples in R X S = 2 x 3
3 B 2
=6
B 3
d. Intersection Operation
1. The set of all tuples that are in both R and S.
2. Intersect create only the rows that appear in both tables.
3. As we true in the case of UNION table must be union-compatible to produce
(create) valid results.
4. For example, you cannot use INTERSECT if one of the attributes is numeric
and one is character – based.

F_NAME F_Name F_Name


Yields
Kumar INTERSECT Sree Sree
Sree Lal Hari
Kiran Hari
Sheshu Krishna
Hari

[Link] M.C.A,[Link],[Link].., Page 55


e. Division Operation
1. The division of the relation R by the relation S is denoted by R ÷ S,
where R ÷ S is given by: R ÷S = ΠR−−S(r) − ΠR−−S((ΠR−−S(r) ×
s) − r)

CODE LOC
A 5
A 9 CODE
yields
A 4 DIVIDE A LOC
B 5 B
5
B 3
C 6
D 7
D 8
E 8

f. Join Operations
1. Join operation combines two relations to create a new relation.
2. The tables should be joined based on a common column.
3. The common column should be compatible in terms of domain.
4. It allows information to be combined from two or more tables.
5. Join is the real power behind the relation database, allowing the use of
independent table linked by common attributes (Characteristics).

There are different types of join operations

 8)Types of Join Operation


There are different types of join operations

Natural Join

The natural join performs an equi join of the two relations R and S over all common
attributes. One occurrence of each common attribute is eliminated from the result. In
other words a natural join will remove duplicate attribute.

In most systems a natural join will require that the attributes have the same name to
identity the attributes to be used in the join. This may require a renaming mechanism.
Even if the attributes do not have same name, we can perform the natural join provided
that the attributes should be of same domain.

[Link] M.C.A,[Link],[Link].., Page 56


Input: Two relations (tables) R and S

Notation: R __ S

Purpose: Relate rows from second table and

– Enforce equality on all column attributes

– Eliminate one copy of common attribute

* Short hand for _ L(R × S):

– L is the union of all attributes from R and S with duplicate removed

– P equates all attributes common to R and S

Equi Join

A special case of condition joins where the condition C contains only

equality.

Example of Equi Join

Given the two relations STAFF and DEPT, produce a list of staff and the

[Link] M.C.A,[Link],[Link].., Page 57


departments they work in.

Theta Join

A conditional join in which we impose condition other than equality condition. If equality
condition is imposed then theta join become equi join. The symbol θ stands for the
comparison operator which could be >, <, >=, <=.

Expression of Theta Join

σθ(R × S)

Illustration of Theta Join

To illustrate theta join consider two relations FRIENDS and OTHERS with

the attributes Name and age.

Outer Join

In outer join, matched pairs are retained unmatched values in other tables are

[Link] M.C.A,[Link],[Link].., Page 58


left null.
Types of Outer Join

The pictorial representation of the left and the right outer join of two relations

R and S are :

1. Left Outer Join. Left outer joins is a join in which tuples from R that do

not have matching values in the common column of S are also included in

the result relation.

2. Right Outer Join. Right outer join is a join in which tuples from S that do not have
matching values in the common column of R are also included in the result relation.

3. Full Outer Join. Full outer join is a join in which tuples from R that do

not have matching values in the common columns of S still appear and

tuples in S that do not have matching values in the common columns of

R still appear in the resulting relation.

Example of Full Outer Left Outer and Right Outer Join

Consider two relations PEOPLE and MENU determine the full outer, left

outer, and right outer join.

[Link] M.C.A,[Link],[Link].., Page 59


Semi-Join

[Link] M.C.A,[Link],[Link].., Page 60


The semi-join of a relation R, defined over the set of attributes A, by relation S, defined
over the set of attributes B, is the subset of the tuples of R that participate in the join of
R with S. The advantage of semi-join is that it decreases the number of tuples that need
to be handled to form the join. In centralized database system, this is important because
it usually results in a decreased number of secondary storage accesses by making better
use of the memory. It is even more important in distributed databases, since it usually
reduces the amount of data that needs to be transmitted between sites in order to
evaluate a query.

Expression for Semi-Join R _F S =_ A(R _F S) where F is the predicate.

 9)ADVANTAGES OF RELATIONAL ALGEBRA:

1. The relational algebra has solid mathematical background.


2. It is the basis of many interesting developments and theorems.
3. If we have two expressions for the same operation
4. And if the expressions are proved to be equivalent
5. Then a query optimizer can automatically substitute the more efficient form.
6. The relational algebra is a high level language
7. It talks in terms of properties of sets of tuples and not in terms of for-loops.
Limitations of Relational Algebra
1. The relational algebra cannot do arithmetic.
2. For example, if we want to know the price of 10 l of petrol, by assuming a 10%
increase in the price of the petrol,
3. It cannot be done using relational algebra.
4. The relational algebra cannot sort or print results in various formats.
5. For example we want to arrange the product name in the increasing order of their
price.
6. It cannot be done using relational algebra.
7. Relational algebra cannot perform aggregates.
8. For example we want to know how many staff is working in a particular
department.
9. This query cannot be performed using relational algebra.
[Link] relational algebra cannot modify the database.
[Link] example we want to increase the salary of all employees by 10%.
[Link] cannot be done using relational algebra.

[Link] M.C.A,[Link],[Link].., Page 61


[Link] relational algebra cannot compute “transitive closure.”
[Link] order to understand the term transitive closure consider the relation
RELATIONSHIP, which describes the relationship between persons.
[Link] the query, Find all direct and indirect relatives of Gopal?
[Link] is not possible to express such kind of query in relational algebra.
[Link] transitive means, if the person A is related to the person B and if the person
B is related to the person C means indirectly the person A is related to the person
C.
[Link] relational algebra cannot express the transitive closure

Relationship
Person1 Person2 Relationship
Hari Krishna Lakshmi Mother
Sree harilal Nandalal Father
Hari Raj Brother
Sree Sravanthi Husband

 10) Relational Calculus


1. The purpose of relational calculus is to provide a formal basis for defining
declarative query languages appropriate for relational databases.
2. Relational Calculus comes in two flavors
a. Tuple Relational Calculus (TRC) and
b. Domain Relational Calculus (DRC).
3. The basic difference between relational algebra and relational calculus is that the
former gives the procedure of how to evaluate the query whereas the latter gives
only the query without giving the procedure of how to evaluate the query:
a. The variable in tuple relational calculus formulae range over tuples.
b. The variable in domain relational calculus formulae range over individual
values in the domains of the attributes of the relations.
c. Relational calculus is nonoperational, and users define queries in terms of
what they want, not in terms of how to compute it. (Declarativeness.)

Relational Calculus and Relational Algebra:


The major difference between relational calculus and relational algebra is
1. A relational calculus query specifies what information is retrieved
2. A relational algebra query specifies how information is retrieved
 Tuple Relational Calculus
1. Tuple relational calculus is a logical language with variables ranging over
tuples.
2. The general form of tuple relational calculus is given by:

{<tuple variable list> | <conditions>} {t | COND(t)}

3. Here t is the tuple variable, which stands for tuples of relation.


4. COND (t) is a formula that describes t.
5. The meaning of the earlier expression is to return all tuples T that satisfy the
condition COND:
a. T/R(T)} means return all tuples T such that T is a tuple in relation R.
b. For example, {[Link]/FACULTY(T)} means return all the names of
faculty in the relation FACULTY.
c. {[Link]/ FACULTY(T) AND [Link]=‘EEE’} means return the value of
the name of the faculty who are working in EEE department.
d.

[Link] M.C.A,[Link],[Link].., Page 62


 Domain relational calculus

1. Domain Relational Calculus is the second form of relational calculus.


2. It uses domain values or variables that take on values from an attribute
domain, rather than values for an entire tuple.
3. However, the DRC is closely related to TRC.
4. DRC acts as a theoretical basis for Query by Example.
5. Queries in the DRC have the form:
{X1, ..., Xn | Condition}
6. The X1, ..., Xn are a list of domain variables.
7. The condition is a logical expression of classical first-order logic.
8. The language QBE is based on DOMAIN RELATIONAL CALCULUS.
9. It differs from tuple calculus in the type of variables used.
[Link] expression is of the form:

{ X1,X2…………..Xn | COND(X1,X2…….Xn, Xn+1,……..Xm+n) }

Example:

Retrieve the birth dates and address of the employee whose name is ‘John
[Link]’

{ uv | ( (q) (r) (s) (t) (w) (x) (y) (z) (EMPLOYEE(qrstuvwxyz) and q = ‘John’
and r = ‘B’ and s = ‘Smith’ ) }
or
{ uv | EMPLOYEE(‘John’, ‘Smith’, ‘B’, t,u,v,w,x,y,z ) }

 11)Explain QBE
1. QBE stands for Query By Example. QBE uses a terminal display with attribute
names as table headings for queries.
2. It is very easy to list the entire schema, simply by scrolling information on the
screen.
3. QBE was developed originally by IBM in the 1970s to help users in their retrieval
of data from a database.
4. QBE represents a visual approach for accessing data in a database through the
use of query templates.
5. QBE can be considered as GUI (Graphical User Interface) based on domain
calculus.
6. QBE allows users to key in their input requests by filling in empty tables on the
screen, and the system will also display its response in tabular form.
7. QBE is user-friendly because the users are not required to formulate sentences for
query requests with rigid query-language syntax.
8. In QBE the request is entered in the form of tables whose skeletons are initially
constructed by QBE.
9. Some of the QBE query template examples:

Example 1. Projection operation

1. In this template P. implies “Print.” The meaning is: Print the PLAYER ADDRESS
who belong to the country INDIA.
2. To make a projection only put P. in any column of the projection.
3. QBE will enforce uniqueness of projections automatically.

 12) Relational algebra Vs Relational Calculus

1. The relational algebra and the relational calculus have the same expressive
power;

[Link] M.C.A,[Link],[Link].., Page 63


2. i.e. all queries that can be formulated using relational algebra can also be
formulated using the relational calculus and vice versa.
3. E. F. Codd first proved this in 1972.
4. This proof is based on an algorithm by which an arbitrary expression of the
relational calculus can be reduced to a semantically equivalent expression of
relational algebra.
5. It is sometimes said that languages based on the relational calculus are "higher
level" or "more declarative"
6. Than languages based on relational algebra because the algebra (partially)
specifies the order of operations while the calculus leaves it to a compiler or
interpreter to determine the most efficient order of evaluation.

[Link] M.C.A,[Link],[Link].., Page 64


UNIT IV

 Introduction to ORACLE

1. Oracle is a Relational Database Management System (RDBMS).


2. Oracle being RDBMS, stored data in tables called relations.
3. These relations are data can be representation in two-dimensional
4. The rows are called tuples it represents records
5. The columns called attributes it represents pieces of information contained in the
record.

 1)Benefits of Standardized Relational Language


The main advantages of standardized language are given below.
1. Reduced training cost
2. Enhanced productivity
3. Application portability
a. Application portability means applications can be moved from machine to
machine when each machine uses SQL.
4. Application longevity:
a. A standard language tends to remain so for a long time,
b. There will be little pressure to rewrite old applications.
5. Reduced dependence on a single vendor SQL language development is given in a
nutshell below:
a. In 1970 E.F. Codd of IBM released a paper “A relational model of data for
large shared data banks.”
b. IBM started the project System R to demonstrate (show) the feasibility
(possibility) of implementing the relational model in a database
management system.
c. The language used in system R project was SEQUEL.
d. SEQUEL was renamed SQL during the project, which took place from 1974 to
1979.
6. The first commercial RDBMS from IBM was SQL/DS. It was available in 1981.
7. Oracle from relational software (now Oracle Corporation) was on the market
before SQL/DS, i.e., 1979.
8. Other products included INGRES from relational Technology Sybase from Sybase,
Inc. (1986), DG/SQL from Data General Corporation (1984).

 2) What are the DATA TYPES in SQL:


It specified which type data and size can be stored in a specific field or it specified the
field size and type in a file.
 Numeric:
1. The number data type is used to store zero, positive and negative values.
2. User can specify a fixed point number using the following form
3. There are different types of data types
a. Number(L,D)
b. Integer
c. Smallint
d. Decimal(l,d)

a. Number(L,D):
1. The declaration Number (7,2) indicates numbers
2. That will be stored with two decimal places and may be up to seven digits
long,

[Link] M.C.A,[Link],[Link].., Page 65


3. It includes the sign and the decimal place. Examples: 12.32, -134.23
4. L means length, D means Decimal numbers

Syntax:
Column-name data-type (L);
or
Column-name data-type (L, D)
Ex:
Sno number (3);
or
sno number(7,2);

b. Integer:
1. It may be abbreviated as INT
2. Integers are (whole) counting numbers,
3. So they cannot be used to store numbers that require decimal places
Syntax:
Column-name data-type (L);
Ex:
Sno integer (3);

c. Smallint:
1. Like Integer, but limited to integer values up to six digits.
2. If your integer values are relatively small, use smallint instead of Int.

Syntax:
Column-name data-type (L);
Ex:
Sno smallint(3);

d. Decimal(l,d)
1. Like the number specification, but the storage length is a minimum
specification.
2. That is, greater lengths are acceptable, but smller ones are not.
3. Decmal (9,2), decimal(9), and decimal are all acceptable.

Syntax:
Column-name data-type (L);
or
Column-name data-type (L, D)
Ex:
Sno decimal (3);
or
sno decimal (7,2);

 Character
The character data type is used to store character ( alphanumeric) data. This can
be fixed length or variable length
1. Char(L)
2. Varchar(L) or Varchar2(L)

a. Char(L)
1. Fixed-length character data fro up to 255 characters.
2. If you store strings that are not as long as the char parameter value
3. The remaining spaces are left unused.
4. Therefore, if you specify char (25), each stored as 25 characters

[Link] M.C.A,[Link],[Link].., Page 66


Syntax:
Column-name data-type (L);
Ex:
city char(18);

b. Varchar (L) or Varchar2(L)

1. Variable-length character data


2. The designation varchar2 (25) will let you store characters long.
3. However, varchar will not leave unused spaces.
4. Oracle automatically converts varchar to varchar2

Syntax:
Column-name data-type (L);
Ex:
Sna varchar(25);

Syntax:
Column-name data-type (L);
Ex:
Sna varchar2(25);

c. Date
1. The Date data type is used to store date and time information.
2. For each date value the information stored is, Century, Year, Month, Day,
Hour, Minute, Second
3. The default format of the date data type is ‘DD-MON-YY’.
4. The format can be changed with NLS_DATE_FORMAT command.

Syntax:
Column-name DATE

Ex: date_of_birth date

Long:
The variable length character data up to 4GB

BLOB:
BLOB means Binary Large Object. It store Binary data up to 4GB

CLOB:
Character Large Object. Single byte character up to 4GB

Long raw:
It uses raw binary data up to 2000 bytes

BFILE:
A BFILE can store up to 4GB of data. The BFILE data type stores unstructured
binary data in operating system files outside the database.

 3)Commands in SQL
SQL commands can be classified in to different types:

1. Data Definition Language commands (DDL)


2. Data Manipulation Language commands (DML)
3. Transaction Control Language (TCL)
4. Data Control Language commands (DCL)

[Link] M.C.A,[Link],[Link].., Page 67


Command Category
CREATE
ALTER
DROP Data Definition Language (DDL)
RENAME
TRUNCATE
INSERT Data Manipulation Language
UPDATE (DML)
DELETE Data Retrieval Language
SELECT (DRL)/(DQL) --------------------------------------------- select

COMMIT
Transaction Control Language
ROLLBACK
(TCL)
SAVEPOINT
GRANT
Data Control Language (DCL)
REVOKE

 DDL (DATA DEFINITION LANGUAGE) COMMANDS:


The set of commands are used to define a database including creating.
Altering, dropping and truncate the table command are
1. CREATE: To create a table
2. ALTER: To the table structure
3. DROP: To Delete a table
4. TRUNCATE: To delete all the records.

 CREATE TABLE STRUCTURE

1. The CREATE TABLE command defines each column (Attribute) of the table
uniquely
2. Each column has a name, data type and size (column width).
3. Each table column definition is separated from the other by a COMMA.
4. Finally the SQL statement is terminated with a semi colon.

Syntax: CREATE TABLE tablename


(column1 datatype constraint ,
column2 datatype constraint ,
column3 datatype constraint );

SQL> create table student (sno int,sname varchar2(10),sadd


varchar2(10));

/* SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNO NUMBER(38)
SNAME VARCHAR2(10)
SADD VARCHAR2(10) */

ALTER TABLE STRUCTURE

1. To change (alter) table structure by changing attribute character and by adding


columns.
2. All changes in the table structure are made by using the ALTER TABLE command.
3. ADD, MODIFY and DROP keywords
4. That produces the specific change user want to create

[Link] M.C.A,[Link],[Link].., Page 68


5. Use ADD to add a column, MODIFY to change column characteristics and DROP
to delete a column from a table
6. Most RDBMSs do not allow you to delete a column (unless the column does not
contain any value).
7. The alter table command can also be used to add table constraints.

Syntax:
Alter table table-name ADD constraint [ADD constraint];

 ADDING A COLUMN:

Alter an existing table by adding one or more columns

Syntax:
Alter table table-name add (column name <data type>
(size));

SQL> alter table student add(totalmarks number(3));

Table altered.

/* SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNO NUMBER(38)
SNAME VARCHAR2(10)
SADD VARCHAR2(10)
TOTALMARKS NUMBER(3) */

 CHANGING (MODIFY) A COLUMNS DATA TYPE:

Some RDBMSs such as oracle, do not let you change data type unless the column
to be changed is empty.
Syntax: Alter table table-name add (column name <data type> (size));

SQL> alter table student modify(sno number(20))

Table altered.

/* SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNO NUMBER (20)
SNAME VARCHAR2 (10)
SADD VARCHAR2 (10) */

 CHANGING (MODIFY) A COLUMN’S DATA CHARACTERISTICS

1. The column to be changed already contains data, make changes in the


column’s characteristics if those changes do not alter the data type. Increase
the width of the column size.

Syntax: Alter table table-name modify (column-name data-type (new


size));

[Link] M.C.A,[Link],[Link].., Page 69


SQL> alter table student modify(sname varchar2(15));

Table altered.

/* SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNO NUMBER(20)
SNAME VARCHAR2(15)
SADD VARCHAR2(10) */

 DROPPING A COLUMN: (REMOVE A COLUMN AND REMOVE


TABLE)

1. User wants to delete a table column by using drop


2. User also remove the table using drop command
3. Some RDBMSs impose restrictions on attribute deletion.
4. The attribute that are involved in foreign key relationships not delete an
attribute of table that contains only that one attribute.

Syntax: Alter table-table-name drop column column-name;

Ex: SQL> alter table student drop column sadd;

Syntax: drop table tablename;

Ex: SQL> drop table student;

o RESTRICTION ON ALTER COMMAND:


The alter table command cannot perform the following
1. Change the name of the table
2. Change the name of the column
3. Decrease the size of a column it table data exists.

 RENAMING TABLES:
Changing the table name from old to new name is called rename a table.

Syn: Rename oldtablename to newtablenaem;

SQL> rename student to stu;

 TRUNCATE:
Truncate command is used to delete to all the records permanently from the
database.

Syn: Truncate table tablename;

Eg:SQL> truncate table student;


 DML (Data manipulation language): DATA MANIPULATION COMMANDS

The basic SQL data manipulation commands

1. INSERT: To insert records into a table


2. UPDATE: To update records in a table.
3. SELECT: To display the all rows and columns
4. DELETE: Delete some or all the records in a table

[Link] M.C.A,[Link],[Link].., Page 70


 INSERT (ADDING TABLE ROWS)

SQL requires the use of the INSERT command to enter data into a table.

Syn: INSERT INTO tablename VALUES( value1, value2, value3……);

SQL>insert into student values(2,'ram','gnt',300);

/* The preceding data entry lines:

1. The row contents are entered between parentheses. Note that the first
character after value is a parenthesis and that the last character in the
command sequence is also a parenthesis.
2. Character (String) and date value must be entered between apostrophes (‘).
3. Numerical entries are not enclosed in apostrophes.
4. Attribute entries are separated by commas.
5. A value is required for each column in the table.

This version of INSERT commands adds one table row at a time. */

 INSERTING ROWS WITH OPTIONAL ATTRIBUTES

1. The attributes that have required values, by listing the attribute names inside
parentheses after the table name.

Syntax: INSERT INTO


tablename(cumnname,columname…..)values(value1,value2….);

SQL> insert into student (sno,sname)values(9,'saran');

 UPPDATE (UPDATING TABLE ROWS)

1. The update command to modify data in a table.

Syntax:
UPDATE TABLENAME
SET COLUMNNAME=EXPRESSION, COLUMNAME=EXPRESSION …,
WHERE CONDITION;
Ex:
SQL> UPDATE student SET totalmarks=499 WHERE sname='sam';

1. UPDATE command has not include the WHERE condition, will apply the changes
to all rows in the specified table.

 SELECT ( LISTING TABLE ROWS)

1. The SELECT command is used to list the contents of a table.

Syntax:
SELECT COLUMNLIST FROM Table name; or Select * from Table name;

The COLUMNLIST represents one or more attributes, separated by commas.


Ex:
SELECT ENO,ENAME FROM EMP; or SELECT * FROM EMP;

[Link] M.C.A,[Link],[Link].., Page 71


The * specifies that all columns appears in the EMP table.

 DELETE ( DELETING TABLE ROWS )

1. It is easy to delete a table row using DELETE statement.

Syntax:
DELETE FROM TABLE_NAME
WHERE CONDITION;
Ex:
SQL> delete from student where sno=2;

1. DELETE is a set-oriented command.


2. The WHERE condition is optional.
3. Do not specify WHERE condition, all rows from the specified table will be
deleted.

 Transaction Control Language (TCL)


1. Transaction changes can be made (create) permanent to a database only if they are
committed.
2. A transaction executable statements and end explicitly with either rollback or
commit statement and implicitly.
a. Commit → This is used for save the changes in database
b. Rollback → This is used for do the undo operation
c. Savepoint → Divide the lengthy transaction into small
transactions

 COMMIT (SAVING TABLE CHANGES)

1. Any changes made to the table contents are not saved on disk until user close
the database,
2. To change the database to use the COMMIT command

Syntax: COMMIT [WORK]; Ex: COMMIT;

1. The COMMIT command permanently saves all changes-


2. Such as rows added, attributes modified, and rows delete to any table in the
database.

 ROLLBACK ( RESTORING TABLE CONTENTS )

1. ROLLBACK command work like undo command.


2. The COMMIT command to store the changes permanently in the database.
3. Restore the database to its previous condition with the ROLLBACK command.
4. To restore the data to their pre-change condition.

Syntax: ROLLBACK; Ex: ROLLBACK


 SAVE POINT:
1. Save point are like markers to divide a lengthy transaction to smaller
transactions.
2. Save points are used in conjunction (Combination) with rollback,
3. To rollback portions of the current transaction.

Syntax: savepoint <savepointname>;

Ex: savepoint s1;


/*Ex: SQL> insert into emp values(12,’manju’);

[Link] M.C.A,[Link],[Link].., Page 72


SQL>insert into emp values(13,’sai’);
SQL>savepoint s1;
SQL> insert into emp values(14,’vani’);
SQL>insert into emp values(15,’anu’);
SQL>savepoint s2;
SQL> insert into emp values(16,’rani’);
SQL>insert into emp values(17,’vasu’);
SQL>rollback to s2;*/
1. In the above example we have to define two savepoint markers.
2. When rollback to s2 is given, whatever transactions happened after savepoint s2
will be undone.

 DCL(Data control Languge)


1. DCL commands are used to enforce (implemented) database security in a multiple
user database environment.
2. Two types of DCL commands
a. GRANT
b. REVOKE.
3. Only Database Administrator's or owner's of the database object can
provide/remove privileges (rights) on a database object.

 GRANT:
1. SQL GRANT is a command used to provide access or privileges on the database objects to
the users.

Syntax:
grant privilegesname on <object name> to <username>

• Priviliges name is all/select /execute

• Object name is table /view name

• Username is name of the user

Example: KUMAR: grant all on customers to BABA;

To view the data

Select * from [Link] ; (select * from [Link])

 Revoke:
1. The REVOKE command removes user access rights or privileges to the database
objects.

Syntax:
revoke privileges on <object name>from <username>

Ex: revoke all on customers from BABA;


 SELECTION:
1. To perform (create, display etc) a query we can the select command.
2. The query is a request for the information.
3. It is the most common database operation.

Syntax:
select[distinct | * | column_name[aliase],………]
From <table_nmae>[where<condition>
[Group by column list ]

[Link] M.C.A,[Link],[Link].., Page 73


[Having<condition>]
[Order by column list];

Syntax:

Select column-name1, column-name2 ……… from table-name;

Ex:
Select sno, sname from student;

Syntax:
Select * from table-name;

Ex:
Select * from ABC;

The above example shows all the columns from the student.

 Selecting distinct rows:

1. To prevent (Check) the selection of duplicate rows, we include distinct clause in


the select command.
2. The following examples would eliminate duplicate values present in sname of the
student table.

Ex:
SQL> Select distinct sname from std;

 Select command with ‘where’ clause:


1. To select specific rows from a table we include a ‘where’ clause in the select
command.
2. It can appear only after the ‘form’ clause.
3. We can retrieve only the rows which specify ‘where’ condition.

Ex:
SQL>select *from std where sno=12;

 Select with order by clause command:


1. This clause is used to arrange rows in ascending or descending order.

SQL> Select * from student order by sname;

1. The above query will display the ascending order, which is default option.
2. To display the rows in descending order

SQL> select * from student order by sname desc;


 Group by Clause
1. Group by clause can be used to divide the rows in a table into smaller groups.
2. Group function can be used to return summary information for each group.

Ex:
Select job,avg (sal) from emp group by job;

Select deptno,min(sal) from emp group by deptno;

We can also use the group by clause to provide results for within groups.

[Link] M.C.A,[Link],[Link].., Page 74


Ex:
To display average monthly salary bill for each type within a department

Select deptno, job, avg(sal), from emp group by deptno,job;

Rows may be pre exclude with WHERE clause, before dividing them into groups.

Ex:
To show the average salary for each JOB excluding manager.

Select job, avg(sal) from emp where job!=’MANAGER’ group by job;

 Having Clause
1. It works like a where clause, except that its logic is only related to the results of
group functions as opposite (different) to columns or expressions for individual
rows, which can still be selected with where clause.

Ex:
Select deptno,sum(sal) from emp group by deptno having sum(sal)>1000;

Select deptno,avg(sal) from emp group by deptno having coun(*)>3;

Select job, avg(sal) from emp where job!=’MANAGER’ group by job;


Or
Select job,avg(sal) from emp having job!=’MANAGER’ group by job;
Or
Select job,avg(sal) from emp group by job having job!=”MANAGER’;

 PROJECTION OPERATION
1. The projection operation performs column wise filtering.
2. Specific columns are selected in projection operation.

Syntax:

SELECT column-name1, column-name2, Column-name N FROM table-name;

If all the columns of the table are selected, then it cannot be considered as PROJECTION.

1. The SQL command to perform PROJECTION operation on the relation PEAKS and
the corresponding results
2. it is clear that only three columns are selected in the result.

Ex: select sno,sname from std;

 3) GROUP FUNCTIONS: OR AGGREGATE FUNCTIONS:


1. These functions can be used for calculations on groups of selected records.
2. Group functions can appear in select lists, GROUP BY and/or HAVING clauses.
They are,

a. Count → The no. of rows containing non-null values


b. Min → The minimum attribute value encountered in a given column
c. Max → The mximum attribute value encountered in a given column
d. Sum → The sum of all valued for given column
e. Avg → The arithmetic mean (average) from specified column

a. COUNT:

[Link] M.C.A,[Link],[Link].., Page 75


1. The count function is used to tally (count) the number of non-null values of an
attribute.
2. COUNT can be used in conjunction (combination) with the distinct clause.

SQL> SELECT COUNT (EMPNO) FROM EMP;

/* COUNT(EMPNO)
------------
14 */

SQL> SELECT COUNT (*) FROM EMP WHERE SAL < =1500;

/* COUNT(*)
--------
7 */
Count (*) returns the number of total rows returned by the query, including the
rows that contain nulls.

b. MAX:
1. The aggregate function Max (column) can be used only in the column list of a select
statement.
2. It returns a minimum value of a expression.

SQL> SELECT MAX (SAL) FROM EMP;

c. MIN:
1. The aggregate function Min (column) can be used only in the column list of a select
statement.
2. It returns min value of a given expression

SQL> SELECT MIN (SAL) FROM EMP;


/*
MIN(SAL)
--------
800 */
d. SUM:
1. The sum function computes the total sum fro any specified attribute, using whatever
condition.

SQL> SELECT SUM (SAL) FROM EMP;

e. AVG:
The avg function format is similar to that of min and max. it returns an average
value of given column name

SQL> SELECT AVG(SAL) FROM EMP

 SINGLE ROW FUNCTIONS:

1. The single row functions can appear in a select command and can also be
included in where class.
2. The single row functions classified as
a. Date ,
b. Numeric
c. Character
d. Mislenious

[Link] M.C.A,[Link],[Link].., Page 76


3. The examples which are not based on a particular table use the system table
‘dual’.
4. It is a table which is automatically created by oracle along with the data
dictionary.
5. DUAL is a table owned by SYS.
6. SYS owns the data dictionary, and DUAL is part of the data dictionary.
7. Dual is a small oracle worktable, which consists of only one row and one
column
8. It contains the value X in that column.
9. Besides arithmetic calculations, is also supports date retrieval and it’s
formatting.

 4)DATE FUNCTIONS: -

They operate on date values producing O/P which also belongs to date,
Data type except for months between date function which returns a number.

1. Add – months: It returns a date data type as a result format add-months date,
number.

Eg: - Select add_months ('27-Aug-04',2) from dual;

/* ADD_MONTH
---------
27-OCT-04 */

2. Months-between:
a. It returns a number date type as a result. Formate: - moths-between
date1, date2;

Eg: - SQL> SELECT MONTHS_BETWEEN ('27 -AUG-85', '06-OCT-83') FROM


DUAL;

/* MONTHS_BETWEEN('27-AUG-85','06-OCT-83')
---------------------------------------
22.68 */

3. System date: It returns the system date;

Eg: -
SQL> SELECT SYSDATE FROM DUAL;

/* SYSDATE
---------
24-SEP-10*/

Returns the date 'x' rounded off to the nearest


ROUND (x, date_format) century, year, month, date, hour, minute, or
second as specified by the 'date_format'.

Returns the date 'x' lesser than or equal to the


TRUNC (x, date_format) nearest century, year, month, date, hour, minute,
or second as specified by the 'date_format'.

NEXT_DAY (x, week_day)


Returns the next date of the 'week_day'on or after

[Link] M.C.A,[Link],[Link].., Page 77


the date 'x' occurs.

It is used to determine the number of days


LAST_DAY (x)
remaining in a month from the date 'x' specified.

examples
NEXT_DAY( ) NEXT_DAY ('01-Jun-08', 'Wednesday') 04-JUN-08

LAST_DAY( ) LAST_DAY ('01-Jun-08') 30-Jun-08

 5) NUMERIC FUNCTIONS: -
1. Numeric functions accept numeric inputs and returns numeric values as the result.
2. The values that numeric functions return or accurate upto 38 decimal digits.
3. Numeric functions are:

Abs( ): - It returns absolute value

SQL> Select abs(-12.3467) from dual ;

/* ABS(-12.3467)
-------------
12.35 */

Power ( ): - It returns the power value to the base value.

SQL> Select power (3,4) from dual;

/* POWER(3,4)
----------
81 */

Trunc ( ): - It returns truncated values

SELECT TRUNC(12.3456,2) FROM DUAL;

/* TRUNC(12.3456,2)
----------------
12.34 */

Round ( ): - It returns a number which is rounded upto some decimal points.

SQL> SELECT ROUND (12.3456,2) FROM DUAL;

/* ROUND(12.3456,2)
----------------
12.35*/

Sqrt(): it returns square root of given number

Sql> select sqrt(25) from dual;

Floor ( ): - It returns the previous value.

SQL> SELECT FLOOR (68.78) FROM DUAL;

[Link] M.C.A,[Link],[Link].., Page 78


/* FLOOR(68.78)
------------
68 */

Ceil ( ): - It returns next value.

SQL> SELECT CEIL (68.78) FROM DUAL;

/*CEIL(68.78)
-----------
69 */
 6) CHARACTER FUNCTIONS: -
1. Characters functions accepts character input it returns either character value or
number some of these functions are

initcap ( ): - It returns first letter as a capital letter of the string.

Eg: - Select initcap ('ram') from dual

/* INI
---
Ram */

Concat( ): - It combines two strings

SQL> Select concat('good', 'day') from dual;

/* CONCAT(
-------
goodday */

Upper ( ): - It convert all lower case letters into upper case.

SQL> Select upper ('good') from dual;

/* UPPE
----
GOOD */

Lower ( ): - It converts all the uppercase letters into lower case.

SQL> SELECT LOWER ('RAM') FROM DUAL;

/* LOW
---
Ram */

Lpad ( ): - It adds the string to the left side of the string1

Eg: - Select Lpad (‘good’,12,’day’) from dual;

/* LPAD('GOOD',
------------
DAYDAYDAGOOD */

Rpad ( ): - It add the string2 to the right side of the string1.

[Link] M.C.A,[Link],[Link].., Page 79


Eg: - Select Rpad (‘good’,12,’day’) from dual;

/* RPAD('GOOD',
------------
Gooddaydayda */

Ltrim ( ): - It removes left side spaces of the string

Eg: - select ltrim(‘ Raj’) from dual;

Rtrim ( ): - It removes right side spaces of the string

Eg: - select rtrim ( ‘sai ‘) from dual;

/* RTR
---
Sai */

SUBSTR (str, position, [length])

SELECT SUBSTR (Store_Name, 3)


FROM Geography
WHERE Store_Name = 'Los Angeles';

Result:

SUBSTR (Store_Name, 3)

s Angeles

Example 2

SELECT SUBSTR (Store_Name, 2, 4)


FROM Geography
WHERE Store_Name = 'San Diego';

Result:

SUBSTR (Store_Name, 2, 4)

an D

Char ( ): - It returns a character according to the ASCII value

Eg: - select chr(65) from dual;

/* Chr
----
A */
INSTR (str, pattern, [starting position, [nth location]])

SELECT INSTR (Store_Name, 'o')


FROM Geography
WHERE Store_Name = 'Los Angeles';

[Link] M.C.A,[Link],[Link].., Page 80


Result:

2
Length (str)

SELECT Length (Store_Name)


FROM Geography
WHERE Store_Name = 'Los Angeles';

Result:

Length (Store_Name)

11

Replace (str1, str2, str3)

In str1, find where str2 occurs, and replace it with str3.

Assume we have the following table:

Table Geography

Region_Name Store_Name

East Boston

East New York

West Los Angeles

West San Diego

If we apply the following Replace function:

SELECT REPLACE (Region_Name, 'ast', 'astern') REGION1


FROM Geography;

Result:

REGION1

Eastern

Eastern

West

West

 7) MISLENIOUS FUNCTIONS:

Greatest ( ): - It returns the highest value

Eg: - select greatest (100,200,300) from dual;

[Link] M.C.A,[Link],[Link].., Page 81


/* GREATEST(100,200,300)
---------------------
300 */

Least ( ): - It returns least value;

Eg: - Select least(100, 200) from dual;

/* LEAST(100,200)
--------------
100 */

User: - It returns user name;

SQL> Select user from dual;

/* USER
-----------
SCOTT */

UID( ): - It return user ID which is stored in server.

SQL> Select UID from dual;

/* UID
----------
66 */

Explain various types of operators in SQL (or) WHERE clause?


The following are the different types of OPERATORS used in where clause.

1) Arithmetic operators : +, -, *, /

2) Comparison operators : =, !=, >, <, >=, <=, <>


between, not
betweenin,
not in
is null,
is not
nulllike

3) Logical operators : And, Or, Not

4) Set operators : union, Union all, Intersect, Minus

1) Arithmetic operators: Which are used for arithmetic calculations like,


Addition (+),Subtraction ( - ), Multiplication ( * ), Division (/)

[Link] M.C.A,[Link],[Link].., Page 82


Ex:
select sal "old_sal", sal+1000 "new_sal" from emp;
select sal "old_sal", sal-1000 "new_salary" from emp where job=’clerk’;
select sal "old_sal", sal+(sal*5/100) "new_sal"
from emp;select 5000/100 from dual;
2) Comparison operators:
a) =, >, <, >=, <=, !=, <>: These are used to compare
the [Link]:
select * from student where no = 2;
select * from student where sno < 2;
select * from student where sno > 2;
select * from student where sno <= 2;
select * from student where sno >= 2;
select * from student where sno != 2;
select * from student where sno <> 2;
b) BETWEEN: This will gives the output based on the column and its lower bound,
upper [Link]:
select * from <table_name> where <col> between <lower bound> and <upper

bound>;

Ex: select * from student where marks between 200 and 400;
c) NOT BETWEEN: This will gives the output based on the column which values
are not in itslower bound, upper bound.
Syntax:
select * from <table_name> where <col> not between <lower bound> and

<upper bound>;

Ex:
select * from student where marks not between 200 and 400;

d) IN: This will gives the output based on the column and its list of
values [Link]:
select * from <table_name> where <col> in ( value1, value2, value3 ……

value n);

Ex:
SQL> select * from student where sno in (1, 2, 3);

e) NOT IN: This will gives the output based on the column which values
are not in thelist of values specified.
Syntax:
select * from <table_name> where <col> not in ( value1, value2, value3 …

value n);

Ex:

[Link] M.C.A,[Link],[Link].., Page 83


select * from student where sno not in (1, 2, 3);

f) IS NULL: This will gives the output based on the null values in the
specified [Link]:
select * from <table_name> where <col> is null;

Ex:
sQL> select * from student where marks is null;

g) NOT NULL: This will gives the output based on the not null values in the
specified [Link]:
select * from <table_name> where <col> is not null;

Ex:
select * from student where marks is not null;

h) LIKE: This will be used to search through the rows of database column based on
the Patternyou specify.
Syntax:
select * from <table_name> where <col> like <pattern>;

i) This will give the rows whose marks are


[Link] * from student where marks
like 100;
ii) This will give the rows whose name start with ‘S’.

select * from student where name like 'S%';

iii) This will give the rows whose name ends with ‘h’.
select * from student where name like '%h';

iv) This will give the rows whose name’s second letter start with ‘a’.
select * from student where name like '_a%';

V) This will give the rows whose name’s third letter start with ‘d’.

select * from student where name like ' d%';

Vi) This will give the rows whose name’s second letter start with ‘t’ from ending.

select * from student where name like '%_t%';

Viii) This will give the rows whose name contains 2


a’s.

[Link] M.C.A,[Link],[Link].., Page 84


select * from student where name like '%a% a %';

3) Logical operators:
a) AND:
This will gives the output when all the conditions become true.
Syntax:
select * from <table_name> where <condition1> and <condition2> and ..

<condition n>;

Ex:
select * from student where sno = 2 and marks >= 200;

 EXPLAIN RELATIONAL SET OPERATORS.


1. Set operators combine the results of two queries into a single one.
2. Queries containing set operators are called compound queries.
3. The set operators are:
a. Union
b. Union all
c. Intersect
d. Minus
a. Union:
1. The union operator merges the output of two or more queries into a single set of
rows and columns.
2. The following statement combines the results with the union operator,
3. It eliminates duplicate selected rows.

Syntax:
Select query
Union
Select query;
Ex:
select job from emp where deptno=10
union
Select job from emp where deptno=20;

b. UNION ALL:

The UNION ALL operator written all rows selected by either query including
duplicates.

Syntax:
Select query
Union all
Select query;
Ex:

select job from emp where deptno=10


union all
Select job from emp where deptno=20;

c. Intersect:
The intersect operator writtens only rows that are common to both the queries.

[Link] M.C.A,[Link],[Link].., Page 85


Syntax:
Select query
intersect
select query;

Ex: select job from emp where deptno=10


Intersect
Select job from emp where deptno=20;

D .Minus:
Minus operator writtens all distinct rows selected only by the first query and not by the
second.

Syntax:
Select query
Minus
Select query;
Ex:
SQL> select job from emp where deptno=10
minus
Select job from emp where deptno=20;

 8) EXPLAIN DIFFERENT TYPES OF CONSTRAINTS.


1. Constraint is a rule that can be applied on a table or a column of a table.
2. Constraints can also be used to prevent (check) mistakes in data entry.
3. Constraints can be categorized into following,

1. Domain Integrity Constraints


a. Not null b. Check

2. Entity Integrity Constraints.


a. Primary key b. Unique

3. Referential Constraint
a. Foreign key

 Domain Integrity constraints


1. Not Null:
1. By default all columns in a table allow NULL values.
2. When a NOT NULL constraint is enforced on a column in a table,
3. It will not allow NULL values into that column.

Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> NOT NULL);
Example:
Create table tab (no number(3) constraint C NOT NULL);

[Link] M.C.A,[Link],[Link].., Page 86


2. Check constraint
1. These are rules govern logical expressions or Boolean expressions.

Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> check
(column name with condition));
Example:

Ex1: Create table stud (marks number (5) constraint c1 check (marks>35));

Ex2: alter table emp add constraint ck_emp check (sal + comm <10000);

 Entity Integrity Constraints


1. Unique Constraint:
1. This constraint allows only unique values to be stored in the column.
2. Oracle rejects duplication of records when the unique key constraint is used.
3. It can also allow NULL values. Since two NULL values are not allowed because
it is duplicate.

Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> unique
(column name));
Ex:
Create table JDC (sno number(10) , sname varchar2(10), sphno number(15)
unique);

2. Primary key constraint:


1. It avoids duplication of rows and does not allow NULL values.
2. Primary key is the combination of NOT NULL and UNIQUE.
3. It is also used to set the relations between the tables.
4.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> primary key);
Ex:
Create table student(sno number(10) constraint P primary key, sname
varchar2(10));

3. Default constraint:
1. Its read automatically value when user not enter value

[Link] M.C.A,[Link],[Link].., Page 87


Syntax:
Create table <table name> (<Column name> <data type>
<Default> <value>)
Ex:
CREATE TABLE Persons (id number (3), name varchar2 (20) default
‘abhyudaya’);
 Referential Integrity Constraints
1. Foreign key Constraint
1. The referential integrity constraints enforce (impose) the relationship between the
tables
2. Tables are used primary key
3. It helps in creating a parent child relation ships between the tables.
4. A referential integrity constraint assigns a column as a foreign key.
5. Child table primary key is called foreign key
6. Parent table primary key is called referenced key is called parent table.

Syntax:
Create table <table name> (<column name> <data type>,
constraint <constraint name> references
<table name> (column name));
Ex:
Create table emp1 (eno number(3) constraint P1 primary key,
ename varchar2(20));

Now connecting the dept and emp using foreign key

Create table dept1(eno number(3) references emp1(eno),


dname varchar2(20));

 9)DELETING, ADDING A CONSTRAINT IN TABLES


1. The user can disable or remove or enable constraints attached to the column
with the help of alter command.

Syntax:

[Link] M.C.A,[Link],[Link].., Page 88


Alter table <table name> disable|enable constraint <constraint name>;

Alter table <table name> modify (<column name> <data type>


constraint <constraint name> <constrain type>);
Removing a Constraint:
1. To remove constraint attached to a column name alter with drop constraint
is used.

Syntax:
Alter table <table name> drop constraint <constraint name>;

 11) EXPLAIN JOINS.


1. The purpose of join is to combine the data spread across the tables.
2. There are basically three types.
a. Simple join,
b. Self join,
c. Outer join.

 Simple Join:
1. It retrieves rows from two tables having a common column and further
2. It classified into
a. Equi join and
b. Non equi join.

a. Equi Join:
A join which is based on equality is called an equi join.

Ex:

Select e. ename, [Link], [Link], [Link], [Link] From emp e , dept d


Where [Link]=[Link];

/* To display employee name, job, department no, department name and


location in which the employees work. */

b. Non Equi Join :


A non equi join specifies the relationship between column belonging to different
tables.

Ex:
Select ename,sal,losal,hisal,grade From emp,salgrade Where sal between losal
and hisal;

/* To display the grades of the employees based on salary. */

 Self Join (Recursive Join):


1. Joining of table to itself is known as self join.
2. An table alias is especially useful when a table must be joined to itself.

Ex:

Select [Link],[Link] from emp e1,emp e2 Where [Link]>[Link] and


[Link]=’CLARK’;

/* To display all employees getting salary > clark.*/

[Link] M.C.A,[Link],[Link].., Page 89


 Outer Join:
1. An outer join returns all the rows returned by simple join as well as those rows
from one table
2. That don’t match any row from the other table Using (+) operator.

Ex:

Select ename, job, dname from emp e, dept d Where [Link](+)=[Link] ;

/*To which department name , job and location from department that does
not corresponding employees*/

 12) EXPLAIN VIEWS OR VIRTUAL TABLES


1. A view is a virtual table based on select query.
2. The query contain column, computed column and aggregated functions from one
or more tables.
3. The tables on which the view is based are called base tables.

Syntax:

Create view <view name> as select query;

Characteristics
1. You can use the name of view any where a table name is expected in SQL
statements.
2. Views are dynamically updated. i.e. the view is recreated on demand each time is
invoked.
3. Views provide a level of security in the database because the view can restrict
users to only specified column and specified rows in a table.
4. View may also be used as the basis for reports.
5. It use little storage space.
6. It establishes physical data Independency.
Disadvantages
1. Use processing time, each time the view is referenced.
2. It may or may not be directly updatable.

Drop View command


To delete a view from the database we use the drop view command.

Syntax:

Drop view <view name>;

Updatable Views
1. User can’t join tables in the update statement.
2. To solve that problem, users have to create update view.
3. An update view is a view that can be used to update attributes in the base table
that are used in the views.

Restrictions:

1. Group by expressions of aggregate functions can not be used in the update views.
2. User can’t use set operators.
3. Most restrictions are base on the use of joins or group operators in view.

Materialized Views

[Link] M.C.A,[Link],[Link].., Page 90


1. A materialized view is a physical copy of the base table
2. The results moved to another schema object.
3. Materialized views are also called snapshots
4. Because they are a kind of photograph of the base table.

Advantage of VIEW
1. The main advantages of view are
a. Improved security,
b. less complexity,
c. better convenience, and
d. Customization.

1. Improved security:
a. We can restrict the user to access on the data that are appropriate for the
user.
b. Hence views provide improved security.

2. Less complexity:
a. A view can simplify queries,
b. By getting data from several tables into a single table
c. Transforming multi table queries into a single table queries.

3. Convenience:
a. A database may contain much information.
b. All the information will not be useful to the users.
c. The users are provided with only the part of the database
d. That is relevant to them rather than the entire database;
e. Hence views provide great convenience to the users.

4. Customization:
a. Views provide a method to customize the appearance of the database
b. So that the users need not see full complexity of database.
c. View creates the illusion of a simpler database customized to the needs of a
particular category of users.

Drawback of VIEW
1. If the base table is modified by adding one or more columns
2. Then the columns added will not be available in the view unless it is recreated.
3. When a view is created from the base table, it is to be noted that all the views are
not updatable.
4. Views created from multiple tables are in general not updatable when there is a
group function, a GROUP BY clause, or restriction operators.

 12)Explain Sub queries and Correlated sub queries

SUBQUERY: (BASIC CHARACTERSTICS OF A SUB QUERY)


1. A Sub query is a query inside a query.
2. A sub query is normally expressed inside parentheses.
3. The first query in the SQL statement is known as the outer query.
4. The query inside the SQL statement is known as the inner query .
5. The inner query is executed first.
6. The outer query of an inner query is used as the input for the outer query.
7. The entire SQL statements are sometimes referred to as a nested query.

Sub queries are 2 types.


1. single row sub queries,
2. multiple row sub queries

[Link] M.C.A,[Link],[Link].., Page 91


Single row sub queries
It returns only one row from the inner select statements.

Multiple row sub queries


It returns more then one row from the inner select statements.

Rules
1. Enclose sub queries in parentheses.
2. Place sub queries on the right side of the comparison condition
3. The order by clause in the sub query is not needed unless you are performing top n
analysis.
4. Single row comparison operators are >,<=,<>,>=

Ex: /* Who gain more than smith salary?*/

Select ename from emp where sal > (select sal from emp where ename=’smith’);

Group functions in sub queries: (Where sub queries)

The most common type of sub query uses an inner SELECT subquery on the right
side of a WHERE comparison expression.

Ex:
SQL> select ename,sal from emp where sal>=(select avg(sal) from emp);

Having clause with sub queries:

A subquery with a HAVING clause , the HAVING clause is used to restrict the
output of a GROUP BY query by applying a conditional criteria to the grouped
rows.

Ex:
SQL> select deptno, sum(sal)
2 from emp
3 group by deptno
4 having sum(sal)>(select avg(sal) from emp);

Multiple row sub queries


It retrieves multiple rows result using the following operators
1. All
2. Any
3. In
4. not exit

1. MULTIROW SUBQUERY OPERATORS: IN, ANY AND ALL


All
1. The use of the ALL operator allows, to compares a single value with a list of
values
2. It returned by the sub-query using comparison operator other than equals.

ANY
1. ANY operator is multi row operator.
2. The ANY operator allows, to compares a single value of the list or less than
any value of the list.

SQL> Select * from staff

[Link] M.C.A,[Link],[Link].., Page 92


Where sal>=All
(Select sal from staff
Where deptna=’comp’);

IN
1. The equal to IN operator, which would be the equivalent of the ANY
operator.

SQL> Select sal*40 from emp


where sal in (select sal from emp where sal>=50000);
/*
select ename ,sal*40 from emp 2
where sal*40>
all(select sal*40 from emp where sal in
(select sal from emp where sal>=50000));
Ex:
Find the employee who earn the same the salary as the min salary for each
departments.
Select ename , sal, deptno from emp
Where sal in(select min(sal)from emp group by deptno);

To display employee who are clerk and whose salary is less than that of any clerk.
Select empno,ename,job,sal from emp
Where sal<any(select sal from emp where job=’clerk’); */

Example of NOT EXISTS Operator


1. In order to understand NOT EXISTS clause,
2. Ex: two relations EMPLOYEE and DEPENDENT.
3. Here DEPENDENT refers to those who are dependent on EMPLOYEE.
4. The attributes of EMPLOYEE relation are eid (employee ID), ename (employee
name). The attributes of the DEPENDENT relation are name (which refers to
dependent name)

[Link] M.C.A,[Link],[Link].., Page 93


5. and eid (employee ID).

[Link] M.C.A,[Link],[Link].., Page 94


Ex:
Sql> select ename from emp
Where not exists (Select eid from dep
Where [Link]=[Link]);
1) Correlated sub query:
1. The subquery , the inner subquery executes first,
2. Its output is used by the outer query,
3. Which then executes until the last outer query executes.
4. A correlated subquery that executes once for each row in the outer query.

UNIT V

PL/SQL: Introduction, Shortcoming in SQL, Structure of PL/SQL, PL/SQL Language


Elements, Data Types, Operators Precedence, Control Structure, Steps to Create a
PL/SQL, Program, Iterative Control, Cursors, Steps to create a Cursors, Procedure,
Function, Packages, Exceptions Handling, Database Triggers, Types of Triggers.

 1) PL/SQL (Procedural Language/Structured Query Language):


1. PL/SQL stands for Procedural Language extension of SQL.
2. PL/SQL is a combination of SQL along with the procedural features of programming
languages.
3. It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of
SQL.

PL/SQL Block Structure:


1. A PL/SQL block contains 1 or more PL/SQL statements.
2. Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL
block.

Syntax:

Declare
Variable declaration
Begin
Process statements
Or execution statement
[Exception
Exception statement]
End;

[Link] M.C.A,[Link],[Link].., Page 95


A PL/SQL block can be divided into four sections. They are
1. Declaration section
2. Begin section
3. Exception section
4. End section

1. Declaration Section:
1. Code blocks start with a declaration section
2. In this block memory variable and other oracle objects can be declared
3. They can be used in SQL statements for data manipulation.

Example:
Declare
First_name varhcar2(10);
Num number(10);

2. Begin Section:
1. It consists of a set of SQL and PL/SQL statements
2. It describes process that has to be applied to table data.
3. Actual data manipulation, retrieval, looping and branching constructs are
specified in this section.
3. Exception Section:
1. This section deals with handling of errors
2. That arise during execution of the data manipulation statements
3. The errors can arise due to syntax and logic.

4. End Section:
a. This makes the end of a PL/SQL block.

Example:

Declare
a number(4);
b number(4);
c number(4);
begin
a:=10;
b:=20;
c:=a+b;
dbms_output.put_line(c);
end;

/*
1. dbms_ouput: it is a package.
2. That includes a number of procedures and functions that accumulate information
in a buffer so that it can be retrieved later.
3. These functions can also be used to display message.
4. put_line: put a piece of information in the package buffer followed by an end-of-
line marker.
5. dbms_ouput.put_line(‘Hello’);*/

 2) PL/SQL Language Elements

There are different elements


1. Character Set
2. Lexical Units

[Link] M.C.A,[Link],[Link].., Page 96


a. Delimiters
b. Identifiers
c. Literals
d. Comments

1. Character Set
1. A PL/SQL program consists of text having specific set of characters.
2. Character set may include the following characters:
a. Alphabets, both in upper case [A–Z] and lower case [a–z]
b. Numeric digits [0–9]
c. Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % , __ # $ & | { } ? [
]
d. Blank spaces, tabs, and carriage returns.

2. Lexical Units
1. A line of PL/SQL program contains groups of characters known as lexical units,
which can be classified as follows:
A. Delimiters
B. Identifiers
C. Literals
D. Comments

A. Delimiters
a. A delimiter is a simple or compound symbol
b. That has a special meaning to PL/SQL.
c. Simple symbol consists of one character
d. Compound symbol consists of more than one character.

B. Identifiers
a. Identifiers are used in the PL/SQL programs
b. To name the PL/SQL program items
i. Like constants, variables, cursors, cursor variables, subprograms,
etc.
c. Identifiers can consists of alphabets, numerals, dollar signs,
underscores, and number signs only.
d. Any other characters like hyphens, slashes, blank spaces, etc.

C. Literals
a. A literal is an explicitly defined character, string, numeric, or Boolean
value,

D. Comments
1. Comments are used in the PL/SQL program
2. It used to improve the readability and understandability of a program.
3. A comment can appear anywhere in the program code.
4. The compiler ignores comments.
5. Generally, comments are used to describe the purpose and use of each
code segment.

Ex: /* Hello World! This is an example of multiline comments in PL/SQL */

 3) What are the data types available in PL/SQL?

Data type Description


Char Character value of fixed length
Varchar2 Variable length character value

[Link] M.C.A,[Link],[Link].., Page 97


Number Numeric values
Date Date values
Inherits the data type from a variable that you declared
% type
previously in database table.
It is used to declare variable to keep a single record, since a
% row
record is nothing but collection of column. This is also known as
type
composite data type.
Boolean data type can be used to store the values true, false or
Boolean
null.

4) Variable declaration
<variable name> data type [(size)] := &variable name;

 5) Explain Control Structures in PL/SQL?


The follow of control statements can be classified into the following categories.
1. Conditional control
2. Iterative control
3. Sequential control

1. Conditional control
1. Conditional control, which run different statements for different data values.
2. It check the condition for single time only even it is true or false
3. The conditional control statements are If and case.
a. IF
i. If then statement
ii. If then else statement
iii. If then else if statement
iv. Nested if statement
b. Case

 If statement
If condition is true it can execute statement 1 to statement n otherwise it
cannot execute statement 1 to statement n.

Syntax:
if(condition) then
Statement 1;
……………
Statement n;
End if;

Example:
DECLARE
a number:=&a;
BEGIN
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if;
END;

 If then else statement


If condition is true it can execute statement 1. If the condition is false it
execute else statement or execute statement 2.

[Link] M.C.A,[Link],[Link].., Page 98


Syntax:
if(condition) then
Statement 1;
else
statement 2;
end if;

Example:
declare
a integer;
b integer;
begin
a:=&a; /* it take run time values*/
b:=&b; /* it take run time values*/
if(a>b) then
dbms_output.put_line(‘A is big’);
else
dbms_output.put_line(‘b is big’);

end if;
end;

 If then else if statement


If condition is true it can execute statement 1. If the condition is false its
again chek for another condition if it is true it can execute statement 2. Other
execute else statement or execute statement 3.

Syntax:
if(condition) then
Statement 1;
elsif(condition) then
statement 2;
else
statement 3;
end if;

Example:
declare
a integer;
b integer;
c integer;
begin
a:=&a;
b:=&b;
c:=&c;
if(a>b and a>c) then
dbms_output.put_line(‘a is big’);
elsif(b>c) then
dbms_output.put_line(‘b is big’);
else
dbms_output.put_line(‘c is big’);
end if;
end;

 Nested if statement

[Link] M.C.A,[Link],[Link].., Page 99


Inner if is called nested if. if condition is false it execute stamen 3.
Other wise it is true its check for another condition if it is true it execute
statement 1 other wise execute statement 2.

Syntax:
if(condition) then
if(condition) then
statement 1;
else
statement 2;
end if;
else
statement 3;
end if;

Example:
declare
a integer;
b integer;
c integer;
begin
a:=&a;
b:=&b;
c:=&c;
if(a>b) then
if(a>c) then
dbms_output.put_line(‘a is big’);
else
dbms_output.put_line(‘c is big’);
endif;
elsif(b>c)
dbms_output.put_line(‘b is big’);
else
dbms_output.put_line(‘c is big’);
end if;
end;

 Case:
Syntax:
case variablename
When value1 then stmt;
When value2 then stmt;
……………
Else stmt;
End case;
1. The case statement runs the first statements for which value equals variable
name remaining conditions are not evaluated.
2. If no value equals to variable name, the case statements runs else statements.

Ex:
declare
Grade char:=’&grade’;
begin
case grade
when ‘A’ then dbms_output.put_line(‘Excellent’);
when ‘B’ then dbms_output.put_line(‘Very good’);
when ‘C’ then dbms_output.put_line(‘Good’);

[Link] M.C.A,[Link],[Link].., Page 100


when ‘D’ then dbms_output.put_line(‘Fair’);
when ‘F’ then dbms_output.put_line(‘poor’);
else dbms_output.put_line(‘no such grade’);
end case;
end;

2. Iterative control (or) Loop controls


Iterative statements are check the condition if condition is true it execute the
statements and again check the condition up to condition is false. There are different
types of iterative statement.

1. Simple loop
2. While loop
3. For loop

1. Simple loop:
The statements that exit a loop are
o Exit
o Exit when

Syntax:
Exit: Exit when:
Loop Loop
Statement; Statement;
Exit; Exit when(condition);
end loop; end loop;

Example: Exit
Declare
n number:=0;
begin
loop
n:=n+1;
dbms_output.put_line(‘the value of n is’||n);
if(n>=10) then
exit;
end if;
end loop;
end;

2. while loop:
It is entry control loop. First check the condition if it is true it can be
execute and again check condition if it is true it can again execution other wise it
close the while loop.
Syntax:
While(condition)
loop
Statement 1;
…………
Statement n;
end loop;
Example:
declare
i number := 0;
begin
while i<= 10

[Link] M.C.A,[Link],[Link].., Page 101


loop
i:= i+ 1;
dbms_output.put_line('the value of i is ' || i);
end loop;
end;
3. For loop:

Syntax:
for variable in[reverse] start . . end
Loop
Statement 1;
…………
Statement n;
end loop;
Example:
begin
for i in 1..10
loop
dbms_output.put_line('the value of i is ' || i);
end loop;
end;

 SEQUENTIAL CONTROL:
1. Sequential control statements, which are not crucial (central or Main) to PL/SQL
programming.
2. The sequential control statements are
a. GOTO
It goes to a specified statement, and NULL, which does nothing.

Goto statement:
1. The Oracle PL/SQL GOTO statement is a sequential control structure available in
Oracle.
2. The GOTO statement immediately transfers program control (called "branching")
using with label or block label.
3. The statement or label name must be unique in the block.

Syntax:
<<Lable>>
Statement 1;
…………..
Statement n;
if(condition) then
Goto label;
end if;
Ex:
declare
n integer:=&n;
i integer:=1;
begin
<<p>>
dbms_output.put_line(i);
i:=i+1;
if(i<=n) then
goto p;
end if;
end;

[Link] M.C.A,[Link],[Link].., Page 102


 6)Explain processing with cursors in PL/SQL.
1. PL/SQL provides to access more than one record from database
2. This method is a combination of select statement and memory management
routines from PL/SQL
3. To retrieve records from database using select statement and places them with in
memory known as cursor.

There are two types of cursors.

 Implicit Cursor –
1. It is automatically created in PL/SQL when the SQL statement returns only
one value.

 Explicit Cursor –
1. It is created to hold the output of an SQL statement that may return two or
more rows.

Syntax:
Cursor <cursor name> is select query;

Cursor process commands open, fetch (get) and close any where between begin and
end keywords of PL/SQL block.

Command Explanation
1. Open the cursor, execute the SQL command and
populate the cursor with data.
Open 2. Before you can use a cursor, you need to open it.
Syntax:
open <cursor name>;
1. The fetch command to retrieve data from the cursor
and copy it to the PL/SQL variables for processing.
Fetch
Syntax:
fetch <cursor name> into <var list>;
1. The close command closes the cursor for processing.
Close Syntax:
close <cursor name>;

Syntax:
Declare
Cursor <cursorname> is <select statement>;
Variable declaration;
Begin
Open <cursorname>
Fetch <cursorname> into variablename1…..;
close <cursorname>;
End;

[Link] M.C.A,[Link],[Link].., Page 103


 Cursor Attributes

Attribute Description
Keeps the count of record for each fetch when the cursor is
%rowcount
open. Other wise it returns 0.
Keep Boolean values TRUE if fetch is successful otherwise
%found
FALSE if fetch did not return any row.
Keep Boolean values TRUE if fetch is did not return any row
%notfound
otherwise FALSE.
Returns TRUE if cursor is open otherwise FALSE if the cursor
%isopen
is closed.

Example:
Declare
a emp%rowtype;
cursor c2 is select * from emp where deptno=&deptno;
begin
open c2;
loop
fetch c2 into a;
if c2%found then
dbms_output.put_line([Link]||’ ‘||[Link]||’
‘||[Link]);
else
exit;
end if;
end loop;
close c2;
end;

 7)Explain PL/SQL Stored functions. or


 Stored procedures or
 Routines or
 sub programs:

Subprograms
1. Subprogram is a program unit/module
2. That performs a particular task. It also called block.
3. These subprograms are combined to form larger programs.
4. This is basically called the 'Modular design'. A
5. Subprogram can be invoked by another subprogram or program which is called
the calling program
6. Subprograms can be created at the schema level, inside the package, and inside
block
7. They are two types of sub programs

1. Procedures
2. Functions

Parameter Modes in PL/SQL Subprograms

User create a Procedure or function, you have to define this three parameters.

1. In
2. Out
3. In out

[Link] M.C.A,[Link],[Link].., Page 104


1. IN
a. IN parameter is referenced to the procedure or function.
b. Input parameter only, the value passed is input only.
c. And value of parameter in not overwritten

2. OUT
a. OUT parameter is referenced to the procedure or function.
b. Output only.
c. And value of parameter is overwritten allow.

3. IN OUT
a. IN OUT parameter is referenced to the procedure or function.
b. Both input and output.
c. And value of parameter is both overwritten allow or not allow.

1. Procedures
These subprograms do not return a value directly, mainly used to perform
an action.

Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name (procedure parameters)
{IS | AS}
BEGIN
< procedure_body >
END;

Example:
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/

Procedure created.

Execute:

When above code is executed using SQL prompt, it will produce the following
result:

EXECUTE greetings; or CALL greetings();

Hello World

PL/SQL procedure successfully completed.

Or
You might call the procedure in a PL/SQL Block.
BEGIN
greetings;
END;
Hello World
PL/SQL procedure successfully completed.

2. Functions

[Link] M.C.A,[Link],[Link].., Page 105


1. These subprograms return a single value, mainly used to compute and return a
value.
2. A PL/SQL function is same as a procedure except that it returns a value.

Syntax:
CREATE OR REPLACE
FUNCTION function_name (function_params) RETURN return_type IS
BEGIN
function_body
RETURN something_of_return_type;
END;

Ex1:
CREATE OR REPLACE FUNCTION ADD_TWO (A INT,B INT) RETURN INT IS

BEGIN
RETURN (A + B);
END;
Calling function:
BEGIN
DBMS_OUTPUT.PUT_LINE(’RESULT IS: ’ || ADD_TWO(12,34));
END;
/
RESULT IS: 46

 8)Benefits of Procedures and Functions


Stored procedures and functions have many benefits and addition to part application
development.
1. It modifies one routine to affect multiple applications.
2. It modifies one routine to eliminate duplicate testing.
3. It avoids PL/SQL parsing at runtime by parsing at compile time.
4. It reduces the number of calls to the database
5. Database network traffic by bundling (collecting) the commands
6. User-defined functions cannot be used in situations
7. That requires an unchanging definition.
8. Thus, you cannot use user-defined functions:
a. In a CHECK constraint clause of
a CREATE TABLE or ALTER TABLE statement
b. In a DEFAULT clause of a CREATE TABLE or ALTER TABLE statement

 11) Explain Triggers in PL/SQL?

A trigger is an action which can be performed automatically whenever the data


manipulations are applied on the table
or
1. A database trigger is a stored procedure
2. That is fired when an insert, update or delete statement is issued against the associated
table.

Syntax:

CREATE [OR REPLACE] TRIGGER trigger-name

BEFORE (OR AFTER)

INSERT OR UPDATE OR DELETE [OF COLUMNS]

[Link] M.C.A,[Link],[Link].., Page 106


ON tablename

[FOR EACH ROW [WHEN (condition)]]

BEGIN

Trigger action;

END;

 Types of PL/SQL Triggers


There are two types of triggers based on the which level it is triggered.
1. Row level trigger –
a. An event is triggered for each row upated, inserted or deleted.

2. Statement level trigger –


a. An event is triggered for each sql statement executed.

In trigger two types of pseudo (artificial) (fake) column are available they are
On the Basis of Type of Trigger/Firing or Triggering Transaction

– BEFORE Triggers

– AFTER Triggers

– INSTEAD OF

BEFORE Triggers

BEFORE triggers execute the trigger action before the triggering statement is executed.
It is used to derive specific column values before completing a triggering DML, DDL
statement or to determine whether the triggering statement should be allowed to
complete.

Example

We can define a BEFORE trigger on the passengers detail table that gets fired before
deletion of any row. The trigger will check the system date and if the date is Sunday, it
will not allow any deletion on the table.

The trigger can be created in Oracle The trigger action can be shown. As soon as we try
to delete a record from passenger detail table, the above

trigger will be fired and due to SUNDAY EXP fired, all the changes will be

rolled back or undone and the record will not be deleted.

AFTER Triggers

AFTER triggers execute the trigger action after the triggering statement is

executed. AFTER triggers are used when we want the triggering statement to complete
before executing the trigger action, or to execute some additional logic to the before
trigger action

[Link] M.C.A,[Link],[Link].., Page 107


[Link] M.C.A,[Link],[Link].., Page 108
Example

We can define an AFTER trigger on the reserv det table that gets fired every time one
row is deleted from the table. This trigger will determine the passenger id of the deleted
row and subsequently delete the corresponding row from the passengers det table with
same passenger id.

Triggers on LOGON and LOGOFF Events

LOGON and LOGOFF triggers can be associated with the database or with

a schema. Their attributes include the system event and username, and they can specify
simple conditions on USERID and USERNAME.

– LOGON triggers fire after a successful logon of a user.

– LOGOFF triggers fire at the start of a user logoff.

Example

Let us create a trigger on LOGON event called pub log, which will store

[Link] M.C.A,[Link],[Link].., Page 109


the number, date, and user of login done by different user in that particular database.
The trigger will store this information in a table called log detail. The table log detail
must be created before trigger creation by logging into Administrator login. The trigger
can be created After logging into another login, if we see the content of the relation

log detail it will show who are all logged into database. The value of the

attribute log times would go on increasing with every login into the database which is
indicated Note The log detail relation is visible only in Administrator login.

[Link] M.C.A,[Link],[Link].., Page 110


Triggers on DDL Statements

This trigger gets fired when DDL statement such as CREATE, ALTER, or

DROP command is issued. DDL triggers can be associated with the database or with a
schema. Moreover depending on the time of firing of trigger, this trigger can be classified
into BEFORE and AFTER. Hence the triggers on

DDL statements can be as follows:

– BEFORE CREATE and AFTER CREATE triggers fire when a schema

object is created in the database or schema.

– BEFORE ALTER and AFTER ALTER triggers fire when a schema object

is altered in the database or schema.

– BEFORE DROP and AFTER DROP triggers fire when a schema object

is dropped from the database or schema.

Example 1

Create or replace trigger abc before insert on dept for each row

Declare

Sdate varchar2(3);

Begin

Sdate:=to_char(sysdate,’dy’);

If sdate in (‘sat’,’sun’) then

[Link] M.C.A,[Link],[Link].., Page 111


Raise_application_error(-2003,’This is weakend’);

End if;

End;

Example 2:

Create or replace trigger etrig

Before insert or update or delete on emp

Declare

Tday varchar2(10);

Begin

Tday:=to_char(sysdate,’dy’);

If tday=’mon’ then

Raise_application_error(-20001,’no transaction on maonday’);

End if;

End;

Example 3

Create or replace trigger strig

Before update on emp for each row

Begin

If :[Link]>=10000 then

Raise_application_error(-20001,’salary not > 10000 update’);

End if;

End;

Example 4:

Create or replace trigger tr4

Before delete on emp for each row

Begin

Insert into etemp(empno,ename) values(:[Link],:[Link]);

Dbms_output.putline(‘backup copied to etemp table’);

End;

[Link] M.C.A,[Link],[Link].., Page 112


Triggers on DML Statements

This trigger gets fired when DML statement such as INSERT, UPDATE, or

DELETE command is issued. DML triggers can be associated with the database or with a
schema. Depending on the time of firing of trigger, this trigger can be classified into
BEFORE and AFTER.

Row Level Triggers

A row level trigger, as its name suggests, is fired for each row that will be

affected by the SQL statement, which fires the trigger. Suppose for example if an
UPDATE statement updates “N” rows of a table, a row level trigger defined for this
UPDATE on that particular table will be fired once for each of those “N” affected rows. If
a triggering SQL statement affects no rows, a row trigger is not executed at all. To
specify a trigger of row type, FOR EACH ROW clause is used after the name of table.

Statement Level Triggers

Unlike row level trigger, a statement level trigger is fired only once on behalf of the
triggering SQL statement, regardless of the number of rows in the table that the
triggering statement affects. Even if the triggering statement affects no rows, the
statement level trigger will execute exactly once. For example, if a DELETE statement
deletes several rows from a table, a statement-level DELETE trigger is fired only once,
regardless of how many rows are deleted from the table.

INSTEAD-OF Triggers

INSTEAD-OF triggers are used to tell Oracle what to do instead of performing the actions
that executed the trigger. It is applicable to both object views and standard relational
database. This trigger can be used to redirect table inserts into a different table or to
update different tables that are the part of the view. This trigger is used to perform any
action instead of the action that executes the trigger.

Enabling and Disabling a Trigger

By default, a trigger is enabled when it is created. Only an enabled trigger gets fired
whenever the trigger restriction evaluates to TRUE. Disabled triggers do not get fired
even when the triggering statement is issued

Syntax

ALTER TRIGGER <Trigger name> ENABLE/DISABLE;

Dropping Triggers

Triggers can be dropped like tables using the drop trigger command. The drop trigger
command removes the trigger structure from the database

[Link] M.C.A,[Link],[Link].., Page 113


Syntax

DROP TRIGGER <trigger name>

NORMALIZATION OF DATABASE TABLES

1) Explain Normalization? Explain different types of Normalizations?

The process of decomposing relations with anomalies to produce smaller, well


structured relations.

A Normal Form is a state of relation that results applying simple rules regarding
functionally dependencies (A constraint between two attributes or two sets of attributes.)

Need for Normalization

Relation is normalize to reduce the redundancy and to remove anomalies existed in

the relation so that we proved a well structured relation with minimal redundancy.

Normalization is five types

First Normal Form(1 NF)

Any Multivalued attribute have been removed, so there is a single value at the
intersection of each row and column of the table.

Second Normal Form(2NF)

Any partial functional dependencies have been removed and also it is a first normal
form.

Third Normal Form(3NF)

Any transitive dependencies have been removed and also it is second normal form.

Boyce/Codd Normal Form (BCNF) (HIGHER NORMAL FORMS)

Any remaining anomalies that results from functionally dependency have been
removed.

Fourth Normal Form(4NF)

Any Multivalued dependencies have been removed.

Fifth Normal Form(5NF)

Any remaining anomalies have been removed.

First Normal Form:

[Link] M.C.A,[Link],[Link].., Page 114


Any Multivalued attribute have been removed, so there is a single value at the
intersection of each row and column of the table. Consider the following example, the relation
emp_id 100 teaches two courses. The course_title become a multi-valued attributes which
indicates that the relation is not in first normal form. To make the relation into first normal
form, the employee details are inserted in no. of records for each course_tiltle of that
employee.

Emp-ID Name Dept-Name Salary Course- Date-


Title completed

100 Kumar Marketing 48000 SPSS 6/19/200X

Surveys 10/7/200X

140 Yugandhar Accounting 52000 Tax Acc 12/8/200X

110 Thrisul Info 43000 SPSS 1/12/200X


Systems

C++ 4/22/200X

190 Vinoothna Finance 55000

150 Dheeraj Marketing 42000 SPSS 6/19/200X

Java 8/12/200X

Emp-ID Name Dept-Name Salary Course- Date-


Title completed

100 Kumar Marketing 48000 SPSS 6/19/200X

100 Kumar Marketing 48000 Surveys 10/7/200X

140 Yugandhar Accounting 52000 Tax Acc 12/8/200X

110 Thrisul Info 43000 SPSS 1/12/200X


Systems

110 Thrisul Info 43000 C++ 4/22/200X


Systems

190 Vinoothna Finance 55000

150 Dheeraj Marketing 42000 SPSS 6/19/200X

150 Dheeraj Marketing 42000 Java 8/12/200X

[Link] M.C.A,[Link],[Link].., Page 115


Second Normal Form:

A relation is in second normal form (2NF) if it is first normal form and every non key
attribute is functionally dependent on the primary key. Thus no non key attribute is
functionally dependent on part of the primary key. A relation that is in first normal form will be
in second normal form if any one of the following conditions is applied.

1. The primary key consists of only one attribute (such as the attribute Emp_ID in
Employee1).
2. No non key attributes exists in the relation (thus all of the attributes in the relation are
components of the primary key).
3. Every non key attribute is functionally dependent on the full set of primary key
attribute.

EMP
EID COURSE NAME EPT-NAME SAL DATECOMPLETED

In the above table is not in the second normal form. Because the primary key relation s
the composite key Employee_ID, Course_title. Therefore the non key attributes name,
Dept_name & salary are functionally dependent on part of the primary key (Emp_ID), but not
on Course_title. To convert a relation to second normal form, we decompose two relations.

EMP1

EID NAME DEPT SAL

EMPCOURSE

EID COURSE DATECOMPLETED

Insertion is possible: we insert only employee details in emp1 table

Deletion possible:

[Link] M.C.A,[Link],[Link].., Page 116


Third Normal Form:

A relation is in third normal form if it is in second normal form and no transitive


dependency exists.

A transitive dependency in a relation is a functional dependency between two or more


non key attributes.

CUST-ID NAME SALESPERSON REGION

Here customer-ID is primary key; all of the remaining attributes are functionally
dependents on this attribute. However, there is a transitive dependency (region) is
functionally dependent on salesperson. There are some problems of the transitive
dependency.

1. Insertion Anomaly: A new salesperson assigned to the north region cannot be


entered until a customer has been assigned to the salesperson.

2. Deletion Anomaly: If customer no. is deleted from the table, we loose the information
of salesperson and region.

3. Updation Anomaly: If salesperson is reassigned several rows must be changed to


reflect that fact. To overcome these facts, we remove transitive dependency in the
above table then we decompose it into two relations.

CUST-ID NAME SALESPERSON SALESPERSON REGION

Boyce-Codd Normal Form:

BCNF is one of the forms of Normalization. A database table is in BCNF if and only if

there are no trivial functional dependencies of attributes on anything other than a superset

of a candidate key. BCNF is also some times referred to as 3.5NF or 3.5 Normal Form.

When a relation has more than one candidate key, anomalies may result even
though that relation is in 3NF.

[Link] M.C.A,[Link],[Link].., Page 117


Ex: student_advisor relation show in fig B-1. This relation has the following attributes Sid
(student_id), subject, lecturer and hour. Sample data for this relation are shown in fig B-1a
and the functional dependencies are shown in figure B-1b.

a) Relation with sample data.

Sid Subject Lecturer Hour

123 Computers Kumar 4

123 Music Ravi 3

456 Physics Gowri 3

786 Music Ntr 7

678 Computer Kumar 5

b) Functional dependencies in student_advisor.

Sid Subject Lecturer Hour

As shown in fig B-1b, the primary key for this relation is the composite key consisting
of Sid and subject. Thus the 2 attributes lecturers and hour are functionally dependent on this
key this reflects the constraint that although a given student may have more than one subject
, for each subject a student has exactly one lecturer and one hour.

There is a second functional dependency in this relation. Subject is functionally


dependent on lecturer. That is, each lecturer advises in exactly one subject. Notice that is not
a transitive dependency. (Functional dependency between 2 non key attributes). In contrast,
in this example a key subject is functionally dependent on a non key attribute (lecturer).

Anomalies in student_advisor:

The student-advisor relation is clearly in 3NF, since there are no partial functional
dependencies and no transitive dependencies. Because of the F.D between subject and
lecturer there are anomalies in this relation.

[Link] M.C.A,[Link],[Link].., Page 118


1. Suppose that computers the lecturer Kumar is replaced by srinu. This change must be
made in 2 or more rows in the table (update).
2. Suppose we want to insert a row with the information that srinu in computer this, of
course, can’t be done until at least one student majoring in computers is assigned
srinu as a lecturer (insert).
3. Finally, if student no 786 withdraws from college, we lose the information that Ntr
lecturer in music (deletion).

BCNF:

The anomalies in student_advisor result from the fact that there is a lecturer that is not
a candidate key in the relation. [Link] and [Link] identified this deficiency and
proposed a stronger definition of 3NF that remedies the problem. If and only if every
determinant in the relation is a candidate key. Student_advisor is not in BCNF because
although the attribute lecturer is a determinant, it is not a candidate key. (Only subject is F.D
on lecturer).

Converting a Relation to BCNF:

A relation is in 3NF can be converted to BCNF following 2 steps.

1. The relation is modified so, that the determinant in the relation that is not a candidate key
becomes a component of the P.K of the revised relation. The attribute that is F.D on that
determinant becomes a non key attribute. The result of applying this rule to student_advisor
is shown in fig B-2a. The determinant lecturer becomes part of the composite P.K. The
attribute subject, which is F.D on lecturer, becomes a non key attribute.

Converting a relation to BCNF relations:

a. revised student_advisor (2NF)

SID LECTURER SUBJECT HOUR

b. two relations in BCNF:

SID LECTURER HOUR

LECTURER SUBJECT

[Link] M.C.A,[Link],[Link].., Page 119


The second step in the conversion process is decomposing the relation to
eliminate the partial F.D. This result in 2 relations, as shown in fig b. These relations are in
3NF and BCNF. Here there is only one candidate key in each relation to remove anomalies.

2). Explain De normalization?

The process of transforming normalized relations into UN normalized physical record


specifications.

In general, de-normalization may partition a relation into several physical records, may
combine attributes from several physical records, and may combine attributes from several
relations together into one physical record.

De-normalization can increase the chance of errors and inconsistencies and can force
reprogramming systems if business rules change. The benefits of de-normalization may no
longer exist and almost leads to more storage space for raw data and may be more space for
database indexes.

STUDENT

Student-ID Campus_Addre
s

APPLICATION

Application- Application_Date Qualification Student-ID


ID

De-normalized Relation

STUDENT

Student-ID Campus_Address Application_Date Qualifica


tion

In the above example one record could be formed with four fields from the student and
scholarship application normalized relations.

[Link] M.C.A,[Link],[Link].., Page 120


Model Question Papers

Subject: DATABASE MANA6EMENT SYSTEM

Time: 3 Hours

Section-A

(Answer any FIVE Question). 5x5=25 Marks

l. Explain Drawbacks of file-Based System.

2. Explain Classification of Database Manatement Systemt.

3. Explain relationship degree.

4. Explain generalization and specialization

5. Explain relational alzebra operation,

6. Explain tuple relational calculus

7, Explain Data ManiPulation Language.

8. Explain Aggregate functions.

9. Explain Structure of Pl/SQL

10. Explain Types of Triggers.

SECTION.B

Answer ANY FIVE Questions. 5Xl0=50 MARKS

1. Drawback of file-Based SYstem

2. Componentt of Database Management Syttem

3. Reduce in ER diagmm to tables

4, Conttraints on specialization and generalization.

5. Dircuss about the CODD Rules.

6. Explain different normal forms'

7. Explain different SQL commands.

8. Explain different constraints in sQL

9. Explain about cursors in detail

10. Explain iterative statements in pl/sql?

[Link] M.C.A,[Link],[Link].., Page 121

You might also like