0% found this document useful (0 votes)
414 views31 pages

DBMS PDF

1. A database management system (DBMS) is a collection of programs that manages database structure and controls access to stored data. It consists of a database, data management system, and supports multiple users and applications. 2. The objectives of a DBMS include ensuring data availability to users, maintaining data integrity, providing data security, and allowing data independence from applications. 3. A DBMS uses metadata to provide descriptions of data characteristics and relationships to link data within the database. This allows structured storage, retrieval and updates to the data.

Uploaded by

Mastan Shaik
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)
414 views31 pages

DBMS PDF

1. A database management system (DBMS) is a collection of programs that manages database structure and controls access to stored data. It consists of a database, data management system, and supports multiple users and applications. 2. The objectives of a DBMS include ensuring data availability to users, maintaining data integrity, providing data security, and allowing data independence from applications. 3. A DBMS uses metadata to provide descriptions of data characteristics and relationships to link data within the database. This allows structured storage, retrieval and updates to the data.

Uploaded by

Mastan Shaik
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
You are on page 1/ 31

Andhra Pradesh State Council of Higher Education

B.Sc. Computer Science/Information Technology (IT) Syllabus Under CBCS


w.e.f.2015-2016 (Modified in April 2016)
Structure of Computer Science/Information Technology (IT) Syllabus
III YEAR V SEMESTER
Paper-V: Data Base Management System
Database Management Systems
UNIT I

Overview of Database Management System: Introduction, file-based system,


Drawbacks of file-Based System ,Data and information, Database, Database
management System, Objectives of DBMS, Evaluation of Database management
System, Classification of Database Management System, DBMS Approach, advantages of
DBMS, Anis/spark Data Model, data models, Components and Interfaces of Database Design, Implementation and Management
Management System. Database Architecture, Situations where DBMS is not Necessary,
DBMS Vendors and Their Products.

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
P. Y. Kumar M.C.A, M.Tech, M.Phil..,
modeling.
Head of the Department
UNIT III
Computer Science
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
UNIT IV

Structured Query Language: Introduction, History of SQL Standard, Commands in


SQL, Data Types in SQL, Data Definition Language, Selection Operation, Projection
Operation, Aggregate functions, Data Manipulation Language, Table Modification
Commands, Table Truncation, Imposition of Constraints, Join Operation, Set Operation,
View, Sub Query, Embedded SQL,

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.
This Book is dedicated to my Daughter. May God Bless you and be with you
little one!

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 1 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 2

 What is a Database Management System


1. A DBMS is a collection programs
UNIT – I 2. That manages database structure
DATABASE SYSTEMS 3. And control access to the data stored in the database.
Data: Or
Data are raw facts. The word raw indicates that the facts have not yet been 1. A DBMS is a collection of programs
processed to reveal their meaning. 2. That enables to user to create, maintain the database.
Or
The term data referred to known raw facts. Text, graphics, images and video
segments that have meaning in the user’s environment A DBMS consists of:
1. A collection of interrelated and persistent data. This part of DBMS is referred to as
Information: database (DB).
Information is the result of processing raw data to reveal ors meaning. Data 2. A set of application programs used to access, update, and manage data. It is
processing can be as simple as organizing data to reveal patterns or as complex as called data management system (DMS).
making forecasts or drawing inferences using statistical modeling. 3. A DBMS is general-purpose software i.e., not application specific. The same DBMS
Or (e.g., Oracle, Sybase, MS Acess, INFORMATICA ,MYSQL etc.)
Data that have been processed in such a way as to increase the knowledge of the 4. It can be used in railway reservation system, library management, university, etc.
person who use the data 5. A DBMS takes care of storing and accessing data, leaving only application specific
Information is produced by processing data. tasks to application programs.
Information is used to reveal the meaning of data.
Accurate, relevant, and timely information os the key Explain Structure of DBMS
1. The DBMS uses an application specific database description to define this
Database: The database consists of logically related data stored in a single data translation.
repository. 2. The database description is generated by a database designer from his or her
conceptual view of the database, which is called the Conceptual Schema.
Metadata: The metadata provide a description of data characteristics and the set of 3. The translation from the conceptual schema to the database description is
relationships that link the data found with in the database. performed using a data definition language (DDL) or a graphical or textual design
interface.
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.  What are the Objectives of DBMS


The main objectives of database management system are
1. Data availability,
2. Data integrity,
3. Data security, and
4. Data independence

1. Data Availability

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 3 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 4


Data availability refers to the fact That the data are creates available to the 1. SQL developed by IBM, became the standard query language for databases. SQL
wide variety of users can access the date easily in a meaningful format was standardized by ISO.

2. Data Integrity In 1980s and 1990s:


Data integrity refers to the correctness of the data in the database. 1. IBM, Oracle, Informix and others developed powerful DBMS.
In other words, the data available in the database is a reliable data
 Classification of Database Management System OR TYPES OF DBMS?
1. Data Security The database management system can be broadly classified into
1. Data security refers to the fact that only authorized users can access the data. 1. Passive Database Management System
Data security can be enforced by passwords. 2. Active Database Management System:
If two separate users are accessing a particular data at the same time,
2. The DBMS must not allow them to make conflicting changes. 1. Passive Database Management System.
1. Passive Database Management Systems are program-driven.
2. Data Independence 2. The users query the current state of database
1. DBMS allows the user to store, update, and retrieve data in efficient manner. 3. And retrieve the information currently available in the database.
DBMS provides an “abstract view” of how the data is stored in the database. 4. Traditional DBMS are passive in the sense that they are explicitly and
In order to store the information efficiently, complex data structures are used synchronously invoked by user or application program initiated operations.
to represent the data. 5. Applications send requests for operations to be performed by the DBMS and
The system hides certain details of how the data are stored and maintained. wait for the DBMS to confirm and return any possible answers.
 Explain Evolution of Database Management Systems 6. The operations can be definitions and updates of the schema, as well as
In recent years, two approaches to DBMS are more popular, which are queries and updates of the data.
a. Object-Oriented DBMS (OODBMS) and
b. Object Relational DBMS (ORDBMS). 2. Active Database Management System.
1. Active Database Management Systems are data-driven or event-driven
The sequential order of the development of DBMS is as follows: systems.
1. Flat files – 1960s–1980s 2. In active database management system, the users specify to the DBMS the
2. Hierarchical – 1970s–1990s information they need.
3. Network – 1970s–1990s 3. If the information of interest is currently available, the DBMS actively monitors
4. Relational – 1980s–present the arrival of the desired information and provides it to the relevant users.
5. Object-oriented – 1990s–present 4. The scope of a query in a passive DBMS is limited to the past and present data,
6. Object-relational – 1990s–present whereas the scope of a query in an active DBMS additionally includes future
7. Data warehousing – 1980s–present data. An active DBMS reverses the control flow between applications and the
8. Web-enabled – 1990s–present DBMS instead of only applications calling the DBMS, the DBMS may also call
applications in an active DBMS.
Early 1960s. 5. DBMS can support many different types of databases according to the no. of
1. Charles Bachman at GE created the first general purpose DBMS Integrated users and the database locations.
Data Store.
2. It created the basis for the network model which was standardized by
1. Single User Database
CODASYL (Conference on Data System Language).
Single user database supports only one user at a time. If user A is using the
Late 1960s: database, users B and C must wait until user A is done. Single user database
1. IBM developed the Information Management System (IMS). runs on PC is called Desktop database.
2. IMS used an alternate model, called the Hierarchical Data Model.
2. Multi user Database
In 1970: It supports multiple users at the same time. It is also called workgroup
1. Edgar Codd, from IBM created the Relational Data Model.
database. It works few than 50 persons.
In 1981: When the database is used by the entire organization and supports many users
1. Codd received the Turing Award for his contributions to database theory. (more than 50) across many departments, the database is known as Enterprise
2. Codd Passed away in April 2003. Database.

In 1976: Locations might also classify Centralized Database, Distributed Database.


1. Peter Chen presented Entity-Relationship model, which is widely used in database
design.
1. Centralized Database
In 1980: The database supports data located at a single site is called Centralized
Database.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 5 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 6

1. Selecting proper field names is also important.


2. Distributed Database 2. The field definitions and naming conventions are not unique to file systems.
Database that supports data distributed across several different sites is called 3. The field names are reasonably descriptive.
4. With proper naming conventions, the file structure becomes self-documenting.
Distributed Database.

Now a days database classify as Operational Database, Data warehouse. 5. That is, by simply looking at field is likely to contain.
6. Some software packages place restrictions in the length of field names.
1. Operational Database 7. So it is wise to be as expressive as possible within those restrictions.
8. In addition, very long field names create it difficult to more than a few fields on
A database that is designed primarily to support company’s day to day operations a page
is classified as an Operational Database or Transactional or Production Database. 9. They creating output values a problem.

2. Data Warehouse 2. DATA REDUNDANCY


Data ware house focus on storing data used to generate information required
1. The file system’s structure creates it difficult to combine data from multiple
to make tactical or strategic decisions.
sources
2. And its lack of security renders the file system.
3. The organizational structure promotes the storage of the same basic data in
 PROBLEMS WITH FILE SYSTEM DATA MANAGEMENT different locations.
4. Because that data stored in difference location will always be updated
File: A file is a collection of records. consistently.
5. Data redundancy exits when the same data stored unnecessarily at different
File system: A file system is a store organization computer files. places.
a. Data inconsistency:
1. The file system method of organizing and managing data b. Data anomalies:
2. It was a definite improvement over a manual system, and 1. Update anomalies
3. The file system served a useful purpose in data management. 2. Insertion anomalies
3. Deletion anomalies
Problems:
1. The simplest data retrieval task requires extensive programming.  Data inconsistency:
2. Any changes in an existing structure can be difficult in a file system environment. 1. Data inconsistency exists when different versions of the same data
3. In file system database is security features are difficult. appear in different places.
 It requires extensive programming. 2. For example: we change an agent phone number or address in the
 It can not perform ad-hoc (selected) queries. AGENT file.
 System administration can be complex and difficult. 3. If we forget to create corresponding changes in the CUSTOMER file
 Security features are likely to be inadequate. 4. The files contain different data for the same agent.

Those limitations in turn, lead to problems of structural and data dependency.  Data anomalies:
1. Data anomalies (difference) exist because any change in any field value
1. STRUCTURAL AND DATA DEPENDENCE: must be correctly made in many places to maintain data integrity.
2. The data anomalies are commonly defined as:
1. A file system show structural dependence,
2. It means that access to a file is dependent on its structure. a. Update anomalies:
3. For example, adding a customer date-of-birth field in CUSTOMER file, 1. Changing any field data, we must change wherever be appear
4. The file system programs must be modified to conform to the new file that field.
structure, 2. In this case a large file system, such changes might occur in
5. They exhibit structural dependence. hundreds or even thousands of records clearly,
6. Even changes in the characteristics of data 3. The possible for data in consistencies is great.
7. Such as changing a field from integer to decimal,
8. It requires all changes in the programs that access the file. b. Insertion anomalies:
9. That is changing the data type etc. 1. To add each new customer in CUSTOMER file,
10.The file system is said to exhibit data dependence. 2. We must also add the corresponding agent data.
3. If we add several hundred new customers,
4. We must also enter several hundred agent names and telephone
1. FIELD DEFINITIONS AND NAMING CONVERTIONS: numbers.

c. Deletion anomalies:

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 7 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 8


1. We delete any field information we also loss another filed 5. Improve data access:
information. 1. The DBMS makes it possible to produce quick answers to ad-hoc queries from a
2. If delete the customers B., you will also delete His agent data. database
3. Clearly this is not desirable (popularly). 2. A query is a specific request issued to the DBMS for data manipulation.
3. The DBMS sends back an answer to the application.

 ROLE AND ADVANTAGES OF THE DBMS 6. Improved decision making:


1. Better managed data and improved data access create
1. The DBMS serves as the intermediary between the user and the database. 2. It possible to generate better quality information
2. The DBMS receives all application requests 3. That information is used to take better decisions.
3. And translates them into the complex (multipart) operations required to fulfill those
requests. 7. Increased end-user productivity:
4. Application program might be written by a programmer using a programming 1. The availability of data, combined with the tools
languages 2. That transforms data into usable information.
5. A DBMS interface between the end user’s applications and the database 3. The end users to take quick decisions
6. First, the DBMS enables (allow) the data in the database to be shared among 4. That is used to success and failure in the global.
multiple applications or users.
7. Second, the DBMS integrates (adds) the many different users’ views of the data into
a single all-encompassing data repository. 8. Multi User Access Control
DBMS provides many advantages such as: 1. DBMS provide many users can access data concurrently with out compromising
the integrity of the database
2. It can control to access multi user
1. Improved data sharing 3. It uses to multiple users can access the database.
2. Improved data security
3. Better data integration 9. Backup and Recovery Management
4. Minimized data inconsistency 1. DBMS provides backup and data recovery
5. Improved data access 2. It generates data safety and integrity.
6. Improved decision making 3. The special utility that allow the DBA to perform routine and special backup
7. Increased end-users productivity 4. And restore procedures when power failure or database failure.
8. Mutli user data access
9. Backup and recovery management 10. Data Integrity Management
10. Data integrity management 1. DBMS supports and implements integrity rules
2. Like not null, check, unique, default, primary key, and foreign key.
1. Improved data sharing:
1. The DBMS helps create an environment in which end users have better access
to more data and better-managed data. WHY DATABASE DESIGN IS IMPORTANT
2. Such access makes it possible for end users to respond quickly to changes in
their environment. 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
2. Improved data security: user requirements does not just happen; its structure must be designed carefully. In
1. The more users access the data, the greater the risks of data security breaks. fact, database design is such a crucial aspect of working with database.
Proper database design requires the designer to identify precisely the database’s
2. A DBMS provides a framework for better enforcement of data privacy and security expected use. Designing a transactional database emphasizes accurate and consistent
policies. 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
3. Better data integration: distributed, multiuser database.
1. It provides view of the organizations operations and a clearer view of the big A well-designed database facilitated data management and generates accurate
picture. and valuable information.
2. It becomes much easier to see how actions in one segment of the company A database contains redundant data when the same data about the same entity
affect other segment (part). 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.
4. Minimized data inconsistency:
1. Data inconsistency exists when different versions of the same data appear in different
places.
2. The probability of data inconsistency is greatly reduced in properly designed
database.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 9 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 10

D a t a b a s e S y s t em 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
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.
DATABASE SYSTEMS (OR)
3. Like data inconsistency, data anomalies, data dependency and structural
THE DATABASE SYSTEM ENVIRONMENT (OR)
dependency.
COMPONENTS AND INTERFACES OF DATABASE MANAGEMENT SYSTEM (OR)
4. DBMS software not only the data structures, but it also the relationship
COMPONENTS OF DATABASESYSTEM
between those structures and the access structures path, in a central location.

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.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 11 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 12


2. Software: – Integrity enforcement. Database manager enforces integrity by checking
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 consistency constraints like the bank balance of customer must be maintained
fully operating system software, DBMS software and application programs and
utilities to a minimum of Rs. 300, etc.

 OS software manages all hardware components and makes its possible for all – Security enforcement. Unauthorized users are prohibited to view the information
other software to run the computers.
 DBMS software manages the database within the database system. Microsoft’s stored in the data base.
Access and SQL server, oracle.
– Backup and recovery. Backup and recovery of database is necessary to ensure
 Application programs and utility software’s are used to access and
manipulated the data in the DBMS. Application programs are most commonly that the database must remain consistent despite the fact of failures.
used to access the data found within the database to generate reports,
tabulations and other information to facilitate decision making. Utilities are the Database Users
software tools used to help manage the database system’s computer
components. 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
3. People:
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,
Database Administrator environment modeling system, etc.
Database Administrator is a person having central control over data and programs Naive End Users
accessing that data. The database administrator is a manager whose responsibilities are
focused on management of technical aspects of the database system. 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 Designer database.
Database designer can be either logical database designer or physical database designer. System Analysts
Logical database designer is concerned with identifying the data, the relationships
between the data, and the constraints on the data that is to be stored in the database. System analysts determine the requirements of end user, and develop specification for
The logical database designer must have thorough understanding of the organizations canned transaction that meets this requirement.
data and its business rule.
Canned Transaction
Database Manager
Ready made programs through which na¨ıve end users interact with the database is
Database manager is a program module which provides the interface between the low called canned transaction.
level data stored in the database and the application programs and queries submitted to
the system:
4. Procedures
– The database manager would translate DML statement into low level 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
file system commands for storing, retrieving, and updating data in the 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
database. information that is generated through the use of such data.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 13 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 14

5. Data: Transaction Manager


The word ‘Data’ covers the collection of facts stored in the database data are
the raw material from which information is generated. It ensures that the database remains in a consistent state despite system failures. The
Integrated Data transaction manager manages the execution of database manipulation requests. The
transaction manager function is to ensure that concurrent access to data does not result
A data can be considered to be a unification of several distinct data files and when any
in conflict.
redundancy among those files is eliminated, the data are said to be integrated data.
File Manager
Shared Data
File manager manages the allocation of space on disk storage. Files are
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 used to store collections of similar data. A file management system manages
redundancy of data are reduced, since repetitions are avoided, the possibility of
inconsistencies is reduced. independent files, helping to enter and retrieve information records.

Persistent Data File manager establishes and maintains the list of structure and indexes

Persistent data are one, which cannot be removed from the database as a side effect of defined in the internal schema. The file manager can:
some other process. Persistent data have a life span that is not limited to single – Create a file
execution of the programs that use them.
– Delete a file
Functional Components of Database System Structure ?
– Update the record in the file
The functional components of database system structure are:
– Retrieve a record from a file
1. Storage manager.
Buffer
2. Query processor.
The area into which a block from the file is read is termed a buffer
Storage Manager
Buffer Manager
Storage manager is responsible for storing, retrieving, and updating data in the
database. Storage manager components are: 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
1. Authorization and integrity manager. program is given the address of the block in main memory, if it is already present in the
2. Transaction manager. buffer. If the block is not in the buffer, the buffer manager allocates space in the buffer
for the block, replacing some other block
3. File manager.

4. Buffer manager.
 DBMS FUNCTIONS ?
Transaction Management
1. A DBMS guarantee the integrity and consistency of the data in the database.
– A transaction is a collection of operations that performs a single logical They include
a. Data dictionary management,
function in a database application. b. Data storage management,
c. Data transformation and presentation,
– Transaction-management component ensures that the database remains in a d. Security managements,
consistent state despite system failures and transaction failure. e. Multi user access control,
f. Backup and recovery management,
– Concurrency control manager controls the interaction among the concurrent g. Data access using a languages
transactions, to ensure the consistency of the database. h. Application programming interfaces
i. And database communication interfaces.
Authorization and Integrity Manager
2. Data dictionary management:
Checks the integrity constraints and authority of users to access data. 1. The DBMS requires that definitions of the data elements and their relationship
(metadata) be stored in a data dictionary.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 15 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 16


2. Any change made in a database structures are automatically recorded in the data 5. And the DML allows end users to extract the data from the database.
dictionary,
3. There supports to modify all the programs that access the changed structure. 10. Database communication interfaces:
1. Current generation DBMS provide special communications
3. Data storage management: 2. It allows the database to accept end user requests within a computer network
1. The DBMS creates the complex (parts) structures required for data storage environment.
2. A modern DBMS System provides storage not only for the data. 3. In fact, database communications capabilities are an essential feature of the modern
3. But also for related data entry forms or screen definitions, report definitions, data DBMS.
validations rules, procedural code, structures to handle video and picture formats and
so on.  DATABASE SYSTEM DISADVANTAGES:

4. Data transformation and presentation: Database systems main disadvantages are


1. The DBMS transforms entered data to the data structures 1. Increased costs
2. That are required to store the data maintaining data independence 2. Management complexity
3. The DBMS translates logical requests into commands 3. Maintaining currency
4. That physically located and retrieve the requested data. 4. Vendor dependence
5. The DBMS formats the physically retrieved data to create it conform to the 5. Frequent upgrade/replacement cycles
user’s logical expectations.
1. Increased costs:
5. Security management: a. Database System required sophisticated hardware and software and highly skilled
1. The DBMS creates a security system personnel.
2. That use user security and data privacy within the database. b. The cost of maintain the hardware, software and personnel required to operate
3. Security rules determine (decide). Which users can access the database which and manage a database system can be large.
data item each user may access and which data operations (read, add, delete
or modify) the user may perform. 2. Management Complexity:
4. This is especially important in multi user database. Systems where many users 1. Database Systems interface with many different technologies
can be access the database simultaneously. 2. And have a significant impact on a company’s resources and culture.
3. Database systems hold crucial company data
6. Multiuser access control: 4. That are accessed from multiple sources, security issues must be assessed
1. The DBMS creates the (parts) complex structures that allowed multi user access to constantly.
the data.
2. In order to provided data integrity and data consistency. 3. Maintaining currency:
3. The DBMS uses sophisticated (difficult) algorithms to ensure 1. To maximize the efficiency of the database system, you must key your system
4. Multi users can access the database concurrently without compromising the current.
integrity of the database. 2. User must perform frequent updates and apply
3. The latest patches and security measures to all components.
7. Backup and recovery management: 4. Because database technologies advances rapidly, personnel training cost tend to
1. The DBMS provides backup and data recovery procedures to support data be significant.
safety
2. Recovery management deals with the recovery of the database after a failure 4. Vendor dependence:
3. Such as a bad sector in the disk of a power failure. 1. Given the heavy investment in technology and personnel training, companies
4. Such capability is critical to the preservation of the database’s integrity. might be reluctant to change database vendors.

8. Data integrity management: 5. Frequent upgrade / replacement cycles:


1. The DBMS promotes and enforces integrity rules to eliminate data integrity 1. DBMS vendors (seller) frequently upgrade their products by adding new
problems functionality.
2. Thus minimizing data redundancy and maximizing data consistency. 2. Such new features often the software. Some of these versions require hardware
3. The data relations stored in the data dictionary are used to enforce data upgrades.
integrity.
 DATA MODEL BASIC BUILDING BLOCKS
9. Database access languages and application programming interface:
1. The DBMS provides data access thorough a query language. 1. The basic building blocks of all data models are entities attributes, relationships and
2. A query language is a non-procedural. constraints.
3. The DBMS’s query language contains two components. 2. An entity is any thing (a person, a place, a thing or an event) about which data to
a. DDL (Data definition language) be collected and stored.
b. DML (Data manipulation language) 3. An attribute is a character of an entity. Attributes are the equivalent of fields in file
4. The DDL defines the structures in the data are housed systems.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 17 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 18

4. A relationship describes an association among entities.


5. Data models are used three types of relationships. Generation Time Model Examples Comments
Used mainly on IBM main
One – to – Many (1: M) 1960s Frame Systems.
First File System VMS/VSA,
Many – to – Many (M: M) 1970s Managed records, not
One – to – One (1: 1) Relationships
Hierarchical IMS
6. A constraint is a restrictions placed on the data constraints are important Early data base system
Second 1970s and Network ADABAS
7. Because they help to ensure data integrity. Navigational All Accesses
Data Model IDS-II
8. Constraints are normally expressed in the form of rules. DB2
Conceptual simplicity
Oracle
Eg: Employee salary must have values that are between 6,000 and 3,50,000 Mid 1970s Relational Entity Relationship modeling
Third MSSQL –
to present Data Model and support for Relational
Server
Data Modeling
MySQL
 BUSINESS RULES Versant
Object Support complex data
FastObjects.Net
1. When database designers go about selecting or determining the entities, Mid 1980s Oriented Extended relational products
Fourth Objectivity/DB
attributes and relationships to Present Extended support object and data ware
DB/2 UDB
2. That will be used to build data model Relational housing.
Oracle 10g
3. They might start by gaining a through understanding of what type of data are Organization and
in an organization, now the data are used and in what time frames they are db XML Management of and
used. Tamino structured data.
4. A business rules is a short, exact, and clear description of a rule, route or Next Present
XML DB2/UDB
principal within a specific organization. Generation Future
Oracle 10g Relational and Object models
MS SQL Server add supports for XML
5. Business rules, derived from a detailed description of an organization’s documents.
operation
6. It helps to create and implement actions within that organizations  DATABASE MODELS
environment.
7. Business rules must be representation in writing and updated to reflect any 1. A database model is a collection of logical constructs
change in the organization’s operational environment. 2. It used to represent the date relationships found within the database models
8. Business rules must be easy to understand and widely disseminated shares a 3. It can be grouped into two categories.
common explanation of the rules. a. Conceptual models and
9. Business rules describes in simple language. b. Implementation models
10.The main sources of business rules are company managers, policy markers,
department managers and written documentation Conceptual model:
11.Such as a company’s procedures, standards or operations manuals. 1. The conceptual model center on the logical nature of the data representation.
2. The conceptual model is disturbed with what is represented in the database rather
DATA MODELING AND DATA MODELS than with how it is represented.
3. Conceptual model included the entity relationship (E-R).
Data modeling, the first step in designing a database, refers to the process of
creating a specific data model for a definite problem domain (area or server). Implementation models:
1. An implementation model is used to how the data are represented in the database
A data model is a relatively simple representation, usually graphical, of more
2. Or how the data structures are implemented to represent what is modeled.
complex real word data structures.
3. Implementation models include
A model is an abstraction (concept) of a more complex real-word object or event.
1. The hierarchical database model
The database environment, a data model represents data structures and their
2. The network database model
characteristics, relations, constraints, transformations and other constraints with the
3. The relational database model
purpose of supporting a specific problem domain.
4. The entity relationship data model and
5. The object oriented database model
THE IMPORTANCE OF DATA MODELS:
1. The hierarchical database model
Data models can facilitate interaction among the designer the application
1. The hierarchical model was developed in the 1960s.
programmer, and the end user. A well developed data model can even foster improved
2. It manages large amounts of data for complex (parts) manufacturing projects.
understanding of the organization for which the database design is developed.
3. Its basic logical structure is represented by an upside down tree.
4. The hierarchical structure contains levels, or segments.
 THE EVOLUTION OF DATA MODELS:
5. A segment is the equaling of a file system’s record type within the hierarchy

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 19 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 20


6. The top layer (the root) is perceived as the parent of the segment directly
SALESREP CUSTOMER
beneath it.

Final Assembly

PRODUCT INVOICE PAYMENT

Component A Component B Component C


INV_LINE

Assembly A Advantages:
Assembly B Assembly C
1. Conceptual simplicity is at least equal to that of
2. It handles more relationship types, such as M:N and multi parent.
3. Data access is more flexible than in hierarchical and file system models.
Part A Part B Part C Part D Part E 4. Data Owner/Member relationship promotes data integrity.
1. The hierarchical database model’s have many advantages over the file system 5. There is conformance to standards.
model. 6. It includes data definition language (DDL) and data manipulation language (DML) in
2. Hierarchical database model’s features helped form the foundation for current database DBMS
models,
3. Database application advantages are artificial, even if in different form in current Disadvantages:
database environments. 1. System complexity limits efficiency still a hierarchical model, navigational system.
2. Navigational system yields (give up) complex implementation, application
Advantages are. development, and management.
1. It promotes data sharing. 3. Structural changes require changes in all application programs.
2. Parent/Child relationship promotes conceptual simplicity.
3. Database security is provided and enforced by DBMS 3. The relational database model
4. Parent/Child relationship promotes data integrity. 1. The relational database model is implemented through a very sophisticated
5. It is efficient with 1: M relationships. (difficult or complicated) relational database management system (RDMBS).
2. The RDBMS performs the same basic functions provided by the hierarchical and
Disadvantages: network DBMS systems and add other functions
1. Different parts implementation requires knowledge of physical data storage 3. That makes the relational database model easier to understand and to
characteristics. implement.
2. Navigational systems give up complex application development, management, 4. The RDBMS manages all of the complex physical details
and use; 5. The relational database is perceived (understand) by the user to be a collection
3. It requires knowledge of hierarchical path. of tables in which data are stored.
4. Changes in structure require changes in all application programs. 6. Each ‘table’ is a matrix consisting of a series of row/column intersections.
5. There are implementation limitations (no multi-parent or M:N relationship) 7. Tables also called relations are related to each other by sharing a common entity
6. There is no data definition or data manipulation language in the DBMS characteristic.
7. There is a lack of standards.
Advantages:
2. The network database model 1. Structural independence is promoted by the use of independent tables.
1. The network model was created to represent complex data relationships 2. Changes in a table structure do not affect data access or application programs.
2. It more effectively than the hierarchical model to improve database 3. Table view largely improves conceptual simplicity
performance, and to impose a database standard. 4. They provide easier database design, implementation, management, and use.
3. The network model, the user understanding the network database as a 5. Ad-hoc query capability is based on SQL.
collection of records in 1:M relationships. 6. Powerful RDBMS isolates (suppurate) the end user from physical level details
4. The network model allows network database terminology a relationship is called 7. And improves implementation and management simplicity.
a set.
5. Each set is composed of at least two record types an owner record and a member Disadvantages:
record. 1. The RDBMS requires extensive hardware and system software overhead.
6. A set represents a 1:M relationship between the owner and the member 2. Conceptual simplicity gives relatively untrained people the tools to use a good
system poorly, and if unchecked, it may produce the same data anomalies found in
file systems.
3. It may promote islands of information problems as individuals and departments
can easily develop their own applications.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 21 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 22

4. The entity relationship data model Advantage


1. First introduced the ER model in 1976. 1. Semantic content is added.
2. It was the graphical representation of entities and their relationships in a 2. Visual representation includes semantic content.
database structure. 3. Inheritance promotes data integrity.
3. The relational data model and ERM combined to provide the foundation for
tightly (Good) structured database design. Disadvantages
4. ER models are normally represented in an entity relationship diagram (ERD) 1. Slow development of standards caused vendors to supply their own
5. It uses graphical representations to model database components. enhancements, thus eliminating a widely accepted standard.
2. It is a complex navigational system.
The ER model components: 3. There is a steep learning curve.
1. Entity 4. High system overhead slows transactions.
2. Entity instance
3. Attribute  Ansi/Spark Data Model (American National Standard Institute/ Standards
4. Relationship Planning and Requirements Committee)
(Or)
Entity:  Explain Degree of Data abstraction.
1. A person place or thing about which data are to be collect and stored. (Or)
2. An entity represented by a rectangle in ER models.  Explain the levels of Data abstraction.
3. The name of the entity is written in the center of the rectangle. (Or)
4. The entity name generally written in capital letters and is written in the singular.  Explain three schema architecture

Entity instance: 1. In the early 1970s the (American National Standards Institute) ANSI (standards
1. Each now in the relational table is known as an entity instance or entity planning and Requirements committee) SPARC defined a framework for data
occurrence in the E-R model. modeling based on degrees of data abstraction.
2. The ANSI/SPARC architecture defines three levels of data abstractions:
Attribute: a. External,
1. An attribute describes a particular characteristic of the entity. b. conceptual and
c. Internal.
Relationship: 3. The ANSI/SPARC framework has been expanded with the addition of a physical
1. Relationships describe associations between two entities. model to explicitly address physical level implementation address physical level
One-to-many (1:M) implementation details of the internal model.
Many-to-many (M:N) and
One-to-many (1:1)
Relationships are represents by a diamond symbol connected with line to the
related entities.
Advantages
1. Visual modeling yields (give up) exceptional conceptual simplicity.
2. Visual representation makes it an effective communication tool
3. It is integrated (include) with main relational model.

Disadvantages
1. There is limited constraint representation
2. There is limited relationship representation.
3. There is no data manipulation language.
4. Loss of information content occurs when attributes are removed from entities to avoid
crowded (full) displays. (This limitation has been addressed in subsequent graphical
versions)
Need for Abstraction
5. The object oriented database model
1. Object oriented data models are typically show using unified modeling The main objective of DBMS is to store and retrieve information efficiently; all the users
language (UML) class diagrams. should be able to access same data. The designers use complex data structure to
2. Unified modeling language is a language based on 00 concepts represent the data, so that data can be efficiently stored and retrieved, but it is not
3. That describes a set of diagrams and symbols that can be used a graphically model necessary for the users to know physical database storage details. The developers hide
system. the complexity from users through several levels of abstraction.
4. UML diagrams are used to represent data and their relationships within the
large UML object oriented systems modeling language.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 23 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 24


Advantages:

Data Independence 1. It provides a relatively easily understood macro level view of the data
environment.
Data independence means the internal structure of database should be 2. The conceptual mode is independent of both software and hardware’s.
3. Software independence means that model.
unaffected by changes to physical aspects of storage. Because of data independence, the 4. Does not depend on the DBMS software
Database administrator can change the database storage structures without affecting the 5. It used to implement the model
users view. 6. Hardware independence means that mode doesn’t depend on the hardware.
7. Used in the implementation of the model.
The different levels of data abstraction are: 8. Therefore charge in either the hardware or the DBMS software will have
no effect on the database design at the conceptual level.
1. Physical level or internal level
3. The Internal Model:
2. Logical level or conceptual level 1. The internal model map (record) the conceptual model to the DBMS.
2. The conceptual models are mapped to tables in the relational model.
3. View level or external level 3. A relational database has been selected the internal schema is expressed using
SQL, the standard Query Language for relational databases.
4. The development of a detailed internal model is especially important to database
1. External model:
designers who work with hierarchical or network models.
5. The internal model depends on specify database software.
1. The external model is the end user’s view of the data environment.
6. It is said to software dependent.
2. The term end user refers to people who use the application programs to
7. A change in DBMS software requires that the internal model be changed
manipulate the data and generate information.
8. User can change the internal model without affecting the conceptual model.
3. Each business unit is subject to specific constrains and requirements
9. A change in storage devices or even a change in operating system will not effect the
4. And each one uses a data subset of the overall data in the organization.
internal model.
5. Therefore, end users working those business units view
6. ER diagrams will be used to represent the external views.
4. The Physical model:
7. A specific representation of an external view known as an external schema.
1. The Physical model operates at the lowest level of abstraction (idea)
8. The use of external view representing subsets of the database.
2. It describing the way data is saved storage in disks or tapes.
3. The physical model requires the definition of both the physical storage devices and
Advantages
the (physical) access methods
4. It required storage devices, creating it both software and hardware dependent.
1. It creates easy to identify specific data
5. The storage structures used are dependent on the software
2. It required to supports each business unit’s operations.
6. The physical model is dependent on the DBMS,
3. It creates the easy designer’s
7. Methods of accessing files and types of hardware storage devices supported
4. It provides feedback about the model’s adequacy (capability).
by the operating system.
5. It helps to ensure security constraints in the database design.
8. User can change the physical model without affecting the internal model.
6. Damaging an entire database is more difficult but data cannot be loss
because
 Explain Database Architecture
7. It creates application program development much simpler.
1. Database architecture essentially explains the location of all the pieces of
information that create the database application.
2. Conceptual model:
2. The database architecture can be classified into
1. A conceptual model is used, graphically represented by an ERD
a. Two-Tier,
2. To integrate (mix) all external views into single view.
b. Three-Tier, and
3. The conceptual model represents a global view of the entire database and
c. Multitier architecture.
organization.
4. That is the conceptual model integrates all external views (entities, relationships,
Two-Tier Architecture
constraints and processes) into a single global view of the entire data in the
1. The two-tier architecture is a client–server architecture
enterprise.
2. The client contains the presentation code and the SQL statements for data access.
5. Also known as conceptual schema,
3. The database server processes the SQL statements and sends query results back to
6. It is the basis for the identification and high-level description of the main data
the client.
objects.
4. The client, or first tier, is primarily responsible for the presentation of data to the user to
7. The most widely used conceptual model is E-R model.
the server
8. The E-R model is illustrated with the help of the ERD.
5. The server, or the second tier, is primarily responsible for supplying data services to the
9. The ERD is used to graphically represent the conceptual schema.
client.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 25 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 26

2. Three-tier architecture offers a technology neutral method of building client/server


applications with vendors who employ standard interfaces which provide services
for each logical “tier.”
3. The three-tier architecture it is clear that in order to improve the performance a
second-tier is included between the client and the server.
4. Through standard tiered interfaces, services are made available to the application.
5. A single application can employ many different services which may reside on
First tier tasks/services
dissimilar platforms or are developed and maintained with different tools.
1. User interface
6. This approach allows a developer to leverage investments in existing systems
2. Presentation services
while creating new application which can utilize existing resources.
3. Application services
7. Although the three-tier architecture addresses performance degradations of the
two-tier architecture, it does not address division-of-processing concerns.
Second tier tasks/services
8. The PC clients and the database server still contain the same division of code
1. Application service
although the tasks of the database server are reduced.
2. Business service/objects
9. Multiple-tier architectures provide more flexibility on division of processing.
3. Data services

Presentation Services
1. “Presentation services” refers to the portion of the application which presents data to the
user.
2. It also provides for the mechanisms in which the user will interact with the data.

Business Services/objects
1. “Business services” are a category of application services.
2. Business services summarize an organizations business processes and
requirements.
3. These rules are derived from the steps necessary to carry out day-today business
in an organization.
4. These rules can be validation rules
5. It used to be sure that the incoming information is of a valid type and format

Application Services
1. “Application services” provide other functions necessary for the Application.
Multitier Architecture
1. A multi-tier, three-tier, or N-tier implementation employs a three-tier logical
Data Services
architecture superimposed on a distributed physical model.
1. “Data services” provide access to data independent of their location.
2. Application Servers can access other application servers in order to supply
2. The data can come from legacy mainframe, SQL RDBMS, or proprietary data access
services to the client application as well as to other Application Servers.
systems.
3. The multiple-tier architecture is the most general client–server architecture.
4. It can be most difficult to implement because of its generality
Advantages:
5. A good design and implementation of multiple-tier architecture can provide the
1. The two-tier architecture is a good approach for systems with stable requirements
most benefits in terms of scalability, interoperability, and flexibility.
and a moderate number of clients.
2. The two-tier architecture is the simplest to implement, due to the number of good
commercial development environments.

Disadvantages:
1. Software maintenance can be difficult because PC clients contain a mixture of
presentation, validation, and business logic code.
2. To make a significant change in the business logic, code must be modified on many PC
clients.
3. Moreover the performance of two-tier architecture can be poor when a large
number of clients submit requests because the database server may be
overwhelmed with managing messages.
 Which Situations where DBMS is not Necessary
Three-tier Architecture
1. It is also necessary to specify situations where it is not necessary to use a DBMS.
1. A “Multitier,” often referred to as “three-tier” or “N-tier,” architecture provides
2. If traditional file processing system is working well
greater application scalability, lower maintenance, and increased reuse of
3. It takes more money and time to design a database,
components.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 27 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 28


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 Vendor dependency:
database [as well as not comfortable in using the DBMS] 1. Give the heavy investment in the technology
6. Then it is not advisable to go for DBMS. 2. And personnel training, companies may be unwilling to change database vendors.
DBMS is undesirable (unwanted) under following situations:
1. DBMS is undesirable if the application is simple, well-defined, and not expected to
Vendor products
change
2. Runtime overheads are not feasible because of real-time requirements. IBM DB2/MVS
3. Multiple accesses to data are not required. DB2/UDB
DB2/400
Compared with file systems, databases have some disadvantages: Informix Dynamic
Server(IDS)
1. Higher hardware costs Microsoft Access
2. Higher programming costs SQL Server
3. High conversion costs DesktopEdition(MSDE)
4. Slower processing of some applications Open Source MySQL
5. Increased vulnerability PostgreSQL
6. More difficult recovery Oracle Oralce DBMS
RDB
 DBMS vendors and their products or Potential costs of implementing the Sybase Adaptive Server Enterprise (ASE)
database or DBMS disadvantages: Adaptive Server Anywhere (ASA)
Database systems do impose (require) significant (major) costs. Watcom

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

Increased costs:
1. Database system requires sophisticated (difficult) hardware and software and
highly skilled personnel.
2. The cost of maintaining the hardware , software can be large
3. And personnel required to operate and manage a database system can be also
large.

Management complexity:
1. Database system interface with many different technologies
2. It has a significant (major) impact on a company resources and culture.

Maintaining currency:
1. To maximize the efficiency of the database system you must keep your system
current.
2. Therefore user must update all the components
3. Because database technologies are rapidly changes, personal training is very cost.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 29 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 30

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


Unit – II
Entity-Relationship Model: Introduction, the building blocks of an entity relationship Example:
diagram, classification of entity sets, attribute classification, relationship degree, 1. Consider the example, student takes course.
relationship classification, reducing ER diagram to tables, enhanced entity-relationship 2. Here student is a strong entity
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 Weak Entities
modeling.
1. A weak entity is an entity type whose existence depends on some other entity
type.
ENTITY RELATIONSHIP(ER) MODELING 2. The entity has a primary key
3. That is partially or totally derived from the parent entity in the relationship.
The E-R Models [ERM]: 4. It is represented by double line rectangle.
1. An entity relationship model [E-R Model] is a defiled logical representation of
the data for an organization or for a business area. Syntax: ENTITY NAME Ex: BANK LOAN
2. The E–R Model is expressed in terms of entities.
3. A E-R Model is normally expressed as an entity relationship diagram Example:
4. It is a graphical representation of an E-R model. 1. Consider the example, customer borrows loan.
The components in E-R Model 2. Here loan is a weak entity.
1. Entities
2. Attributes ASSOCIATIVE ENTITY
3. Relationships
1. An associative entity is an entity type that associates the instances of one or
 ENTITIES: more entity type.
EMPLOYEE 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
1. An entity is an object of interest to the end user. instances.
2. An entity is represented by a rectangle containing the entity’s name. 5. It is represented by a diamond shape with in a rectangle.
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.
5. A collection of entities known as entity set or entity type. EMTITY NMAE
6. Each row in the relational table is known as an entity instance or entity occurrence
(event).  ATTRIBUTES: (Attribute Classification or Different types of attributes)
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. 1. An attribute is a property or characteristics of an entity.
A particular place, for example Coimbatore city can be an entity. 2. Attributes are represented by ovals and are connected to the entity rectangle with
a line.

There are different types of entities


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

Strong Entities EMPLOYEE


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.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 31 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 32


Entity type: EMPLOYEE 2. For example the attribute address is subdivided into street, city, state and zip
code.
Attributes: Ename
Door_no
Eno
Esal street City
Male/Female
Note: The naming attributes we use an initial capital letter followed by lower case letter. Address

There are different types of attributes 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
1. Domain Multivalued attribute
2. Composite and simple attributes
3. Single-valued attribute
4. Multivalued attribute
5. Derived attribute
6. Identifiers 1. Multivalve attributes are attributes that may take on more than one value for a
7. Composite primary keys given entity instance.
2. A multi value attribute with an ellipse with double lines.
Domains
1. Attribute have a domain. Ename
2. A domain is the ser of possible values for a given attribute. skill
3. For example the domain for the gender attribute consists of only two possible: M Eno
or F.
EMPLOYEE
Male Female
Derived attributes
Gender

Required and optional attributes


1. A required attribute is an attribute that must have a value.
2. It cannot be left empty. 1. A derived attribute is an attribute whose value is calculated (derived) from other
3. An optional attribute is an attribute that does not require a value; attributes.
4. It can be left empty. 2. The derived attributes need not be physically stored within the database.
3. Derived attributes are sometimes referred to as computed attributes.
36 4. Indicate a derived attribute using an ellipse with a dashed line.

Age Vehicle
Ename
Required attribute optional attribute skill
Eno
Composite and simple attributes:
1. A composite attribute is an attribute that can be further subdivided to yield (give EMPLOYEE Join_date
up) additional attributes. Experience

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 33 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 34

Identifiers (Primary keys)


a. one-to-one,
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 1 1
Principal Manages Department
table.
3. Identifiers are underlined I n the ERD. b. one-to many
Ex: 1 M
Subject has Lectures
Jdc(Eno, ename, salary);
Null Value Attribute c. many to many
In some cases, a particular entity may not have any applicable value for an attribute. For M N
Lectures Teach Subjects
such situation, a special value called null value is created. Null value situations Not
applicable Not known
3. Cardinality expresses the minimum and maximum number of entity occurrence
Example (incidence) associated with one occurrence of the related entity.
4.
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 M N
Lectures Teach Subjects
Composite identifiers
EXISTENCE DEPENDENCE
A composite identifier is a primary key composed of more than one attribute. 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
JDC( Eno, Deptno, Ename, Salary ) entity occurrence.
3. In entity can exist apart from one or more related entities, it is said to be
 RELATIONSHIPS existence-independent.
1. Relationship is an association between entities. Author Book
2. The entities that participate each relationship is identified by a name that
describes the relationship
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
3. The relationship represents diamond symbol. RELATIONSHIP STRENGTH
4. Relationships between entities always operate in both directions.
1. Relationship strength is based on how the primary key of a related entity is
5. For example: the relationship between the entities named EMPLOYEE and SKILL demined.
6. An EMPLOYEE may learn many SKILLS. Each SKILL may learn by many EMPLOYEE
2. To implement a relationship, the primary key of one entity connects as a foreign
7. key in the related entity.
Ex:
M N
CITY Vehicle ROOTS College (SNO, SNAME, SSECTION)
Hostel (SNO, SNAME, ROOMECODE,)

1. Hear Hostel student no is dependent on college sno


CONNECTOVITY AND CARDONALITY 2. student don’t have sno in college that student sno not to store in hostel
1. The term connectivity is used to describe the relationship classification.
2. The entity relationships may be classified as 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,)

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 35 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 36


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
EMPLOYEE Manages
entity.

College (SNO, SNAME, SSECTION) One_to_many (1 – N):


Hostel (SNO, SNAME, ROOMECODE,)
One instant of entity type
RELATIONSHIP PARTICIPATION associated more than one instant of
Participation in an entity relationship is either optional or mandatory. the same entity then it is called one-
Optional:
to-many relationship
1. Optional participation means that one entity occurrence does not require a
corresponding entity occurrence in a particular relationship. In this Eg manages is shown as 1 to many relationship between the instances of the
2. Ex: Some Lecturers may Teach any Students I Each Student must be taught by at employee entity type.
least one Lecturer
Some organizations it may be possible for one employee to be managed by many other
Lectures
M
Teaches
N
Student employees.

Many_to_many (N – N)
Mandatory:
More than one instant of entity type
1. Mandatory participation means that one entity occurrence requires a associated with more than one
corresponding entity occurrence in a particular relationship. Has-
instant of the same entity then it is
2. Some Lecturers may not Teach any Students I Each Student must be taught by at ITEM components
called many-to-many relationship
least one Lecturer
M N
Lecturer Teaches Student

 REATIONSHIP DEGREE (DEGREES OF RELATIONSHIP) 1. In this eg we represent many to many relationships.


2. The entity type item is used to represent all types of components.
The degree of relationship is number of entities or participates associated with a 3. Components for the name of the relationship that associated lower level item and
relationship. The most common relationship degrees in E-R models are higher level items.
1. Unary (Degree I) BINARY RELATIONSHIP:
2. Binary (Degree II) A binary relationship is relationship between the instances of two entity types.
3. Ternary (Degree III)
Higher relationship degrees are also possible but they are rear in use. One_to_one(1-1): One instance of the one entity type can be associated with one
instances of other entity type.
UNARY RELATIONSHIP:
1. A unary relationship is a relationship between the instances of a single entity
EMPLOYEE Is_assigned PARKING PLACE
type.
2. These relationships are also called a recursive relationship.
One-to-one relationship (1-1): This eg indicates that an employee is assigned one parking place and each parking
One instant of entity type place is assigned to only one employee.
associated one instant of the PERSON Is-married_to

same entity then it is called One to many (1-N): One instance of the one entity type can be associated with
number of instances of other entity type.
one-to-one relationship
Eg: PRODUCT
In this Eg is_married_to is shown as a 1-1 relationship between instances of the PRODUCT LINE Contains

person entity type.


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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 37 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 38

Many-to-many: The number of instances of one entity type can associated with RELATIONSHIPS WITHIN THE RELATIONAL DATABASE
number of instances of other entity type. 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)
Eg: STUDENT Registers-
_for COURSE The 1:M Relationship:

The 1: M relationship is the relational database norm. consider the PAINTER paints
This eg indicated that an employee may complete more than one course and then PAINTING example.
each course may have many employees.

TERNARY RELATIONSHIP PAINTER paints PAINTING


1. A ternary relationship is a simultaneous relationship among the instances of three
entity types. The 1:M relationship between PAINTER and PAINTING
PART

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
VENDOR Supplies WAREHOUSE
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:
Shipping mode
unitcost

1. In this eg vendor can supply various parts to warehouse. As the 1: 1 table implies, in this relationship, one entity can be related to only one
2. The relationship supply is used to record to specific parts that are supplied by a other entity, and vice-versa. For example, one department chair – a professor – can
given vendor to a particular warehouse. chair only one department can have only one department chair. The entities PROFESSOR
3. Thus there is three-entity type VENDOR, PARTS, WAREHOUSE. and DEPARTMENT thus exhibit a 1: 1 relationship.
4. There are two attributes are relationship is shipping code and unit-cost.

Quaternary Relationships 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
Quaternary relationships involve four entities. The example of quaternary placed in the same table when they should not be.

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

The 1:1 relationship between PROFESSOR and DEPARTMENT

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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 39 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 40


INDEXS: Reducing ER Diagram to Tables
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 Mapping Algorithm
index key and a set of pointers.
The mapping algorithm gives the procedure to map ER diagram to tables.
DBMS use index for many different purposes. An index can be used to retrieve The rules in mapping algorithm are given as:
data more efficiently. But indexes can also be used by a DBMS to retrieve data ordered
by a specific attribute or attributes. – For each strong entity type say E, create a new table. The columns of the table are the
attribute of the entity type E.
For example, creating an index on a customer’s last name will allow you to – For each weak entity W that is associated with only one 1–1 identifying
retrieve the customer data alphabetically by the customer’s last name.
owner relationship, identify the table T of the owner entity type. Include
Index play an important role in DBMSs for the implementation of primary keys, as columns of T, all the simple attributes and simple components of the
when you define a table’s primary key column(s). The DBMS automatically creates a composite attributes of W.
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. – For each weak entity W that is associated with a 1–N or M–N identifying
relationship, or participates in more than one relationship, create a new
 Symbols Used in ER Diagram
1. The elements in ER diagram are Entity, Attribute, and Relationship. table T and include as its columns, all the simple attributes and simple
2. The different types of entities like strong, weak, and associative entity, components of the composite attributes of W. Also form its primary key
3. Different types of attributes like multivalued and derived attributes and identifying
relationship and their corresponding symbols by including as a foreign key in R, the primary key of its owner entity
– For each binary 1–1 relationship type R, identify the tables S and T of
the participating entity types. Choose S, preferably the one with total
Strong entity Associate entity
participation. Include as foreign key in S, the primary key of T. Include
as columns of S, all the simple attributes and simple components of the
composite attributes of R.
Week entity
Attribute – For each binary 1–N relationship type R, identify the table S, which is at
N side and T of the participating entities. Include as a foreign key in S, the primary key
of T. Also include as columns of S, all the simple attributes and simple components of
composite attributes of R.
Multivalue attri. – For each M-N relationship type R, create a new table T and include as
Relation ship
columns of T, all the simple attributes and simple components of composite attributes of
R. Include as foreign keys, the primary keys of the participating entity types. Specify as
the primary key of T, the list of
foreign keys.
– For each multivalued attribute, create a new table T and include as
Identify Rel.Ship Derive Attribute
columns of T, the simple attribute or simple components of the attribute
A. Include as foreign key, the primary key of the entity or relationship

type that has A. Specify as the primary key of T, the foreign key and the

columns corresponding to A.

Regular Entity

Regular entities are entities that have an independent existence and generally

represent real-world objects such as persons and products. Regular entities

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 41 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 42

are represented by rectangles with a single line.

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.
Converting “Weak Entities” in ER Diagram to Tables

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.
Converting Binary Relationship to Table
Mapping Multivalued Attributes in ER Diagram to Tables
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,

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 43 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 44


and many-to-many.

Mapping one-to-Many Relationship

Converting Ternary Relationship to Tables

Mapping Associative Entity to Tables

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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 45 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 46

ADVANCED DATA MODELING

 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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 47 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 48


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

INHERITANCE V-name
Cab Type
1. The property of inheritance enables (allow) an entity subtype to inherit the V-ID
attributes and relationships of the super type.
2. A super type contains those attributes that are common to all of its subtype.
Truck Capacity
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. Price Engine Displacement

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.

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 Make Model
process of viewing an object as a more refined, specialized object.

V-name
V-ID

Vehicle

Engine Displacement
Price

Cab Type
Car Truck

Capacity
No. of passengers

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:

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 49 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 50

In the above diagrams car, truck and motor cycle contains a no. of attributes in
Description Location
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 Part-no Quantity
Part S-ID
general entity types. This more general entity type (vehicle) together with the resulting on Hand
supertype / subtype relationships is shown in above fig b.

The entity car has the specific attribute, no. of passengers, while truck has 2 Routing-No Supplier
specific attributes capacity and cab type. Thus generalization has allowed us to group Unit
entity types along with their common attributes and at the same time preserve specific Price

attribute that are peculiar to each subtype. Manufactur Purchased


Supplies
ed Part Part
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:
In the above ex entity type part having attributes partno, description, unit price,
The process of defining one or more subtypes of the supertype and forming
location, quality on hand, routing no and supplier.(a supplier attribute is Multivalued
supertype/subtype relationships.
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.
Price ISA Relationship and Attribute Inheritance
Supplier
Description
Supplier-ID
IS A relationship supports attribute inheritance and relationship participation.
Part-no
Part
Routing-No In the EER diagram, the subclass relationship is represented by ISA

Quantity relationship. Attribute inheritance is the property by which subclass entities


on Hand Location
inherit values for all attributes of the superclass.

Consider the example ofEMPLOYEEentity set in a bank. TheEMPLOYEE

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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 51 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 52


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.

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.
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 PERIODICALS.This


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. With total
 Constraints on Specialization and Generalization specialization, an instance of the supertype must be a member of at least one
The constraints on specialization and generalization can be broadly classified into subtype.
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 Partial Specialization
and Crocodile which can live in both land and water hence the division of Partial completeness refers to the fact that an entity instance in the superclass
ANIMAL into LAND and WATER animals is an example of overlap constraint. need not be a member of any subclass in the specialization. With partial

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 53 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 54

specialization, an instance of a supertype may or may not be a member of any Entity Clusters
subtype. EER diagrams are difficult to read when there are many entities and relationships.
Example of Partial Specialization One possible solution is to group entities and relationships into entity clusters.
Consider the PERSON specialization into EMPLOYEE and STUDENT. This Entity cluster is a set of one or more entity types and associated relationships
is an example of partial specialization because there can be a person who is grouped into a single abstract entity type.
unemployed and does not study.
Connection Traps

Connection trap is the misinterpretation of the meaning of certain relationships.


This connection traps can be broadly classified into fan and chasm trap. Any
conceptual model will contain potential connection traps. An error in the
interpretation of the meaning of the relationship may cause the database to be
incapable of storing certain information. Both the fan and chasm trap arise when
the relationships appear to exist between entity types, but the links between
occurrences may be ambiguous or not exist. Related groups of entities could
become clusters.

12) 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.

Fan Trap
Fan trap occurs when the model represents a relationship between entity types
but the pathway between certain entity occurrences is ambiguous. Fan trap occurs
when 1–M relationships fan out from a single entity. In order to understand the
concept of Fan trap, consider the following example
Contractor works in a team. . . . . . . . . Statement (1)
Team develops projects. . . . . . . . . . . . Statement (2)
Statement (1) represents M–1 relationship. Statement (2) represents 1–M
Composition is a stronger form of aggregation where the part cannot exist relationship. But the information about which contractors are involved in
without its containing whole entity type and the part can only be part of one entity developing which projects is not clear.
type.Consider the example of DEPARTMENT has PROJECT. Each project is
Consider another example of Fan trap.
associated with a particular DEPARTMENT. There cannot be a PROJECT without
DEPARTMENT. Hence DEPARTMENT has PROJECT is an example of composition. Department is on Site. . . . . . . . . Statement (1)
Site employs Staff. . . . . . . . . . . . . . . Statement (2)

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 55 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 56


Statement (1) represents M–1 relationship, because many departments may be in
a single site. Statement (2) represents 1–M relationships. However which staff Differences of Specialization & generalization:
works in a particular department is ambiguous. The fan trap is resolved by
reconstructing the original ER model to represent the correct association
Chasm Trap
A chasm trap occurs when a model suggests the existence of a relationship No specilaization generalization
1. It is a Top down approach It is a Bottom Up apporach
between entity types, but the pathway does not exist between certain entity
2. Specialization stems from single Generalization proceeds from the recognition
occurrences. It occurs where there is a relationship with partial participation,
entity set; it emphasizes differences that a number of entity sets share some
which forms part of the pathway between entities that are related. Consider the among entities the set by creating common features(namely,they are described
relationship shown later. distinct low level entity sets. by the same attributes and participate in the
same relationship sets)
3. The process of designating sub The process of designating groupings from
groupings with in an entity set is various entity sets is called Generalization
called Specialization.
A single branch may be allocated to many staff who oversees the management of 4. Specialization is a result of taking a Generalization is a result of taking the lower
properties for rent. It should be noted that not all staff oversee property and not subset of higher level entity set to level entity sets to produce a higher level
all property is managed by a member of staff. Hence there exist a partial form a lower level entity set. entity set.
participation of Staff and Property in the relation “oversees,” which means that
some properties cannot be associated with a branch office through a member of
staff. Hence the model has to modified as shown later
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

 Relational Data Model


15) Advantages of ER Modeling 1. The relational model uses a collection of tables to represent both data and
An ER model is derived from business specifications. ER models separate relationships.
2. Tables are logical structures maintained by the database manager.
the information required by a business from the activities performed within a 3. The relational model is a combination of three components,
a. Structural
business. Although business can change their activities, the type of information b. Integrity and
tends to remain constant. Therefore, the data structures also tend to be c. Manipulative parts.
constant. The advantages of ER modeling are summarized later:
a. Structural Part
1. The ER modeling provides an easily understood pictorial map for the 1. The structural part defines the database as a collection of relations.
database design.
2. It is possible to represent the real world problems in a better manner in b. Integrity Part
ER modeling. 1. The database integrity is maintained in the relational model using primary
3. The conversion of ER model to relational model is straightforward. and foreign keys.
4. The enhanced ER model provides more flexibility in modeling real world
c. Manipulative Part
problems.
1. The relational algebra and relational calculus are the tools
5. The symbols used to represent entity and relationships between entities are 2. It used to manipulate data in the database.
simple and easy to follow. 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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 57 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 58

6. The column will have data value. Determinants:


7. All values in a column must conform to the same data format The attribute on the left-hand side of the arrow in a functional dependency is
8. The order of the rows and columns is unimportant to the DBMS. called a determinant.
9. In relational model attributes can be in any order. Eg: In the EMP-COURSE relation the combination of eno, course_tittle is a
10.In relational model rows can be in any order. determinant.
11.Relations must have a key.
12.Keys can be a set of attributes.  Types of SQL Keys
13.Each column has a specific range of values known as the attribute domain
14.Domain is the set of valid values for an attribute. There are different types keys relation data model. They are
15.Degree of the relation is the number of attributes (columns) in the relation. 1. Composite key
16.Cardinality of the relation is the number of tuples (rows) in the relation 2. Candidate key
3. Super key
Keys: 4. Alternate key
1. A key is a one or more attributes that determine (decide) other attributes. 5. Secondary key
2. For example sno identifies all of the student attributes 6. Primary key
3. Such as sfname, slname, sintial, dob, class and phno. 7. Foreign key
4. The one attribute determines other attribute is called determination. 1. Composite key:
A B a. It is a combination of two or more columns in a table
In the above A determines B. A is called determination. b. That can be used to uniquely identify each row in the table.
c. Such a multi attribute key is known as composite key.
Functional dependence: Ex:
CREATE TABLE BABA
1) Functional dependency is a relationship that exists when one attribute uniquely (Sno integer, deptno
determines another attribute. integer, address varchar(50), PRIMARY KEY (sno, deptno));
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. Explanation:
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. 2. Candidate key:
5) A also agree in value for attribute B a. A Candidate Key can be any column or a combination of columns
b. That can qualify as unique key in database.
Functional Dependencies and Keys c. There can be multiple Candidate Keys in one table.
A functional dependency is a constraint between two attributes or two sets of d. Each Candidate Key can qualify as Primary Key.
attributes. e. [A Primary Key is a column or a combination of columns that uniquely identify a
If the attribute (B) is functionally dependent on a composite key(A) but not on any record
f. A minimal super key. A super key that does not contain a subset of attributes
subset of that composite key, the attribute (B) is fully functionally dependent on (A).
that is itself a super key. ]
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. CREATE TABLE BABA
The functional dependency of B on A is represented by an arrow as follows. (Sno integer, deptno integer, email varchar(50), PRIMARY KEY (sno, deptno,email));
AB
Eg: Consider the relation EMP-COURSE Explanation: EmpID , EmailID and SSN all will be always unique for any
employee in that case all these three columns called as candidate keys.
EMP-COURSE (Eno, Course_title, Date_completed);
Eno, Course_title  Date_completed. 3. Super key:
a. Super key is a combination of columns
Fully functional dependencies b. That uniquely identifies any row within a RDBMS table.
1. All non candidate key attributes must depend on the primary key. c. It is reduced to the minimum number of columns required to uniquely identify each
2. (Remember, a candidate key attribute is any key (for example, a primary or row.
foreign key) d. An attribute or combination of attributes that uniquely identifies each row in a
3. It used to uniquely identify a database record. table is called super key.
4. If the attribute (B) is functionally dependent on a composite key(A) Exp :
5. But not on any subset of that composite key, the attribute (B) is fully functionally
dependent on (A). 4. Alternate key:
EMP-COURSE (Eno, Course_title,); a. A Alternate key is a key that can be work as a primary key.
Eno Course_title 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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 59 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 60


primary key then rest candidate key called as alternate key.
Exp: 4. Active Online Catalog Based on the Relational model: The system list is a
1. Suppose in employee table EmpID is primary key collection of tables that the DBMS maintains for its own use. These tables hold the
2. Then Emailid and SSN are called as alternate key description of the structure of the database.
3. It mean later on these key can be act as primary key without affecting existing data in
table. 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,
Secondary key: data manipulation operations, security and integrity constraints and transaction
1. An attribute (or combination of attributes) used strictly for data retrieval management operations.
purpose is called secondary key.
Exp : 6. The View Updation Rule: It used to All views that are theoretically updateable must
create table tnam(ano number, bno number, bname char(12), primary be updateable by the system.
key(ano,bno))
In this bno is secondary key. 7. High Level insert, update, and Delete: it used to rows should be treated as sets in
insert, delete and update operations.
Primary key:
1. An attribute that uniquely identifies each row in a relation is called primary 8. Physical data independence: Application Program must remain un impaired
key. (undamaged) when any changes are made in storage representation or access
2. The combination of unique and not null method.
3. It cannot support duplicate value and also empty value in attribute
9. Logical Data Independence :Users and user Programs should be independent of
Ex: CREATE TABLE BABA the logical structure of the database.
(Sno integer, deptno integer, address varchar(50), PRIMARY KEY (sno));
Or 10. Integrity independence: Integrity constraints must be storable in System catalog.
CREATE TABLE BABA
11. Distribution independence: Database must allow manipulation of Distributed data
(Sno integer primary key, sna varchar2(20)); located on other computer systems.

12. Non – Subversion Rule: This rule states that different levels of the language can
Foreign key: not subvert or bypass the integrity rules and constraints.
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  Integrity rules or relational integrity:
PRIMARY KEY in another table. 1. Relational database integrity rules are very important to good database design.
4. The table containing the foreign key is called the child table, and the table 2. Many (but by no means all) RDBMSs enforce integrity rules automatically.
containing the candidate key is called the referenced or parent table. 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.
CREATE TABLE BABA1 ( 1. Domain Integrity.
Sno int PRIMARY KEY, 2. Entity Integrity.
Sna varchar2(20) NOT NULL, 3. Referential Integrity.
SID int FOREIGN KEY REFERENCES JDC(ID)
); 1. Domain Integrity:
1. A domain is a set of values which is assigned to an attribute.
 Explain Dr. E.F.CODD Rules 2. The components of the domain are domain name, meaning, data type, size and
[For any RDBMS to be accepted as full fledged RDBMS it has to follow the 12 CODD range of the values.
rules . The rules are] There are 12 CODD rules.
Ex: student relation the domains are regdno, name.
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. 2. Entity Integrity :
1. All primary key entries are unique, and no part of a primary key may be null.
2. The guaranteed access Rule: Every data value in a relational database should be 2. Each row will have a unique identity, and foreign key values can properly
logically accessible by specifying a combination of the table name, the primary key reference primary key values.
value on column name. 3. A primary key is an attribute in a relation which is used to identify each row in a
relation.
3. Systematic Treatment of NULL values: DBMS must support NULL values to 4. No. of components of a primary key value may be NULL.
represent missing or inapplicable information. They must be distinct from zero or 5. This is called as entity integrity.
spaces. 6. A NULL is an undefined value. One NULL is not equal to another NULL.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 61 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 62

4. Selection operation can be considered as row wise filtering.


5. This is pictorially represented also known as RESTRICT
3. Referential Integrity : 6. It creates values for all rows found in a table that satisfy a given
1. A referential integrity is used to implement the foreign key. condition.
2. A foreign key is a non key attribute in the relation R and it is a primary key in 7. Select can be used to list all of the row values, or it can create only those
relation R2. row values
3. This key is called as foreign key. The value of the foreign key is either NULL or primary 8. That matches a specified criterion.
key. 9. Select create a horizontal subset of a table.
4. Another integrity rules that can be enforced in the relational model are the Syntax
NOT NULL and UNIQUE constraints. σ Predicate (R).

NOT NULL: its not supports empty value in attribute. The NOT NULL constraint ex: σ subject = "database"(Books)
can be placed a value for that column.
P_CODE P_DESCRIPT PRICE
UNIQUE: The UNIQUE constraint is used to not support duplicate values exists 123456 Flash light 5.26
column. 123457 Lamp 25.15
123458 Box Fan 10.99
123459 9v battery 1.92
 What is a Relational Algebra 123455 100W bulb 1.47
1. The relational algebra is a notional language with operations 123454 Powerdrill 34.99
2. That work on one or more relations to define another relation without changing
the original relation. SELECT only PRICE less than Rs. 2.00 yields P_CODE P_DESCRIPT PRICE
3. The both the operands and the results are relations; 123459 9v battery 1.92
4. The output from one operation can become the input to another operation. 123455 100W bulb 1.47
5. This allows expressions to be nested in the relational algebra. This property is called 1. b. Projection Operation
closure. 2. The projection operation works on a single relation R
6. Relational algebra is an abstract language, 3. And defines a relation that contains a vertical subject of R,
7. It means that the queries formulated in relational algebra are not intended to be 4. And extracting the values of specified attributes and elimination duplicates.
executed on a computer. 5. The projection operation can be considered as column wise filtering.
8. Relational algebra consists of group of relational operators that can be used to It’s creates all values for selected attributes. In other words, project creates
manipulate relations to obtain a desired result. a vertical subset of a table.
9. Knowledge about relational algebra allows us to understand query execution and
optimization in relational database management system. Syntax
a1,a2,......an (R).
 Explain Relational Algebra Operations (Relational Set operators) [Where a1, a2, . . . . . . an are attributes and R stands for relation To illustrate
Operations in relational algebra can be classified into set operation and database projection operation consider the relation STAFF, with the attributes Staff number,
operations. Name, Gender, Date of birth, and Salary.]
1. Unary and Binary Operations SALES:
1. Unary operation involves one operand,
a. selection P_CODE PRICE
b. Projection P_DESCRIPT PRICE
2. Binary operation involves two operands. 123456 Flashlight 5.26 5.26
PROJECT PRICE yields
a. Union operation 123457 Lamp 25.15 25.15
b. Difference operation 123458 Box Fan 10.99 10.99
c. Cartesian product operation 123459 9v battery 1.92 Select price from sales; 1.92
d. Intersection operation 123455 100w bulb 1.47 1.47
e. Division operation 123454 Power drill 34.99 34.99
f. Join operations operation
2. Relational algebra operations PRICE
P_DESCRIPT
3. Set Operations Database operations Flashlight 5.26
PROJECT P_DESCRIPTand PRICE yields Lamp 25.15
Three main database operations are SELECTION, PROJECTION, and JOIN. Box Fan 10.99
9v battery 1.92
1. a. Selection Operation 100w bulb 1.47
1. The selection operation works on a single relation R Select components, price, from sales; Power drill 34.99
2. And it defines a relation that contains only those tuples of R
3. That satisfies the specified condition (Predicate).
2. a. Union Operation

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 63 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 64


1. Union combines all rows from two tables, excluding (without) duplicate 3. The result of Cartesian product contains all attributes from both relations R and S.
rows. 4. It’s creates all possible pairs of rows from two tables
2. The tables must have the same attribute characteristics to be used in the 5. It is also known as the Cartesian product.
UNION. 6. For example one table has six rows and the other table has three rows,
Or 7. The PRODUCT creates a list composed of 6 X 3 = 18 rows.
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, Relational Algebra Symbol for Cartesian product:
5. Duplicate tuples being eliminated. The Cartesian product between the two relations R and S is denoted by R ×
S.

Relational Algebra Expression Example


If there are 5 tuples in relation “R” and 2 tuples in relation “S” then the
The union of two relations R and S are denoted by R ∪ S. R ∪ S is pictorially number of tuples in R × S is 5 ∗ 2 = 10.
represented R S
R S
A 1 A 1
P_CODE PRICE A 2
P_DESCRIPT
B 2 A 3
123456 Flashlight 5.26 Note:
PRICE B 1
123457 Lamp 25.15 P_CODE P_DESCRIPT No. of tuples in R X S = 2 x 3
UNION 3 B 2
123458 Box Fan 10.99 345678 Microwave 160.00 =6
B 3
123459 9v battery 1.92 345679 Dishwasher 500.00
123455 100w bulb 1.47 d. Intersection Operation
123454 Powerdrill 34.99 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
P_CODE P_CESCRIPT PRICE (create) valid results.
123456 Flashlight 5.26 4. For example, you cannot use INTERSECT if one of the attributes is numeric
123457 Lamp 25.15 and one is character – based.

OUTPUT 123458 Box Fan 10.99


123459 9v battery 1.92 F_NAME F_Name F_Name
Yields
123455 100w bulb 1.47 Kumar INTERSECT Sree Sree
123454 Powerdrill 34.99 Sree Lal Hari
345678 Microwave 160 Kiran Hari
345679 Dishwasher 500 Sheshu Krishna
Hari
b. Difference Operation
1. The set difference operation defines a relation consisting of the tuples e. Division Operation
2. That is in relation R but not in S. 1. The division of the relation R by the relation S is denoted by R ÷ S,
3. It create all rows in one table that are not found in the other table where R ÷ S is given by: R ÷S = ΠR−−S(r) − ΠR−−S((ΠR−−S(r) ×
4. That is, it subtracts one table from the other. s) − r)
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 CODE LOC
subtracting the second table from the first table. A 5
A 9 CODE
yields
Relational Algebra Expression A 4 DIVIDE A LOC
The difference between two relations R and S is denoted by R–S. B 5 B
F_NAME F_Name F_Name 5
Yields B 3
Krishna Sree Krishna C 6
sree DIFFERENCE Kumar Sridhar D 7
Sridhar Hari Sheshu D 8
Sheshu Kiran E 8
Hari
f. Join Operations
c. Cartesian Product Operation 1. Join operation combines two relations to create a new relation.
1. The Cartesian product operation defines a relation 2. The tables should be joined based on a common column.
2. That is the concatenation of every tuples of relation R with every tuples of relation 3. The common column should be compatible in terms of domain.
S.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 65 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 66

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

 Types of Join Operation


There are different types of join operations

Natural Join Equi Join


The natural join performs an equi join of the two relations R and S over all common A special case of condition joins where the condition C contains only
attributes. One occurrence of each common attribute is eliminated from the result. In
other words a natural join will remove duplicate attribute. equality.
In most systems a natural join will require that the attributes have the same name to Example of Equi Join
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 Given the two relations STAFF and DEPT, produce a list of staff and the
that the attributes should be of same domain.
departments they work in.
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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 67 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 68


Theta Join R still appear in the resulting relation.

A conditional join in which we impose condition other than equality condition. If equality Example of Full Outer Left Outer and Right Outer Join
condition is imposed then theta join become equi join. The symbol θ stands for the
comparison operator which could be >, <, >=, <=. Consider two relations PEOPLE and MENU determine the full outer, left

Expression of Theta Join outer, and right outer 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

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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 69 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 70

 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.
Semi-Join 8. For example we want to know how many staff is working in a particular
department.
The semi-join of a relation R, defined over the set of attributes A, by relation S, defined 9. This query cannot be performed using relational algebra.
over the set of attributes B, is the subset of the tuples of R that participate in the join of 10.The relational algebra cannot modify the database.
R with S. The advantage of semi-join is that it decreases the number of tuples that need 11.For example we want to increase the salary of all employees by 10%.
to be handled to form the join. In centralized database system, this is important because 12.This cannot be done using relational algebra.
13.The relational algebra cannot compute “transitive closure.”
it usually results in a decreased number of secondary storage accesses by making better
14.In order to understand the term transitive closure consider the relation
use of the memory. It is even more important in distributed databases, since it usually RELATIONSHIP, which describes the relationship between persons.
reduces the amount of data that needs to be transmitted between sites in order to 15.Consider the query, Find all direct and indirect relatives of Gopal?
evaluate a query. 16.It is not possible to express such kind of query in relational algebra.
17.Here transitive means, if the person A is related to the person B and if the person
Expression for Semi-Join R _F S =_ A(R _F S) where F is the predicate. B is related to the person C means indirectly the person A is related to the person
C.
18.But relational algebra cannot express the transitive closure

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 71 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 72


10.An expression is of the form:
Relationship
Person1 Person2 Relationship { X1,X2…………..Xn | COND(X1,X2…….Xn, Xn+1,……..Xm+n) }
Hari Krishna Lakshmi Mother
Sree harilal Nandalal Father Example:
Hari Raj Brother
Sree Sravanthi Husband Retrieve the birth dates and address of the employee whose name is ‘John
B.Smith’
 Relational Calculus
1. The purpose of relational calculus is to provide a formal basis for defining { uv | ( (q) (r) (s) (t) (w) (x) (y) (z) (EMPLOYEE(qrstuvwxyz) and q = ‘John’
declarative query languages appropriate for relational databases. and r = ‘B’ and s = ‘Smith’ ) }
2. Relational Calculus comes in two flavors or
a. Tuple Relational Calculus (TRC) and { uv | EMPLOYEE(‘John’, ‘Smith’, ‘B’, t,u,v,w,x,y,z ) }
b. Domain Relational Calculus (DRC).
3. The basic difference between relational algebra and relational calculus is that the  Explain QBE
former gives the procedure of how to evaluate the query whereas the latter gives 1. QBE stands for Query By Example. QBE uses a terminal display with attribute
only the query without giving the procedure of how to evaluate the query: names as table headings for queries.
a. The variable in tuple relational calculus formulae range over tuples. 2. It is very easy to list the entire schema, simply by scrolling information on the
b. The variable in domain relational calculus formulae range over individual screen.
values in the domains of the attributes of the relations. 3. QBE was developed originally by IBM in the 1970s to help users in their retrieval
c. Relational calculus is nonoperational, and users define queries in terms of of data from a database.
what they want, not in terms of how to compute it. (Declarativeness.) 4. QBE represents a visual approach for accessing data in a database through the
use of query templates.
Relational Calculus and Relational Algebra: 5. QBE can be considered as GUI (Graphical User Interface) based on domain
The major difference between relational calculus and relational algebra is calculus.
1. A relational calculus query specifies what information is retrieved 6. QBE allows users to key in their input requests by filling in empty tables on the
2. A relational algebra query specifies how information is retrieved screen, and the system will also display its response in tabular form.
 Tuple Relational Calculus 7. QBE is user-friendly because the users are not required to formulate sentences for
1. Tuple relational calculus is a logical language with variables ranging over query requests with rigid query-language syntax.
tuples. 8. In QBE the request is entered in the form of tables whose skeletons are initially
2. The general form of tuple relational calculus is given by: constructed by QBE.
9. Some of the QBE query template examples:
{<tuple variable list> | <conditions>} {t | COND(t)}
Example 1. Projection operation
3. Here t is the tuple variable, which stands for tuples of relation.
4. COND (t) is a formula that describes t. 1. In this template P. implies “Print.” The meaning is: Print the PLAYER ADDRESS
5. The meaning of the earlier expression is to return all tuples T that satisfy the who belong to the country INDIA.
condition COND: 2. To make a projection only put P. in any column of the projection.
a. T/R(T)} means return all tuples T such that T is a tuple in relation R. 3. QBE will enforce uniqueness of projections automatically.
b. For example, {T.name/FACULTY(T)} means return all the names of
faculty in the relation FACULTY.  Relational algebra Vs Relational Calculus
c. {T.name/ FACULTY(T) AND T.deptid=‘EEE’} means return the value of
the name of the faculty who are working in EEE department. 1. The relational algebra and the relational calculus have the same expressive
power;
 Domain relational calculus 2. i.e. all queries that can be formulated using relational algebra can also be
formulated using the relational calculus and vice versa.
1. Domain Relational Calculus is the second form of relational calculus. 3. E. F. Codd first proved this in 1972.
2. It uses domain values or variables that take on values from an attribute 4. This proof is based on an algorithm by which an arbitrary expression of the
domain, rather than values for an entire tuple. relational calculus can be reduced to a semantically equivalent expression of
3. However, the DRC is closely related to TRC. relational algebra.
4. DRC acts as a theoretical basis for Query by Example. 5. It is sometimes said that languages based on the relational calculus are "higher
5. Queries in the DRC have the form: level" or "more declarative"
{X1, ..., Xn | Condition} 6. Than languages based on relational algebra because the algebra (partially)
6. The X1, ..., Xn are a list of domain variables. specifies the order of operations while the calculus leaves it to a compiler or
7. The condition is a logical expression of classical first-order logic. interpreter to determine the most efficient order of evaluation.
8. The language QBE is based on DOMAIN RELATIONAL CALCULUS.
9. It differs from tuple calculus in the type of variables used.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 73 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 74

UNIT IV 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
 Introduction to ORACLE Column-name data-type (L, D)
Ex:
1. Oracle is a Relational Database Management System (RDBMS). Sno number (3);
2. Oracle being RDBMS, stored data in tables called relations. or
3. These relations are data can be representation in two-dimensional sno number(7,2);
4. The rows are called tuples it represents records
5. The columns called attributes it represents pieces of information contained in the b. Integer:
record. 1. It may be abbreviated as INT
2. Integers are (whole) counting numbers,
 Benefits of Standardized Relational Language 3. So they cannot be used to store numbers that require decimal places
The main advantages of standardized language are given below. Syntax:
1. Reduced training cost Column-name data-type (L);
2. Enhanced productivity Ex:
3. Application portability Sno integer (3);
a. Application portability means applications can be moved from machine to
machine when each machine uses SQL. c. Smallint:
4. Application longevity: 1. Like Integer, but limited to integer values up to six digits.
a. A standard language tends to remain so for a long time,
2. If your integer values are relatively small, use smallint instead of Int.
b. There will be little pressure to rewrite old applications.
5. Reduced dependence on a single vendor SQL language development is given in a Syntax:
nutshell below: Column-name data-type (L);
a. In 1970 E.F. Codd of IBM released a paper “A relational model of data for Ex:
large shared data banks.” Sno smallint(3);
b. IBM started the project System R to demonstrate (show) the feasibility
(possibility) of implementing the relational model in a database d. Decimal(l,d)
management system. 1. Like the number specification, but the storage length is a minimum
c. The language used in system R project was SEQUEL.
specification.
d. SEQUEL was renamed SQL during the project, which took place from 1974 to
1979. 2. That is, greater lengths are acceptable, but smller ones are not.
6. The first commercial RDBMS from IBM was SQL/DS. It was available in 1981. 3. Decmal (9,2), decimal(9), and decimal are all acceptable.
7. Oracle from relational software (now Oracle Corporation) was on the market
before SQL/DS, i.e., 1979. Syntax:
8. Other products included INGRES from relational Technology Sybase from Sybase, Column-name data-type (L);
Inc. (1986), DG/SQL from Data General Corporation (1984). or
Column-name data-type (L, D)
 DATA TYPES: Ex:
It specified which type data and size can be stored in a specific field or it specified the Sno decimal (3);
field size and type in a file. or
 Numeric: sno decimal (7,2);
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  Character
3. There are different types of data types The character data type is used to store character ( alphanumeric) data. This can
a. Number(L,D) be fixed length or variable length
b. Integer 1. Char(L)
c. Smallint 2. Varchar(L) or Varchar2(L)
d. Decimal(l,d)
a. Char(L)
a. Number(L,D): 1. Fixed-length character data fro up to 255 characters.
1. The declaration Number (7,2) indicates numbers
2. If you store strings that are not as long as the char parameter value
2. That will be stored with two decimal places and may be up to seven digits
long, 3. The remaining spaces are left unused.
4. Therefore, if you specify char (25), each stored as 25 characters

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 75 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 76


Syntax: 4. Data Control Language commands (DCL)
Column-name data-type (L);
Ex: Command Category
city char(18); CREATE
ALTER
b. Varchar (L) or Varchar2(L) DROP Data Definition Language (DDL)
RENAME
1. Variable-length character data TRUNCATE
2. The designation varchar2 (25) will let you store characters long. INSERT
3. However, varchar will not leave unused spaces. UPDATE Data Manipulation Language
4. Oracle automatically converts varchar to varchar2 DELETE (DML)
SELECT
Syntax: COMMIT
Column-name data-type (L); Transaction Control Language
ROLLBACK
Ex: (TCL)
SAVEPOINT
Sna varchar(25); GRANT
Data Control Language (DCL)
REVOKE
Syntax:
Column-name data-type (L);  DDL (DATA DEFINITION LANGUAGE) COMMANDS:
Ex: The set of commands are used to define a database including creating.
Sna varchar2(25); Altering, dropping and truncate the table command are
1. CREATE: To create a table
c. Date 2. ALTER: To the table structure
1. The Date data type is used to store date and time information. 3. DROP: To Delete a table
2. For each date value the information stored is, Century, Year, Month, Day, 4. TRUNCATE: To delete all the records.
Hour, Minute, Second
3. The default format of the date data type is ‘DD-MON-YY’.  CREATE TABLE STRUCTURE
4. The format can be changed with NLS_DATE_FORMAT command.
1. The CREATE TABLE command defines each column (Attribute) of the table
Syntax: uniquely
Column-name DATE 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.
Ex: date_of_birth date 4. Finally the SQL statement is terminated with a semi colon.

Long: Syntax: CREATE TABLE tablename


The variable length character data up to 4GB (column1 datatype constraint ,
column2 datatype constraint ,
BLOB: column3 datatype constraint );
BLOB means Binary Large Object. It store Binary data up to 4GB
SQL> create table student (sno int,sname varchar2(10),sadd
CLOB: varchar2(10));
Character Large Object. Single byte character up to 4GB
/* SQL> desc student;
Long raw: Name Null? Type
It uses raw binary data up to 2000 bytes ----------------------------------------- -------- ----------------------------
SNO NUMBER(38)
BFILE: SNAME VARCHAR2(10)
A BFILE can store up to 4GB of data. The BFILE data type stores unstructured SADD VARCHAR2(10) */
binary data in operating system files outside the database.
ALTER TABLE STRUCTURE

 Commands in SQL 1. To change (alter) table structure by changing attribute character and by adding
SQL commands can be classified in to different types: columns.
2. All changes in the table structure are made by using the ALTER TABLE command.
1. Data Definition Language commands (DDL) 3. ADD, MODIFY and DROP keywords
2. Data Manipulation Language commands (DML) 4. That produces the specific change user want to create
3. Transaction Control Language (TCL)

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 77 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 78

5. Use ADD to add a column, MODIFY to change column characteristics and DROP
to delete a column from a table SQL> alter table student modify(sname varchar2(15));
6. Most RDBMSs do not allow you to delete a column (unless the column does not
contain any value). Table altered.
7. The alter table command can also be used to add table constraints.
/* SQL> desc student;
Syntax: Name Null? Type
Alter table table-name ADD constraint [ADD constraint]; ----------------------------------------- -------- ----------------------------
SNO NUMBER(3,1)
 ADDING A COLUMN: SNAME VARCHAR2(15)
SADD VARCHAR2(10) */
Alter an existing table by adding one or more columns
 DROPPING A COLUMN: (REMOVE A COLUMN AND REMOVE TABLE)
Syntax:
Alter table table-name add (column name <data type> 1. User wants to delete a table column by using drop
(size)); 2. User also remove the table using drop command
3. Some RDBMSs impose restrictions on attribute deletion.
SQL> alter table student add(totalmarks number(3)); 4. The attribute that are involved in foreign key relationships not delete an
attribute of table that contains only that one attribute.
Table altered.
Syntax: Alter table-table-name drop column column-name;
/* SQL> desc student;
Name Null? Type Ex: SQL> alter table student drop column sadd;
----------------------------------------- -------- ----------------------------
SNO NUMBER(3,1) Syntax: drop table tablename;
SNAME VARCHAR2(15)
SADD VARCHAR2(10) Ex: SQL> drop table stu;
TOTALMARKS NUMBER(3) */
o RESTRICTION ON ALTER COMMAND:
 CHANGING (MODIFY) A COLUMNS DATA TYPE: The alter table command cannot perform the following
1. Change the name of the table
Some RDBMSs such as oracle, do not let you change data type unless the column 2. Change the name of the column
to be changed is empty. 3. Decrease the size of a column it table data exists.
Syntax: Alter table table-name add (column name <data type> (size));
 RENAMING TABLES:
SQL> alter table student modify(sno decimal(3,1)); Changing the table name from old to new name is called rename a table.

Table altered. Syn: Rename oldtablename to newtablenaem;

/* SQL> desc student; SQL> rename student to stu;


Name Null? Type
----------------------------------------- -------- ----------------------------  TRUNCATE:
SNO NUMBER (3, 1) Truncate command is used to delete to all the records permanently from the
SNAME VARCHAR2 (10) database.
SADD VARCHAR2 (10) */
Syn: Truncate table tablename;

Eg:SQL> truncate tale stu;


 DML (Data manipulation language): DATA MANIPULATION COMMANDS
 CHANGING (MODIFY) A COLUMN’S DATA CHARACTERISTICS
The basic SQL data manipulation commands
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 1. INSERT: To insert records into a table
the width of the column size. 2. UPDATE: To update records in a table.
3. SELECT: To display the all rows and columns
Syntax: Alter table table-name modify (column-name data-type (new 4. DELETE: Delete some or all the records in a table
size));

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 79 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 80


 INSERT (ADDING TABLE ROWS)
 DELETE ( DELETING TABLE ROWS )
SQL requires the use of the INSERT command to enter data into a table.
1. It is easy to delete a table row using DELETE statement.
Syn: INSERT INTO tablename VALUES( value1, value2, value3……);
Syntax:
SQL>insert into student values(2,'ram','gnt',300); DELETE FROM TABLE_NAME
WHERE CONDITION;
/* The preceding data entry lines: Ex:
SQL> delete from student where sno=2;
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 1. DELETE is a set-oriented command.
command sequence is also a parenthesis. 2. The WHERE condition is optional.
2. Character (String) and date value must be entered between apostrophes (‘). 3. Do not specify WHERE condition, all rows from the specified table will be
3. Numerical entries are not enclosed in apostrophes. deleted.
4. Attribute entries are separated by commas.
5. A value is required for each column in the table.  Transaction Control Language (TCL)
1. Transaction changes can be made (create) permanent to a database only if they are
This version of INSERT commands adds one table row at a time. */ committed.
2. A transaction executable statements and end explicitly with either rollback or
 INSERTING ROWS WITH OPTIONAL ATTRIBUTES commit statement and implicitly.
a. Commit  This is used for save the changes in database
1. The attributes that have required values, by listing the attribute names inside b. Rollback  This is used for do the undo operation
parentheses after the table name. c. Savepoint  Divide the lengthy transaction into small
transactions
Syntax: Insert into
tablename(cumnname,columname…..)values(value1,value2….);  COMMIT (SAVING TABLE CHANGES)

SQL> insert into student (sno,sname)values(9,'saran'); 1. Any changes made to the table contents are not saved on disk until user close
the database,
 UPPDATE (UPDATING TABLE ROWS) 2. To change the database to use the COMMIT command

1. The update command to modify data in a table. Syntax: COMMIT [WORK]; Ex: COMMIT;

Syntax: 1. The COMMIT command permanently saves all changes-


UPDATE TABLENAME 2. Such as rows added, attributes modified, and rows delete to any table in the
SET COLUMNNAME=EXPRESSION, COLUMNAME=EXPRESSION …, database.
WHERE CONDITION;
Ex:  ROLLBACK ( RESTORING TABLE CONTENTS )
SQL> UPDATE student SET totalmarks=499 WHERE sname='sam';
1. ROLLBACK command work like undo command.
1. UPDATE command has not include the WHERE condition, will apply the changes 2. The COMMIT command to store the changes permanently in the database.
to all rows in the specified table. 3. Restore the database to its previous condition with the ROLLBACK command.
4. To restore the data to their pre-change condition.

 SELECT ( LISTING TABLE ROWS) Syntax: ROLLBACK; Ex: ROLLBACK


 SAVE POINT:
1. The SELECT command is used to list the contents of a table. 1. Save point are like markers to divide a lengthy transaction to smaller
transactions.
Syntax: 2. Save points are used in conjunction (Combination) with rollback,
SELECT COLUMNLIST FROM Table name; or Select * from Table name; 3. To rollback portions of the current transaction.

The COLUMNLIST represents one or more attributes, separated by commas. Syntax: savepoint <savepointname>;
Ex:
SELECT ENO,ENAME FROM EMP; or SELECT * FROM EMP; Ex: savepoint s1;
/*Ex: SQL> insert into emp values(12,’manju’);
The * specifies that all columns appears in the EMP table. SQL>insert into emp values(13,’sai’);

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 81 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 82

SQL>savepoint s1; [Order by column list];


SQL> insert into emp values(14,’vani’);
SQL>insert into emp values(15,’anu’); Syntax:
SQL>savepoint s2;
SQL> insert into emp values(16,’rani’); Select column-name1, column-name2 ……… from table-name;
SQL>insert into emp values(17,’vasu’);
SQL>rollback to s2;*/ Ex:
1. In the above example we have to define two savepoint markers. Select sno, sname from std;
2. When rollback to s2 is given, whatever transactions happened after savepoint s2
will be undone. Syntax:
Select * from table-name;
 DCL(Data control Languge)
1. DCL commands are used to enforce (implemented) database security in a multiple Ex:
user database environment. Select * from ABC;
2. Two types of DCL commands
a. GRANT The above example shows all the columns from the student.
b. REVOKE.
3. Only Database Administrator's or owner's of the database object can  Selecting distinct rows:
provide/remove privileges (rights) on a database object.
1. To prevent (Check) the selection of duplicate rows, we include distinct clause in
 GRANT: the select command.
1. SQL GRANT is a command used to provide access or privileges on the database objects to 2. The following examples would eliminate duplicate values present in sname of the
the users. student table.

Syntax: Ex:
grant privilegesname on <object name> to <username> SQL> Select distinct sname from std;

 Priviliges name is all/select /execute  Select command with ‘where’ clause:


1. To select specific rows from a table we include a ‘where’ clause in the select
 Object name is table /view name command.
2. It can appear only after the ‘form’ clause.
 Username is name of the user 3. We can retrieve only the rows which specify ‘where’ condition.

Example: KUMAR: grant all on customers to BABA; Ex:


SQL>select *from std where sno=12;
To view the data
 Select with order by clause command:
Select * from username.objectname ; (select * from KUMAR.customers) 1. This clause is used to arrange rows in ascending or descending order.

 Revoke: SQL> Select * from std order by sname;


1. The REVOKE command removes user access rights or privileges to the database
objects. 1. The above query will display the ascending order, which is default option.
2. To display the rows in descending order
Syntax:
revoke privileges on <object name>from <username> SQL> select * from std order by sname desc;
 Group by Clause
Ex: revoke all on customers from BABA; 1. Group by clause can be used to divide the rows in a table into smaller groups.
 SELECTION: 2. Group function can be used to return summary information for each group.
1. To perform (create, display etc) a query we can the select command.
2. The query is a request for the information. Ex:
3. It is the most common database operation. Select job,avg (sal) from emp group by job;

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


select[distinct | * | column_name[aliase],………]
From <table_nmae>[where<condition> We can also use the group by clause to provide results for within groups.
[Group by column list ]
[Having<condition>] Ex:

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 83 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 84


To display average monthly salary bill for each type within a department 2. COUNT can be used in conjunction (combination) with the distinct clause.

Select deptno, job, avg(sal), from emp group by deptno,job; SQL> SELECT COUNT (EMPNO) FROM EMP;

Rows may be pre exclude with WHERE clause, before dividing them into groups. /* COUNT(EMPNO)
------------
Ex: 14 */
To show the average salary for each JOB excluding manager.
SQL> SELECT COUNT (*) FROM EMP WHERE SAL < =1500;
Select job, avg(sal) from emp where job!=’MANAGER’ group by job;
/* COUNT(*)
 Having Clause --------
1. It works like a where clause, except that its logic is only related to the results of 7 */
group functions as opposite (different) to columns or expressions for individual Count (*) returns the number of total rows returned by the query, including the
rows, which can still be selected with where clause. rows that contain nulls.

Ex: b. MAX:
Select deptno,sum(sal) from emp group by deptno having sum(sal)>1000; 1. The aggregate function Max (column) can be used only in the column list of a select
statement.
Select deptno,avg(sal) from emp group by deptno having coun(*)>3; 2. It returns a minimum value of a expression.

Select job, avg(sal) from emp where job!=’MANAGER’ group by job; SQL> SELECT MAX (SAL) FROM EMP;
Or
Select job,avg(sal) from emp having job!=’MANAGER’ group by job;
Or c. MIN:
Select job,avg(sal) from emp group by job having job!=”MANAGER’; 1. The aggregate function Min (column) can be used only in the column list of a select
statement.
 PROJECTION OPERATION 2. It returns min value of a given expression
1. The projection operation performs column wise filtering.
2. Specific columns are selected in projection operation. SQL> SELECT MIN (SAL) FROM EMP;
/*
Syntax: MIN(SAL)
--------
SELECT column-name1, column-name2, Column-name N FROM table-name; 800 */
d. SUM:
If all the columns of the table are selected, then it cannot be considered as PROJECTION. 1. The sum function computes the total sum fro any specified attribute, using whatever
condition.
1. The SQL command to perform PROJECTION operation on the relation PEAKS and
the corresponding results SQL> SELECT SUM (SAL) FROM EMP;
2. it is clear that only three columns are selected in the result.
e. AVG:
Ex: select sno,sname from std; The avg function format is similar to that of min and max. it returns an average
value of given column name
 GROUP FUNCTIONS: OR AGGREGATE FUNCTIONS:
1. These functions can be used for calculations on groups of selected records. SQL> SELECT AVG(SAL) FROM EMP
2. Group functions can appear in select lists, GROUP BY and/or HAVING clauses.
They are,  SINGLE ROW FUNCTIONS:

a. Count  The no. of rows containing non-null values 1. The single row functions can appear in a select command and can also be
b. Min  The minimum attribute value encountered in a given column included in where class.
c. Max  The mximum attribute value encountered in a given column 2. The single row functions classified as
d. Sum  The sum of all valued for given column a. Date ,
e. Avg  The arithmetic mean (average) from specified column b. Numeric
c. Character
a. COUNT: d. Mislenious
1. The count function is used to tally (count) the number of non-null values of an
attribute.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 85 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 86

3. The examples which are not based on a particular table use the system table SQL> Select abs(-12.3467) from dual ;
‘dual’.
4. It is a table which is automatically created by oracle along with the data /* ABS(-12.3467)
dictionary. -------------
5. DUAL is a table owned by SYS. 12.35 */
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 Power ( ): - It returns the power value to the base value.
column
8. It contains the value X in that column. SQL> Select power (3,4) from dual;
9. Besides arithmetic calculations, is also supports date retrieval and it’s
formatting. /* POWER(3,4)
----------
 DATE FUNCTIONS: - 81 */

They operate on date values producing O/P which also belongs to date, Trunc ( ): - It returns truncated values
Data type except for months between date function which returns a number.
SELECT TRUNC(12.3456,2) FROM DUAL;
1. Add – months: It returns a date data type as a result format add-months date,
number. /* TRUNC(12.3456,2)
----------------
Eg: - Select add_months ('27-Aug-04',2) from dual; 12.34 */

/* ADD_MONTH Round ( ): - It returns a number which is rounded upto some decimal points.
---------
27-OCT-04 */ SQL> SELECT ROUND (12.3456,2) FROM DUAL;

2. Months-between: /* ROUND(12.3456,2)
a. It returns a number date type as a result. Formate: - moths-between ----------------
date1, date2; 12.35*/

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


DUAL; Floor ( ): - It returns the previous value.

/* MONTHS_BETWEEN('27-AUG-85','06-OCT-83') SQL> SELECT FLOOR (68.78) FROM DUAL;


---------------------------------------
22.68 */ /* FLOOR(68.78)
------------
3. System date: It returns the system date; 68 */

Eg: - Ceil ( ): - It returns next value.


SQL> SELECT SYSDATE FROM DUAL;
SQL> SELECT CEIL (68.78) FROM DUAL;
/* SYSDATE
--------- /*
CEIL(68.78)
24-SEP-10*/ -----------
69 */
 CHARACTER FUNCTIONS: -
1. Characters functions accepts character input it returns either character value or
number some of these functions are

 NUMERIC FUNCTIONS: - initcap ( ): - It returns first letter as a capital letter of the string.
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. Eg: - Select initcap ('ram') from dual
3. Numeric functions are:
/* INI
Abs( ): - It returns absolute value ---
Ram */

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 87 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 88


----
Concat( ): - It combines two strings A */

SQL> Select concat('good', 'day') from dual;  MISLENIOUS FUNCTIONS:

/* CONCAT( Greatest ( ): - It returns the highest value


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

Upper ( ): - It convert all lower case letters into upper case. /* GREATEST(100,200,300)
---------------------
SQL> Select upper ('good') from dual; 300 */

/* UPPE Least ( ): - It returns least value;


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

Lower ( ): - It converts all the uppercase letters into lower case. /* LEAST(100,200)
--------------
SQL> SELECT LOWER ('RAM') FROM DUAL; 100 */

/* LOW User: - It returns user name;


---
Ram */ SQL> Select user from dual;

Lpad ( ): - It adds the string to the left side of the string1 /* USER
-----------
Eg: - Select Lpad (‘good’,12,’day’) from dual; SCOTT */

/* LPAD('GOOD', UID( ): - It return user ID which is stored in server.


------------
DAYDAYDAGOOD */ SQL> Select UID from dual;

Rpad ( ): - It add the string2 to the right side of the string1. /* UID
Eg: - Select Rpad (‘good’,12,’day’) from dual; ----------
66 */
/* 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 */

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

Eg: - select chr(65) from dual;

/* C

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 89 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 90

 EXPLAIN DIFFERENT TYPES OF CONSTRAINTS. 3. It is also used to set the relations between the tables.
1. Constraint is a rule that can be applied on a table or a column of a table. 4.
2. Constraints can also be used to prevent (check) mistakes in data entry. Syntax:
3. Constraints can be categorized into following, Create table <table name> (<column name> <data type>
constraint <constraint name> primary key);
1. Domain Integrity Constraints Ex:
a. Not null b. Check Create table student(sno number(10) constraint P primary key, sname
varchar2(10));
2. Entity Integrity Constraints.
a. Primary key b. Unique 3. Default constraint:
1. Its read automatically value when user not enter value
3. Referential Constraint
a. Foreign key Syntax:
Create table <table name> (<Column name> <data type>
 Domain Integrity constraints <Default> <value>)
1. Not Null: Ex:
1. By default all columns in a table allow NULL values. CREATE TABLE Persons (id number (3), name varchar2 (20) default
2. When a NOT NULL constraint is enforced on a column in a table, ‘abhyudaya’);
3. It will not allow NULL values into that column.  Referential Integrity Constraints
1. Foreign key Constraint
Syntax: 1. The referential integrity constraints enforce (impose) the relationship between the
Create table <table name> (<column name> <data type> tables
constraint <constraint name> NOT NULL); 2. Tables are used primary key
Example: 3. It helps in creating a parent child relation ships between the tables.
Create table tab (no number(3) constraint C NOT NULL); 4. A referential integrity constraint assigns a column as a foreign key.
5. Child table primary key is called foreign key
2. Check constraint
6. Parent table primary key is called referenced key is called parent table.
1. These are rules govern logical expressions or Boolean expressions.
Syntax:
Syntax:
Create table <table name> (<column name> <data type>,
Create table <table name> (<column name> <data type>
constraint <constraint name> references
constraint <constraint name> check
<table name> (column name));
(column name with condition));
Ex:
Example:
Create table emp1 (eno number(3) constraint P1 primary key,
ename varchar2(20));
Ex1: Create table stud (marks number (5) constraint c1 check (marks>35));
Create table dept (eno number(3), dname varchar2(20));
Ex2: alter table emp add constraint ck_emp check (sal + comm <10000);
Now connecting the dept and emp using foreign key
 Entity Integrity Constraints
1. Unique Constraint:
Create table dept1(eno number(3) references emp1(eno),
1. This constraint allows only unique values to be stored in the column.
dname varchar2(20));
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
 DELETING, ADDING A CONSTRAINT IN TABLES
it is duplicate.
1. The user can disable or remove or enable constraints attached to the column
with the help of alter command.
Syntax:
Create table <table name> (<column name> <data type>
Syntax:
constraint <constraint name> unique
Alter table <table name> disable|enable constraint <constraint name>;
(column name));
Ex:
Alter table <table name> modify (<column name> <data type>
Create table JDC (sno number(10) , sname varchar2(10), sphno number(15)
constraint <constraint name> <constrain type>);
unique);
Removing a Constraint:
1. To remove constraint attached to a column name alter with drop constraint
2. Primary key constraint:
is used.
1. It avoids duplication of rows and does not allow NULL values.
2. Primary key is the combination of NOT NULL and UNIQUE.
Syntax:

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 91 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 92


Alter table <table name> drop constraint <constraint name>; Ex:
SQL> select eno,ename from emp minus select sno, sname from std;

 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.  EXPLAIN JOINS.
3. The set operators are: 1. The purpose of join is to combine the data spread across the tables.
a. Union 2. There are basically three types.
b. Union all a. Simple join,
c. Intersect b. Self join,
d. Minus c. Outer join.
a. Union:
1. The union operator merges the output of two or more queries into a single set of  Simple Join:
rows and columns. 1. It retrieves rows from two tables having a common column and further
2. The following statement combines the results with the union operator, 2. It classified into
3. It eliminates duplicate selected rows. a. Equi join and
b. Non equi join.
Syntax:
Select query a. Equi Join:
Union A join which is based on equality is called an equi join.
Select query;
Ex: Ex:
1. SQL>select empno,ename from emp union select no, name from std;
2. SQL> select *from emp union select *from std; Select e. ename, e.job, d.deptno, d.dname, d.loc From emp e , dept d
Where e.deptno=d.deptno;

b. UNION ALL: /* To display employee name, job, department no, department name and
location in which the employees work. */
The UNION ALL operator written all rows selected by either query including
duplicates. b. Non Equi Join :
A non equi join specifies the relationship between column belonging to different
Syntax: tables.
Select query
Union all Ex:
Select query; Select ename,sal,losal,hisal,grade From emp,salgrade Where sal between losal
Ex: and hisal;

Select *from emp UNION ALL select *from std; /* To display the grades of the employees based on salary. */

c. Intersect:  Self Join (Recursive Join):


The intersect operator writtens only rows that are common to both the queries. 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.
Syntax:
Select query Ex:
intersect
select query; Select e1.ename,e1.sal from emp e1,emp e2 Where e1.sal>e2.sal and
e2.ename=’CLARK’;
Ex:
SQL> select eno,ename from emp intersect select sno,sname from std; /* To display all employees getting salary > clark.*/
Minus:
Minus operator writtens all distinct rows selected only by the first query and not by the  Outer Join:
second. 1. An outer join returns all the rows returned by simple join as well as those rows
from one table
Syntax: 2. That don’t match any row from the other table Using (+) operator.
Select query
Minus Ex:
Select query;

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 93 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 94

Select ename, job, dname from emp e, dept d Where d.deptno(+)=e.deptno ; b. less complexity,
c. better convenience, and
/*To which department name , job and location from department that does d. Customization.
not corresponding employees*/
1. Improved security:
 EXPLAIN VIEWS OR VIRTUAL TABLES a. We can restrict the user to access on the data that are appropriate for the
1. A view is a virtual table based on select query. user.
2. The query contain column, computed column and aggregated functions from one b. Hence views provide improved security.
or more tables.
3. The tables on which the view is based are called base tables. 2. Less complexity:
a. A view can simplify queries,
Syntax: b. By getting data from several tables into a single table
c. Transforming multi table queries into a single table queries.
Create view <view name> as select query;
3. Convenience:
Characteristics a. A database may contain much information.
1. You can use the name of view any where a table name is expected in SQL b. All the information will not be useful to the users.
statements. c. The users are provided with only the part of the database
2. Views are dynamically updated. i.e. the view is recreated on demand each time is d. That is relevant to them rather than the entire database;
invoked. e. Hence views provide great convenience to the users.
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. Customization:
4. View may also be used as the basis for reports. a. Views provide a method to customize the appearance of the database
5. It use little storage space. b. So that the users need not see full complexity of database.
6. It establishes physical data Independency. c. View creates the illusion of a simpler database customized to the needs of a
Disadvantages particular category of users.
1. Use processing time, each time the view is referenced.
2. It may or may not be directly updatable. Drawback of VIEW
1. If the base table is modified by adding one or more columns
Drop View command 2. Then the columns added will not be available in the view unless it is recreated.
To delete a view from the database we use the drop view command. 3. When a view is created from the base table, it is to be noted that all the views are
not updatable.
Syntax: 4. Views created from multiple tables are in general not updatable when there is a
group function, a GROUP BY clause, or restriction operators.
Drop view <view name>;
 Explain Sub queries and Correlated sub queries
Updatable Views
1. User can’t join tables in the update statement. SUBQUERY: (BASIC CHARACTERSTICS OF A SUB QUERY)
2. To solve that problem, users have to create update view. 1. A Sub query is a query inside a query.
3. An update view is a view that can be used to update attributes in the base table 2. A sub query is normally expressed inside parentheses.
that are used in the views. 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 .
Restrictions: 5. The inner query is executed first.
6. The outer query of an inner query is used as the input for the outer query.
1. Group by expressions of aggregate functions can not be used in the update views. 7. The entire SQL statements are sometimes referred to as a nested query.
2. User can’t use set operators.
3. Most restrictions are base on the use of joins or group operators in view. Sub queries are 2 types.
1. single row sub queries,
Materialized Views 2. multiple row sub queries
1. A materialized view is a physical copy of the base table
2. The results moved to another schema object. Single row sub queries
3. Materialized views are also called snapshots It returns only one row from the inner select statements.
4. Because they are a kind of photograph of the base table.
Multiple row sub queries
Advantage of VIEW It returns more then one row from the inner select statements.
1. The main advantages of view are
a. Improved security, Rules

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 95 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 96


1. Enclose sub queries in parentheses. SQL> Select sal*40 from emp
2. Place sub queries on the right side of the comparison condition where sal in (select sal from emp where sal>=50000);
3. The order by clause in the sub query is not needed unless you are performing top n /*
analysis. select ename ,sal*40 from emp 2
4. Single row comparison operators are >,<=,<>,>= where sal*40>
all(select sal*40 from emp where sal in
Ex: /* Who gain more than smith salary?*/ (select sal from emp where sal>=50000));
Ex:
Select ename from emp where sal > (select sal from emp where ename=’smith’); Find the employee who earn the same the salary as the min salary for each
departments.
Group functions in sub queries: (Where sub queries) Select ename , sal, deptno from emp
Where sal in(select min(sal)from emp group by deptno);
The most common type of sub query uses an inner SELECT subquery on the right
side of a WHERE comparison expression. To display employee who are clerk and whose salary is less than that of any clerk.
Select empno,ename,job,sal from emp
Ex: Where sal<any(select sal from emp where job=’clerk’); */
SQL> select ename,sal from emp where sal>=(select avg(sal) from emp);
Example of NOT EXISTS Operator
Having clause with sub queries: 1. In order to understand NOT EXISTS clause,
2. Ex: two relations EMPLOYEE and DEPENDENT.
A subquery with a HAVING clause , the HAVING clause is used to restrict the 3. Here DEPENDENT refers to those who are dependent on EMPLOYEE.
output of a GROUP BY query by applying a conditional criteria to the grouped 4. The attributes of EMPLOYEE relation are eid (employee ID), ename (employee
rows. name). The attributes of the DEPENDENT relation are name (which refers to
dependent name)
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


Where sal>=All
(Select sal from staff 5. and eid (employee ID).
Where deptna=’comp’);

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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 97 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 98

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.

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

Ex: A PL/SQL block can be divided into four sections. They are
Sql> select ename from emp 1. Declaration section
Where not exists (Select eid from dep 2. Begin section
Where dept.eid=emp.eid); 3. Exception section
Correlated sub query: 4. End section
1. The subquery , the inner subquery executes first,
2. Its output is used by the outer query, 1. Declaration Section:
3. Which then executes until the last outer query executes. 1. Code blocks start with a declaration section
4. A correlated subquery that executes once for each row in the outer query. 2. In this block memory variable and other oracle objects can be declared
Embedded SQL 3. They can be used in SQL statements for data manipulation.
SQL can be used in conjunction with a general purpose programming language such as
PASCAL, C, C++, etc. The programming language is called the host language. Embedded Example:
SQL statements are SQL statements written within application programming languages Declare
such as C and Java First_name varhcar2(10);
Dynamic SQL Num number(10);
Programs containing embedded dynamic SQL statements must be precompiled like those
containing static SQL, but unlike static SQL, the dynamic SQL statements are 2. Begin Section:
constructed and prepared at run time. The SQL statement text is prepared and executed 1. It consists of a set of SQL and PL/SQL statements
using either the PREPARE and EXECUTE statements, or the EXECUTE IMMEDIATE 2. It describes process that has to be applied to table data.
statement. The statement can also be executed with cursor operations if it is a SELECT 3. Actual data manipulation, retrieval, looping and branching constructs are
statement specified in this section.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 99 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 100


3. Exception Section: A. Delimiters
1. This section deals with handling of errors a. A delimiter is a simple or compound symbol
2. That arise during execution of the data manipulation statements b. That has a special meaning to PL/SQL.
3. The errors can arise due to syntax and logic. c. Simple symbol consists of one character
d. Compound symbol consists of more than one character.
4. End Section:
a. This makes the end of a PL/SQL block. B. Identifiers
a. Identifiers are used in the PL/SQL programs
Example: b. To name the PL/SQL program items
i. Like constants, variables, cursors, cursor variables, subprograms,
Declare etc.
a number(4); c. Identifiers can consists of alphabets, numerals, dollar signs,
b number(4); underscores, and number signs only.
c number(4); d. Any other characters like hyphens, slashes, blank spaces, etc.
begin
a:=10; C. Literals
b:=20; a. A literal is an explicitly defined character, string, numeric, or Boolean
c:=a+b; value,
dbms_output.put_line(c);
end; D. Comments
1. Comments are used in the PL/SQL program
/* 2. It used to improve the readability and understandability of a program.
1. dbms_ouput: it is a package. 3. A comment can appear anywhere in the program code.
2. That includes a number of procedures and functions that accumulate information 4. The compiler ignores comments.
in a buffer so that it can be retrieved later. 5. Generally, comments are used to describe the purpose and use of each
3. These functions can also be used to display message. code segment.
4. put_line: put a piece of information in the package buffer followed by an end-of-
line marker. Ex: /* Hello World! This is an example of multiline comments in PL/SQL */
5. dbms_ouput.put_line(‘Hello’);*/
 What are the data types available in PL/SQL?
 PL/SQL Language Elements
Data type Description
There are different elements
Char Character value of fixed length
1. Character Set
2. Lexical Units Varchar2 Variable length character value
a. Delimiters Number Numeric values
b. Identifiers
c. Literals Date Date values
d. Comments Inherits the data type from a variable that you declared
% type
previously in database table.
1. Character Set
1. A PL/SQL program consists of text having specific set of characters. It is used to declare variable to keep a single record, since a
% row
2. Character set may include the following characters: record is nothing but collection of column. This is also known as
type
a. Alphabets, both in upper case [A–Z] and lower case [a–z] composite data type.
b. Numeric digits [0–9] Boolean data type can be used to store the values true, false or
Boolean
c. Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % , __ # $ & | { } ? [ null.
]
d. Blank spaces, tabs, and carriage returns. Variable declaration
<variable name> data type [(size)] := &variable name;
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  Control Structures:
B. Identifiers The follow of control statements can be classified into the following categories.
C. Literals 1. Conditional control
D. Comments 2. Iterative control
3. Sequential control

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 101 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 102

1. Conditional control  If then else if statement


1. Conditional control, which run different statements for different data values. If condition is true it can execute statement 1. If the condition is false its
2. It check the condition for single time only even it is true or false again chek for another condition if it is true it can execute statement 2. Other
3. The conditional control statements are If and case. execute else statement or execute statement 3.
a. IF
i. If then statement Syntax:
ii. If then else statement if(condition) then
iii. If then else if statement Statement 1;
iv. Nested if statement elsif(condition) then
b. Case statement 2;
else
 If statement statement 3;
If condition is true it can execute statement 1 to statement n otherwise it end if;
cannot execute statement 1 to statement n.
Example:
Syntax: declare
if(condition) then a integer;
Statement 1; b integer;
…………… c integer;
Statement n; begin
End if; a:=&a;
b:=&b;
Example: c:=&c;
DECLARE if(a>b and a>c) then
a number:=&a; dbms_output.put_line(‘a is big’);
BEGIN elsif(b>c) then
if(a<10)then dbms_output.put_line(‘b is big’);
dbms_output.put_line(‘welcome to pl/sql’); else
end if; dbms_output.put_line(‘c is big’);
END; end if;
end;
 If then else statement
If condition is true it can execute statement 1. If the condition is false it  Nested if statement
execute else statement or execute statement 2. 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
Syntax: statement 1 other wise execute statement 2.
if(condition) then
Statement 1; Syntax:
else if(condition) then
statement 2; if(condition) then
end if; statement 1;
else
Example: statement 2;
declare end if;
a integer; else
b integer; statement 3;
begin end if;
a:=&a; /* it take run time values*/
b:=&b; /* it take run time values*/ Example:
if(a>b) then declare
dbms_output.put_line(‘A is big’); a integer;
else b integer;
dbms_output.put_line(‘b is big’); c integer;
begin
end if; a:=&a;
end; b:=&b;

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 103 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 104


c:=&c; Statement; Statement;
if(a>b) then Exit; Exit when(condition);
if(a>c) then end loop; end loop;
dbms_output.put_line(‘a is big’);
else Example: Exit
dbms_output.put_line(‘c is big’); Declare
endif; n number:=0;
elsif(b>c) begin
dbms_output.put_line(‘b is big’); loop
else n:=n+1;
dbms_output.put_line(‘c is big’); dbms_output.put_line(‘the value of n is’||n);
end if; if(n>=10) then
end; exit;
end if;
 Case: end loop;
Syntax: end;
case variablename
When value1 then stmt; 2. while loop:
When value2 then stmt; 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
Else stmt; close the while loop.
End case; Syntax:
1. The case statement runs the first statements for which value equals variable While(condition)
name remaining conditions are not evaluated. loop
2. If no value equals to variable name, the case statements runs else statements. Statement 1;
…………
Ex: Statement n;
declare end loop;
Grade char:=’&grade’; Example:
begin declare
case grade i number := 0;
when ‘A’ then dbms_output.put_line(‘Excellent’); begin
when ‘B’ then dbms_output.put_line(‘Very good’); while i<= 10
when ‘C’ then dbms_output.put_line(‘Good’); loop
when ‘D’ then dbms_output.put_line(‘Fair’); i:= i+ 1;
when ‘F’ then dbms_output.put_line(‘poor’); dbms_output.put_line('the value of i is ' || i);
else dbms_output.put_line(‘no such grade’); end loop;
end case; end;
end; 3. For loop:

2. Iterative control (or) Loop controls Syntax:


Iterative statements are check the condition if condition is true it execute the for variable in[reverse] start . . end
statements and again check the condition up to condition is false. There are different Loop
types of iterative statement. Statement 1;
…………
1. Simple loop Statement n;
2. While loop end loop;
3. For loop Example:
begin
1. Simple loop: for i in 1..10
The statements that exit a loop are loop
o Exit dbms_output.put_line('the value of i is ' || i);
o Exit when end loop;
end;
Syntax:
Exit: Exit when:  SEQUENTIAL CONTROL:
Loop Loop

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 105 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 106

1. Sequential control statements, which are not crucial (central or Main) to PL/SQL Cursor process commands open, fetch (get) and close any where between begin and
programming. end keywords of PL/SQL block.
2. The sequential control statements are
a. GOTO Command Explanation
It goes to a specified statement, and NULL, which does nothing.
1. Open the cursor, execute the SQL command and
Goto statement: populate the cursor with data.
1. The Oracle PL/SQL GOTO statement is a sequential control structure available in Open 2. Before you can use a cursor, you need to open it.
Oracle. Syntax:
2. The GOTO statement immediately transfers program control (called "branching") open <cursor name>;
using with label or block label. 1. The fetch command to retrieve data from the cursor
3. The statement or label name must be unique in the block. and copy it to the PL/SQL variables for processing.
Fetch
Syntax:
Syntax: fetch <cursor name> into <var list>;
<<Lable>> 1. The close command closes the cursor for processing.
Statement 1; Close Syntax:
………….. close <cursor name>;
Statement n;
if(condition) then Syntax:
Goto label; Declare
end if; Cursor <cursorname> is <select statement>;
Ex: Variable declaration;
declare Begin
n integer:=&n; Open <cursorname>
i integer:=1; Fetch <cursorname> into variablename1…..;
begin close <cursorname>;
<<p>> End;
dbms_output.put_line(i);
i:=i+1;  Cursor Attributes
if(i<=n) then
goto p; Attribute Description
end if;
Keeps the count of record for each fetch when the cursor is
end; %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
 Explain processing with cursors in PL/SQL. otherwise FALSE.
1. PL/SQL provides to access more than one record from database Returns TRUE if cursor is open otherwise FALSE if the cursor
%isopen
2. This method is a combination of select statement and memory management is closed.
routines from PL/SQL
3. To retrieve records from database using select statement and places them with in Example:
memory known as cursor. Declare
a emp%rowtype;
There are two types of cursors. cursor c2 is select * from emp where deptno=&deptno;
begin
 Implicit Cursor – open c2;
1. It is automatically created in PL/SQL when the SQL statement returns only loop
one value. fetch c2 into a;
if c2%found then
 Explicit Cursor – dbms_output.put_line(a.empno||’ ‘||a.ename||’
1. It is created to hold the output of an SQL statement that may return two or ‘||a.sal);
more rows. else
exit;
Syntax: end if;
Cursor <cursor name> is select query; end loop;
close c2;

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 107 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 108


end; AS
BEGIN
 Explain PL/SQL Stored functions. or dbms_output.put_line('Hello World!');
 Stored procedures or END;
 Routines or /
 sub programs:
Procedure created.
Subprograms
1. Subprogram is a program unit/module Execute:
2. That performs a particular task. It also called block.
3. These subprograms are combined to form larger programs. When above code is executed using SQL prompt, it will produce the following
4. This is basically called the 'Modular design'. A result:
5. Subprogram can be invoked by another subprogram or program which is called
the calling program EXECUTE greetings; or CALL greetings();
6. Subprograms can be created at the schema level, inside the package, and inside
block Hello World
7. They are two types of sub programs
PL/SQL procedure successfully completed.
1. Procedures
2. Functions Or
You might call the procedure in a PL/SQL Block.
Parameter Modes in PL/SQL Subprograms BEGIN
greetings;
User create a Procedure or function, you have to define this three parameters. END;
Hello World
1. In PL/SQL procedure successfully completed.
2. Out
3. In out 2. Functions
1. These subprograms return a single value, mainly used to compute and return a
1. IN value.
a. IN parameter is referenced to the procedure or function. 2. A PL/SQL function is same as a procedure except that it returns a value.
b. Input parameter only, the value passed is input only.
c. And value of parameter in not overwritten Syntax:
CREATE OR REPLACE
2. OUT FUNCTION function_name (function_params) RETURN return_type IS
a. OUT parameter is referenced to the procedure or function. BEGIN
b. Output only. function_body
c. And value of parameter is overwritten allow. RETURN something_of_return_type;
END;
3. IN OUT
a. IN OUT parameter is referenced to the procedure or function. Ex1:
b. Both input and output. CREATE OR REPLACE FUNCTION ADD_TWO (A INT,B INT) RETURN INT IS
c. And value of parameter is both overwritten allow or not allow.
BEGIN
1. Procedures RETURN (A + B);
These subprograms do not return a value directly, mainly used to perform END;
an action. Calling function:
BEGIN
Syntax: DBMS_OUTPUT.PUT_LINE(’RESULT IS: ’ || ADD_TWO(12,34));
CREATE [OR REPLACE] PROCEDURE procedure_name (procedure parameters) END;
{IS | AS} /
BEGIN RESULT IS: 46
< procedure_body >
END;  Benefits of Procedures and Functions
Stored procedures and functions have many benefits and addition to part application
Example: development.
CREATE OR REPLACE PROCEDURE greetings 1. It modifies one routine to affect multiple applications.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 109 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 110

2. It modifies one routine to eliminate duplicate testing. 9. The package specification does not contain any procedures or functions.
3. It avoids PL/SQL parsing at runtime by parsing at compile time. 10.Applications or users can call packaged procedures and functions
4. It reduces the number of calls to the database
5. Database network traffic by bundling (collecting) the commands Advantages of Packages
6. User-defined functions cannot be used in situations Packages offer a lot of advantages. They are as follows.
7. That requires an unchanging definition. 1. User can create package to store all related functions and procedures are grouped
8. Thus, you cannot use user-defined functions: together into single unit called packages.
a. In a CHECK constraint clause of 2. Package is reused.
a CREATE TABLE or ALTER TABLE statement 3. All function and procedure within a package can share variable among them
b. In a DEFAULT clause of a CREATE TABLE or ALTER TABLE statement 4. Packages are support overloading to overload functions and procedures.
5. Package are improve the performance to loading the multiple object into memory at
 Difference Between Function and Procedure once, therefore, subsequent calls to related program doesn't required to calling
Function: physically I/O.
1. Functions must always return a value. 6. Packages are reduced the traffic because all block execute all at once.
2. Functions cannot alter data or objects in a server. 7. Packages enable the organization of commercial applications into efficient modules.
3. You can embed functions within a SELECT statement. 8. Each package is easily understood
4. Functions can accept input parameters but can return only a single return 9. Packages interfaces between packages are simple, clear and well defined.
value. 10.Packages allow granting of privileges efficiently.
5. TEMP tables can’t be used in functions. 11.Packages promote code reuse through the use of libraries
6. user-defined functions cannot be used in CHECK or DEFAULT constraints 12.That contain stored procedures and functions, thereby reducing redundant coding .
7. and cannot manipulate database values 13.Each package is easy to understand, and the interfaces between packages are simple,
8. It is mandatory for a function to have at least one RETURN statement clear, and well defined.
9. It will not allow to do the DML on existing tables. But still we can do the DML 14.Easier Application Design it stored programs and subprograms
operation only on the table variable inside the user defined functions. 15.Packages can specify which types, items, and subprograms are public (visible and
10.The transaction statement cannot be used in the function. Normally we won't accessible) or private (hidden and inaccessible).
do any DML operations in the function. 16.For example, if a package contains four subprograms, three might be public and one
11.The parameters for the stored procedures can be any data types which are private.
available on the sql server. 17.The package hides the implementation of the private subprogram so that only the
package (not your application) is affected if the implementation changes.
18.They can be shared by all subprograms that execute in the environment.
Procedures: 19.To maintain data across transactions without having to store it in the database.
1. Stored procedures do not have this requirement. 20.User call a packaged subprogram for the first time, the whole package is loaded into
2. Stored procedures can alter data and objects in database and server. memory.
3. Stored procedures cannot be embedded within a SELECT statement. 21.To related subprograms in the package require no disk I/O.
4. Stored procedures can also accept OUTPUT parameters. 22.Packages stop cascading dependencies and thereby avoid unnecessary recompiling.
5. Both TEMP tables and Table variables can be used in stored procedures. 23.Change the implementation of a packaged function
6. It is not mandatory for a procedures to have at least one RETURN statement
7. In case of procedures with RETURN statement, simply the control of execution Units of Packages
is transferred back to the portion of code that called the procedure.
8. The stored procedures can do all the DML operations like insert the new record, As described earlier, a package is used to store together, the logically related PL/SQL
update the records and delete the existing records. units.
9. The transaction statement can be used inside the stored procedures. 1. Procedures
10.The function won't allow several data types of the sql server as a parameter. 2. Functions
3. Triggers
 Explain Packages 4. Cursors
1. A package can be defined as a collection of related program objects. 5. Variables
2. Such as procedures, functions, and associated cursors and variables together as a
unit in the database. Parts of Package
3. A package is a group of related procedures and functions A Package has two parts. They are:
4. It stored together and sharing common variables, as well as local procedures and 1. Package specification
functions. 2. Package body
5. A package contains two separate parts:
a. The package specification and 1. Package Specification
b. The package body. 1. The specification declares the types, variables, constants, exceptions, cursors,
6. The package specification and package body are compiled separately and subprograms
7. And stored in the data dictionary as two separate objects. 2. These are public and thus available for use outside the package.
8. The package body is optional and need not to be created

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 111 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 112


3. In case in the package specification declaration there is only types, constants, A trigger is an action which can be performed automatically whenever the data
exception, or variables, manipulations are applied on the table
4. Then there is no need for the package body because package specification are or
sufficient for them. 1. A database trigger is a stored procedure
5. Package body is required when there is subprograms like cursors, functions, 2. That is fired when an insert, update or delete statement is issued against the associated
etc. table.

2. Package Body Syntax:


1. The package body fully defines subprograms such as cursors, functions, and
procedures. CREATE [OR REPLACE] TRIGGER trigger-name
2. All the private declarations of the package are included in the package body.
3. It implements the package specification. BEFORE (OR AFTER)
4. A package specification and the package body are stored separately in the
database. INSERT OR UPDATE OR DELETE [OF COLUMNS]
5. This allows calling objects to depend on the specification only, not on both.
6. Oracle invalidates the calling object if the package specification is changed. ON tablename

Creating a Package [FOR EACH ROW [WHEN (condition)]]


1. A package consists of package specification and package body.
2. Creation of a package involves creation of the package specification and then BEGIN
creation of the package body.
3. The package specification is declared using the CREATE PACKAGE command. Trigger action;

Syntax: END;
CREATE [OR REPLACE] PACKAGE <package name>
[AS/IS]

PL/SQL package specification  Types of PL/SQL Triggers


There are two types of triggers based on the which level it is triggered.
1. All the procedures, sub programs, cursors declared in the CREATE PACKAGE 1. Row level trigger –
command a. An event is triggered for each row upated, inserted or deleted.
2. They are described and implemented fully in the package body along with
private members. 2. Statement level trigger –
a. An event is triggered for each sql statement executed.
Syntax:
In trigger two types of pseudo (artificial) (fake) column are available they are
CREATE [OR REPLACE] PACKAGE BODY <package name> On the Basis of Type of Trigger/Firing or Triggering Transaction
[AS/IS]
– BEFORE Triggers
PL/SQL package body
– AFTER Triggers
Referencing Package Subprograms
– INSTEAD OF
<PACKAGE NAME>.<VARIABLE NAME>
BEFORE Triggers
To reference procedures we have to use the syntax as follows: 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
EXECUTE <package name>.<procedure name(variables)>;
statement or to determine whether the triggering statement should be allowed to
Removing a Package complete.
A package can be dropped from the database just like any other table or database
object. The exact syntax of the command to be used for dropping a package is: Example

DROP PACKAGE <PACKAGE NAME>; 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
 Triggers: will not allow any deletion on the table.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 113 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 114

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

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.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 115 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 116


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

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.

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 117 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 118

If tday=’mon’ then

Raise_application_error(-20001,’no transaction on maonday’);

Triggers on DDL Statements End if;

This trigger gets fired when DDL statement such as CREATE, ALTER, or End;

DROP command is issued. DDL triggers can be associated with the database or with a Example 3
schema. Moreover depending on the time of firing of trigger, this trigger can be classified
into BEFORE and AFTER. Hence the triggers on Create or replace trigger strig

DDL statements can be as follows: Before update on emp for each row

– BEFORE CREATE and AFTER CREATE triggers fire when a schema Begin

object is created in the database or schema. If :old.sal>=10000 then

– BEFORE ALTER and AFTER ALTER triggers fire when a schema object Raise_application_error(-20001,’salary not > 10000 update’);

is altered in the database or schema. End if;

– BEFORE DROP and AFTER DROP triggers fire when a schema object End;

is dropped from the database or schema. Example 4:

Example 1 Create or replace trigger tr4

Create or replace trigger abc before insert on dept for each row Before delete on emp for each row

Declare Begin

Sdate varchar2(3); Insert into etemp(empno,ename) values(:old.empno,:old.ename);

Begin Dbms_output.putline(‘backup copied to etemp table’);

Sdate:=to_char(sysdate,’dy’); End;

If sdate in (‘sat’,’sun’) then

Raise_application_error(-2003,’This is weakend’); Triggers on DML Statements

End if;

End; This trigger gets fired when DML statement such as INSERT, UPDATE, or

Example 2: 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
Create or replace trigger etrig BEFORE and AFTER.

Before insert or update or delete on emp

Declare Row Level Triggers

Tday varchar2(10);

Begin A row level trigger, as its name suggests, is fired for each row that will be

Tday:=to_char(sysdate,’dy’); 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

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 119 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 120


UPDATE on that particular table will be fired once for each of those “N” affected rows. If 3. Meaningful messages can be flagged so that the developer can become aware
a triggering SQL statement affects no rows, a row trigger is not executed at all. To (alert) of error and warning conditions and act upon them.
specify a trigger of row type, FOR EACH ROW clause is used after the name of table. 4. In traditional error checking system, if same error is to be checked at several
places
Statement Level Triggers 5. User required a code the same error check at all those places.
6. We will write the exception for that particular error only once in the entire code.
Unlike row level trigger, a statement level trigger is fired only once on behalf of the 7. That type error occurs at any place in code, the exceptional handler will
triggering SQL statement, regardless of the number of rows in the table that the automatically raise the defined exception.
triggering statement affects. Even if the triggering statement affects no rows, the 8. Being a part of PL/SQL, exceptions can be coded at suitable places and can be
coded isolated (remote) like procedures and functions.
statement level trigger will execute exactly once. For example, if a DELETE statement
9. This improves the overall readability of a PL/SQL program.
deletes several rows from a table, a statement-level DELETE trigger is fired only once, 10.Oracle’s internal exception mechanism combined with user-defined exceptions
regardless of how many rows are deleted from the table. 11.It reduce the development efforts required for cumbersome (weightily) error
handling.
INSTEAD-OF Triggers 12.These two types of exceptions.
1. Pre-defined Exceptions
INSTEAD-OF triggers are used to tell Oracle what to do instead of performing the actions 2. User Defined Exceptions
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 1. Pre-defined Exceptions (Internally)
update different tables that are the part of the view. This trigger is used to perform any 1. It is also called internally
action instead of the action that executes the trigger. 2. PL/SQL provides many pre-defined exceptions
3. Which are executed when any database rule is violated by a program
Enabling and Disabling a Trigger 4. For example, the predefined exception NO_DATA_FOUND is raised when a
SELECT INTO statement returns no rows.
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 2. User Defined Exceptions
even when the triggering statement is issued 1. User-defined exceptions must be declared and raised explicitly by RAISE
statements.
Syntax 2. Exceptions can be declared only in the declarative part of a PL/SQL block,
subprogram, or package.
ALTER TRIGGER <Trigger name> ENABLE/DISABLE; 3. An exception is declared by introducing its name, followed by the keyword
EXCEPTION
Dropping Triggers
Syntax
Triggers can be dropped like tables using the drop trigger command. The drop trigger DECLARE
command removes the trigger structure from the database <exception name>EXCEPTION;

Syntax Raising User-Defined and Internal Exceptions


1. Internally defined exceptions which are automatically raised by “OracleS” run time
DROP TRIGGER <trigger name> engine
2. User-defined exceptions have to be raised explicitly by using RAISE statement.
RAISE <exception name>;

User-Defined Error Reporting – Use of Raise Application Error


1. RAISE APPLICATION ERROR lets display the messages we want whenever a
 Explain Exceptions Handling standard internal error occurs.
1. An exception is an error condition during a program execution. 2. RAISE APPILCATION ERROR associates an Oracle Standard Error Number with
2. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the message we define.
the program Syntax
3. And an appropriate action is taken against the error condition. RAISE APPLICATION ERROR (Oracle Error Number, Error Message,
4. There are two types of exceptions TRUE/FALSE);
 System-defined exceptions 1. Any database error the database server automatically Exceptions are raised
 User-defined exceptions 2. But exceptions can be raised explicitly by the programmer by using the command
RAISE.
Advantages of Using Exceptions
1. When executing programs on encountering error conditions DECLARE
2. The behavior of application becomes more reliable. c_id customers.id%type := 8;

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 121 P.y.kumar M.C.A,M.Tech,M.Phil.., Page 122

c_name customerS.No.ame%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO cname, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

P.y.kumar M.C.A,M.Tech,M.Phil.., Page 123

You might also like