0% found this document useful (0 votes)
12 views50 pages

Bca Dbms Short Notes

The document provides a comprehensive overview of Database Management Systems (DBMS), covering topics such as the definition, advantages, disadvantages, and various data models. It includes detailed explanations of the Entity-Relationship Model, Relational Model, Structured Query Language (SQL), and PL/SQL, along with their functionalities and applications. Additionally, it discusses the evolution of DBMS, the classification of databases, and the risks and costs associated with the database approach.

Uploaded by

maxpayne.130604
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)
12 views50 pages

Bca Dbms Short Notes

The document provides a comprehensive overview of Database Management Systems (DBMS), covering topics such as the definition, advantages, disadvantages, and various data models. It includes detailed explanations of the Entity-Relationship Model, Relational Model, Structured Query Language (SQL), and PL/SQL, along with their functionalities and applications. Additionally, it discusses the evolution of DBMS, the classification of databases, and the risks and costs associated with the database approach.

Uploaded by

maxpayne.130604
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/ 50

II BSC DATABASE MANAGEMENT SYSTEM

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


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

1. What is DBMS and Write about its advantages(OR)objectives and disadvantagesof DBMS?
Ans:
Data
Data
ata is collection of raw facts like numbers
numbers, names and marks. The processed data is called information like
total and average.
Database
The database is a collection of inter-related
related data which is used to retrieve,
retrieve insert and delete the data
efficiently. It is also used to organize the data in the form of a table
table, schema, views, and reports, etc.

DBMS:
o Database management system is a software which is used to manage the database.
database For example: MySQL,
Oracle, etc are a very popular commercial database which is used in different applications
applications.
o DBMS provides an interface to perform various operations like database creation,
creation, storing data in it,
updating data, creating a table in the database and a lot more.
DBMS refers to organized collection of data or programmes. there are four basic functionsperformed by
DBMS. they are: a. create, modify and deletion of tables
b. insert, modifyand deletion of data within a table
c. retrieval of data based on user request
d. generating reports based on data and user requirements
Advantages of DBMS/ objectives of DBMS

1. Improved data sharing: DBMS allows to access the data by different users at a time. so, anytable in the
data base can possible to access the data simultaneously for end users.
2. Data integration: DBMS supports data integration. It represents overall data is located in asingle data
base i.e., it combines the data from different locations.
3. Multiple access: In DBMS, each user can use any application and to operate the data base. DBMS
support multiple accesses.
4. Backup and recovery: DBMS supports backup and recovery facility it can be useful if there is a
problem in the database in case of failure. DBMS supports recovery algorithms. It recovers the data from the
crashed database.
5. Data security: DBMS provides a framework for data privacy each user has a username and password.
So, with the help of username and password functionality, the security can be provided.
6. Concurrent access: DBMS supports various locks for processing the data in a serializable way. So, it
can support concurrent execution for database operation.
7. Efficient access: DBMS strongly provides efficient access because it retrieval of data including large
files in query format.
8. Reduced redundancy: redundancy means the same data and information in different locations. So,
unnecessary to store the extra copies of data. DBMS does not support redundancy so, no data is repeated.
9. Inconsistency: In DBMS, inconsistency is avoided all required data is stored insame location. i.e., no
data is duplicated and changes are made at one location.
10. Mass storage: DBMS can store a lot of data.
11. Platform independent: No particular platform is required to work on DBMS.

Disadvantages of DBMS
o Cost of Hardware and Software: It requires a high speed of data processor and largememory size to
run DBMS software.
o Size: It occupies a large space of disks and large memory to run them efficiently.
o Complexity: Database system creates additional complexity and requirements.
o Higher impact of failure: Failure is highly impacted the database because in most of the organization, all
the data stored in a single database and if the database is damaged due to electric failure or database
corruption then the data may be lost forever.
2. Define file system? Write about drawbacks of file system?
Ans : It is a mechanism of organizing the data in a file by writing programs is called file system. The
purpose of file is used to store the data permanently.
In general, the file containing collection of records. Each record contain collection of fieldsand each field
can store the data. In the file system, the data is stored in different files on the hard disk. so, these files are
not possible to share the data by different users. this type of mechanism is good at that time. But now a days
it is not possible.
Advantages:
1. The file system design is easier to understand.
2. In the file system avoid some problems in DBMS software.
Disadvantages or drawbacks:
The drawbacks of file system is represented as follows
1. No data sharing: The file system does not support data sharing so, we must duplicate every fileto
different users.
2. No data integrity: In the file system, the data files are stored in different location around the disk. So it
is difficult to maintain data files.
3. No data security: In the file system, does not support any security. It cannot controlunauthorized user to
access the data.
4. Increased Redundancy: Redundancy is major problem that occupies more space in disk. Itis maintain
multiple copies of the data.
5. No multiple access: In the file system, it is possible to access the data only one user at a time. Itallows
only a particular program to operate the database.
6. No concurrent access: The file system does not support concurrent access. Because it does notsupport
data sharing.
7. No backup and recovery: in the file system there is any standard method to backup the data.

The copy command is used to copy the required files. It does not contain any predefinedalgorithms for
recover the data.
8. No data models: The file system does not have any data model the records are stored in thedata file
according to the file format.
For example the file system is represented as follows

3. Difference between Data and Information

DATA INFORMATION
1. Data is collection of raw facts. 1. Information is processed data.
2. It is unarranged and unorganized. 2. It is arranged and organized.
3. It is un meaningful 3. It is meaningful.
4.Data is input. 4. Information is output.
5. It represents facts beforeprocessing. 5. It represents results.
6. It is not helpful in decision making. 6. It is helpful in decision making.
7. Data is large amount. 7. Information is small.
8. Data is unprocessed records. 8. Information is processed records.
9. If data is lost, it is very difficult. 9. If information is lost it is easily derived from
10. It is usedless frequently. data.
Ex: -In a student database marks arerepresented 10. It is used frequently
as data. Ex: -In a student database total, average are
represented as information.
4. what is database?
Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. lets discuss few examples.
An online telephone directory would definitely use database to store data pertaining topeople, phone
numbers, other contact details, etc.

5. Write about Evolution of DBMS?


Early 1960s.
1. Charles Bachman created the first general purpose DBMS Integrated Data Store.
2. It created the basis for the network model .
Late 1960s:
1. IBM developed the Information Management System (IMS).
2. IMS used an alternate model, called the Hierarchical Data Model.
In 1970:
1. Edgar Codd, from IBM created the Relational Data Model.
In 1981:
1. Codd received the Turing Award for his contributions to database theory.
2. Codd Passed away in April 2003.
In 1976:
1. Peter Chen presented Entity-Relationship model, which is widely used in databasedesign.
IN 1980:
1. SQL developed by IBM, became the standard query language for databases. SQLwasstandardized by ISO.
In 1980s and 1990s:
1. IBM, Oracle, Informix and others developed powerful DBMS.
6. Explain classification of DBMS?

DBMS stands for Data Base Management system. It is used to store the data in the form oftables. It stores
thedata in organized manner.

7. Classification Of DBMS:

The classification of DBMS can be divided into 3 types based onfunctionality they are:
1. It is based on data model. 2. It is based on users.
3. It is based on database distribution.
1. Based on datamodel: In this functionality, the database is designed on based on datamodel. It is easy
to understand the meaning of thedata. There are different types of data models for support the
database. for examplethey are:
 Hierarchical data model
 Network data model
 Relational data model
 ER data model
 Object oriented data model
2. Based on users: In this functionality, the database can be designed based on users. In generally it
can be dividedinto 2types. They are:
 Single user database
 Multi user database
 Single user database: In this functionality, the database operations can beperformed only one user at a
time. It is called as single user database.
 Multiuser database: In this functionality, the database operations can be performedmore than oneuser
at a time. It is called as multiuser database.
3. Based on distribution: In this functionality, it can be divided into 4 types they are:
 Centralized database
 Distributed database
 Homogenious database
 Hetrogenious database
 Centralised database: In this functionality, the database is gathered at one system from differentsystems in
a network. It is called as centralised database.
 Distributed database: In this functionality, the database is stored at different systems in anetwork. so, it
can be distributed. It is called as distributed database.
 Homogenious Database: In this functionality, the same type of database is stored in a System. It is called
as Homogenious database.
 Hetrogeneous database: In this functionality, different types of database is stored in aSystem. It is called as
heterogeneous database.
7. Explain DBMS Approach?Advantages and cost and risks of database approach?
An information system that uses a Database Management System (DBMS) to manage its information
has a particular structure, comprising three components: Data, DBMS, and Application software. This
structure as described below is referred to as the database approach to information system development.
The central component of the database approach is the DBMS. This software is also referred to as the
“database engine” or the “back end. ” With regard to the data it manages, it has several responsibilities
including the following:
Data Definition: providing a way to define and build the database
Data Manipulation: providing a way to insert and update data in the database
Query Execution: retrieving information from the data in the database
Data Integrity: ensuring that data stored is well-formed
Data Security: enforcing restrictions about who is able to access what data Provenance: logging
capabilities to provide an audit trail for data changes Multiuser Concurrency: supporting the activities of
many users at the same time

Advantages:
 Ease of application development
 Reduced data redundancy
 Data can be shared
 Data security
 Backup and recovery
 Multiple access
 Data integrity
Disadvantages
Cost of Hardware and Software: It requires a high speed of data processor and largememory size to run
DBMS software.
Size: It occupies a large space of disks and large memory to run them efficiently.
Risks of the database approach
 New specialised personnel: Need to hire or train new personnel e. g. databaseadministrators and
application programmers.
 Need for explicit backup.
 Organisational conflict: Different departments have different information needs and data representation.
 Large size: Often needs alarmingly large amounts of processing power.
 Expensive: Software and hardware expenses.
 High impact of failure

8. Explain various Data Models?

1. A Data Model is a relatively simple representation, usually graphical, of more complex real-world data
structures.
2. The Data Model gives a clear view of database structure included in Databasedesign. Based on the
relationships the data models can be classified as below.
1. Hierarchical Data Model
2. Network Data Model
3. Relational Data Model
4. Object-Oriented Data Model
5. Entity Relational Data Model

1. Hierarchical Data Model: It is an oldest data model. In this model, the files arearranged in a
topdown approach. It represents a tree structured data model.
It contain level or segments. In this functionality, the top file is called as root node, thebottom filesare
called as child nodes and intermediate files are called as parent files. so, it is a parent-child relationship. It
support one-to-many relationship.
Advantages:
 Easy to add and delete records.
 It is simple to operate the records.
 It supports data sharing.
 Data can be retrieved easily due to the explicit links present between the table structures.
Disadvantages
o This model could not support many-to-many and many-to-one associations.
o There is no DDL and DML in DBMS.
o Poor flexibility

2. Network Data Model: It is represented in the form of graph. It contain set of points and
associations betweenthe files. It can support types of data structures. They are.
1. record type2. set type
The network database model is a model for modeling the entities in such a way that one child entity can
have more than one parent entity. In 1969, the network model was presented by Charles Bachman.
Advantages:
 It is very efficient to retrieve the data.
 It is simple and easy to design.
 It can support one-to-many and many-to-many relationship.
 Many parents can have many children.
 Many children can have many parent
 It support data integrity.
 It has DDL and DML functionality.
Disadvantages:
 It requires complex implementation.
 Insertion, updating and deletion operations more complex in this model.

we can see that the subject is the child class and student and degree are the parentclasses.
So, the subject has two parent classes. STUDENT has one child and the Degree classalso have one child.
This kind of relationship among entities represents the network model.
3. Relational Data Model: It was introduced by ‘EF codd’, in the year 1970’s. Inthis model, the data is
represented in the form of tables. The table containcollection of rows and columns.
Each row is represented as record or tuple. Each column is representedas attribute or field. It is a2-
dimensional object.
So, in this model, the data is collected in the form of tables. These tables areimplemented using keys
likeprimary key, foreign key and so on.
Advantages:
 Relational data model is simpler than hierarchical and network datamodels.
 Changes in the structure do not affect the data access.
 Easy to design.
 Easy to implementation.
 It support query feature.
Disadvantages:
 Hrdware and software problems.
 It may suffer information.

Attribute: Each column in a Table. Attributes are the properties.


Tuple – It is nothing but a single row of a table, which contains a single record.
Relation Schema: A relation schema represents the name of the relation with itsattributes.
Degree: The total number of attributes which in the relation is called the degree ofthe relation.
Cardinality: Total number of rows present in the Table.
Column: The column represents the set of values for a specific attribute.
4. Object-Oriented Data Model: In this model, both data and their relationship are combined into
single structure. It is called as an object. so, the database is organized in the form of objects. It can perform
operations like insert, delete, modify and so on.
To represent the complex real world problems there was a need for a data model that is closely
related to real world. Object Oriented Data Model represents the real world problems easily.
In Object Oriented Data Model, data and their relationships are contained in a single structure which
is referred as object in this data model. In this, real world problems are represented as objects with
different attributes. All objects have multiple relationships between them.

Advantages of Object Oriented Data Model :


 Codes can be reused due to inheritance.
 Easily understandable.
 Cost of maintenance can reduced due to reusability of attributes and functionsbecause of inheritance.

Disadvantages of Object Oriented Data Model :


 It is not properly developed so not accepted by users easily.

5. Entity Relationship Data Model: ER stands for Entity Relationship. It is a highlevel datamodel. It was
developed by ‘chen’ in 1976. It is used to represent entities, attributes, Relationships and constraints in
symbolic form. Entity is anything in which the data to be collected.
Advantages:
 It is easy to view the database.
 It contain entities and relationships.
 Database designers, programmers and end user are easily understand thegraphical representation.
representation
Disadvantages:
 It is a limited Relationship representation
representation.
 It is a limited constraint representation.
 It cannot support DML functionality.

For, example ER data model is represented as

9. Explain components and interfaces of DBMS?


DBMS stands for Data Base Management system. It is used to store the data in theform of tables. It stores
the datain organized manner.
Components of DBMS
1. Data 2. Procedures3. Hardware 4. Software 5. users

1. Data:
The word ‘Data’ covers the collection of facts stored in the database data are the rawmaterialfrom which
information is generated.
2. Procedures
Procedures are the instructions and rules that govern the design and use of the databasesystem.
3. Hardware:
Hardware refers to all the system’s physical devices. The database system’smain and most
easily identified hardware component is the computer.
4. Software:
Software refers to the collection of programs used by the computer within thedatabase system.

5. users:

Database Administrator
Database Administrator is a person having central control over data andprograms accessing that data.
Database Designer
Database designer can be either logical database designer or physical databasedesigner.
designer
Database manager
The database manager would translate DML statement into low level file systemcommands forstoring
forstoring,
retrieving, and updating data in the database
database.
Database Users
Database users are the people who need information from the database to carry out theirbusiness
responsibility. The database users can be broadly classified into two categories like application
programmers and end users.
System Analysts
System analysts determine the requirements of end user, and developspecification for canned transaction
that meets this requirement.

10. Explain database architecture?


Database architecture uses programming languages to design a particular type of software for businesses or
organizations. Database architecture focuses on the design, development, implementation and maintenance
of computer programs thatstore and organize information for businesses, agencies and institutions.

1- tier architecture:
One-tier architecture involves putting all of the required components for asoftware application ortechnology
on a single server or platform.

2- tier architecture:
The two-tier is based on Client Server architecture. The two-tier architecture is like client server
application. The direct communication takesplace between client and server. There is no intermediate
between client andserver.

3- Tier Architecture
A 3 Tier Architecture in DBMS is the most popular client server architecture in DBMS in which the
development and maintenance of functional processes, logic, data access, data storage, and user interface
is done independently as separate modules. Three Tier architecture contains a presentation layer, an
application layer, and a database server.
A 3-tier architecture has the following layers:
1. Presentation layer (your PC, Tablet, Mobile, etc. )
2. Application layer (server)
3. Database Server

11. Explain 3 level architecture/ Ansi Spark Data Model/Data Abstraction/3 schemaarchitecture in
DBMS?
The 3level architecture provides an essential details for an operation by hiding complex details from the
user. It is called as Data Abstraction. In DBMS, the data abstraction can be performed through the following
levels. they are:
 External/view level
 Conceptual/logical level
 Physical/internal level
These levels are also called as schema. It represents the design of the database orpart of the database, to store
the information.
1. External level
 It is also known as view level.
 This is highest level architecture and closest to the user.
 The user doesn’t need to know the database schema details such as data structure, table definition etc.
 External level is related to the data which is viewed by individual end users.
2. Conceptual level
 It is also known as logical level.
 The conceptual level is a higher level than the physical level.
 This level is maintained by DBA(database administrator).
 The whole design of the database such as relationship among data , schema of dataetc. are described in this
level.
 It is the middle level between external or internal levels.
3. Internal level
 It is also known as physical level.
 This is the lowest level of the architecture.
 This data is stored in the external hard drives in the form of bits.
 This level describes how the data actually stored in the storage device.
 This physical level also discuses encryption techniques.
 This level is also responsible for allocating space of the data.
UNIT-2
ENTITYRELATIONSHIPMODEL

1. What is ER Model?Explain Building Blocks of an Entit yRelationship? Entity–relationship


modeling was developed for database and design by Peter Chenand published in a 1976.
 An entity relationship model[E-RModel]is a defined logical representation of the data
for an organization.
 The E–R Model is expressed interms of entities.
 A E-R Model is normally expressed as an entity relationship diagram.
 It is a symbolic representation of an E-R model.
 The E-R Diagram used for representing E-R model can be easily convertedinto relations(tables)in relational
model.
 It is a top-down approach to database design.
The components in E-R Model
1. Entities
2. Attributes
3. Relationships

BUILDINGBLOCKS:
1. The E-R model can be carried out with the help of pictorial representation of entities, attributes
and relationships.
2. The basic building blocks of Entity Relationship diagram are Entity, Attribute andRelationship.
3. The following are the representations.

Entity Data objects aboutwhich informationcan be


collected and stored. Entity EntityName
Entities are
represented byRectangles.
Attribute Properties of anentity. Attributes are Attribute
representedby ellipses shape.

Relationships arerepresented by diamond shaped box


Relationship

Entity set:
Entity Set is a collection or a group of ‘entities’ sharing exactly the ‘same set ofattributes’. All
entities can be distinctly identified in an entity set. This is because all the entities have a different set of
value for some set of attributes.

TYPES OF ENTITIES(OR)CLASSIFICATION OF ENTITIES:


1. Strong Entity Types 2. Weak Entity Types 3. Recursive Entity Types
4. Composite Entity Types or Associative Entity Types5. Super Type and Sub Type Entities
1. Strong entity: It is also called as regular type entity. It is a collection of attributesand it contain a primary
key. It is represented by using single rectangle.
2. Weak entity: It is a collection of attributes and it cannot have primary key. It isrepresented by using
double rectangle.

3. Recursive Entity Types: Self When there is a relationship between two entitiesof the same type, it is
known as a recursive relationship.
An employee can supervise multiple employees. Hence, this is a recursive relationship of entity employee
with itself. This is a 1 to many recursive relationship as one employee supervises many employees.

4. Composite Entity Types


It contain a relationship as well as an entity. It is represented by diamond with in arectangle.

5. Super and subtype entity: A super type is a generic entity. It contain a relationship with
one or more subtypes.
Supertypeentity

Subtypee Subtypee Subtypee


Types of Attributes-In ER diagram, attributes associated with an entity set may be of the following types-

1. Simple attributes
2. Composite attributes
3. Single valued attributes
4. Multi valued attributes
5. Derived attributes
6. Key attributes
1. Simple Attributes-
Simple attributes are those attributes which can not be divided further.

Example-
Here, all the attributes are simple attributes as they can not be divided further.
2. Composite Attributes-
Composite attributes are those attributes which are composed of many other simpleattributes.

Example-
Here, the attributes “Name” and “Address” are composite attributes as they arecomposed of many other
simple attributes.
3. Single Valued Attributes-
Single valued attributes are those attributes which can take only one value for a given entity from an entity
set.

Example-
Here, all the attributes are single valued attributes as they can take only one specificvalue for each entity.
4. Multi Valued Attributes-
Multi valued attributes are those attributes which can take more than one value for agiven entity from an
entity set.
Example-Here, the attributes “Mob_no” and “Email_id” are multi valued attributes as they cantake more
than one values for a given entity.

5. Derived Attributes-
Derived attributes are those attributes which can be derived from other attribute(s).

Example-age
6. Key Attributes-
Key attributes are those attributes which can identify an entity uniquely in an entity set.

Example-
Here, the attribute “Roll_no” is a key attribute as it can identify any studentuniquely.

TYPES (OR)CLASSIFICATION OF RELATIONSHIPS:


The degree of a relationship is the number of entities associated with the relationship. The degree of
relationship is also called as “cardinality”.

ONE-TO-ONE RELATIONSHIP:
Only one entity of the first set is related to only one entity of the second set, such arelationship is
called one-to-one relationship.
For example a teacher teaches student. Only one teacher is teaching to only one student.

ONE-TO-MANY RELATIONSHIP:
Only one entity of the first set is related to multiple entities of the second set, sucharelationship is
called one-to-many relationship.
For example a teacher teaches students. Only teacher is teaching multiple students.

MANY-TO-ONE RELATIONSHIP:
Multiple entities of the first set are related to only one entity in the second set, sucha relationship iscalled
many-to-one relationship.
For example teachers teach a student. Many teachers are teaching only to onestudent.

MANY-TO-MANY RELATIONSHIP:
Multiple entities of the first set are related to multiple entities of the second set, such a relationshipis called
many-to-many relationship.
For example teachers teach students. Many teachers teaching many students.

2. Explain Relationship Degree?


RELATIONSHIP DEGREE:
A Relationship degree indicates the number of entities associated with a relationship. The three most
commonrelationship degree in ER Models are:
1. Unary 2. Binary 3. Ternary
1. Unary : A unary relationship is a relationship between the instances of a single entitytype. (one
entity isinvolved in the relationship)

2. Binary : A binary relationship exists when two entities are associated in Relationship. For
example, We have two entity type ‘Customer’ and ‘Account’ where each ‘Customer’ has an ‘Account’
which stores the account details of the ‘Customer’.

3. Ternary: A ternary relationship exists when exactly three entity type participates. When such
a relationship is present we say that the degree is 3.
For example, We have three entity type ‘Employee’, ‘Department’ and ‘Location’. The relationship
between these entities are defined as an employee works in a department, an employee works at a particular
location.

3. Explain EER Data Model?


EER Model
EER is a high-level data model that incorporates the extensions to the original ER model.
It is a diagrammatic technique for displaying the following concepts
 Sub Class and Super Class
 Specialization and Generalization
 Union or Category
 Aggregation
 Inheritance
These concepts are used when the comes in EER schema and the resulting schemadiagrams called as EER
Diagrams.
Features of EER Model
 EER creates a design more accurate to database schemas.
 It includes all modeling concepts of the ER model.
 Diagrammatic technique helps for displaying the EER schema.
 It includes the concept of specialization and generalization.
 It is used to represent a collection of objects that is union of objects of different ofdifferent entity types.

A. Sub Class and Super Class

 Sub class and Super class relationship leads the concept of Inheritance.
 The relationship between sub class and super class is denoted with symbol.
1. Super Class
 Super class is an entity type that has a relationship with one or more subtypes.
 An entity cannot exist in database merely by being member of any super class.
For example: Shape super class is having sub groups as Square, Circle, Triangle.
2. Sub Class
 Sub class is a group of entities with unique attributes.
 Sub class inherits properties and attributes from its super class.
For example: Square, Circle, Triangle are the sub class of Shape super class.

B. Specialization and Generalization


1. Generalization
 Generalization is the process of generalizing the entities which contain the properties of all the generalized
entities.
 It is a bottom approach, in which two lower level entities combine to form a higher levelentity.
 Generalization is the reverse process of Specialization.
 It defines a general entity type from a set of specialized entity type.
For example:

In the above example, Tiger, Lion, Elephant can all be generalized as Animals.
2. Specialization
 Specialization is a process that defines a group entities which is divided into sub groups based on their
characteristic.
 It is a top down approach, in which one higher entity can be broken down into two lower level entity.
 It maximizes the difference between the members of an entity by identifying the unique characteristic or
attributes of each member. It defines one or more sub class for the super class and also forms the super
class/subclassrelationship.
For example

In the above example, Employee can be specialized as Developer or Tester, based onwhat role they play in
an Organization.
3. Category or Union
 Category represents a single super class or sub class relationship with more than one super class.
 It can be a total or partial participation.
For example Car booking, Car owner can be a person, a bank (holds a possession on a Car) or a company.
Category (sub class) → Owner is a subset of the union of the three super classes → Company, Bank, and
Person. A Category member must exist in at leastone of its super classes.
4. Aggregration and composition:
Aggregation is a process of relation between two entities is treated as a single entity. It is a special kind
ofrelationship. It may be represented as “IS-A”, ”HAS-A” relationship.
Composition is a special case of aggregation, it is a restricted aggregation. In generally, composition is
definedas an object contain other object for example, it isrepresented as

5. Inheritance: Inheritance is defined as a mechanism where the sub or child class inherits the
properties and characteristics of the super class or other derived classes.

4. Write about IS A Relationship and Attribute Inheritance?


IS A relationship supports attribute inheritance and relationship participation.
In the EER diagram, the subclass relationship is represented by IS A relationship.
Attribute inheritance is the property by which subclass entities inherit values for all attributesof the super
class.
Consider the example of EMPLOYEE entity set in a bank. The EMPLOYEEin a bank can be CLERK,
MANAGER, CASHIER, ACCOUNTANT, etc. It
is to be observed that the CLERK, MANAGER, CASHIER, ACCOUNTANTinherit some of the attributes
of the EMPLOYEE.

5. What is Multiple Inheritance?


Inheritance is a method which can derive or construct new classes from the existing class. In multiple
inheritance we have more than two base class which are combine inherited by onlyone derived class.
Inheritance strongly supports the concept of reusability, i. e. Newly created class reuses theproperties of
already existing ones.

6. Write about Advantages of ER modeling?


1. ER model is a logical representation of an enterprise data. ER model isa diagrammatic
representation of logical structure of database.
2. ER model describes relationship among entities and attributes. 3. ER diagram is firstly developed
by Peter Chen in 1976. Advantages of ER Model
1. Conceptually it is very simple: ER model is very simple because if we know relationship
between entities and attributes, then we can easily draw an ER diagram.
2. Better visual representation: ER model is a diagrammatic representation of any logical
structure of database. By seeing ER diagram, we can easily understand relationship among entities and
relationship.
3. Effective communication tool: It is an effective communication tool for database designer.
4. Highly integrated with relational model: ER model can be easily converted into relational
model by simply converting ER model into tables.
5. Easy conversion to any data model: ER model can be easily converted into another data model
like hierarchical data model, network data model and so on.
Disadvantages of ER Model
1. Limited constraints and specification
2. Loss of information content: Some information be lost or hidden in ER model
3. Limited relationship representation: ER model represents limitedrelationship as compared to
anotherdata models like relational model etc.
4. No representation of data manipulation: It is difficult to show data
manipulation in ER model.
5. Popular for high level design: ER model is very popular for designing highlevel design

7. Explain constraints on specialization and generalization?Constraints on


specialization/generalization
There are three constraints that may apply to a specialization/generalization: membership constraints,
disjoint constraints and completeness constraints.
 Membership constraints
Condition defined: Membership of a specialization/generalizationrelationship can be defined as a
condition in the requirements
 User defined: Sometimes the designer can define the super class-subclassrelationship. This can be done to
simplify the design model or represent acomplex relationship that exists between entities.
 Disjoint constraints
Disjoint: The disjoint constraint only applies when a super class has more than one subclass. If the
subclasses are disjoint, then an entity occurrencecan be a member of only one of the subclasses,
Overlapping: This applies when an entity occurrence may be a member of morethan one subclass,

 Completeness constraints
Total: Each superclass (higher-level entity) must belong to subclasses (lower-level entity sets), e. g. a
student must be postgrad or undergrad. Torepresent completeness in the specialization/generalization
relationship.

Partial: Some super classes may not belong to subclasses (lower-level entitysets), e. g. some people at
UCT are neither student nor staff. The keyword “Optional” is used to represent a partial
specialization/generalization relationship.
We can show both disjoint and completeness constraints in the ER diagram. Following our examples, we
can combine disjoint and completeness constraints.

Some members of a university are both students and staff. Not all members of theuniversity are staff and
students.

A student in the university must be either an undergraduate or postgraduate, butnot both.


8. Explain reducing ER diagram to tables?

 ER diagram is converted into the tables in relational model.


 This is because relational models can be easily implemented by RDBMS like MySQL , Oracleetc.
Following rules are used for converting an ER diagram into the tables-
Rule-01: For Strong Entity Set With Only Simple Attributes-
A strong entity set with only simple attributes will require only one table in relational model.

Roll_no Name Sex


Example-

Schema : Student ( Roll_no , Name , Sex )


Rule-02: For Strong Entity Set With Composite Attributes-Example-

Roll_no First_name Last_name House_no Street City

Schema : Student ( Roll_no , First_name , Last_name , House_no , Street , City )


Rule-03: For Strong Entity Set With Multi Valued Attributes-Example-

Roll_no City
Rule-04: Translating Relationship Set into
i a Table-Example-

Emp_no Dept_id since

Schema : Works in ( Emp_no , Dept_id , since )

Rule-05: For Binary Relationships With Cardinality Ratios-


The following four cases are possible-
Case-01: Binary relationship with cardinality ratio m: n Case-02: Binary relationship with cardinality ratio
1: n Case-03: Binary relationship with cardinality ratio m:
m 1 Case-04: Binary relationship with cardinality
ratio 1: 1
Example:

Following is the structure of the table for the ER Diagram:


UNIT-3 RELATIONAL MODEL
1. Explain E. F CODD’S Rules?
CODD’S RELATIONAL DATABASE RULES:
CODD Rules are very important features in the database management system. These rules are used to store
and retrieve the data in efficient manner. The rules are represented as follows:
Rule 0: Foundation Rule
A relational database management system stores the data using relational capabilities.
Rule 1: Information Rule
All information in the database should be represented in one way as values in a table.
Rule 2: Guaranteed access Rule
Each and every data in the database must contain a table name. The table contains collection of rowsand
columns.
Rule 3: Systematic treatment of Null values
Null values are supported in the Relational Database Management System (RDBMS)for representing missing
values in a systematic way.
Rule 4: Dynamic online catalogue based on Relational model:
The database description is represented at the logical level in the same way as ordinary data.
Rule 5: comprehensive data sublanguage Rule
A Relational Database System may support several languages for accessing the data. It contains:
 Data definition
 View definition
 Data Manipulation
 Integrity constraints
 Authorization
 Transaction boundaries and soon.
Rule 6: View updating Rule
All views are automatically updatable by the system.
Rule 7: High level insert, update and delete
The database can perform insertion, update and deletion of data.
Rule 8: Physical data Independence
The data stored in a database must be independent of the applications that access the database. Any change
in thephysical structure of a database must not have any impact on how the data is being accessed by
external applications.
Rule 9: Logical Data Independence
The logical data in a database must be independent of its user’s view (application). Any change in logical
data must not affect the applications using it. For example, if two tables are merged or one is split into two
differenttables, there should be no impact or change on the user application.
Rule 10: Integrity constraints
Integrity constraints are performed by the Relational Database but not in application programs.
Rule 11: Distribution Independence
In the RDBMS, application programs and terminal activities are physically centralized.
Rule 12: Non subversion Rule
The Relational Database supports a low level language. It contain integrity rules or constraints in the higher
level Relational language.
2. Explain about Relational Data model?
In a Relational data model, data is collected and stored in the form of tables. It was designed by “E. F.
codd”. The main purpose of relational data model is to create different tables and to create relationships
using various keys.
Every relational data model supports various functionalities and components. for example they are:

 Tables
 Keys
 Set operators or integrity rules.

Table: A table is a two dimensional object . It stores the data in the form of rows andcolumns. Row is called
as tuple.
sno sname age address
Row orTuple

Column
Keys: The keys are very important component in relational data model. These are used to uniquely identify
the data. These are also used to establish relationship between the tables. for example they are:
 Candidate key
 Primary key
 Secondary key
 Super key
 Foreign key
 Surrogate key
Candidate key: It is used to identify any column it contain a single value. Every table may contain more
than onecandidate key. The best candidate key is selected as primary key.
Primary key: Every table must have a single primary key. In generally, it is the combination of unique and
notnull. The best candidate key is selected as primary key.
Secondary key: This key contain duplicate values. so, it is difficult to identify a particular data.
Super key: It indicates an additional key that allows to identify the particular value i. e. , uniquely identify
eachrow in the table.
Foreign key: It is also called as reference key. It is used to mapping between the fields. The fields may be
twotable or same table.
Surrogate key: It is also called as artificial key. It is used to uniquely identify the data from the table.
3. Write about the concept of Relational Integrity?
Integrity rules or relational integrity:
1. Relational database integrity rules are very important to good database design.
2. Many (but by no means all) RDBMSs enforce integrity rules automatically.
3. The set of rules which are used to maintain the accuracy of the data and to integrate (add) the data in database
is called as integrity constraints.
1. Domain Integrity.
2. Entity Integrity.
3. Referential Integrity.
1. Domain Integrity:
1. A domain is a set of values which is assigned to an attribute.
2. The components of the domain are domain name, meaning, data type, size and range of the values.
Ex: student relation the domains are regdno, name.
2. Entity Integrity :
1. All primary key entries are unique, and no part of a primary key may be null.
2. Each row will have a unique identity, and foreign key values can properly reference primary key values.
3. A primary key is an attribute in a relation which is used to identify each row in a relation.
4. No. of components of a primary key value may be NULL.
5. This is called as entity integrity.
3. Referential Integrity :
1. A referential integrity is used to implement the foreign key.
Another integrity rules that can be enforced in the relational model are the
NOT NULL and UNIQUE constraints.
NOT NULL: its not supports empty value in attribute. The NOT NULL constraint can be placed a value for
that column.
UNIQUE: The UNIQUE constraint is used to not support duplicate values exists column.
4. Explain Set Operations (OR)Relational algebra?
Relational algebra is a procedural query language. It gives a step by step process to obtain the result of the
query. It uses operators to perform queries.
Relational SET OPERATORS (Relational Algebra)
 In Oracle database SQL supports 8 types of relational algebra and relational SET operators.
 SET operators are used to combine information of similar types from one or more than one table.
 Types of SET operators: -
1) UNION
2) INTERSECT
3) MINUS (difference)
4)DIVIDE
5) PRODUC T(Cartesian product)
6)PROJECT
7) SELECT
8) Join

2. INTERSECT : -∩
The INTERSECT operator returns the rows that are common between two sets of rows.
 Apply INTERSECT operator on both tables.
Example: -select spec, fee from student intersect select spec, free from admission;
Output:
Spec Fee
BSC 12000
BCOM 10000
BCA 20000

3) MINUS/DIFFERANCE :
(-)
The MINUS operator returns the rows unique to first query.
 It combines records from 2 queries and returns the first table records which were not placed in the 2nd table.
 Apply MINUS operator on both tables.
example - 1: -select spec, fee from student minus select spec, free from admission;
Output: Spec Fee
BA 8000
2) DIVIDE : -This operator specifies table1 is DIVIDE by table2 to produce table3 whenever both table1 &
table2 using a common field. Table A DIVIDE Table B
Sname Avg Sname
Xyz 70 Xyz
abc 60 Pqr
pqr 50
xyz 50
Pqr 90
 The output of a Table A divided by Table B is.
 The only value associated with both ‘xyz’ & ‘pqr’ is 50 only

Output: -
Avg
50
3) PRODUCT (or) Cartesian Product : -
 This operator returns all the possible pairs of records from the two tables. .
 If table1 having 3 records and table2 having 3 records then the product of e tables will return 3 x 3 = 9
records.
Example: Select students. stdno, students. sname, subjects. spec, subjects. subjfrom students,
subjects;
STUDENTS PRODUCT SUBJECTS
Stdno Sname Spec Subj
1 Murthy BSC English
2 Sailu BSC Maths
3 Bharat BSC Computers
OUTPUT:
Stdno Sname Spec Subj
1 Murthy BSC English
1 Murthy BSC Maths
1 Murthy BSC Computers
2 Sailu BSC English
2 Sailu BSC Maths

4) PROJECT : -π
 it returns the selected field from the database table. (it returns single or multiple
fields)
Example: select fee from student;
Student table PROJECT fee yields 
Stdno Sname Fee Fee
1 Sailu 12000 12000
2 Mounika 10000 10000
3 Ramya 20000 20000
4 Indu 8000 8000
5) SELECT : -σ
 The SELECT statement is used to query or retrieve data from a table in the database.
 A query may retrieve information from specified columns or all columns in a table.
Display ALL fields Example : -
SQL\>SELECT * FROM STUDENT;
Display some specified fields Example : -

SQL\>SELECT Stdno, Sname FROM STUDENT;

Display some specified fields based on Condition: -

SQL\>SELECT Stdno, Sname FROM STUDENT WHERE RNO=3;


6)
JOINS: Join Operations
1. Join operation combines two relations to create a new relation.
2. The tables should be joined based on a common column.
3. It allows information to be combined from two or more tables.
Types:
Left outer join: The functionality of left outer join is used to display all rows in left hand relation and

includes only those matching rows from the right hand relation.

Right outer join: αThe functionality of right outer join is used to display all rows in right hand relation and
includes only those matching rows from the left hand relation
Full outer join: The functionality of full outer join is used to display all rows in left hand relation and
display all Rows in right hand relation.
Advantages of Relational Algebra:
1. Easy to use
2. flexibility
3. security
4. Data independence
5. Data manipulation language
6. Relational algebra is a high level language.
Limitations of Relational Algebra:
1. The relational algebra cannot perform aggregates.
2. The relational algebra cannot modify the database.
3. The relational algebra cannot sort or print results in various formats.
4. The relational algebra cannot do arithematic.
5. The query cannot be perform using relational algebra.
5. Explain Relational Integrity?
1. Relational Integrity constraints are the set of rules and restrictions which are used to maintain the data
consistency and integrity of a Relation (Table).
2. A database is only as good as the information stored in it.
3. It prevent the entry of incorrect information (incorrect information is not allowed).
Following are the four main types of Relational Integrity Constraints in the Database Management
System:
1. Key Constraint
2. Referential Integrity constraint
3. Entity Integrity constraint
4. Domain constraint
Key Constraint
A key constraint is that constraint which uniquely identifies the tuple of a relation. A Relation should
haveatleast one key constraint.

Referential Integrity Constraint


The referential integrity constraint is a type of constraint that exists between two tables for maintaining the
dataconsistency in both the tables.

In the Course table, Course_ID is a primary key.

Entity Integrity Constraint


An entity integrity constraint states that the value of the primary key attribute cannot be NULL.

Domain Constraint
Domain constraint is that constraint which defines the set of rules for an attribute of 'Relation'. It specifies
that thefield accepts only those values which exist in the defined domain.
Domain Constraints are the user-defined data types such as Date, String, Integer, Currency, character, etc.

6. Explain functional dependencies?


Functional Dependency
The functional dependency is a relationship that exists between two attributes. It typically existsbetween
the primary key and non-key attribute within a table.
X → Y
The left side of FD is known as a determinant, the right side of the production is known as a dependent. It is
introduced by E. F Codd.
Functional dependency is represented by using arrow mark 
For example:
Assume we have an employee table with attributes: Emp_Id, Emp_Name, Emp_Address.
Here Emp_Id attribute can uniquely identify the Emp_Name attribute of employee table because if we
know the Emp_Id, we can tell that employee name associated with it.
Functional dependency can be written as:
1. Emp_Id → Emp_Name
We can say that Emp_Name is functionally dependent on Emp_Id. Types of Functional dependency

1. Trivial functional dependency


o A → B has trivial functional dependency if B is a subset of A.
o The following dependencies are also trivial like: A → A, B → B
Example:
Consider a table with two columns Employee_Id and Employee_Name.
{Employee_id, Employee_Name} → Employee_Id is a trivial functional dependency as
Employee_Id is a subset of {Employee_Id, Employee_Name}.

2. Non-trivial functional dependency


o A → B has a non-trivial functional dependency if B is not a subset of A.
o When A intersection B is NULL, then A → B is called as complete non-trivial.

Example:
1. ID → Name,
2. Name → DOB

7. Explain Normalization?Types of Normal forms?


o Normalization is the process of organizing the data in the database.
o Normalization is used to minimize the redundancy from a relation or set of relations. It is also used to
eliminate undesirable characteristics like Insertion, Update, and Deletion Anomalies.
o Normalization divides the larger table into smaller and links them using relationships.
o The normal form is used to reduce redundancy from the database table.
Data modification anomalies can be categorized into three types:
o Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a new tuple into arelationship
due to lack of data.
o Deletion Anomaly: The delete anomaly refers to the situation where the deletion of data results in the
unintended loss of some other important data.
o Updatation Anomaly: The update anomaly is when an update of a single data value requires multiplerows
of data to be updated.
Types of normal forms:
The database normalization process is divided into following the normal form:
 First Normal Form (1NF)
 Second Normal Form (2NF)
 Third Normal Form (3NF)
 Boyce-Codd Normal Form (BCNF)
 Fourth Normal Form (4NF)
 Fifth Normal Form (5NF)
1.First Normal Form
1. Each column is unique in 1NF.
2.first normal form disallow the multi-valued attribute.
Example: Relation EMPLOYEE is not in 1NF because of multi-valued attribute EMP_PHONE.
EMPLOYEE table:
EMP_ID EMP_NAME EMP_PHONE EMP_STATE
14 John 7272826385, UP
9064738238
20 Harry 8574783832 Bihar
12 Sam 7390372389, Punjab
8589830302
The decomposition of the EMPLOYEE table into 1NF has been shown below:
EMP_ID EMP_NAME EMP_PHONE EMP_STATE
14 John 7272826385 UP
14 John 9064738238 UP
20 Harry 8574783832 Bihar
12 Sam 7390372389 Punjab
12 Sam 8589830302 Punjab
2.Second Normal Form (2NF)
o In the 2NF, relational must be in 1NF.
o In the second normal form, all non-key attributes are fully functional dependent on the primary key
Example: Let's assume, a school can store the data of teachers and the subjects they teach. In a
school, a teacher can teach more than one subject.
TEACHER table
TEACHER_ID SUBJECT TEACHER_AGE
25 Chemistry 30
25 Biology 30
47 English 35
83 Math 38
83 Computer 38
TEACHER_DETAIL table:
TEACHER_ID TEACHER_AGE
25 30
47 35
83 38
TEACHER_SUBJECT table:
TEACHER_ID SUBJECT
25 Chemistry
25 Biology
47 English
83 Math
83 Computer
3. Third normal form(3NF): Every non prime attribute of table must be dependent on primary key.
The transitive functional dependency should be removed from the table. The table must be in second normal
form 2NF.
Consider the student detail table in which the student_id is primary key, but street, city and state dependent
on zip. The dependency between zip and other field is transitive dependency. Hence to apply 3NF we have
to move the street, city and state to new table with Zip as primary key.

4. Boyce codd normal form(BCNF)


1. It is in 3NF.
2. BCNF stands for Boyce-Codd-Normal Form.
3. For every functional dependence xy, x should be super key of table.

Example:
Key={std, course}
{std, course}teacherafter decompose, the BCNF table is: super key eliminate the redundant data.

Super key

Here there is no transitive dependency . In this table super key is here. so this table is in BCNF
5. Fourth normal form (4NF)
o A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-valued dependency.
o For a dependency A → B, if for a single value of A, multiple values of B exists, then
the relationwill be a multi-valued dependency.
Example
STUD
STU_ID COURSE HOBBY
21 Computer Dancing
21 Math Singing
34 Chemistry Dancing
74 Biology Cricket
59 Physics Hockey

The given STUDENT table is in 3NF, but the COURSE and HOBBY are two independent entity. Hence,
there is no relationship between COURSE and HOBBY.
In the STUDENT relation, a student with STU_ID, 21 contains two courses, Computer and Math and
two hobbies, Dancing and Singing. So there is a Multi-valued dependency on STU_ID, which leads to
unnecessary repetition of data.
So to make the above table into 4NF, we can decompose it into two tables:
STUDENT_COURSE

STU_ID COURSE
21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics

STUDENT_HOBBY
STU_ID HOBBY
21 Dancing
21 Singing
34 Dancing
74 Cricket
59 Hockey

6. Fifth normal form (5NF)


o A relation is in 5NF if it is in 4NF and not contains any join dependency and joining should belossless.
o 5NF is satisfied when all the tables are broken into as many tables as possible in order to avoid
redundancy.
o 5NF is also known as Project-join normal form (PJ/NF).
Example
SUBJECT LECTURER SEMESTER
Computer Anshika Semester 1
Computer John Semester 1
Math John Semester 1
Math Akash Semester 2
Chemistry Praveen Semester 1

So to make the above table into 5NF, we can decompose it into three relations P1, P2 & P3
P1
SEMESTE SUBJECT
Semester 1 Computer
Semester 1 Math
Semester 1 Chemistry
Semester 2 Math
P2
SUBJECT LECTURER
Computer Anshika
Computer John
Math John
Math Akash
Chemistry Praveen
P3
SEMSTER LECTURER
Semester 1 Anshika
Semester 1 John
Semester 1 John
Semester 2 Akash
Semester 1 Praveen

UNIT-4:SQL
1)SQL (Structured Query Language) INTRODUCTION:
SQL (Structured Query Language) is a domain-specific language used for managing and manipulating
relational databases. It allows users to interact with databases to perform various tasks like querying data,
updating records, and managing database structures.
2)SQL, which stands for Structured Query Language, is a domain-specific language used for managing and
manipulating relational databases. It has a rich history that spans several decades. Here are some key
milestones in the history of SQL:
1. Early Database Management Systems (1960s):
 In the 1960s, early database management systems (DBMS) were being developed. However, data
access was primarily done through low-level programming languages, making it cumbersome and
complex.
2. SEQUEL (Structured English Query Language) (1970s):
 In the early 1970s, Donald D. Chamberlin and Raymond F. Boyce, working at IBM, developed
SEQUEL as a high-level language for managing data in IBM's System R. SEQUEL was later
renamed SQL due to trademark issues.
3. SQL Standardization (1986):
 SQL was standardized for the first time in 1986 by the American National Standards Institute
(ANSI). This standard was later adopted by the International Organization for Standardization (ISO).
4. SQL-89 (SQL1):
 In 1989, the first official SQL standard was published, known as SQL-89 or SQL1. It defined the
basic features of SQL and laid the foundation for future versions.
5. SQL-92 (SQL2):
 SQL-92, released in 1992, brought significant improvements and added many new features,
including support for integrity constraints, triggers, and more advanced data types.
6. SQL-99 (SQL3):
 The SQL-99 standard, also known as SQL3, was a major milestone in the evolution of SQL. It
introduced support for object-oriented features, recursive queries, and several other enhancements.
7. Database Vendors and SQL Implementations:
 Over the years, various database vendors, such as Oracle, Microsoft, IBM, and PostgreSQL,
developed their own SQL implementations with proprietary extensions. This led to some
fragmentation in the SQL language.
8. SQL:2003 (SQL3):
 SQL:2003 was a significant update to the standard, incorporating many features from commercial
database systems, and introduced the concept of "SQL/XML" for handling XML data.
9. Ongoing Development and Expansions:
 Since SQL:2003, the SQL standard has continued to evolve with new versions being released. Each
version brings additional features, enhancements, and clarifications to the language.
10. NoSQL Databases:
 In recent years, with the rise of NoSQL databases, which use non-relational data models, SQL faced
competition from alternative query languages specific to each NoSQL database system.
11. SQL:2016 and Beyond:
 The SQL:2016 standard introduced JSON support and several other improvements. Subsequent
versions have likely been released (beyond my knowledge cutoff in September 2021), with further
advancements and adaptations to the changing database landscape.
SQL remains one of the most widely used and essential tools in the field of database management and
continues to evolve to meet the needs of modern data management systems.
3)Data Base Language Commands: It Provides Data Definition Language (DDL) and Data Manipulation
Language (DML). DDL supports the database schemas and DML specifies the database queries and updates.

DDL: It defines the skeleton of the schema of the database. A schema is a collection of files with association
between relevant pairs of files. A schema is assigned a name which represents the name of the database.
DDL commands are Create, alter and drop.

DML: It defines on data of the database. Retrieving data from the database such as inserting data, Update
the data i.e. modifying the data and deleting data from the data base.

TCL: TCL means Transaction Control Language. The commands used in TCL are Commit, Savepoint and
roll back.

DCL:Data control language is used to give and take back the previlisation rights to the users on our database
usage by using GRANT AND REVOKE commands

Creating stud08 table


Create: It is a DDL command used to create a new table, view, functions, procedures, triggers.
Syntax:
SQL> Create table table_name(Col_name1 data_type(size), Col_name2 data_type(size),…);
Example:
SQL> create table stud08(sno number(3),name varchar2(15),Branch char(3));
Output: Table created.

Alter, Update Drop, Delete, Truncate, Rename Commands

Alter: It is a DDL command used to alter the table. It is of 3 types alter..add, alter..drop, alter..modify.
Syntax:
Alter..Add: It is used to add constraints and also for adding additional columns to an existing table.
SQL> alter table <table name> add constraint <constraint name> constraint type(column name);
Syntax for adding additional columns to an existing table:
SQL> alter table <table_name> add (<coloumn_name> <type>);
Example:
Adding Sub1,Sub2, Sub3,Total, Average fields to stud08 table:
SQL> alter table stud08 add(sub1 number(3),sub2 number(3),sub3 number(3), Total number(3), Average
number(3));
Output: Table altered.

After adding field’s stud08 table:

SQL> select * from stud08;


SNO NAME BRANCH SUB1 SUB2 SUB3 TOTAL AVERAGE
---------- ------ ------ ---------- ---------- ---------- ---------- ----------
101 Satya BCA
103 Swathi BCA
102 Suni BCA
104 Rama BCA

Alter..Modify: It is used to modify the data type or size of column of a table. We cannot add not null
constraint using alter..add. We can add not null constraint using alter..modify.
Syntax:
SQL> alter table <table name> modify <column_name > <datatype> <size>;
Example:
Modifying Not Null Constraint to Stud08:
SQL> alter table stud08 modify(name varchar2(15) not null);
Output: Table altered.
Alter..Drop: It is used to drop the constraint OR column from table.
Syntax:
SQL> alter table <table_name> drop constraint;
Example:
Dropping column from stud08:
SQL> alter table stud08 drop column dob;
Output: Table altered.
Dropping Not null Constraint from stud08:
SQL> alter table stud08 drop constraint name_nn;
Output: Table altered.
Truncate: This Command is used to delete all the rows from a table. This first drops the table and then
recreates the table.
Syntax:
SQL> truncate table table_name;
Example:
SQL> truncate table stud08;
Output: Table truncated.
After using truncate command st08 table:
SQL> select * from st08;
Output: no rows selected
Drop: This command is used to drop or delete the table.
Syntax: SQL> drop table table_name;
Example:
SQL> drop table st08;
Output: Table dropped.

DML COMMANDS
Inserting values into stud08 table:

Insert: This command is used to insert records into a table.


Syntax:
SQL>insert into <table_name> values(&col1_name,&col2_name,. . );
Example:
SQL> Insert into std08 values (&sno, '&name', '&branch');
Output:
Enter value into sno: 101
Enter value into sname: Satya
Enter value into Branch: BCA
SQL>/
Enter value into sno: 102
Enter value into sname: Swathi
Enter value into Branch: BCA
……
After inserting records Stud08 Table:
SQl> select * from stud08;
SNO NAME BRANCH
----- ------ -------
101 Satya BCA
103 Swathi BCA
102 Suni BCA
104 Rama BCA
Update: It is a DML command used to modify the data of a table.
Syntax:
SQL> Update <table_name> set <column_name> = <value> where condition;
Example:
Updating Total, Average fields in stud08 table:
SQL> update stud08 set total = sub1 + sub2 + sub3;
Output: 4 rows updated.
SQL> update stud08 set average = total/3;
Output: 4 rows updated.
After Updating Stud08 table:
SQL> select * from stud08;
SNO NAME BRANCH SUB1 SUB2 SUB3 TOTAL AVERAGE
---------- ------ ------ ---------- ---------- ---------- ---------- ----------
101 Satya BCA 82 84 86 252 84
103 Swathi BCA 81 81 81 243 81
102 Suni BCA 81 80 80 241 80
104 Rama BCA 79 80 81 240 80
Delete: It is a DML command used to delete the records from a table.
Syntax:
SQL> delete from <table_name> where condition;
Example:
Deleting Records from table:
SQL> delete from stud08 where sno = 102;
Output: 1 row deleted.
SQL> delete from stud08 where name = 'Rama';
Output: 1 row deleted.
After deleting records stud08 table:
SQL> select * from stud08;
SNO NAME BRANCH SUB1 SUB2 SUB3 TOTAL AVERAGE
---------- ------ ------ ---------- ---------- ---------- ---------- ----------
101 Satya BCA 82 84 86 252 84
103 Swathi BCA 81 81 81 243 81
Rename: It is used to rename an existing table.
Syntax:
SQL> rename old_table_name to new_table_name;
Example:
SQL> rename stud08 to st08;
Output: Table renamed.

TCL COMMANDS:
Transaction language commands are savepoint, rollback and commit. By using these commands ,we can
control the transactions and it’s results by saving all the details temporarily and can also go for perminant
save or undo operations, if needed.
Savepoint: Is used to create asavepoint and store the transaction details temporarily
Syntax:
savepoint <savepoint name>;
example:
savepoint incsal;
savepoint created successfully.
Update emp set sal=sal+sal*10/100;
Select * from emp;
Table will display with updated salary to all employees
Rollback:It is used to erase the content from temporary storage space
Syntax:
rollback to savepoint name;
Example:
rollback to incsal;
commit: It is used to save the transaction results permanently in the disk.
Synatax: commit;
o/p:commit completed
4)WRITE A SHORT NOTE ON DATATYPES OF SQL
In SQL (Structured Query Language), data types define the type of data that can be stored in a database
table's columns. Each column in a table is assigned a specific data type, which determines the kind of data it
can hold. SQL supports a wide range of data types, allowing for flexibility in storing and manipulating
different types of data. Here are some commonly used SQL data types:
1. Numeric Data Types:
 INTEGER/NUMBER: Used to store whole numbers (e.g., 1, 100, -15).
 DECIMAL/NUMERIC: Used to store fixed-point numbers with specified precision and scale (e.g.,
3.14, -123.456).
 FLOAT/REAL: Used to store floating-point numbers with approximate precision.
2. Character Data Types:
 CHAR: Fixed-length character strings (e.g., 'Hello', 'SQL').
 VARCHAR: Variable-length character strings with a maximum length (e.g., 'OpenAI', 'Data').
 TEXT: Used for large blocks of text data (e.g., paragraphs, documents).
3. Date and Time Data Types:
 DATE: Used to store dates (e.g., '2023-07-26').
 TIME: Used to store time of day (e.g., '14:30:00').
 TIMESTAMP/DATETIME: Stores both date and time information (e.g., '2023-07-26 14:30:00').
4. Boolean Data Type:
 BOOLEAN/BOOL: Represents true or false values.
Database systems may have additional vendor-specific data types or extensions beyond the standard SQL
data types. It's essential to refer to the documentation of the specific database system you are using to
understand the full range of data types available and their characteristics. Choosing the appropriate data
types for your database columns is crucial for efficient storage and retrieval of data and maintaining data
integrity.

5)Built-in Functions POWER():


Arithmetic Functions: SQL> select power(5,2) from dual;
ABS(): POWER(5,2)
SQL> select abs(-6) from dual; ----------
ABS(-6) 25
---------- 25
6 SIGN():
6 SQL> select sign(-5) from dual;
CEIL(): SIGN(-5)
SQL> select ceil(3.3) from dual; ----------
CEIL(3.3) -1
---------- -1
4 String Functions:
4 Lower():
FLOOR(): SQL> select lower('ADITYA PG COLLEGE')from
SQL> select floor(1.3) from dual; dual;
FLOOR(1.3) LOWER('ADITYAPGCO
---------- ------------------
1 aditya pg college
1 Upper():
MOD(): SQL> select upper('aditya pg college')from dual;
SQL> select mod(5,2) from dual; UPPER('adityapgco
MOD(5,2) ------------------
---------- ADITYA PG COLLEGE
1 Initcap():
1 SQL > select initcap(‘aditya’) from dual;
ROUND(): INITCAP(‘aditya)
SQL> select round(15.913,1) from dual; ----------------
ROUND(15.913,1) Aditya
--------------- Rpad():
15.9 SQL> select rpad('teja',10,'*') from dual ;
15.9 RPAD('TEJA
SQRT(): ----------
SQL> select sqrt(36) from dual; teja******
SQRT(36) Lpad():
---------- SQL> select lpad('satish',10,'*') from dual ;
6 LPAD('SATI
6 ----------
****satish
Substr():
SQL> select substr('oracle record',1,6) from emp ; SQL> select next_day(sysdate,'SUN') from dual;
SUBSTR(‘oracl NEXT_DAY(
------------------- ---------
oracle 13-NOV-11
Instr(): SQL> select last_day(sysdate) from dual;
SQL> select instr('aditya pg college','college') from emp; LAST_DAY(
INSTR('ADITYAPGCOL ---------
------------------- 30-NOV-11
11
Ascii():
SQL> select ascii('a') from dual; Aggregate Functions
ASCII('A') Sum:is used to calculate summation of a column
---------- values.
97 SQL> select sum(sal) from emp08;
Length: SUM(SAL)
SQL> select length('ADITYA PG COLLEGE') from ----------
dual; 135000

LENGTH('ADITYAPGCOLLEGE') Avg():IS used to calculate average value of a


-------------------------- column values.
15 SQL> select avg(sal) from emp08;
Date Functions: AVG(SAL)
SQL> select sysdate from dual; ----------
SYSDATE 13500
--------- Min():is used to calculate minimum of a column
10-NOV-11 values.
SQL> select sysdate,sysdate+3 from dual; SQL> select min(sal) from emp08;
SYSDATE SYSDATE+3 MIN(SAL)
--------- --------- ----------
10-NOV-11 13-NOV-11 12000
SQL> select add_months(sysdate,11) from dual; Max():is used to calculate maximum of a column
ADD_MONTH values.
--------- SQL> select max(sal) from emp08;
10-OCT-12 MAX(SAL)
SQL> select ----------
months_between(add_months(sysdate,2),sysdate) from 15000
dual; Count():used to calculate the no.of rows of a table.
SQL> select count(*) from student08;
MONTHS_BETWEEN(ADD_MONTHS(SYSDATE, COUNT(*)
2),SYSDATE) ----------
--------------------------------------------- 6
2
6)Joins in ORACLE
1. The purpose of a join is to combine the data across tables.
2. A join is actually performed by the where clause which combines the specified rows of tables.
3. If a join involves in more than two tables then Oracle joins first two tables based on the joins condition and
then compares the result with the next table and so on.
TYPES
1 Equi join
2 Non-equi join
3 Self join
4 Natural join
5 Cross join
6 Outer join
 Left outer
 Right outer
 Full outer
7 Inner join
Assume that we have the following tables.
SQL> select * from dept;
DEPTNO DNAME LOC
10 INVENTORY HYBD
20 FINANCE BGLR
30 HR MUMBAI
SQL> select * from emp;
EMPNO ENAME JOB MGR DEPTNO
111 saketh analyst 444 10
222 sudha clerk 333 20
333 jagan manager 111 10
444 madhu engineer 222 40
1. EQUI JOIN
A join which contains an equal to ‘=’ operator in the joins condition.
Ex:SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno;

EMPNO ENAME JOB DNAME LOC


111 saketh analyst INVENTORY HYBD
333 jagan manager INVENTORY HYBD
222 sudha clerk FINANCE BGLR

2. NON-EQUI JOIN
A join which contains an operator other than equal to ‘=’ in the joins condition.
Ex:SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno > d.deptno;
EMPNO ENAME JOB DNAME LOC
222 sudha clerk INVENTORY HYBD
444 madhu engineer INVENTORY HYBD
444 madhu engineer FINANCE BGLR
444 madhu engineer HR MUMBAI
3. SELF JOIN
Joining the table itself is called self join.
Ex: SQL> select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp e2 where e1.empno=e2.mgr;
EMPNO ENAME JOB DEPTNO
111 jagan analyst 10
222 madhu clerk 40
333 sudha manager 20
444 saketh engineer 10
4. NATURAL JOIN
Natural join compares all the common columns.
Ex:SQL> select empno,ename,job,dname,loc from emp natural join dept;
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
333 jagan manager INVENTORY HYBD
222 sudha clerk FINANCE BGLR
5. CROSS JOIN
This will gives the cross product.
Ex:SQL> select empno,ename,job,dname,loc from emp cross join dept;
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
222 sudha clerk INVENTORY HYBD
333 jagan manager INVENTORY HYBD
444 madhu engineer INVENTORY HYBD
111 saketh analyst FINANCE BGLR
222 sudha clerk FINANCE BGLR
333 jagan manager FINANCE BGLR
444 madhu engineer FINANCE BGLR
111 saketh analyst HR MUMBAI
222 sudha clerk HR MUMBAI
333 jagan manager HR MUMBAI
444 madhu engineer HR MUMBAI
6. OUTER JOIN
Outer join gives the non-matching records along with matching records.
LEFT OUTER JOIN
This will display the all matching records and the records which are in left hand side table those that are not
in right hand side table.
Ex:SQL> select empno,ename,job,dname,loc from emp e left outer join dept d
on(e.deptno=d.deptno); Or
SQL> select empno,ename,job,dname,loc from emp e,dept d where
e.deptno=d.deptno(+);
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
333 jagan manager INVENTORY HYBD
222 sudha clerk FINANCE BGLR
444 madhu engineer

RIGHT OUTER JOIN


This will display the all matching records and the records which are in right hand side table those that are
not in left hand side table.
Ex:SQL> select empno,ename,job,dname,loc from emp e right outer join dept d
on(e.deptno=d.deptno);Or
SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno(+) =
d.deptno;
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
333 jagan manager INVENTORY HYBD
222 sudha clerk FINANCE BGLR
HR MUMBAI
FULL OUTER JOIN
This will display the all matching records and the non-matching records from both tables.
Ex:
SQL> select empno,ename,job,dname,loc from emp e full outer join dept d
on(e.deptno=d.deptno);
EMPNO ENAME JOB DNAME LOC
333 jagan manager INVENTORY HYBD
111 saketh analyst INVENTORY HYBD
222 sudha clerk FINANCE BGLR
444 madhu engineer
HR MUMBAI
7. INNER JOIN
This will display all the records that have matched.
Ex:SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno);
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
333 jagan manager INVENTORY HYBD
222 sudha clerkx` FINANCE BGLR
7) short notes on set operators in sql
In SQL (Structured Query Language), set operators allow you to perform operations on the results of two or
more SELECT queries. These operators enable you to combine, compare, and manipulate data from
different tables or queries. Here are the main set operators in SQL:
1. UNION:
 The UNION operator combines the results of two or more SELECT queries and removes duplicate
rows, presenting a single result set.
 The syntax is: SELECT column1, column2 FROM table1 UNION SELECT column1, column2
FROM table2;
 Note that the number of columns and their data types must be the same in all SELECT queries
involved.
2. UNION ALL:
 The UNION ALL operator is similar to UNION but retains duplicate rows in the final result set.
 The syntax is: SELECT column1, column2 FROM table1 UNION ALL SELECT column1,
column2 FROM table2;
3. INTERSECT:
 The INTERSECT operator returns only the rows that appear in both SELECT queries. It finds the
common elements between the two result sets.
 The syntax is: SELECT column1, column2 FROM table1 INTERSECT SELECT column1,
column2 FROM table2;
 Like UNION, the number of columns and their data types must match in both SELECT queries.
4. EXCEPT (or MINUS in some database systems):
 The EXCEPT operator returns the distinct rows from the first SELECT query that do not appear in
the second SELECT query.
 The syntax is: SELECT column1, column2 FROM table1 EXCEPT SELECT column1,
column2 FROM table2;
 As with INTERSECT and UNION, the number of columns and their data types must match.
5. NOT EXISTS:
 While not a traditional set operator, the NOT EXISTS clause allows you to check for the absence of
matching rows between two queries based on a specific condition.
 The syntax is often used with a subquery: SELECT column1, column2 FROM table1 WHERE
NOT EXISTS (SELECT 1 FROM table2 WHERE table1.column1 = table2.column1);
These set operators are powerful tools for data manipulation and are used to combine or compare
datasets to extract relevant information. When using set operators, it's essential to ensure that the
columns' data types and the number of columns in the participating queries are compatible to avoid
errors.
8) write a short note on views concept in sql with example
In SQL, a view is a virtual table derived from one or more tables or other views. It does not store data on its
own but rather presents the data from the underlying tables in a structured manner. Views allow users to
encapsulate complex queries, provide a security layer by limiting data access, and simplify the querying
process by abstracting underlying table structures.
Creating a view involves defining the SELECT query that will populate the view with data. Once created,
the view can be queried like a regular table, providing a convenient and consistent way to access specific
data subsets. Let's illustrate this with a simple example:
Suppose we have a database with two tables: "Employees" and "Departments." The "Employees" table
contains the following columns: emp_id, emp_name, emp_salary, and dept_id. The "Departments" table
contains dept_id and dept_name.
1. Employees table:
2. | emp_id | emp_name | emp_salary | dept_id |
3. |1 | John | 50000 |1 |
4. |2 | Alice | 60000 |2 |
5. |3 | Bob | 55000 |1 |
6. |4 | Eve | 48000 |3 |
2. Departments table:
3. | dept_id | dept_name |
4. |1 | IT |
5. |2 | Finance |
6. |3 | Marketing |
Now, let's create a view that shows the employee's name, salary, and the correspondin
correspondingg department name
instead of the department ID.
CREATE VIEW EmployeeDetails AS
SELECT emp_name, emp_salary, dept_name
FROM Employees
JOIN Departments ON Employees.dept_id = Departments.dept_id;

The above SQL code creates a view named "EmployeeDetails" tha


thatt combines data from both the
"Employees" and "Departments" tables based on the department ID.
Now, we can query the view:SELECT
SELECT * FROM EmployeeDetails;
The result would be:
| emp_name | emp_salary | dept_name |
| John | 50000 | IT |
| Alice | 60000 | Finance |
| Bob | 55000 | IT |
| Eve | 48000 | Marketing |
With the view in place,
lace, we can easily access the employee details along with the department names without
having to write complex join queries every time.Remember that views are read-only,
read only, meaning you cannot
use them to perform insert, update, or delete operations directly. Changes to the data should be made
through the underlying base tables.
9) sub queries concept with example
In SQL, a subquery (also known as an inner query or nested query) is a query embedded within another
query. Subqueries are used to retrieve data that
that will be used as a condition or a value in the outer query.
They allow for complex queries to be broken down into smaller, more manageable parts. Here's a short note
with an example to illustrate the concept of subqueries:
Example: Let's consider two tables:
bles: "Employees" and "Departments."

Example of a Subquery: Suppose we want to retrieve the names of employees who work in the "Marketing"
department. We can use a subquery to achieve this:
SELECT first_name, last_name, salary
FROM employees
WHERE department = 'IT'
AND salary > (SELECT AVG(salary) FROM salaries);
In this examples:
1)select ename from emp where sal=(select
select max(sal) from emp
emp);
2) select name from employees where departmentid = (select
select departmentid from departments where
departmentname = 'marketing')
1. The inner subquery (SELECT DepartmentID FROM Departments WHERE DepartmentName =
'Marketing') retrieves the DepartmentID for the department with the name 'Marketing' from the
"Departments" table.
2. The outer query SELECT Name FROM Employees WHERE DepartmentID = ... filters the rows from
the "Employees" table, matching the DepartmentID obtained from the subquery, and returns the names of
employees who work in the Marketing department.

The subquery is executed first, and its result is used in the outer query to determine which employees' names
to retrieve. Subqueries can be used in various parts of SQL statements, such as the SELECT, FROM,
WHERE, HAVING, and JOIN clauses, depending on the specific requirement.Subqueries allow for a more
modular and organized approach to querying the database, making SQL queries more flexible and powerful.
However, it's essential to use subqueries judiciously and consider their potential impact on performance, as
they can add complexity and overhead to the query execution.
UNIT-5:PL/SQL
INTRODUCTION TO PL/SQL& STRUCTURE OF PL/SQL PROGRAM
PL/SQL (Procedural Language/Structured Query Language) is an extension of SQL used in Oracle Database
systems. It is a powerful and versatile programming language designed to enhance SQL's capabilities by
allowing procedural constructs, such as loops, conditions, and exception handling, to be incorporated
directly into the database environment.
Introduction: It is a development tool that not only supports SQL data manipulation but also provides
facilities of conditional checking, branching and looping. It sends an entire block of SQL statements to the
oracle engine all in one go. It also permits dealings with errors as required and facilitates displaying user-
friendly messages when errors are encountered.
Structure of PL/SQL:
SQL> Declare
Declarations;
Begin
Executable statements;
[Exception
Exception handler;]
End;

Elaborate structure of pl/sql program:-


PL/SQL (Procedural Language/Structured Query Language) is Oracle's extension of SQL, which allows for
the creation of stored procedures, functions, and anonymous blocks of code. The structure of a PL/SQL
program typically follows a standard pattern:
1. DECLARE: This optional section is used to define any variables, constants, cursors, or user-defined types
that will be used within the program. It sets up the program's data structures.
2. BEGIN: This mandatory section is where the actual program logic resides. It contains the sequence of
statements that perform specific tasks, calculations, or data manipulations.
3. EXCEPTION: Also optional, this section handles exceptions or errors that may occur during the execution
of the program. It allows you to gracefully manage errors and take appropriate actions.
4. END: This is the end of the PL/SQL block. It marks the conclusion of the program and doesn't require a
semicolon at the end.Putting it all together:
DECLARE
emp_name VARCHAR2(100);
emp_salary NUMBER(10, 2);
BEGIN
-- Assigning values to variables
emp_name := 'John Doe';
emp_salary := 50000;
-- Rest of the program
EXCEPTION
WHEN OTHERS THEN
-- Exception handling code
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;;
PL/SQL Program for Arithmetic Operations:
declare
a number:=&a;
b number:=&b;
begin
dbms_output.put_line('Addition is:'||(a+b));
dbms_output.put_line('Subtraction is:'||(a-b));
dbms_output.put_line('Multiplication is:'||(a*b));
dbms_output.put_line('Division is:'||(a/b));
end;
Output:
Enter value for a: 20
old 2: a number:=&a;
new 2: a number:=20;
Enter value for b: 10
old 3: b number:=&b;
new 3: b number:=10;

Addition is:30
Subtraction is:10
Multiplication is:200
Division is:2
PL/SQL procedure successfully completed.
SHORT NOTE ON DATA TYPES OF PL/SQL
PL/SQL (Procedural Language/Structured Query Language) is an extension of SQL used in Oracle Database
to write procedural code. It supports various data types to store different types of data. Here's a short note on
the data types in PL/SQL:
1. Scalar Data Types:
 NUMBER: Used for numeric data, including integers and decimals.
 VARCHAR2/CHAR: Used for character strings. VARCHAR2 is variable-length, while CHAR is
fixed-length.
 DATE: Used for date and time values.
 BOOLEAN: Used for Boolean values (TRUE, FALSE, or NULL).
2. Composite Data Types:
 RECORD: Used to hold a related set of variables of different data types, like a structure in other
programming languages.
 TABLE: Used to store collections of data. PL/SQL supports nested tables, associative arrays (index-
by tables), and variable-sized arrays.
3. Reference Data Types:
 REF CURSOR: Used to reference a cursor variable, enabling dynamic SQL and query result
retrieval.
 %TYPE and %ROWTYPE: These are not actual data types but rather placeholders used to define
variables based on the data type of a column or an entire row in a table, respectively.
4. LOB Data Types:
 CLOB: Used for large character objects, storing character data up to 4GB.
 BLOB: Used for large binary objects, such as images or binary data, up to 4GB.
 NCLOB: Used for large character objects with a national character set, up to 4GB.
 BFILE: Used to store binary data in operating system files, linked to the database.

4) SHORT NOTE ON OPERATOR PRECEDENCE OF PL/SQL


PL/SQL's ability to combine SQL's data manipulation power with procedural programming constructs
makes it a valuable tool for developing efficient and feature-rich database applications in Oracle
environments.
Let's see an example to understand how operator precedence works in PL/SQL:
DECLARE
a INT := 10;
b INT := 5;
c INT := 3;
result INT;
BEGIN
result := a + b * c; -- Multiplication has higher precedence than addition.
DBMS_OUTPUT.PUT_LINE('Result: ' || result); -- Output: Result: 25
END;
In the example, even though addition and multiplication are present in the same expression, the
multiplication is performed first because of its higher precedence. If we wanted the addition to be evaluated
first, we could use parentheses to explicitly set the precedence.

3. Explain control structure or control statements?

Control Structures:The follow of control statements can be classified into the following categories.

1. Conditional control
2. Iterative control
3. Jump statements

1. Conditional control
Conditional control, which run different statements for different data values.
if statement
i. If then statement
ii. If then else statement
iii. If then else if statement
iv. Nested if statement

1. If then statement
If condition is true it can execute statement 1 to statement n otherwise it cannot execute statement 1
to statement n.
Syntax:
if(condition) then
statement 1;
……………
statement n;
end if;
Example:
declare
a number:=&a;
begin
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if; end;/
2. if then else statement
If condition is true it can execute statement 1.
If the condition is false it execute else statement or execute statement 2.
Syntax:
if(condition) then
statement1;
else statement2;
end if; Example:
declare
a number:=&a;
b number:=&b;
begin
if(a>b) then dbms_output.put_line(‘a is
big’);else
dbms_output.put_line(‘b is big’);end if;
end;
3. if then else if statement:
If condition is true it can execute statement 1.
If the condition is false its again check for another condition if it is true it can execute statement 2.
Other execute else statement or execute statement 3.
Syntax:
if(condition) then
statement1;
else if(condition) then
statement2;
else statement3;
end if;
Example:
declare
a number:=&a;b
number:=&b;
c number:=&c;
begin
if(a>b and a>c)
then
dbms_output.put_li
ne(‘a is big’);else
if(b>c) then
dbms_output.put_li
ne(‘b is big’);
else
dbms_output.put_li
ne(‘c is big’);
end if;
end;

4.Nested if statement:

Inner if is called nested if. if condition is false it execute statement3.


Other wise it is true its check for another condition if it is true it execute statement1
other wise execute statement2.
Syntax:
if(condition)
then if(condition)
then statement1;
else statement2;
end if;
else statement3;
end if;
Example:
declare
a number:=&a; b
number:=&b; c
number:=&c;begin
if(a>b) thenif(a>c) then
dbms_output.put_line(‘a is big’);
else
dbms_output.put_line(‘c is big’);
end if;
else if(b>c) dbms_output.put_line(‘b is
big’);
else
dbms_output.put_line(‘c is big’);end if;
end;
LOOPING STATEMENTS:
1. for loop
PL/SQL for loop is used when when you want to execute a set of statements for a predetermined
number of times. The loop is iterated between the start and end integer values.
syntax of for loop:
for variable in initial_value …. final_valueloop
statements;
end loop;
example:
declare
i number:=1;
begin
for i in 1…..10
loop
dbms_output.put_line(i);
end loop;
2. while loop: PL/SQL while loop is used when a set of statements has to be executed as longas
a condition is true.
syntax:
while <condition>
loop statements; end
loop;
Example:
declare
i integer := 1;
begin
while i <= 10 loop
dbms_output.put_line(i); i :=
i+1;
end loop;
end; output:
1
2…1
Simple loop:This is the simple loop syntax
Syntax:
loop statement;
………….
………… end
loop;
Example:
loop dbms_output.put_line(‘dbms’);
end loop;
3. JUMP STATEMENTS:
Goto statement:
Pl/ SQL GOTO statement is used for transferring the control and flow of execution from one
point to the other which is a labeled block or singlestatement with a label.
Example:
begin
goto header_message;
<<greeting_message>>
dbms_output.put_line( 'hi' );goto
ending_message;
<<header_message>>
dbms_output.put_line( ' demonstration of working of pl/ sql goto statement ' ); goto
greeting_message;
<<ending_message>>
dbms_output.put_line( 'wish you all the best for your learnings...' );end;
Output:

Continue statement:
The CONTINUE statement causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
Syntax:Continue; example:
When the above code is executed at the SQL prompt, it produces the following result −
declare
a number(2) :=
10; begin
-- while loop execution
while a < 20 loop
dbms_output.put_line ('value of a: ' ||
a);a := a + 1;
if a = 15 then
-- skip the loop using the continue statement
a := a + 1;
continue
;end if;
end
loop;end;
/
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

4. Explain Cursors?Types of cursors?steps to create a cursors?


1. pointer to a memory location that the DBMS uses to process a sql Query.
2.use a retrieve and manipulate database data.

There are two types of Cursors.


 Implicit Cursors
 Explicit Cursors
Implicit cursor:
 Executing a SELECT query creates an implicit cursor.
 Can only be used with queries that return exactly one record.
Explicit cursor:
 Use for queries that return multiple records.
 Must be explicitly declared and used.
Using an Explicit cursor:
 Declare the cursor
 Open the cursor
 Fetch the cursor
 Close the cursor
Example:
declare
name emp.ename%type;
work emp.job%type;
cursor c1 is select ename,job from emp;
begin
open c1;
loop
fetch c1 into name,work;
exit when c1%not found;
dbms_output.put_line(name ||’is working as’||work);
end loop;
close c1;
end;
/
Output:
Ravi is working as accountant
Raju is working as manager
Swathi is working as HR
7. Explain procedure in PL/SQL?
PL/SQL Procedure
1.A procedure is a sub program and it performs a specific task. 2.The
procedure is used to reduce the code.
3. It represents clarity of the program.
4. The procedure can be defined with the help of create or replace command.
Syntax:
create or replace procedure procedurename(args) as
variable declaration;
begin
statements;
end;
example:
create or replace procedure add(a in number,b in number) as c
in number;
begin
c:=a+b;
dbms_output.put_line( c );
end;
/
Output:
Enter value a:=2
Enter value b:=3
C:=5
8. Explain functions in PL/SQL?
1.A function is a sub program and it perform a specific task.
2.The function is used to reduce the code.
3. It represents clarity of a program.
4. The function can be defined with the help of create or replace command.
Syntax:
create or replace function functionname(args)
return datatype is
variable declaration;
begin
statements;
return(variable);
end;
Example:
create or replace function adder(a in number, b in number)
return number
is
c in number;

begin
c :=a+b;
return( c );
end;
/
Output:
Enter a value:5
Enter b value:2
C:=7

9. Explain Triggers?Types of Triggers?


Triggers in oracle are blocks of PL/SQL code which oracle engine can execute automatically
based on some action or event.
These events can be:
 DDL statements (CREATE, ALTER, DROP, TRUNCATE)
 DML statements (INSERT, SELECT, UPDATE, DELETE)
 Database operation like connecting or disconnecting to oracle (LOGON, LOGOFF,
SHUTDOWN)
PL/SQL: Types of Triggers
The above diagram clearly indicated that Triggers can be classified into threecategories:
1. Level Triggers
2. Event Triggers
3. Timing Triggers
Level Triggers

There are 2 different types of level triggers, they are:


1. ROW LEVEL TRIGGERS
 It fires for every record that got affected with the execution of DML
statements like INSERT, UPDATE, DELETE etc.
 It always use a FOR EACH ROW clause in a triggering statement.
2. STATEMENT LEVEL TRIGGERS
 It fires once for each statement that is executed.

Event Triggers

There are 3 different types of event triggers, they are:


1. DDL EVENT TRIGGER
 It fires with the execution of every DDL statement(CREATE, ALTER,
DROP, TRUNCATE).
2. DML EVENT TRIGGER
 It fires with the execution of every DML statement(INSERT, UPDATE,
DELETE).
3. DATABASE EVENT TRIGGER
 It fires with the execution of every database operation which can beLOGON,
LOGOFF, SHUTDOWN, SERVERERROR etc.

Timing Triggers

There are 2 different types of timing triggers, they are:


 BEFORE TRIGGER
 It fires before executing DML statement.
 Triggering statement may or may not executed depending upon thebefore
condition block.
 AFTER TRIGGER
 It fires after executing DML statement.
Syntax for creating triggers:

create or replace trigger triggername (before/after)(insert/update/delete) on tablename for each row


begin
statement; end;
EXAMPLE
create or replace trigger t after insert on student for each rowbegin
update student set tot=m1+m2+m3;
end;
/
PL/SQL program to make a table for read only using triggers
create or replace trigger emptrg before insert or update or delete on empl08 for each row
declare
begin
raise_application_error(-20000,'Table is in Read Only mode');
end;
Output:
SQL> @ z:\dbms\emptrg.sql
6 /
Trigger created.
After executing trigger inserting a record in empl08 table:
SQL> insert into empl08 values(&eno,'&ename','&dsgn',&sal);
Enter value for eno: 107
Enter value for ename: Ram
Enter value for dsgn: Mgr
Enter value for sal: 12000
old 1: insert into empl08 values(&eno,'&ename','&dsgn',&sal)
new 1: insert into empl08 values(107,'Ram','Mgr',12000)
insert into empl08 values(107,'Ram','Mgr',12000)
*
ERROR at line 1:
ORA-20000: Table is in Read Only mode
ORA-06512: at "SCOTT.EMPTRG", line 3
ORA-04088: error during execution of trigger 'SCOTT.EMPTRG'

You might also like