0% found this document useful (0 votes)
32 views84 pages

4th Sem BSC Dbms

The document provides an overview of Database Management Systems (DBMS), explaining the concepts of data and information, the structure and purpose of DBMS, and its advantages over traditional file systems. It details the components of a DBMS, including hardware, software, people, procedures, and data, as well as the levels of data abstraction defined by the ANSI/SPARC architecture. The document emphasizes the importance of DBMS in managing large volumes of data efficiently and securely.

Uploaded by

Krish Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views84 pages

4th Sem BSC Dbms

The document provides an overview of Database Management Systems (DBMS), explaining the concepts of data and information, the structure and purpose of DBMS, and its advantages over traditional file systems. It details the components of a DBMS, including hardware, software, people, procedures, and data, as well as the levels of data abstraction defined by the ANSI/SPARC architecture. The document emphasizes the importance of DBMS in managing large volumes of data efficiently and securely.

Uploaded by

Krish Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 84

RAO’S DEGREE COLLEGE::NELLORE

“DBMS”

Bsc(CS)
CLASS – BCA IV SEMESTER

(Source of Grasping Subject & Gaining Marks)

“THE FEAR OF THE


LORD
IS THE BEGINNING OF WISDOM"
INTRODUCTION AND FUNDAMENTALS
DATA: The collection of “raw facts” is called data. The word raw indicates that the facts have not yet been processed
to know their meaning. The data doesn’t have any specific meaning. The data may be numeric, text, audio, video
etc. The data can be processed to get information. The raw data must be properly formatted for storage, processing
and presentation.
Example: Raw Data:
1 BBB 50 70
6 CCC 90 90
2 AAA 70 40
9 DDD 30 50
INFORMATION: The collection of processed data is called information. The information has a specific meaning. The
information can be in a table format or graphical format.
In this “information age”, production of accurate, relevant, and timely information is the key to good decision
making. Timely and useful information requires accurate data.
Example:
a) Information in Table format:
STNO STNAME SUB 1 SUB 2 TOTAL PERC
1 BBB 50 70 120 60.0
6 CCC 90 90 180 90.0
2 AAA 70 40 110 55.0
9 DDD 30 50 80 40.0
Data Dictionary:
Data dictionary is the table which contains the information about database objects. It
contains information like
1. external, conceptual and internal database description
2. description of entities , attributes as well as meaning of data elements
3. synonyms, authorization and security codes
4. database authorization
The data stored in the data dictionary is called meta data.
The terms data and information can be used interchangeably. But it is very essential to distinguish the data and
information.

Data Processing Information

Fig : Data and Information.

1. Give the introduction of DBMS.

Introduction:- DBMS stands for Database Management System. We can break it like this
DBMS = Database + Management System. Database is a collection of data and Management System is a set of
programs to store and retrieve those data. Based on this we can define DBMS like this: DBMS is a collection of
inter-related data and set of programs to store & access those data in an easy and effective manner.
Database systems are basically developed for large amount of data. When dealing with huge amount of data,
there are two things that require optimization: Storage of data and retrieval of data.
Storage: According to the principles of database systems, the data is stored in such a way that it acquires lot less
space as the redundant data (duplicate data) has been removed before storage.
Fast Retrieval of data: Along with storing the data in an optimized and systematic manner, it is also important that
we retrieve the data quickly when needed. Database systems ensure that the data is retrieved as quickly as possible.
The main purpose of database systems is to manage the data. Consider a university that keeps the data of
students, teachers, courses, books etc. To manage this data we need to store this data somewhere where we can add
new data, delete unused data, update outdated data, retrieve data, to perform these operations on data we need a
Database management system that allows us to store the data in such a way so that all these operations can be
performed on the data efficiently.
Explain about the objectives of DBMS.
Database management system has made a revolution in all the industries that handles lots of data. All these
organizations are making a huge profit just because of database management system. This is why because DBMS
provides a lot benefits to all these companies and there are lots of objectives of using a database management system.
The following are the various Objectives of Database Management System.
Mass Storage :-DBMS can store a lot of data in it. So for all the big firms, DBMS is really ideal technology to use.
It can store thousands of records in it and one can fetch all that data whenever it is needed.
Removes Duplicity :-If you have lots of data then data duplicity will occur for sure at any instance. DBMS guarantee
it that there will be no data duplicity among all the records. While storing new records, DBMS makes sure that same
data was not inserted before.
Multiple Users Access :- No one handles the whole database alone. There are lots of users who are able to access
database. So this situation may happen that two or more users are accessing database. They can change whatever they
want, at that time DBMS makes it sure that they can work concurrently.
Data Protection:-Information such as bank details, employee’s salary details and sale purchase details should always
be kept secured. Also all the companies need their data secured from unauthorized use. DBMS gives a master level
security to their data. No one can alter or modify the information without the privilege of using that data.
Data Back up and recovery :- Sometimes database failure occurs so there is no option like one can say that all the
data has been lost. There should be a backup of database so that on database failure it can be recovered. DBMS has
the ability to backup and recover all the data in database.
Everyone can work on DBMS :- There is no need to be a master of programming language if you want to work on
DBMS. Any accountant who is having less technical knowledge can work on DBMS. All the definitions and
descriptions are given in it so that even a non-technical background person can work on it.
Integrity :- Integrity means the data is authentic and consistent. DBMS has various validity checks that make your
data completely accurate and consistence.
Platform Independent :- One can run dbms at any platform. No particular platform is required to work on database
management system.
FILES AND FILE SYSTEMS
FILES
A file is a collection of bytes. All data is stored as a file with a file name that is unique within the disk. The
structure of a file is known to the software that manipulates it.
In early processing systems, an organization’s information was stored as groups of records in separate files.
These file processing systems consist of few data files and many application programs. Programmers use
programming languages such as COBOL, C and C++ to write applications to access files to perform data management.
As systems became more complex, file processing system had little flexibility and difficult to maintain.
Basic File terminology:
Data: Data are raw facts, such as student number, marks etc. Data have little meaning unless they have been
processed properly. The smallest piece of data that can be recognized by the computer is a single character, such as
an alphabet, digit or symbol. A single character requires 1 byte of computer storage.
Field: A character or group of characters (alphabetic or numeric) that has a specific meaning. A .field is used to
define and store data.
Record: A set of one or more fields that describes a person, place, or thing. For example, the fields that constitute a
record for a student may consist of name, address, phone number, date of birth, etc.
File: A collection of related records is called a file. For example, a file might contain data about students of a
college, or a file might contain the records for the customers of a bank etc.
ADVANTAGES:
1. The data files can be easily located in memory devices.
2. They occupy less space in memory devices.
3. They can be opened in any editor like any other text files.

DISADVANTAGES (PROBLEMS WITH FILE SYSTEMS):


There are some disadvantages with the file oriented approach. They are
1. Program-data dependency: In file oriented approach, each and every program maintains the file
descriptions. If any changes made to the file structure then it requires changes in all programs. So the
program and data are dependent to each other.
2. Data redundancy and inconsistency: In file systems, the same information may be duplicated in several files.
So the repetition of data increases memory wastage and inconsistency in the data.
3 .Difficulty in accessing data: It is difficult to easily retrieve required data in file processing systems. They
require programs to access needed data.
4. Recovery problems: When a failure occurs in file processing system, it is difficult to restore the data to the
consistent state that existed prior to the failure.
5. Lengthy development:File oriented approach takes more time to develop the application programs. Each
and every change of a file requires changes in all application programs.
6.Integrity problems:In file oriented approach, it is difficult to maintain integrity constraints. Hence invalid data
can be entered in to data files.
7 Sharing problems: In file oriented systems, it is difficult to share the data among several users. It requires
programs for sharing of data.
8. Security problems: In file processing systems, there is no centralized system to control the data. So it is not
possible to provide better securities to the data files.
DATBASE AND DBMS
DATABASE: A database is the collection of logically interrelated data about a particular organization. It is a
shared, integrated computer structure end user data and metadata. A database is developed to quickly
retrieve needed data. For example, Bank database, hospital database, library database and so on.
End user data is the raw facts defined by the user.

Metadata: Meta data means data about data. It provides detailed description of characteristics or properties of
other data. It contains details like data type, field size, and allowable values. For example the Meta data for a
student database is
Colum Name Data type Width Min value Max value Description
STNO Number 5 1 199 Student
Number
STNAME Varchar2 20 ---- ----- Student Name
SUBI Number 3 0 100 Subject 1 Marks
SUB2 Number 3 0 100 Subject2 Marks

DBMS: DBMS means database management system. It is a collection of programs that manage the
database structure and control access to the data stored in the database. It provides user to store,
modify and extracts information from a database.
ADVANTAGES OF THE DATABASE MANGEMENT SYSTEMS
The database management system has number of advantages as compared to file based processing system.
They are
Program-data independency
In database system, the data descriptions are stored in a central location called “data dictionary”. The
application programs are stored separately in database system. The changes in the data do not require
changes in the programs. Hence the program and data are independent to each other.
1. Avoids data redundancy
The database system does not allow the repeated data into the database. The reduction of duplicated data
minimizes memory wastage. Hence consistent data can also be maintained in the database.
2. Easily accessing data
In database system, the end users without programming knowledge can easily access data from the database
using query languages.
4. No recovery problems
When a failure occurs in database system, it is easily restoring the data to the consistent state that existed prior
to the failure.
5. No Lengthy Development
Use of languages like SQL and PL|SQL, database approach takes less time to develop the application programs.
Each and every change does not require changes in all application programs.
6. Integrity can be maintained
In data base systems, integrity can be maintained easily by defining various constraints... So the data in the
database is always accurate
7.Data can be shared
In data base system, the database is shared among several users. Each user can access the required information
of the database at any time.
8.Prevents unauthorized access
In database system, there is a centralized control system for accessing database information. So it is provide
better securities to the database. The Database Administrator controls and manages database by using security
standards.
The DBMS supports many users to access the database information at a time. Database systems are designed
to manage large organizations’ like banks, universities, railways etc.
THE DATABASE SYSTEM ENVIRONMENT OR COMPONENTS OF A DATA BASE SYSTEM
A database management system (DBMS) consists of several components. Each component plays very important
role in the database management system environment. The major components of database management system
are:
1. Hardware
2. Software
3. People
4. Procedures
5. Data
1. HARDWARE: It refers to all the physical devices. For example, computers (micro, mainframe, super), storage
devices, printers, Input / Output devise, network devices, and other devices.
2. SOFTWARE: The working of the database system fully, it requires three types of software. They are operating
system soft ware, DBMS software, and application software.
a) Operating system Software: It manages all hardware components and makes it possible for all other
software to run on the computers. Examples of OS are Microsoft Windows, Unix, Linux etc.,
b) DBMS Software: It manages the database within the database system. Examples of DBMS software are
MS.Access, Oracle etc.,
c) Application Software: These are used to access and manipulate data in the DBMS. Examples are SQL,
PL/SQL, and other programming languages.
3. PEOPLE: The uses are the people who manage the databases and perform different operations on the
database.
i) Database Administrators (DBA): A person manages the overall database management system is
called Database Administrator
ii) Programmers are the persons, who design and imp0lement the application programs. They create
the data entry screens, reports and procedures through which end users access and manipulate
database’s data
iii) End Users: The end-users are the people who interact with database management system to insert,
update, delete and view data. They are also called data entry operators.
4. PROCEDURES: Procedures refer to the instructions and rules that help to design the database and to use the
database system.
5. DATA: Data is the most important component of the DBMS. The collection of “war facts” is called data. It
does not have any specific meaning. The data may be numeric, text, audio, video etc. The data can be
processed to get information.
 Ansi/Spark Data Model (American National Standard Institute/ Standards Planning and
Requirements Committee) (Or)Explain Degree of Data abstraction.(Or)Explain the levels of Data
abstraction.(Or)Explain three schema architecture

1. In the early 1970s the (American National Standards Institute) ANSI (standards planning and
Requirements committee) SPARC defined a framework for data modeling based on degrees of
data abstraction.
2. The ANSI/SPARC architecture defines three levels of data abstractions:
a. External,
b. conceptual and
c. Internal.
3. The ANSI/SPARC framework has been expanded with the addition of a physical model to
explicitly address physical level implementation address physical level implementation details
of the internal model.
The different levels of data abstraction are:

1. Physical level or internal level

2. Logical level or conceptual level

3. View level or external level

In the above diagram:


o It shows the DBMS architecture.
o Mapping is used to transform the request and response between various database levels
of architecture.
o Mapping is not good for small DBMS because it takes more time.
o In External / Conceptual mapping, it is necessary to transform the request from external
level to conceptual schema.
o In Conceptual / Internal mapping, DBMS transform the request from the conceptual to
internal level.

1. Internal Level
o The internal level has an internal schema which describes the physical storage structure of
the database.
o The internal schema is also known as a physical schema.
o It uses the physical data model. It is used to define that how the data will be stored in a block.
o The physical level is used to describe complex low-level data structures in detail.
2. Conceptual Level
o The conceptual schema describes the design of a database at the conceptual level.
Conceptual level is also known as logical level.
o The conceptual schema describes the structure of the whole database.
o The conceptual level describes what data are to be stored in the database and also
describes what relationship exists among those data.
o In the conceptual level, internal details such as an implementation of the data structure
are hidden.
o Programmers and database administrators work at this level.

3. External Level
o At the external level, a database contains several schemas that sometimes called as
subschema. The subschema is used to describe the different view of the database.
o An external schema is also known as view schema.
o Each view schema describes the database part that a particular user group is interested
and hides the remaining database from that user group.
The view schema describes the end user interaction with database systems.
8) Database System versus File System
DBMS File Processing System

Minimal data redundancy problem in


Data Redundancy problem exits
DBMS

Data Inconsistency does not exist Data Inconsistency exist here

Accessing database is easier Accessing is comparatively difficult

Data is scattered in various files and files may be of


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

Transactions like insert, delete, view,


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

Concurrent access and recovery is


Concurrent access and recovery is not possible
possible in database

Security of data Security of data is not good

A database manager (administrator)


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

DATA MODELS:
Hierarchical Data Model: Mid 1960s Rockwell collaborates with IBM to create the Information Management System
(IMS), IMS lead the mainframe database market in 70’s and early 80’s.
In this model, files are related in a parent/child manner, with each child file having at most one parent file.
Advantages Limitations

Efficient searching. Complex implementation

Less redundant data. Difficult to manage and lack of standards,


can’t easily handle many-many relationships.

Data independence. Lacks structural independence.

Database security and integrity.

Network Data Model:-


Early 1960s, Charles Bachmann developed first DBMS at Honeywell, Integrated Data Store (IDS)
It standardized in 1971 by the CODASYL group (Conference on Data Systems Languages).
In Network data model, files are related as owners and members, similar to the common network model except that
each member file can have more than one owner.
Network data model identified the following three database components:

1. Network schema—database organization[structure]


2. Sub-schema—view s of database per user
3. Data management language — at low level , procedural

4.
Advantages Limitations

Ability to handle more relationship System complexity and difficult to design


types and maintain

Ease of data access Lack of structural independence as data


access method is navigational.

Data Integrity

Data Independence
5. Object Oriented Database Model:

It supports the modeling and creation of the data as objects.

Advantages Limitations

Can efficiently manage a large number of Switching an existing database to OODBMS


different data types. requires an entire change from scratch.

Objects with complex behaviors are easy to An OODBMS is typically tied to a specific
handle using inheritance and polymorphism etc. programming language and an API; this reduces
its flexibility.

Reduces the large number of relations by Ad-hoc queries are difficult to implement as one
creating objects. cannot join two classes as one can join two
tables in RDBMS. Therefore, queries depend
upon the design of the system.

Creates problems when deleting data in bulk.

Object Relational Database Model:


Object relational databases span the object and relational concepts.

Advantages Limitations

Large storage capacity The architecture of the object relational model


is not appropriate for web applications.

High access speed

Schema and sub-schema :


A schema is a logical data base description and is drawn as a chart of the types of data that are
used . It gives the names of the entities and attributes and specify the relationships between them.
A database schema includes such information as :
a) Characteristics of data items such as entities and attributes .
b) Logical structures and relationships among these data items .
c) Format for storage representation.
d) Integrity parameters such as physical authorization and back up policies.
A subschema is derived schema derived from existing schema as per the user requirement. There may
be more then one subschema create for a single conceptual schema

Costs & Risks of Database Approach:


The database approach emphasizes data integration and sharing across organizations. As with any
business decision, the database approach entails some additional costs and risks that must be
recognized and managed when implementing this approach. Mentionable some costs & risks of
database approach are as follows;

Figure: A sample of Cost and Risks of Database Approach


1. New Specialized Personnel: Frequently, organizations that adopt the database approach need
to hire or train individuals to design & implement databases, provide database administration
services and manage a staff of new people, further, because of the rapid changes in technology
these new people will have to be retrained or upgraded on a regular basis.
2. Installation & Management Costs and complexity: A multi-user database management system
is a large and complex suite of software that has a high initial cost, requires a staff of trained
personnel to install and operate, and also has substantial annual maintenance & support costs.
Installing such a system may also require upgrades to the hardware and data communications
system in the organization.
3. Conversion Costs: The cost of converting the traditional file processing systems to modern
database technology: measured in terms of money, time, and organizational commitment.
4. Need for explicit Backup & Recovery: A shared corporate database must be accurate and
available at all times. These require that comprehensive procedures be developed and used for
providing backup copies of data and for restoring a database when damage occurs.
5. Organizational Conflict: A shared database requires a consensus on data definitions and
ownership as well as responsibilities for accurate data maintenance. Experience has shown that
conflicts on data definitions, data formats, and coding, rights to update shared data are frequent
and often difficult to resolve.
Difference Between Schema and Instance
Schema Instance

It is the collection of information stored in a


It is the overall description of the database.
database at a particular moment.

Data in instances can be changed using


The schema is same for the whole database.
addition, deletion, and updation.

Does not change Frequently. Changes Frequently.

Defines the basic structure of the database i.e. how It is the set of Information stored at a
the data will be stored in the database. particular time.

UNIT-II
(ENTITY RELATIONAL DATA MODEL)
RELATIONAL DATABASE MODEL
The relational model was introduced by Dr.E.F.Codd in 1970. It is a conceptual theory of data based on the
mathematical theory of relations.
In a relation model, data is stored in tables. Three key items are used frequently in
Relational database
Models: relations, attributes, and domains.
6. A relation is a table with columns and rows.
7. The named columns of the relation are called attributes.
8. The domain is the set of values of the attributes.
LOGICAL VIEW OF DATA
The relational models allow users to view the data logically rather than physically. The logical view of the relational is
database is facilitated by the creation of data relationships through a table.
A Table of dimensional structure contains rows & columns. The data is stored in these rows & columns. A
table is also called relation.
For example: student table shown as
HTNO STNAME MARKS
101 AAA 90
102 BBB 20
103 CCC 80

Properties (or) characteristics of a Relation (or) Table:-


1) A table is viewed as a two dimensional structure that contains rows & columns.
2) Each attribute or column within a table has a unique name.
3) Only one value must be existed at the intersection of each row & column.
4) Each row in a table should be unique.
5) Each table must have an attribute (or) a combination of attributes that uniquely identifies
each row. It means each table have a primary key.
6) All values in a column must follow to the same data type.
1. BASIC BUILDING BLOCKS
The basic building blocks of all data models entities, attributes, relationships and constraints.
ENTITIES: An entity is a person, a place, an event, or a thing which about data are to be collected and stored. It
represents a particular type of an object in the real world.
Examples: Person: customer, Student, Employee etc.
Place : Nellore, India, America etc.
Event: Payment, reservation etc.
Thing: Pen, TV, Computer etc.
It represents as Rectangular box

ATTRIBUTES: An attribute is a property or a characteristic of an entity. Each entity is associated with a set of
attributes. The attributes are also called as fields.
It represents as

RELATIONSHIPS: A relationship describes an association between entities. Data models use 3 types of relationships.
It represents as

1. One – to – one Relationship: An entity instance is associated to only one instance of another entity.
Example: One employee can join only in one department.
2. One– to–many Relationship: An entity is associated to many instances of another entity.
Example: One employee can join in many departments.
3. Many– to–many Relationship: Many entity instances are associated to many instances of other
entity.
Example: Many employees can join in many departments.
CONSTRAINTS: A constraints is a condition or rule that is placed on the data. Constraints are more important to
maintain data integrity. The constraints can be domain, entity and referential.
Example: 1. An employee`s salary must not exceed than 3000.
2. A student`s marks must be between 0 to 100.
Explain about different types of entity sets in ER-Model.
An entity is a thing or an object which is distinguishable from other objects in the real world. Collection of entities of
same type is called as an ‘entity set’.
Ex:- STUDENT, EMPLOYEE, CAR, FAN, etc.
Entity sets can be classified in to two types. They are: (1). Strong Entity Set.
(2). Weak Entity Set.
(1). Strong Entity Set:- An entity set which has a key attribute(primary key or composite key) or identifier that
uniquely identifies each and every entity in an entity set can be denoted by the symbol ‘Rectangle’

Ex:-
Sno Sname

STUDENT

Address
Telephone
DOB

Empno Ename

EMPLOYEE

Address
Salary
DOJ

In the above example ‘Sno’ attribute is key attribute in ‘STUDENT’ entity set and ‘empno’ is the key attribute in
‘EMPLOYEE’ entity set.
(2). Weak Entity Set:- An entity set which does not have any key attribute or identifier is called as ‘Weak entity set’.
In ER-Model weak entity set is denoted by the symbol ‘Double Rectangle’

Dependent_Nam address
e

DEPENDENT

age Relationship
In the above example there is no unique identifier or key attribute for ‘DEPENDENT’ entity set. So, it is
considered as Weak entity set.

3. Explain about different types of attributes in ER-Model.


Properties of entities are called as attributes. Generally attributes are classified into following types:
1.Single-Valued attribute

2.Multi-Valued attribute

3.Simple attribute

4.Composite attribute

5.Stored attribute

6.Derived attribute
(1) Single-Valued attribute:- A Single-Valued attribute can have only one value for a given entity occurrence.
Ex:- sno, sname, empno, ename, etc.

sno sname empno ename


(2) Multi-Valued attribute:- A multi-valued attribute can have more than one value for a given entity occurrence.
Ex:-

Telephone_no

(3).Simple attribute:- The attribute which cannot be divided further is called as simple attribute.
Ex:-
empno

(4).Composite attribute:- The attribute which can be sub-divided further is called composite attribute.
Ex:- mname
streeet city
fname lname

name address

state pincode

country
(5).Stored attribute:- A stored attribute is an attribute about which the database designer wants to store data in the
database.
Ex:-
DOB
(6).Derived attribute:- A derived attribute is an attribute whose value can be computed from other stored attribute.
Ex:-
4. Explain about relationship degree and classification in ER-Model.
Relationship is an association among several entity sets. The degree of a relationship indicates that the number of
entities or entity sets that participate in that relationship. The following are the different types of relationship degrees.
1.Unary Relationship
2.Binary Relationship
3.Ternary Relationship
1.Unary Relationship:- The association is maintained with only one entity set then that relationship is called as unary
relationship. Ex:-

PERSON Marrie
d to

Fig : Unary Relationship


2.Binary Relationship:- When there is an association is maintained between two entity sets in a relationship then it is
called binary relationship. Majority of the relationships are binary relationships.

STUDENT COURSE
learn
s
Fig : Binary Relationship
3. Ternary Relationship:- When there is an association is maintained among 3-entity sets in a relationship then it is
called ternary relationship.

write receive PATIENT


DOCTOR PRESCRIPTION
s s

Fig : Ternary Relationship

Reducing E-R Diagrams to Tables


A database conforming to an E-R diagram can be represented by a collection of tables.
We'll use the E-R diagram of Reduction of ER diagram to Table The database can be represented
using the notations, and these notations can be reduced to a collection of tables.
In the database, every entity set or relationship set can be represented in tabular form.
The ER diagram is given below:
There are some points for converting the ER diagram to the table:
o Entity type becomes a table.
In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms individual tables.
o All single-valued attribute becomes a column for the table.
In the STUDENT entity, STUDENT_NAME and STUDENT_ID form the column of STUDENT table.
Similarly, COURSE_NAME and COURSE_ID form the column of COURSE table and so on.
o A key attribute of the entity type represented by the primary key.
In the given ER diagram, COURSE_ID, STUDENT_ID, SUBJECT_ID, and LECTURE_ID are the key attribute
of the entity.
o The multivalued attribute is represented by a separate table.
In the student table, a hobby is a multivalued attribute. So it is not possible to represent multiple values
in a single column of STUDENT table. Hence we create a table STUD_HOBBY with column name
STUDENT_ID and HOBBY. Using both the column, we create a composite key.
o Composite attribute represented by components.
In the given ER diagram, student address is a composite attribute. It contains CITY, PIN, DOOR#, STREET,
and STATE. In the STUDENT table, these attributes can merge as an individual column.
o Derived attributes are not considered in the table.
In the STUDENT table, Age is the derived attribute. It can be calculated at any point of time by
calculating the difference between current date and Date of Birth.
Using these rules, you can convert the ER diagram to tables and columns and assign the mapping
between the tables. Table structure for the given ER diagram is as below:
Figure: Table structure

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
These concepts are used when the comes in EER schema and the resulting schema diagrams called
as EER Diagrams.
Features of EER Model
 EER creates a design more accurate to database schemas.
 It reflects the data properties and constraints more precisely.
 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 of different 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.
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 level entity.
 Generalization is the reverse process of Specialization.
 It defines a general entity type from a set of specialized entity type.
 It minimizes the difference between the entities by identifying the common
features.
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 superclass/subclass
relationship.
For example
In the above example, Employee can be specialized as Developer or Tester, based on what role they play in an
Organization.
C. 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 least one of its super classes.

D. Aggregation
 Aggregation is a process that represent a relationship between a whole object and its component parts.
 It abstracts a relationship between objects and viewing the relationship as an object.
 It is a process when two entity is treated as a single entity.

In the above example, the relation between College and Course is acting as an Entity in Relation with Student.
2) ISA Relationship and Attribute Inheritance
IS A relationship supports attribute inheritance and relationship participation. In the EER

diagram, the subclass relationship is represented by ISA relationship. Attribute

inheritance is the property by which subclass entities inherit values for all attributes of

the superclass.Consider the example ofEMPLOYEEentity set in a bank. TheEMPLOYEE in

a bank can be CLERK, MANAGER, CASHIER, ACCOUNTANT, etc. It is to be observed that

the CLERK, MANAGER, CASHIER, ACCOUNTANT

inherit some of the attributes of the EMPLOYEE.

In this example the superclass is EMPLOYEE and the subclasses are CLERK,

MANAGER, and CASHIER. The subclasses inherit the attributes


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

A subclass with more than one superclass is called a shared subclass. A subclass inherits attributes
not only of its direct superclass, but also of all its predecessor superclass, that is it has multiple
inheritance from its super classes. In multiple inheritance a subclass can be subclass of more than
one superclass.
Constraints on Specialization and Generalization
The constraints on specialization and generalization can be broadly classified into
disjointness and completeness. The dis jointness constraint allows us to specify whether an
instance of a super type may simultaneously be a member of two or more subtypes. In dis
jointness we have two categories (1) Overlap and
(2) Disjoint. In completeness we have two categories

(1) Total and (2) Partial

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

Disjoint Constraint
Disjoint refers to the fact that the same entity instance may be a member of only one subclass of the
specialization.
Example of Di jointness Constraint
Consider the example of CATALOGUE. The CATALOGUE is a superclass,
which can be further subdivided into BOOKS, JOURNALS, and PERIODICALS. This falls under disjoint Ness
because a BOOK entity can be neither JOURNAL nor PERIODICAL.
Total Specialization
Total completeness refers to the fact that every entity instance in the superclass must be a member of
some subclass in the specialization. With total specialization, an instance of the supertype must be a
member of at least one subtype.

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

Advantages OF ER Modeling:-
1. SIMPLE : It is simple to draw an ER diagram when we know entities and relationships.
2. EFFECTIVE : It is an effective communication tool.
3. EASY TO UNDERSTAND : The design of ER is very logical and hence they are easy to design and
understand.They show database capabilities like how tables, keys and columns are used to find a
solution to the given question.
4. INTEGRATED : The ER Model can be easily integrated with relational model.
5. USEFUL IN DECISION MAKING : Since some of the entities in the database are analyzed by an ER-Diagram,
So by drawing an ER-Diagram we come to know what kind of attributes and relationship exist between them.
6. EASY CONVERTION : It can be easily converted to other type of models.
7. DATABASE TROUBLESHOOTING : ER diagrams are used to analyze existing databases to find and resolve the
key issues in logic or deployment. Drawing the diagram should reveal where it’s going wrong.
8. FLEXIBLE: ER models are flexible and can be modified easily to accommodate changes in the database design
or structure.
9. MINIMIZES DATA REDUNDANCY: ER models help minimize data redundancy by identifying and eliminating
duplicate data entries.
10. SCALABILITY: ER models can be used for databases of varying sizes, from small to large.
11. VISUAL REPRESENTATION: ER models provide a visual representation of the database structure, making it
easier for stakeholders to understand and provide feedback.
12. DOCUMENTATION: ER models provide useful documentation for future reference, making it easier to
maintain and update the database in the long run.
UNIT-III
RELATIONAL DATABASE MODEL
The relational model was introduced by Dr.E.F.Codd in 1970. It is a conceptual theory of data based on the
mathematical theory of relations.
In a relation model, data is stored in tables. Three key items are used frequently in
Relational database
Models: relations, attributes, and domains.
1. A relation is a table with columns and rows.
2. The named columns of the relation are called attributes.
3. The domain is the set of values of the attributes.

CODD’S RELATIONAL DATABASE RULES


Dr.E.F.Codd defined a set of 12 rules which qualify a database product as relational. These rules are called
Codds’s rules. Any DBMS that satisfy these rules then the DBMS is said to “fully relational”. The rules are given
below:
1. Information Rule
It states that all information in a relational database must be represented by values.
2. Guaranteed Access Rule
It states that every value in the database must be accessed by combination of table name, Primary key and
Column name
3. Systematic treatment of nulls rule
It states that there should be a systematic procedure in the use of nulls.
4. Online catalogue rule
It states that all the information within the catalog(database) must be accessed with the same command.
5. Data sub- language rule
It states that the RDBMS should have language that allows data definition, manipulation security, security,
constraints, and transaction management operations.
6. View updating rule
It states that when the changes made in the view must be effected to its base table.
7. High-Level Insert Update and Delete Rule
It states that the RDBMS should support insertion, updation and deletion of data the table level i.e. a set of records.
8. Physical data independence rule
It states that the changes to the physical level (how the data is stored) must not require a change in programs.
9. Logical data independence rule
It states that changes to the logical level (adding columns, changing column lengths etc.) must not require a change
in programs.
10. Integrity independence rule
It states that integrity constraints must be stored separately in the catalog. The must not include in application
programs.
11. Distribution independence rule
It states that the distribution of portions of the database to various locations should not be visible to users of the
database.
12. Non subversion rule
It states that if low level access is allowed to system then it should be able to subvert (damage) the integrity rule to
change data.
KEYS USED IN DATABASE MODEL

A key is an attribute (also known as column or field) or a combination of attributes that is used to uniquely
identify records. They are also called Identifier Attributes.
1. Super Key: A super key is once or more attributes that identify the records uniquely. Any Unique key
with Non Unique key combination is called a super key of the relationship. A table con have many
Super Keys.
Example: Consider the relation.
Student (HTNO, Stname, Course, Address)
The super keys are
i. (HTNO)
ii. (HTNO, Stname)
iii. (HTNO, Stname, Course)
iv. (HTNO, Stname, Course, Address)
2. Candidate Key:
A candidate key can be defined as minimal Super Key. It is a set of one or more attributes that uniquely
identify a record in a relation.
For example, consider the relation
Student (HTNO, Stname, Course, Address)
The super keys are
The super keys are
1. (HTNO) -
2. (HTNO, Stname)
3. (HTNO, Stname, Course)
4. (HTNO, Stname, Course, Address)
3. Primary key: The key is one or more attributes that identify a row uniquely in a table. Any candidate key is a
primary key of a table. It is chosen by database designer while creating a table.
Example :{ HTNO}
4. Foreign key: A foreign key is an attribute in a table holds the values of an attribute of another or same
table. It is present in child table.
For example,
Student (HTNO, Stname, Course, Address) Here, HTNO is the Primary key.
Marks (HTNO, sub1, sub2) Here, HTNO is the Foreign key
 EXPLAIN DIFFERENT TYPES OF CONSTRAINTS.
1. Constraint is a rule that can be applied on a table or a column of a table.
2. Constraints can also be used to prevent (check) mistakes in data entry.
3. Constraints can be categorized into following,

1. Domain Integrity Constraints


a. Not null b. Check

2. Entity Integrity Constraints.


a. Primary key b. Unique

3. Referential Constraint
a. Foreign key
 Domain Integrity constraints
1. Not Null:
1. By default all columns in a table allow NULL values.
2. When a NOT NULL constraint is enforced on a column in a table,
3. It will not allow NULL values into that column.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> NOT NULL);
Example:
Create table tab (no number(3) constraint C NOT NULL);

2. Check constraint
1. These are rules govern logical expressions or Boolean expressions.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> check
(column name with condition));
Example:

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

Ex2: alter table emp add constraint ck_emp check (sal + comm <10000);
 Entity Integrity Constraints
1. Unique Constraint:
1. This constraint allows only unique values to be stored in the column.
2. Oracle rejects duplication of records when the unique key constraint is used.
3. It can also allow NULL values. Since two NULL values are not allowed because it is
duplicate.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> unique
(column name));
Ex:
Create table JDC (sno number(10) , sname varchar2(10), sphno number(15)
unique);
2. Primary key constraint:
1. It avoids duplication of rows and does not allow NULL values.
Primary key is the combination of NOT NULL and UNIQUE.
1. It is also used to set the relations between the tables. 4.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> primary key);
Ex:
Create table student(sno number(10) constraint P primary key, sname
varchar2(10));

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

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

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

Create table dept (eno number(3), dname varchar2(20));

Now connecting the dept and emp using foreign key

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


dname varchar2(20));

Relational Algebra in DBMS:-


Relational database systems are expected to be equipped with a query language that can assist its users to query the
database instances. There are two kinds of query languages − relational algebra and relational calculus.
Relational Algebra:
Relational algebra is a procedural query language, which takes instances of relations as input and yields instances of
relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept
relations as their input and yield relations as their output. Relational algebra is performed recursively on a relation
and intermediate results are also considered relations.
The fundamental operations of relational algebra are as follows −
 Select
 Project
 Union
 Set different
 Cartesian product
 Rename
We will discuss all these operations in the following sections.
1. Select Operation (σ):-
It selects tuples that satisfy the given predicate from a relation.
Notation − σp(r)
Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use
connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < , >, ≤.
For example −
σsubject = "database"(Books)
Output − Selects tuples from books where subject is 'database'.
σsubject = "database" and price = "450"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" and price = "450" or year > "2010"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after
2010.

2. Project Operation (∏):-


It projects column(s) that satisfy a given predicate.
Notation − ∏A1, A2, An (r)
Where A1, A2 , An are attribute names of relation r.
Duplicate rows are automatically eliminated, as relation is a set.
For example −
∏subject, author (Books)
Selects and projects columns named as subject and author from the relation Books.
3. Union Operation (∪)
It performs binary union between two given relations and is defined as −

r ∪ s = { t | t ∈ r or t ∈ s}
Notation − r U s
Where r and s are either database relations or relation result set (temporary relation).
For a union operation to be valid, the following conditions must hold −
 r, and s must have the same number of attributes.
 Attribute domains must be compatible.
 Duplicate tuples are automatically eliminated.

∏ author (Books) ∪ ∏ author (Articles)


Output − Projects the names of the authors who have either written a book or an article or both.

4. Set Difference (−) :-


The result of set difference operation is tuples, which are present in one relation but are not in the second relation.
Notation − r − s
Finds all the tuples that are present in r but not in s.
∏ author (Books) − ∏ author (Articles)
Output − Provides the name of authors who have written books but not articles.
Cartesian Product (Χ)
Combines information of two different relations into one.
Notation − r Χ s
Where r and s are relations and their output will be defined as −

r Χ s = { q t | q ∈ r and t ∈ s}
σauthor = 'tutorialspoint'(Books Χ Articles)
Output − Yields a relation, which shows all the books and articles written by tutorialspoint.

5. Rename Operation (ρ) :-


The results of relational algebra are also relations but without any name. The rename operation allows us to
rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ.
Notation − ρ x (E)
Where the result of expression E is saved with name of x.
Additional operations are −
 Set intersection
 Assignment
 Natural join
Relational Calculus:
There is an alternate way of formulating queries known as Relational Calculus. Relational calculus is a non-procedural
query language. In the non-procedural query language, the user is concerned with the details of how to obtain the
end results. The relational calculus tells what to do but never explains how to do. Most commercial relational
languages are based on aspects of relational calculus including SQL-QBE and QUEL.
Why it is called Relational Calculus?
It is based on Predicate calculus, a name derived from branch of symbolic language. A predicate is a truth-valued
function with arguments. On substituting values for the arguments, the function result in an expression called a
proposition. It can be either true or false. It is a tailored version of a subset of the Predicate Calculus to communicate
with the relational database.
Many of the calculus expressions involves the use of Quantifiers. There are two types of quantifiers:

o Universal Quantifiers: The universal quantifier denoted by ∀ is read as for all which means that in a given set
of tuples exactly all tuples satisfy a given condition.

o Existential Quantifiers: The existential quantifier denoted by ∃ is read as for all which means that in a given
set of tuples there is at least one occurrences whose value satisfy a given condition.
Before using the concept of quantifiers in formulas, we need to know the concept of Free and Bound Variables.
A tuple variable t is bound if it is quantified which means that if it appears in any occurrences a variable that is not
bound is said to be free.
Free and bound variables may be compared with global and local variable of programming languages.
Types of Relational calculus:

1. Tuple Relational Calculus (TRC)


It is a non-procedural query language which is based on finding a number of tuple variables also known as range
variable for which predicate holds true. It describes the desired information without giving a specific procedure for
obtaining that information. The tuple relational calculus is specified to select the tuples in a relation. In TRC, filtering
variable uses the tuples of a relation. The result of the relation can have one or more tuples.
Notation:
A Query in the tuple relational calculus is expressed as following notation
1. {T | P (T)} or {T | Condition (T)}
Where
T is the resulting tuples
P(T) is the condition used to fetch T.
For example:
1. { T.name | Author(T) AND T.article = 'database' }
Output: This query selects the tuples from the AUTHOR relation. It returns a tuple with 'name' from Author who
has written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and Universal Quantifiers (∀).
For example:

1. { R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}


Output: This query will yield the same result as the previous one.
2. Domain Relational Calculus (DRC)
The second form of relation is known as Domain relational calculus. In domain relational calculus, filtering variable

connectives ∧ (and), ∨ (or) and ┓ (not). It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable. The
uses the domain of attributes. Domain relational calculus uses the same operators as tuple calculus. It uses logical

QBE or Query by example is a query language related to domain relational calculus.


Notation:
1. { a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where
a1, a2 are attributes
P stands for formula built by inner attributes
For example:

1. {< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}


Output: This query will yield the article, page, and subject from the relational javatpoint, where the subject is a
database.
9)ADVANTAGES OF RELATIONAL ALGEBRA:
1. The relational algebra has solid mathematical background.
2. It is the basis of many interesting developments and theorems.
3. If we have two expressions for the same operation
4. And if the expressions are proved to be equivalent
5. Then a query optimizer can automatically substitute the more efficient form.
6. The relational algebra is a high level language
7. It talks in terms of properties of sets of tuples and not in terms of for-loops.
Limitations of Relational Algebra
1. The relational algebra cannot do arithmetic.
2. For example, if we want to know the price of 10 l of petrol, by assuming a 10% increase in
the price of the petrol,
3. It cannot be done using relational algebra.
4. The relational algebra cannot sort or print results in various formats.
5. For example we want to arrange the product name in the increasing order of their price.
6. It cannot be done using relational algebra.
7. Relational algebra cannot perform aggregates.
8. For example we want to know how many staff is working in a particular department.
9. This query cannot be performed using relational algebra. 10.The
relational algebra cannot modify the database.
11.For example we want to increase the salary of all employees by 10%. 12.This
cannot be done using relational algebra.
13. The relational algebra cannot compute “transitive closure.”
14. In order to understand the term transitive closure consider the relation
RELATIONSHIP, which describes the relationship between persons.
15. Consider the query, Find all direct and indirect relatives of Gopal? 16.It is not
possible to express such kind of query in relational algebra.
17. Here transitive means, if the person A is related to the person B and if the person B is related
to the person C means indirectly the person A is related to the person C.
18. But relational algebra cannot express the transitive closure
Relationship
Person1 Person2 Relationship
Hari Krishna Lakshmi Mother
Sree harilal Nandalal Father
Hari Raj Brother
Sree Sravanthi Husband
Functional Dependency:-
The functional dependency is a relationship that exists between two attributes. It typically exists between the primary
key and non-key attribute within a table.
1. X → Y
The left side of FD is known as a determinant, the right side of the production is known as a dependent.
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


1. A → B has trivial functional dependency if B is a subset of A.
2. The following dependencies are also trivial like: A → A, B → B

3. Example:
4. Consider a table with two columns Employee_Id and Employee_Name.
5. {Employee_id, Employee_Name} → Employee_Id is a trivial functional dependency as
6. Employee_Id is a subset of {Employee_Id, Employee_Name}.
7. Also, Employee_Id → Employee_Id and Employee_Name → Employee_Name are trivial dependencies

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

What is normalization? Explain the need of normalization.


Normalization is the process of decomposing the relations into smaller and well structured relations. So that
the data redundancy can be minimized and database anomalies can be removed.
Normalization is a formal process for deciding which attributes should be placed together in a relation based
on the concept of determination. Normalization can be accomplished and understood in stages. Each of which
corresponds to a normal form.
A “normal form” is a state of a relation that results from applying simple rules regarding functional
dependencies to that relation. The following are the different types of normal forms:
1.First Normal Form(1NF)
2.Second Normal Form(2NF) Basic Normal Forms (or) Lower Level Normal Forms.
3.Third Normal Form(3NF)
4.Boyce Codd Normal Form(BCNF)
5.Fourth Normal Form(4NF) Advanced Normal Forms(or)Higher Level Normal Forms.
6.Fifth Normal Form(5NF)

6. Explain about different types of database anomalies.


If the table or relation contains data redundancy (i.e) repetition of same data at multiple places in the same
relation or in different relations then different database anomalies or problems may be occurred. They are:
(1). Insert Anomalies (2). Delete Anomalies (3). Update Anomalies.
(1). Insert Anomalies:- The errors that are occurred when we insert new records into the database are called as
“Insert Anomalies”.
(2). Delete Anomalies:- The errors that are occurred when we delete existing records from the database are called
as “Delete Anomalies”.
(3).Update Anomalies:- The errors that are occurred when we update existing records from the database are called
as “Update Anomalies”.

7. Explain about functional dependencies: Functional dependency (FD) is a constraint between any two
attributes or any two sets of attributes. For example consider two attributes ‘A’ and ‘B’, the functional dependency
between two attributes ‘A’ and ‘B’ is denoted by A B. This notation can be read as ‘A’ functionally determines
‘B’ (or) ‘A’ uniquely determines ‘B’ (or) ‘B’ is functionally dependent on ‘A’.
Left hand side of the arrow of the functional dependency are called as determinants and right hand side of the
arrow are called as dependents. The attributes that are part of the determinants are called as key attributes and
attributes that are part of the dependents are called as non-key attributes.
Ex:- Table (or) Relation : BOOK
Attributes : book_id, book_title, author, publisher.
Functional Dependencies:-
FD1 : book_id book_title,author,publisher
FD2 : book_id,book_title author,publisher
FD3 : book_id,book_title,author publisher

8. Write about basic normal forms (or) Write about 1NF, 2NF and 3NF.
First Normal Form (1NF):- A relation is said to be in first normal form (1NF), if it does not contain any multi-valued
attributes, i.e all the values of columns in a relation are atomic.
Ex:- Consider the following Relation (or) Table.
EMPNO ENAME SAL COURSE_NAME DATE_COMPLETED
100 SMITH 25000 C 05-OCT-2019
C++ 10-NOV-2019
101 CLARK 36000 JAVA 11-JAN-2020
ORACLE 15-FEB-2020
The above relation is not in first normal form (1NF), because the relation having multiple values of a column.
But every column must contains atomic values only. So, we have to convert the above relation into 1NF and is given
below:
EMPNO ENAME SAL COURSE_NAME DATE_COMPLETED
100 SMITH 25000 C 05-OCT-2019
100 SMITH 25000 C++ 10-NOV-2019
101 CLARK 36000 JAVA 11-JAN-2020
101 CLARK 36000 ORACLE 15-FEB-2020
Hence the above relation is in First Normal Form (1NF).
First Normal Form(1NF) : As per First Normal Form, no two Rows of data must contain repeating group of
information i.e each set of column must have a unique value, such that multiple columns cannot be used to
fetch the same row.

 It is performed by the three steps


2. Eliminate the repeating groups.
3. Identifying the primary key
4. Identify all the functional dependencies
Ex:

The primary key for the above table was made up of attributes are (PROJ_NUM, EMP-NUM)
 Functional dependencies:-
1. (PROJ_NUM, EMP-NUM ) NO_HOUR
2. EMP-ID ENAME,JOB,CHG_HRS
3. PROJ_NUM PROJ_NAME
4. JOB CHG_HRS
 The attribute CHG-HRS is depending functionally on JOB and JOB is depending on EMP-ID
then we can say transitive dependence exist between EMP-ID, JOB & CHG- HOUR
Second Normal Form (2NF):- A relation is said to be in second normal form (2NF), if it satisfies the following
properties:

 The relation must be in 1NF.


 It does not contain any partial functional dependencies.

Ex:-

EMPNO ENAME SAL COURSE_NAME DATE_COMPLETED

The functional dependencies are :


FD1 : EMPNO,COURSE_NAME DATE_COMPLETED
FD2 : EMPNO ENAME,SAL
In the second functional dependency (FD2) there is a partial functional dependency. So, we have to decompose the
relation in to two new relations and are given below:
EMPLOYEE
EMPNO ENAME SAL

COURSE
EMPNO COURSE_NAME DATE_COMPLETED

Hence the above two relations are in 2NF.


Third Normal Form (3NF):- A relation is said to be in third normal form (3NF), if it satisfies the following
properties:

 The relation must be in 2NF


 It does not contain any transitive dependencies.

Consider the following relation : CUSTOMER

CUST_ID CUST_NAME SALESPERSON_ID REGION

The functional dependencies in the above relation are :


FD1 : CUST_ID CUST_NAME,SALESPERSON_ID,REGION
FD2 : SALESPERSON_ID REGION
In second functional dependency (FD2) there is a transitive dependency. So, we have to decompose the relation in to
two new relations and these are given below:
SALESPERSON
SALESPERSON_ID REGION

CUSTOMER
CUST_ID CUST_NAME SALESPERSON_ID

Hence the above two relations are in third normal form (3NF).
UNIT-IV
Structured Query Language(SQL)
Introduction:
Structured Query Language (SQL) is the standard set of commands used to access data within the
relational database. All tasks related to relational data management such as creating tables, querying the
database for information, modifying the data in the database, deleting them, granting access to users and
so on can be done using SQL.
SQL is a high level language that provides a greater level of abstraction than procedural languages.
It is so designed that the programmer can specify what data is needed but need not specify how to retrieve it.
 SQL allows the end-users and systems personnel to deal with a number of database management
systems where it is available.
 Applications written in SQL can be easily ported across systems.
 SQL as a language is independent of the way it is implemented internally. It means, a query returns the
same result regardless of whether optimizing has been done with indexes or not.
 The language while being simple and easy to learn can handle complex situations.
 The SQL has strong theoretical base and there is no ambiguity. Hence the results to be expected are
well defined.
 All SQL operations are performed at a set level. It means, one SELECT statement can retrieve multiple
rows, one UPDATE statement can modify multiple rows. This set-at-a-time feature of the SQL makes it
powerful than the record-at-a-time processing techniques used in languages like COBOL.
1. What is SQL? What are different types of SQL commands?
SQL stands for “Structured Query Language”, it is used to perform all operations in a relational database.
The different types of SQL commands are:

 DDL(Data Definition Language) commands


 DML(Data Manipulation Language) commands
 TCL(Transaction Control Language) commands
 DCL(Data Control Language) commands

SQL

DDL DML TCL DCL

2.Explain different data types available in SQL (or) oracle.


The following are the different data types available in SQL (or) oracle:
(1) char (2) varchar/varchar2 (3) long (4) date (5) timestamp (6) number (7) raw (8) long raw
(9) BLOB,CLOB (10) bfile.
(1) char:- ‘char’ datatype is used when the user wants to store a fixed length of characters. It can hold alpha numeric
vales in the range of one byte to 2000 bytes.
(2) varchar/varchar2:- Both varchar and varchar2 data types are used when the user wants to store variable length of
character values. These two data types can hold data values of type alpha numeric.
(3) long:- long data type is used to store variable length of alpha numeric values up to 2 GB of size. But only one
column of a table can have the data type ‘long’.
(4) date:- date data type is used to store data values related to date. The default date format is “DD-MON-YY”
or “dd-mon-yy”.
(5) Time stamp:- The time stamp data type is used to store data values related to date and time. The default time
format is HH-MM-SS.
(6) Number:- Number data type is used to store only numeric values in the of both integers and real values.
(7) raw:- raw data type is used to store binary data with a maximum size of 2000 bytes.
(8) long raw:- This data type is used to store raw large binary data values.
(9) BLOB(Binary Large Object), CLOB(Character Large Object):- These data types are used to store binary and
character large object data values.
(10) bfile:- This data type is used to store external binary files.

3.Explain different types of DDL commands. (what a table using with DDL)
A table is one of the objects of Oracle database. It is the basic unit of data storage in a relational database
management system. Every table has a table name and a set of columns (fields) and rows (records) in which
the data is stored. Each column is identified by a column name and it is given a data type and width.
DDL commands are used to define the structure of the database. The following are the different types
of DDL commands.
(1) create (2) alter (3) truncate (4) drop.
(1) create:- This command is used to create the structure of the table.
Syntax:- create table <tablename> (column1 <data type1>,column2 <data type2>,column3 <data type3>,------------
--------------,columnN <data typeN>);
Ex:- create table student(sno number(2),sname char(20),address varchar(20));
(2) alter:- This command is used to modify or change the structure of the table.
Syntax:- alter table <table name> add (column1 <data type1>,column2 <data type2>,-----------------);
alter table <table name> modify (column1 <new_datatype>(width),column2 <new_ data type>(width),------------);
alter table <table name> drop column <columnName>;
alter table <table name> drop (column1,column2,column3,---------------);
Ex:- 1.alter table student add(dob date,telephone number(10));
2.alter table student modify(sname varchar(20));
3.alter table student drop column telephone;
(3) truncate:- This command is used to remove all the records from the table but it does not remove the structure of
the table.
Syntax:- truncate table<table name>;
Ex:- truncate table student;
(4) drop:- This command is used to remove both the records and the structure of the table.
Syntax:- drop table <table name>;
Ex:- drop table student;
SQL OPERATORS:
An operator is a special character used to perform arithmetic and logical operations. In SQL, these
operators are classified into four types. They are arithmetic, relational, logical and set operators.
1. Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations like addition, subtraction etc.
These are as follows:
Operator Meaning
+ Addition
 Subtraction
* Multiplication
/ Division
|| Concatenation

2. Relational Operators:
These are used to compare two values and to get the result either true or false. These are as follows:

Operator Meaning
> Greater than
< Less than
= Equal to
>= Greater than or equal to
<= Less than or equal to
<> , != Not equal to

Special Comparison (Relational) Operators:


These operators are only available in SQL and are used in conditions. These operators will simplify the
complex conditions. These are as follows:

Operator Meaning
IN Equal to any member of the list
IS Test for nulls
LIKE Test for pattern
BETWEEN Test for range of values
ALL Compares every value of a suquery
ANY or SOME Compares each value of a subquery
EXISTS True if subquery returns at least one row
3. Logical Operators
These operators are used to combine two or more conditions or to negate the result of a condition.
These are as follows:
Operator Meaning
AND Returns true if both conditions are true
OR Returns true if either conditions are true
NOT Negates the result of a condition

4. Set Operators:
Set operators are used to combine the results of two separate queries into a single result. These are as
follows:
Operator Meaning
UNION Returns all distinct rows from both queries
UNION ALL Returns all rows from both queries
INTERSECT Returns only common rows of both queries
MINUS Returns all distinct rows of the first query but not in the second one.

4.Explain different types of DML commands.


DML commands are used to manipulate the database. The following are the different DML commands.
(1)Insert (2) update (3) delete (4) select
(1) Insert:- This command is used to insert new records in to the table.
Syntax:- insert into <tablename> values (column1 value, column2 value, column3 value,--------------);
EX:- insert into student values(1,’Rama’,’Nellore’,’27-jan-95’);
(2) update:- This command is used to change or update the values of the existing records in the table.
Syntax:- update <tablename> set <condition>;
Ex:- 1. update student set address=’kovur’ where sno=20;

2. update stud set tot=m1+m2+m3;

3. update stud set avg=tot/3;

(3) delete:- This command is used to remove records from the table.
Syntax:- delete from <table name> where <condition>;

Ex:- 1. delete from student;


2. delete from student where sno=20;
3. delete from student where sno<=10;
(4) select:- This command is used to retrieve records from the table.
Syntax:- select <columnlist> from <tablename> where <condition>;
Ex:- 1. select * from student;
2. select sno,sname,dob from student;
3. select * from student where sno<=10;

5. What is a query? Explain it with examples. (or) Explain about ‘select’ queries with examples.
A query is a statement requesting that the information retrieval . ‘SELECT’ command is used to retrieve or
access the data values from the database. The statements that are built by using ‘SELECT’ command are called as
‘Select Queries”.
Syntax:- select <column list> from <tablename> [where <condition>];
Ex:- 1. select * from student;
2. select sno,sname,dob from student;
3. select sno,sname,dob from student where sno<=20;
Selecting unique values:-
To retrieve unique values of a column ‘DISTINCT’ clause is used in the select command.
Syntax:- SELECT DISTINCT <COLUMN NAME> FROM <TABLE NAME>;
Ex:- 1. select distinct sname from student;
2. select distinct ename from emp;
Selecting ordered data:- To retrieve the data values of a table in a specified order(ascending/descending) the ‘ORDER
BY’ clause is used in the SELECT command.
Syntax:- select <column list> from <table name> order by <column list> asc/desc;
Ex:-1. select sno,sname,dob from student order by sname asc;
2. select * from emp order by sal desc;

6. Explain about aggregate functions in SQL.


Aggregate functions take collection of values as the input and they produce single value as the result or output.
The following are the different types of aggregate functions in SQL. They are:

1) sum( )
2) avg( )
3) min( )
4) max( )
5) count( )
6) count(*)
1) sum() :- This function calculates sum or total of all values for the given columns.
Ex:- select sum(sal) from emp;
2) avg() :- This function calculate the average of all values for the given columns.
Ex:- select avg(sal) from emp;
3) min() :- This function finds the minimum of all values for the given columns.
Ex:- select min(sal) from emp;
4) max() :- This function finds the maximum of all values for the given columns.
Ex:- select max(sal) from emp;
5) count() :- This function counts the total number of records for the given table.
Ex:- select count(*) from emp;
count function can also be used to count the non-null values of a column for the given table.
Ex:- select count(comm) from emp;
6) COUNT(*): This function counts the number of rows present in the specified table.
Eg: 1. Select count(*) from emp;

Write about relational set operators in SQL. Set operators combine the result of two component queries into
a single resultant table. SQL supports the following types of set operators.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
1. UNION:- This operator is used to display all the records selected by either query. This operation produces
distinct rows or records as the result.
Ex:- Consider the following two tables ‘X’ and ‘Y’
Table : X Table : Y
Item code Item name
Item name
1 Powder
2 Soap
4 Pen
Item code
2 Soap
3 Cream
4 Pencil

Query:- select * from X union select * from Y;


Output:-
Item code Item name
1 Powder
2 Soap
3 Cream
4 Pen
4 Pencil

Query:- select * from X union all select * from Y;


Output:-
Item code Item name
1 Powder
2 Soap
2 Soap
3. INTERSECT:- This operator is used to display all the common distinct rows or
3 Cream
records as the result.
4 Pen
4 Pencil Query:- select * from X intersect select * from Y;
Output:-
Item code Item name
2 Soap

4. MINUS:- This operator is used to display all the distinct rows selected by the first query but which are not in
the second query.
Query:- select * from X minus select * from Y;
Output:-
Item code Item name
1 Powder
4 Pen
8.Write about sub queries or nested queries in SQL.
A query within another query is called a sub query. The statement containing a sub query is called a parent
query or outer query and the query inside the statement is called a child query or inner query. There are two different
types of sub queries. They are: (1) Single row sub queries
(2) Multiple row sub queries
(1) Single row Sub queries:- The sub queries that return only one row are called single row sub queries.
Ex:- select ename,deptno,sal from emp where sal=(select max(sal) from emp);
Output:-
ENAME DEPTNO SAL
KING 10 5000
(2) Multiple row Sub queries:- Sub queries that return more than one row are called multiple row sub queries.
To perform multiple row sub queries the following operators are used.
 In operator
 Any operator
 All operator
 Exists operator
In operator:- In operator checks if the value of the outer query is equal to any of the values in the inner query.
Query:- select ename,deptno,sal from emp where sal in (select max(sal) from emp group by deptno);
Output:-

ENAME DEPTNO SAL


BLAKE 30 2850
SCOTT 20 3000
FORD 20 3000
KING 10 5000
Any operator:- when this operator is used a record will be selected if the value in the outer query satisfies the
condition with any one of values retrieved from the sub query or inner query.
Query:- select ename,deptno,sal from emp where sal>=any(select avg(sal) from emp group by deptno);

All operator:- The all operator is used to check for all the values returned by the sub query. The condition is
checked for all the values and the records that catch all the values are displayed.
Query:- select ename,sal,deptno from emp where sal>=all(select avg(sal) from emp group by deptno);

Exists:- When this operator is used, the outer query is executed if inner query evaluates to true.
Query:- select deptno,dname,loc from dept where exists(select * from emp);
Output:-
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
QUERIES(SELECT QUERIES)
The query is a process that retrieves required information from the database. The SELECT command is used to
query the database. A query can be used for the following purposes:
 To retrieve data from one or more tables
 To sort the data on multiple columns either in ascending or descending order
 To filter data using conditions
 To group the rows based on multiple columns
 To join multiple tables together
SELECT command:
It is also a DML command used to retrieve data from one or more system tables, user-defined tables, views
or synonyms. It is a powerful statement for querying the data.
Syntax:
SELECT [DISTINCT] */columnlist
FROM tablename1 [, tablename2, ……]
[WHERE condition]
[GROUP BY columnlist]
[HAVING condition]
[ORDER BY column [DESC],……] ;
Here, the table names are the existing tables. The ‘*’ represents all columns of the table and ‘columnlist’ indicates
the specified columns from table. When the SELECT command is used without optional clauses, it displays all
the rows from the specified tables.
Eg:
1. SELECT * FROM employee;
It displays all rows and columns of the table employee.
2. SELECT empname, job FROM employee;
It displays all rows of the columns empname and job of the table employee

The DISTINCT clause eliminates duplicate values in the output. It displays unique values from among them.
Simply this clause displays only one value from the duplicates.

Eg:
1. SELECT DISTINCT job FROM employee;

The WHERE clause is used to display the rows based on the condition. When it is used, it displays all the rows
that match the given condition.
Eg:
1. SELECT * FROM emp WHERE salary < 5000;
2. SELECT * FROM emp WHERE job=’CLERK’ AND salary BETWEEN 2000 AND 4000;

The GROUP BY clause is used to combine a group of rows based on particular column(s).
Eg:
1. SELECT JOB, COUNT(*) FROM employee GROUP BY job;
2. SELECT SUM(salary) FROM employee GROUP BY deptno, job;
The HAVING clause is used to specify a condition using group functions.
Eg:
SELECT JOB, COUNT(*) FROM employee GROUP BY job HAVING COUNT(*) > 3;
The ORDER BY clause is used to display rows either in ascending or descending order based on the specified
columns. The DESC is used to display rows in descending order. If it is omitted, SELECT command displays rows
in ascending order.
Eg:
1. SELECT * FROM employee ORDER BY empname;
2. SELECT * FROM employee ORDER BY job, empname;
3. SELECT * FROM employee ORDER BY salary DESC;

QUERIES WITH SPECIAL OPERATORS


BETWEEN: This operator is used to check whether a value is present in the specified range of values or not.
Syntax: Operand [NOT] BETWEEN x AND y
Eg. SELECT * FROM EMP WHERE SAL BETWEEN 2500 AND 5000;
IN: This is used to check whether a value is present in the set of values or not.
Syntax: Operand [NOT] IN (Values)
Eg.: SELECT * FROM EMP WHERE JOB IN(‘CLERK’,’MANAGER’);
LIKE: This operator is used to check for pattern matching for the character data type values. It uses wild card
characters (% , _ ) to check pattern matching. The character ‘%’ represents any number of characters and
underscore ‘_’ represents single character.
Syntax : Operand [NOT] LIKE pattern-string
Eg:
1. SELECT * FROM EMP WHERE ENAME LIKE ‘SM%’
2. SELECT * FROM EMP WHERE ENAME LIKE ‘_ _ A%’
IS : This operator is used to compare null values only.
Eg: SELECT * FROM EMP WHERE JOB IS NULL;
ANY or SOME: This operator is used to compare a value to each value returned by a subquery. It returns true
if any of the values match the condition. It must be used along with comparison operator i.e. >, <, = etc.
Syntax : Operand [NOT] relational-opearator ANY (subquery)
Eg: SELECT * FROM EMP WHERE SAL > ANY(SELECT SAL FROM EMP WHERE JOB=’MANAGER’)
ALL: This is used to compare a value to every value returned by a subquery. It returns true if all the values match
the condition. It must be used along with comparison operator i.e. >, <, = etc.
Syntax : Operand [NOT] relational-opearator ALL (subquery)
Eg: SELECT * FROM EMP WHERE SAL > ALL(SELECT SAL FROM EMP WHERE JOB=’MANAGER’)

EXISTS: This operator returns true if the subquery returns atleast one row.
Eg.: SELECT * FROM EMP WHERE EXISTS (SELECT * FROM D
TABLES
(DDL Commands)
A table is one of the objects of Oracle database. It is the basic unit of data storage in a relational database
management system. Every table has a table name and a set of columns (fields) and rows (records) in which the data
is stored. Each column is identified by a column name and it is given a data type and width.
SQL DATA TYPES
The data type is the characteristic nature of a column in a table. It specifies what type of data to be entered
into the column of a table. The following are different data types available in SQL. They are
 NUMBER
 CHAR
 VARCHAR / VARCHAR2
 LONG
 DATE
 RAW
 LONG RAW
1. NUMBER(L, D):
 This data type allows numeric values only.
 L specifies the length and D specifies the number of decimal places within the length
 The length should be in the range from 1 to 38 digits.
 The length is optional and if we omit, it takes 38 digits as default length.
2. CHAR(size):
 This data type stores fixed length character strings.
 The ‘size’ indicates maximum number of characters allowed in each cell of column
 The ‘size’ must be in the range from 1 to 255 bytes.
 The ‘size’ is optional and if we omit, the default length is 1 character.
3. VARCHAR(size) / VARCHAR2(size):
 This data type stores variable length character strings.
 The ‘size’ indicates maximum number of characters allowed in each cell of column
 The ‘size’ must be in the range from 1 to 2000 bytes.
4. LONG:
 This data type is used to store variable length character strings.
 We can store upto 2 Giga Bytes of data in each cell.
 We should not specify size for this data type
5. DATE:
 This data type used to enter date and time values
 This data type occupies 7 bytes in the memory
 By default, we must enter date values in ‘DD-MON-YY’ format.
 The date values must be in the range from ‘1-JAN-4712 B.C.’ to ’31-DEC-4712 A.D.’
6. RAW(size):
 It is used to store binary or hexadecimal data.
 The ‘size’ must be in the range from 1 to 255 bytes.
 It is useful to store multimedia information like images, audio and video files.
7. LONG RAW:
 This data type is also used to store binary or hexadecimal data.
 We can store images upto 2 Giga Bytes
 We should not specify size for this data type
 It is useful to store multimedia information like images, audio and video files.
TYPES OF SQL COMMANDS(SQL SUB COMMANDS)
When an instruction is executed at SQL prompt then it is called SQL command.
The SQL commands are classified into the following categories.
1.Data definition Language(DDL) commands
2.Data Manipulation Language(DML) commands
3.Data Control Language(DCL) Commands
4.Transaction Control Language(TCL) commands
1.Data definition Language(DDL) commands:-
The DDL commands are used to create, alter and drop various database objects i.e tables, views and indexes.
The commands that begin with CREATE, ALTER,DROP are referred as DDL commands. These are auto commit
commands, because they process and save objects automatically in the database.
Ex:- CREATE TABLE, CREATE USER,
ALTER TABLE, ALTER USER,
DROP TABLE , DROP USER etc.
2.Data Manipulation Language(DML) commands:-
The DML commands are used to manipulate data within the database objects. The commands
INSERT,UPDATE,DELETE and SELECT are treated as DML commands. They are used to insert, modify, delete and
retrieve data in the database objects. These are not auto commit commands.
EX:- 1. INSERT INTO STUDENT VALUES(100,’XYZ’);
2.UPDATE STUDENT SET ROLLNO=100;
3.DELETE FROM STUDENT;
4.SELECT * FROM STUDENT;
3.Data Control Language(DCL) commands:-
The DML commands are used to control user access to the database objects. These are used to provide authorisation
to the users to protect the database. GRANT and REVOKE are referred as DCL commands. They used to Grant or
Remove various privileges and roles to users.
EX:- 1. GRANT ALL TO USER1;
2.REVOKE ALL FROM USER1;
4.Trasaction Control Language(TCL) commands:-
The TCL commands a re used to Manage the changes made by DML commands. These Commands are used
to save or Cancel the process of DML commands. COMMIT,ROLLBACK and SAVEPOINT commands are referred as TCL
commands.
EX:- 1.COMMIT;
2.ROLLBACK;
Data definition Language(DDL) commands:-
The DDL commands are used to create, alter and drop various database objects i.e tables, views and indexes.
The commands that begin with CREATE, ALTER,DROP are referred as DDL commands. These are auto commit
commands, because they process and save objects automatically in the database.
EMPNO NAME DESIGNATION SALARY
ROWS

Logical Structure Of A Table

CREATE TABLE command:


It is one of the DDL commands and is used to define the structure of a table. Structure means a collection
of different columns of different data types. We can’t store any data item into the table using this command.
This command is also used to define various constraints to a table.
Syntax:
CREATE TABLE tablename ( column-name-1 datatype(size),
column-name-2 datatype(size),
:
:
column-name-n datatype(size) );
In the above syntax,
i. The ‘tablename’ is a user-defined word which identifies the name of the table. The table name must not be
ii. exist in the database.
iii. The column names are also user-defined words which specify the names of the fields. The column names
iv. must be unique in a table’s structure.
v. The data type is any valid SQL data types
Eg:
CREATE TABLE employee ( Empno number(4),
EmpnameVarchar2(30),
Designation Varchar2(15),
Joindate Date,
Salary Number(8,2) );
ALTER TABLE command:
It is also one of DDL commands and is used to modify the structure of an existing table. We can use
this command for different purposes.
1. ALTER TABLE…ADD method:-
This method is used to add new columns to the existing table.
Syntax: ALTER TABLE tablename ADD ( column-name datatype(size),…. );
In the above syntax, the specified table name must be present in the database. The column names must not
be exist in the table.
Eg: ALTER TABLE employee ADD ( HRA number(8,2), Birthdate Date);

2. ALTER TABLE…MODIFY method:-


This method is used to modify the data type and width of existing columns of a table. When we want to
decrease the column width or to change the data type, the specified column must be blank.
Syntax: ALTER TABLE tablename MODIFY (column-name datatype(size), …. );
In the above syntax, the specified table name must be present in the database. The column names must be
exist in the table.
Eg: ALTER TABLE employee MODIFY ( Designation Varchar2(20) );

3. ALTER TABLE…DROP method:-


This method is used to drop constraints from the specified table.
Syntax:
ALTER TABLE tablename DROP CONSTRAINT constraint_name ;
In the above syntax, the ‘constraint_name’ is a name given to the constraint.
Eg:
1. ALTER TABLE employee DROP CONSTRAINT SYS_C00235 ;
2. ALTER TABLE student DROP CONSTRAINT fk_stno;
DROP TABLE command:
This command is one of DDL commands and is used to drop (delete) a table permanently from the
database. After dropping a table, we cannot retrieve (Rollback) it from the database. While execution of this
command it removes data, structure and all related information of the specified table.
Syntax: DROP TABLE tablename;
Eg: DROP TABLE employee;
TRUNCATE TABLE command:
It is a DDL command that is used to delete all rows of the specified table. Once data is deleted, we
cannot retrieve (rollback) from the database.
Syntax: TRUNCATE TABLE tablename;
Eg: TRUNCATE TABLE employee
DESCRIBE command:
It is one of DDL commands and is used to display the structure of the specified table. We can also use
this command to display the structure of a View or Synonym.
Syntax:
DESC[RIBE] objectname;
Here, the object name can be table, view or synonym name which must be present in the database.
Eg: DESCRIBE employee;
DESC employee;
DML Commands
INSERT command:
It is one of DML commands used to add one or more rows to a table. This command adds the rows only
at the end of the table. It doesn’t insert any row in between existing rows of a table.
Inserting Single Row:
Method-1: INSERT INTO tablename VALUES ( values-list );
Eg: 1. INSERT INTO employee VALUES ( 1001,’KUMAR’,’MANAGER’,4500);
Eg: 2.
INSERT INTO employee (Empname, Joindate ) VALUES (‘XYZ’, ’12-JUN-89’ );
Inserting Multiple (bulk) Rows:
We can also insert multiple rows by retrieving records from another table using SELECT statement as
follows:
Method-1: INSERT INTO tablename Query;
Eg:
1. INSERT INTO sample SELECT * FROM employee;
2. INSERT INTO sample SELECT * FROM employee WHERE job=’CLERK’;
Method-2: INSERT INTO tablename(column-list) query;
1. INSERT INTO newemp (ename, job) SELECT Empname, Job FROM emp;
2. INSERT INTO newemp (ename, job) SELECT Empname, Job FROM emp WHERE sal>5000;
UPDATE command:
It is one of DML commands used to modify the values of a table. We can update whether all rows or
columns or set of rows or columns in a table.
Syntax: UPDATE tablename SET column = value , …… [ WHERE condition ] ;
Eg:
1. UPDATE employee SET HRA = salary * 20 / 100;
2. UPDATE student SET course = BCA WHERE sno = ‘100’;
3. UPDATE student set total=sub1+sub2+sub3;
DELETE command:
It is one of DML commands used to delete the data from a table. We can use this command to remove
all the rows or specified rows from the table. However, we cannot delete a value or the values in a particular column.
Syntax:
DELETE [FROM] tablename [WHERE condition] ;
In the above syntax,
 The ‘tablename’ is the name of the existing table,
 The WHERE clause is optional and is used to delete the table based on the given condition. If it is omitted,
 the DELETE command will delete all the rows in the table.
Eg:
1. DELETE FROM student;
It deletes all rows from ‘student’ table.
2. DELETE FROM student WHERE result = ‘FAIL’;
It deletes rows from student table whose result is ‘FAIL’ ;
QUERIES(SELECT QUERIES)
The query is a process that retrieves required information from the database. The SELECT command is used to
query the database. A query can be used for the following purposes:
 To retrieve data from one or more tables
 To sort the data on multiple columns either in ascending or descending order
 To filter data using conditions
 To group the rows based on multiple columns
 To join multiple tables together
SELECT command:
It is also a DML command used to retrieve data from one or more system tables, user-defined tables, views
or synonyms. It is a powerful statement for querying the data.
Syntax:
SELECT [DISTINCT] */columnlist
FROM tablename1 [, tablename2, ……]
[WHERE condition]
[GROUP BY columnlist]
[HAVING condition]
[ORDER BY column [DESC],……] ;
Here, the table names are the existing tables. The ‘*’ represents all columns of the table and ‘columnlist’ indicates
the specified columns from table. When the SELECT command is used without optional clauses, it displays all
the rows from the specified tables.
Eg:
3. SELECT * FROM employee;
It displays all rows and columns of the table employee.
4. SELECT empname, job FROM employee;
It displays all rows of the columns empname and job of the table employee

The DISTINCT clause eliminates duplicate values in the output. It displays unique values from among them. Simply
this clause displays only one value from the duplicates.
Eg:
2. SELECT DISTINCT job FROM employee;
3. SELECT DISTINCT * FROM employee;

The WHERE clause is used to display the rows based on the condition. When it is used, it displays all the rows that
match the given condition.
Eg:
3. SELECT * FROM emp WHERE salary < 5000;
4. SELECT * FROM emp WHERE job=’CLERK’ AND salary BETWEEN 2000 AND 4000;

The GROUP BY clause is used to combine a group of rows based on particular column(s).
Eg:
3. SELECT JOB, COUNT(*) FROM employee GROUP BY job;
4. SELECT SUM(salary) FROM employee GROUP BY deptno, job;

The HAVING clause is used to specify a condition using group functions.


Eg:
SELECT JOB, COUNT(*) FROM employee GROUP BY job HAVING COUNT(*) > 3;
The ORDER BY clause is used to display rows either in ascending or descending order based on the specified
columns. The DESC is used to display rows in descending order. If it is omitted, SELECT command displays rows in
ascending order.
Eg:
4. SELECT * FROM employee ORDER BY empname;
5. SELECT * FROM employee ORDER BY job, empname;
6. SELECT * FROM employee ORDER BY salary DESC;
7.
QUERIES WITH SPECIAL OPERATOR
BETWEEN: This operator is used to check whether a value is present in the specified range of values or not.
Syntax: Operand [NOT] BETWEEN x AND y
Eg. SELECT * FROM EMP WHERE SAL BETWEEN 2500 AND 5000;
IN: This is used to check whether a value is present in the set of values or not.
Syntax: Operand [NOT] IN (Values)
Eg.: SELECT * FROM EMP WHERE JOB IN(‘CLERK’,’MANAGER’);
LIKE: This operator is used to check for pattern matching for the character data type values. It uses wild card
characters (% , _ ) to check pattern matching. The character ‘%’ represents any number of characters and
underscore ‘_’ represents single character.
Syntax : Operand [NOT] LIKE pattern-string
Eg:
3. SELECT * FROM EMP WHERE ENAME LIKE ‘SM%’
4. SELECT * FROM EMP WHERE ENAME LIKE ‘_ _ A%’
IS : This operator is used to compare null values only.
Eg: SELECT * FROM EMP WHERE JOB IS NULL;
ANY or SOME: This operator is used to compare a value to each value returned by a subquery. It returns true if any
of the values match the condition. It must be used along with comparison operator i.e. >, <, = etc.
Syntax : Operand [NOT] relational-opearator ANY (subquery)
Eg: SELECT * FROM EMP WHERE SAL > ANY(SELECT SAL FROM EMP WHERE JOB=’MANAGER’)
ALL: This is used to compare a value to every value returned by a subquery. It returns true if all the values match
the condition. It must be used along with comparison operator i.e. >, <, = etc.
Syntax : Operand [NOT] relational-opearator ALL (subquery)
Eg: SELECT * FROM EMP WHERE SAL > ALL(SELECT SAL FROM EMP WHERE JOB=’MANAGER’)

EXISTS: This operator returns true if the subquery returns atleast one row.
Eg.: SELECT * FROM EMP WHERE EXISTS (SELECT * FROM DEPT);
AGGREGATE FUNCTIONS
The aggregate functions are also known as group functions. They perform a task on a group of items and
produce a single value for the entire group. There are 6 different functions used in SQL. They are

COUNT(*):
This function counts the number of rows present in the specified table.
Eg: 1. Select count(*) from emp;
2. Select count(*) from emp where job=’CLERK’;
COUNT( ):
This function counts the number of values present in the specified column by ignoring null values. It can be
used for any datatype column.
Syntax: COUNT([DISTINCT/ALL] column)
Eg-1: Select count(salary) from emp;
This example counts the no. of values present in salary column by ignoring nulls.
Eg-2: Select count(distinct sal) from emp;
This example counts the no. of values present in salary column by ignoring null and duplicate values.

SUM( ):
This function returns the sum of values of the specified column by ignoring null values. It must be used for
number datatype columns only.
Syntax: SUM([DISTINCT/ALL] column)
Eg-1: Select sum(salary) from emp;
This example returns the sum of values of salary column by ignoring nulls.
Eg-2: Select avg(distinct sal) from emp;
This example returns the sum of values of salary column by ignoring null and duplicate values.
AVG( ):
This function returns the average of values of the specified column by ignoring null values. It must be used for
number datatype columns only.
Syntax: AVG([DISTINCT/ALL] column)
Eg-1: Select avg(salary) from emp;
This example returns the average of values of salary column by ignoring nulls.
Eg-2: Select avg(distinct sal) from emp;
This example returns the average of values of salary column by ignoring null and duplicate values.
MAX( ):
This function returns the maximum value from the values of the specified column by ignoring null values. It
can be used for any datatype column.
Syntax: MAX([DISTINCT/ALL] column)
Eg: Select MAX(salary) from emp;
This example returns the maximum value of salary column by ignoring nulls.
MIN( ):
This function returns the minimum value from the values of the specified column by ignoring null values. It
can be used for any datatype column.
Syntax: MIN([DISTINCT/ALL] column)
Eg-1: Select MIN(salary) from emp;
This example returns the minimum value of salary column by ignoring nulls.
SUB-QUERIES OR CO-RELATED QUERIES
A query within another query is called sub-query. It is also known as nested query. It is a technique used
to process multiple tables that involves placing an inner query (SELECT…FROM…WHERE) within WHERE or
HAVING clause of another (outer) query. The inner query provides values for the condition of the outer query.
An outer query or inner query can have multiple sub-queries.

Rules for using subqueries:


1. The inner query must be specified on the right hand side of the condition.
2. The inner query must be enclosed within parenthesis
3. Proper comparison operator must be used in the outer query’s condition based on the output of inner query.
Types of subqueries:
There are two types of sub-queries used in SQL. They are nested sub-query and correlated sub-query.
1. Nested sub-query:
It is the most commonly used sub-query. A nested sub-query is classified into single row sub-query and
multiple row sub-query.
Single row subquery:
When the inner query returns only one row (value) to the outer query then it is called single row sub-query.
Eg: List employee details whose job is Kumar’s job.
Select * From Emp Where Job = (Select Job From Emp Where Empname=’KUMAR’);
Multiple row subquery:
When the inner query returns multiple rows (values) to the outer query then it is called multiple row sub-
query.
Eg-1: List employee details whose job is Kumar’s or John’s job.
Select * From Emp Where Job = (Select Job From Emp Where Empname In(’KUMAR’,’JOHN’));
Eg-2: List employee details whose salary is greater than any manager’s salary
Select * From Emp Where salary > any (Select salary from emp where job=’manager’);
2. Correlated sub-query
Normally, the outer query depends on the data returned by inner query. But the correlated sub-query uses
the result of the outer query to determine the processing an inner query. That means, the inner query is some what
different for each row references in the outer query. In this case, the inner query must be computed for each outer
row. But in other sub-queries, the inner query is computed only once for all rows processed in the outer query.
Eg: List employee details whose salary is greater than their department’s average salary.
Select * From Emp A Where salary > (Select avg(salary) from emp B where B.Deptno=A.Deptno);
8.Write about sub queries or nested queries in SQL.
A query within another query is called a sub query. The statement containing a sub query is called a parent
query or outer query and the query inside the statement is called a child query or inner query. There are two
different types of sub queries. They are: (1) Single row sub queries
(2) Multiple row sub queries
(1) Single row Sub queries:- The sub queries that return only one row are called single row sub queries.
Ex:- select ename,deptno,sal from emp where sal=(select max(sal) from emp);

Output:-
ENAME DEPTNO SAL
KING 10 5000
(2) Multiple row Sub queries:- Sub queries that return more than one row are called multiple row sub queries.
To perform multiple row sub queries the following operators are used.
 In operator
 Any operator
 All operator
 Exists operator
In operator:- In operator checks if the value of the outer query is equal to any of the values in the inner query.
Query:- select ename,deptno,sal from emp where sal in (select max(sal) from emp group by deptno);
Output:-

ENAME DEPTNO SAL


BLAKE 30 2850
SCOTT 20 3000
FORD 20 3000
KING 10 5000
Any operator:- when this operator is used a record will be selected if the value in the outer query satisfies the
condition with any one of values retrieved from the sub query or inner query.
Query:- select ename,deptno,sal from emp where sal>=any(select avg(sal) from emp group by deptno);

All operator:- The all operator is used to check for all the values returned by the sub query. The condition is
checked for all the values and the records that catch all the values are displayed.
Query:- select ename,sal,deptno from emp where sal>=all(select avg(sal) from emp group by deptno);
Exists:- When this operator is used, the outer query is executed if inner query evaluates to true.
Query:- select deptno,dname,loc from dept where exists(select * from emp);
Output:-
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

JOINS (JOINING DATABASE TABLES) OR(SQL JOIN OPERATORS)


A join is a relational operation that combines two or more tables into single table using a common
column. It is the most frequently used relational operation to process multiple tables.
A join is a query that combines data from two or more tables or views. Oracle performs a join
whenever multiple tables appear in the query’s FROM clause.
Most joins contain WHERE clause condition that compares two columns, each from different tables.
Such a condition is called join condition. An important rule in forming a join condition is that there should be
atleast one condition for each pair of tables being joined.
The general form for joining tables is as follows:
Syntax:
SELECT [DISTINCT/ALL] */columnlist FROM tablename1 [alias], tablename2 [alias], ……
[WHERE joincondition] [GROUP BY columnlist] [HAVING condition] [ORDER BY column [DESC],……] ;
Here, the columnlist contains any columns from the specified tables. But common columns must be qualified
with corresponding table names to avoid ambiguity.
Types of Joins:
There are several types joins used in relational databases. Some of them are:
1. Equi Join
2. Natural Join
3. Outer Join
4. Self Join
5. Cartesian Join
Equi Join:
When two tables are joined using equality operator in the join condition then it is called equi join. It
combines rows of two tables that are having equl values in the specified columns of the join condition.

Eg-1:
Select Ename, Job, Emp.Deptno, Dept.Deptno, Dname From Emp, Dept Where Emp.Deptno=Dept.Deptno;
Natural Join:
It is as same as equi join except that one of the duplicate columns is eliminated in the result table. It is the
most commonly used join operation.
For example, if equi join is written as
Select Ename, Job, Emp.Deptno, Dept.Deptno, Dname From Emp, Dept Where Emp.Deptno=Dept.Deptno;
Then, it displays same values for emp.deptno and dept.deptno in the result table. Hence to eliminate
such duplicate columns, the natural join is written as follows:
Select Ename, Job, Emp.Deptno, Dname From Emp, Dept Where Emp.Deptno=Dept.Deptno;
Outer Join:
It is an extension of equi or natural join. An outer join displays rows in the result table that don’t have
matching values in the common columns. It means if a row in one table doesn’t have a matching row in the other
table then it is also included in the output.
This type of join is performed by placing outer join operator i.e. (+) in the join condition. This operator must
be used only one side of the condition. Normally, it is placed for child table’s column.
Eg:
Select Ename, Job, Emp.Deptno, Dept.Deptno, Dname From Emp, Dept Where Emp.Deptno(+)=Dept.Deptno;
Self Join:
A self join is a join of a table to itself. That is each row of a table combined with a row of the same table.
The self join can be viewed as joining of two copies of the same table.
To perform self join, a table appears twice in the FROM clause and is followed by different alias.
Oracle combines and returns the rows of the table that satisfies the join condition.

Eg: List employee details along with their manager’s name


Select A.Empno, A.Ename, B.Ename “Manager” From Emp A, Dept B Where A.MGR=B.Empno;

Cartesian Join:
When multiple tables are joined without join condition then it is called Cartesian join. It combines all
rows of one table with every row of the other table. As a result, it returns the Cartesian product. For example, if
a table contains 10 rows and other contains 5 rows then the Cartesian product is 50 rows.
Eg:
Select * from Emp, Dept;

UNIT-V
9. Explain about different types of literals in SQL or PL/SQL.
A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier. For example,
TRUE, 786, ‘dbms’ are all literals of type Boolean, number, or string. PL/SQL, literals are case-sensitive. PL/SQL
supports the following kinds of literals −
 Numeric Literals
 Character Literals
 String Literals
 BOOLEAN Literals
 Date and Time Literals

The following table provides examples from all these categories of literal values.
S.No Literal Type & Example
Numeric Literals

1 050 78 -14 0 +32767

6.6667 0.0 -12.0 3.14159 +7800.00

6E5 1.0E-8 3.14159e0 -1E38 -9.5e-3


Character Literals
2
'A' '%' '9' ' ' 'z' '('

String Literals

3 'Hello, world!'

'Degree Students'

'19-NOV-12'
4 BOOLEAN Literals

TRUE, FALSE, and NULL.


Date and Time Literals
5
DATE '01-JUN-19';

TIMESTAMP '01-JUN-19 12:01:01';

To embed single quotes within a string literal, place two single quotes next to each other as shown in the following
program −
DECLARE
message varchar2(30):= 'This is a class room.';
BEGIN
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
This is a class room.
2) PL/SQL Language Elements:-
There are different elements
1. Character Set
2. Lexical Units
a. Delimiters
b. Identifiers
c. Literals
d. Comments
1. Character Set
1. A PL/SQL program consists of text having specific set of characters.
2. Character set may include the following characters:
a. Alphabets, both in upper case [A–Z] and lower case [a–z]

c. Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % ,


b. Numeric digits [0–9]
#$&|{}?[
]
d. Blank spaces, tabs, and carriage returns.
2. Lexical Units
1. A line of PL/SQL program contains groups of characters known as lexical units, which can
be classified as follows:
A. Delimiters
B. Identifiers
C. Literals
D. Comments
A. Delimiters
a. A delimiter is a simple or compound symbol
b. That has a special meaning to PL/SQL.
c. Simple symbol consists of one character
d. Compound symbol consists of more than one character.

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

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

D. Comments
1. Comments are used in the PL/SQL program
2. It used to improve the readability and understandability of a program.
3. A comment can appear anywhere in the program code.
4. The compiler ignores comments.
5. Generally, comments are used to describe the purpose and use of each code
segment.
Ex: /* Hello World! This is an example of multiline comments in PL/SQL */
3) What are the data types available in PL/SQL?

Data type Description


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

Explain about different types of operators in SQL or PL/SQL.

SQL or PL/SQL supports 3-different types of operators. They are :

1. Comparison operators
2. Logical operators
3. Special operators

1. Comparison operators:- These operators are used to compare the column data with specific values in a condition.
The following are the different types of comparison operators.
Comparison operators Description
= Equal to
< > , != Not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Ex:- 1. Select * from emp where sal>=20000;
2. select ename,deptno from emp where sal<=10000;

2. Logical operators:- These operators compare two or more than two conditions at a time to determine whether a
row can be selected for the output. These operators are given below:
Logical operators Description
OR For the row to be selected at least one of the conditions must be true
AND For the row to be selected all the specified conditions must be true
NOT For the row to be selected the specified condition must be false
Ex:- 1. select ename from emp where job=’analyst’ or job=’salesman’;
2. select ename from emp where job=’clerk’ and deptno=20;
3.Special operators:- These operators are used to enhance the search capabilities of a SQL query. These are given
below
Special operators Description
LIKE Matching a pattern from a column . Column value is similar to specified character(s).
IN Checking a value in a set. Column value is equal to any one of a specified set of values.
BETWEEN Checking a value with in a range. Column value is between two values, including the end
values specified in the range.
Ex:- 1. select ename from emp where ename like ‘S%’;
2. select ename,sal from emp where sal between 10000 and 30000;

1. Explain about the features of PL/SQL or Write about the advantages of PL/SQL.
Procedural Language SQL(PL/SQL) is a block structured language. The basic unit of PL/SQL is called a block
which contains declarative statements, executable statements and error handling statements.
Features of PL/SQL :- Following are the features of PL/SQL :
1. Allows users to embed(extend) one or more ‘SQL’ statements together and execute as a single SQL unit.
2. Allows declaration of variables and constants.
3. Allows usage of conditional control statements and iterative control statements.
4. Allows programming of error handling using exceptions.
5. Allows Row-by-Row processing of data using cursors.
6. Allows triggers to be created and fired.

2. Write the general structure of a PL/SQL program.


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

PL/SQL Block Structure:


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

1. Declaration part
2. Executable part
3. Error handling part
1) Declaration part :- This is the first section of a PL/SQL block. This section is used to declare variables,
constatnts,cursors,etc.
2) Executable part :- This part contains all the SQL and PL/SQL statements which are used for querying and
processing the data. ‘BEGIN’ is used to mark the beginning of the block and ‘END’ ends the block. There must
be at least one executable statement with in a set of ‘BEGIN’ and ‘END’ statements.
3) Error handling part :- This part is called exception handling part and it contains the error handling statements.

Structure of a PL/SQL Block :-


declare

< declarative statements >

begin

< executable statements >

exception

< exception handling statements >

End;

Ex:- (1) begin

dbms_output.put_line(‘Demo on PL/SQL’);

end;

(2) declare
X number;

begin

X := &X;

dbms_output.put_line(‘ The value of X = ‘|| X);

end;

3. Write about conditional control structures or conditional control statements in PL/SQL.


Conditional control statements in PL/SQL are used to execute a sequence of statements based on a certain
condition. The following are the different conditional control statements in PL/SQL.

1) IF .. THEN
2) IF .. THEN .. ELSE
3) IF .. THEN .. ELSE IF
1) IF .. THEN :- The sequence of statements are executed only if the given condition evaluates ‘TRUE’.

Syntax :- IF <condition> THEN


< Sequence of statements >;
END IF;

EX :- Example:
DECLARE
a number:=&a;
BEGIN
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if;
END;
IF .. THEN .. ELSE :- The sequence of statements will be executed when the given condition is true otherwise
another set of statements will be executed.

Syntax :- IF <condition> THEN


< Sequence of statements1 >;
ELSE
< Sequence of statements2 >;
END IF;
EX :- declare
N number;
begin
N:=&N;
if N > 0 then
dbms_output.put_line(‘The given number is positive);
else
dbms_output.put_line(‘The given number is negative);
end if;
end;
/

2) IF .. THEN .. ELSE IF :- Conditions are evaluated one-by-one from top to bottom. If any condition is
evaluated as ‘TRUE’ its associated sequence of statements will be executed.

Syntax :- IF <condition1> THEN


< Sequence of statements1 >;
ELSE IF <condition2> THEN
< Sequence of statements2 >;
ELSE IF <condition3> THEN
< Sequence of statements3 >;
:
:
ELSE
< Sequence of statements N>;
END IF;
END IF
END IF;
Ex:- declare
A number:=&A;
B number:=&B;
begin
if A > B then
dbms_output.put_line(‘ A is big’);
else if B > A then
dbms_output.put_line(‘ B is big’);
else
dbms_output.put_line(‘ Both are equal ‘);
end if;
end;

4. Write about iterative or repetitive control structures or control statements in PL/SQL.


A single statement or group of statements will be executed continuously or repeatedly until the given
condition has been satisfied. Then those statements are called as iterative or repetitive control statements. There are 3-
different types of iterative statements available in PL/SQL. They are:

1. Loop
2. While Loop
3. For Loop

1.Loop:- Sequence of statements will be executed repeatedly until the condition has been satisfied. The condition is
specified inside the loop statement.
Syntax:- LOOP
<Sequence of statements>;
END LOOP;
Ex:- declare
A number := &A;
begin
loop
dbms_ouput.put_line(A);
A := A+1;
if A > 20 then
exit;
end if;
end loop;
end;
2. While Loop :- The sequence of statements will be executed continuously until the condition in the while loop is
satisfied.
Syntax:- WHILE <condition> LOOP
<Sequence of statements>;
END LOOP;

Ex:- declare
I number := 1;
S number :=0;
begin
while I < = 20 loop
S := S + I;
I := I + 1;
end loop;
dbms_output.put_line(‘ The sum of 20 numbers=’||S);
end;
3. For Loop:- For loop is used to iterate the sequence of statements over a specified range of integers.
Syntax :- FOR variable IN lowerbound .. upperbound LOOP
<Sequence of statements> ;
END LOOP;
Ex:- declare
S number;
E number;
begin
S:=&start;
E:=&end;
for X in S..E loop
if mod(X,2)=0 then
dbms_output.put_line(X);
end if;
end loop;
end;

5. Explain about cursors in PL/SQL (or) What is a cursor? Write the steps to create a cursor.
When a query inside a PL/SQL block returns more than one record oracle requires the place holder to place the
values. The variable provided in the INTO clause can contain only one value at a time. Inorder to process multiple
records cursors are used.Whenever a SQL statement is issued the database server opens an area of memory in which
the command is parsed and executed. This area is called a ‘cursor’. Each cursor has 4-attributes, which are given
below:

1. %ROWCOUNT:- Returns the number of rows processed by a SQL statement.


2. %FOUND:- Holds true if at least one row is processed.
3. %NOT FOUND:- Holds true if no rows are processed.
4. %IS OPEN:- Holds true if a cursor is opened.

Cursor manipulation is performed by using the following four commands.


1.Declare:- Is used to declare a cursor.
2.Open:- Is used to open a cursor.
3.Fetch:-Is used to fetch or process a cursor.
4.Close:-Is used to close a cursor.
The following example is used to select all the employee names and their jobs from the ‘emp’ table.
declare
cursor c1 is select ename,job from emp;
mename varchar(20);
mjob varchar(20);
begin
open c1;
loop
fetch c1 into mename,mjob;
exit when c1% not found;
dbms_output.put_line(mename||’ is a ‘||mjob);
end loop;
close c1;
end;
/

Subprograms
1. Subprogram is a program unit/module
2. That performs a particular task. It also called block.
3. These subprograms are combined to form larger programs.
4. This is basically called the 'Modular design'. A
5. Subprogram can be invoked by another subprogram or program which is called the calling
program
6. Subprograms can be created at the schema level, inside the package, and inside block
7. They are two types of sub programs

1. Procedures
2. Functions
Parameter Modes in PL/SQL Subprograms

User create a Procedure or function, you have to define this three parameters.

1. In
2. Out
3. In out

1. IN
a. IN parameter is referenced to the procedure or function.
b. Input parameter only, the value passed is input only.
c. And value of parameter in not overwritten

2. OUT
a. OUT parameter is referenced to the procedure or function.
b. Output only.
c. And value of parameter is overwritten allow.

3. IN OUT
a. IN OUT parameter is referenced to the procedure or function.
b. Both input and output.
c. And value of parameter is both overwritten allow or not allow.

1. Procedures
These subprograms do not return a value directly, mainly used to perform an action.

Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name (procedure parameters)
{IS | AS}
BEGIN
< procedure_body >
END;
Example:
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN

END;
dbms_output.put_line('Hello World!');
/

Procedure created.

Execute:

When above code is executed using SQL prompt, it will produce the following
result:

EXECUTE greetings; or CALL greetings(); Hello

World

PL/SQL procedure successfully completed.

Or
You might call the procedure in a PL/SQL Block.
BEGIN
greetings;
END;

Hello World
PL/SQL procedure successfully completed.

2. Functions
1. These subprograms return a single value, mainly used to compute and return a value.
2. A PL/SQL function is same as a procedure except that it returns a value.

Syntax:
CREATE OR REPLACE
FUNCTION function_name (function_params) RETURN return_type IS
BEGIN
function_body
RETURN something_of_return_type;
END;

Ex1:
CREATE OR REPLACE FUNCTION ADD_TWO (A INT,B INT) RETURN INT IS
BEGIN
RETURN (A + B);
END;

BEGIN Calling function:

END;
DBMS_OUTPUT.PUT_LINE(’RESULT IS: ’ || ADD_TWO(12,34));
/

RESULT IS: 46

 8)Benefits of Procedures and Functions


Stored procedures and functions have many benefits and addition to part application development.
1. It modifies one routine to affect multiple applications.
2. It modifies one routine to eliminate duplicate testing.
3. It avoids PL/SQL parsing at runtime by parsing at compile time.
4. It reduces the number of calls to the database
5. Database network traffic by bundling (collecting) the commands
6. User-defined functions cannot be used in situations
7. That requires an unchanging definition.
8. Thus, you cannot use user-defined functions:
a. In a CHECK constraint clause of
a CREATE TABLE or ALTER TABLE statement
b. In a DEFAULT clause of a CREATE TABLE or ALTER TABLE statement

 9)Difference Between Function and Procedure Function:


1. Functions must always return a value.
2. Functions cannot alter data or objects in a server.
3. You can embed functions within a SELECT statement.
4. Functions can accept input parameters but can return only a single return value.
5. TEMP tables can’t be used in functions.
6. user-defined functions cannot be used in CHECK or DEFAULT constraints
7. and cannot manipulate database values
8. It is mandatory for a function to have at least one RETURN statement
9. It will not allow to do the DML on existing tables. But still we can do the DML operation
only on the table variable inside the user defined functions.
10. The transaction statement cannot be used in the function. Normally we won't do any
DML operations in the function.
11. The parameters for the stored procedures can be any data types which are available
on the sql server.

 10) Explain Packages


1. A package can be defined as a collection of related program objects.
2. Such as procedures, functions, and associated cursors and variables together as a unit in the
database.
3. A package is a group of related procedures and functions
4. It stored together and sharing common variables, as well as local procedures and functions.
5. A package contains two separate parts:
a. The package specification and
b. The package body.
6. The package specification and package body are compiled separately
7. And stored in the data dictionary as two separate objects.
8. The package body is optional and need not to be created
9. The package specification does not contain any procedures or functions.
10.Applications or users can call packaged procedures and functions

Advantages of Packages
Packages offer a lot of advantages. They are as follows.
1. User can create package to store all related functions and procedures are grouped together
into single unit called packages.
2. Package is reused.
3. All function and procedure within a package can share variable among them
4. Packages are support overloading to overload functions and procedures.
5. Package are improve the performance to loading the multiple object into memory at once,
therefore, subsequent calls to related program doesn't required to calling physically I/O.
6. Packages are reduced the traffic because all block execute all at once.
7. Packages enable the organization of commercial applications into efficient modules.
8. Each package is easily understood
9. Packages interfaces between packages are simple, clear and well defined.
10.Packages allow granting of privileges efficiently.
11. Packages promote code reuse through the use of libraries
12. That contain stored procedures and functions, thereby reducing redundant coding . 13.Each
package is easy to understand, and the interfaces between packages are simple,
clear, and well defined.
14. Easier Application Design it stored programs and subprograms
15. Packages can specify which types, items, and subprograms are public (visible and accessible)
or private (hidden and inaccessible).
16. For example, if a package contains four subprograms, three might be public and one private.
17. The package hides the implementation of the private subprogram so that only the package
(not your application) is affected if the implementation changes.
18. They can be shared by all subprograms that execute in the environment.
19. To maintain data across transactions without having to store it in the database. 20.User call a
packaged subprogram for the first time, the whole package is loaded into
memory.
21. To related subprograms in the package require no disk I/O.
22. Packages stop cascading dependencies and thereby avoid unnecessary recompiling. 23.Change
the implementation of a packaged function

Units of Packages

As described earlier, a package is used to store together, the logically related PL/SQL units.
1. Procedures
2. Functions
3. Triggers
4. Cursors
5. Variables

Parts of Package
A Package has two parts. They are:
1. Package specification
2. Package body
1. Package Specification
1. The specification declares the types, variables, constants, exceptions, cursors, and
subprograms
2. These are public and thus available for use outside the package.
3. In case in the package specification declaration there is only types, constants, exception,
or variables,
4. Then there is no need for the package body because package specification are sufficient
for them.
5. Package body is required when there is subprograms like cursors, functions, etc.

2. Package Body
1. The package body fully defines subprograms such as cursors, functions, and procedures.
2. All the private declarations of the package are included in the package body.
3. It implements the package specification.
4. A package specification and the package body are stored separately in the database.
5. This allows calling objects to depend on the specification only, not on both.
6. Oracle invalidates the calling object if the package specification is changed.
Creating a Package
1. A package consists of package specification and package body.
2. Creation of a package involves creation of the package specification and then creation
of the package body.
3. The package specification is declared using the CREATE PACKAGE command.

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

PL/SQL package specification

1. All the procedures, sub programs, cursors declared in the CREATE PACKAGE command
2. They are described and implemented fully in the package body along with private
members.

Syntax:

CREATE [OR REPLACE] PACKAGE BODY <package name> [AS/IS]

PL/SQL package body

Referencing Package Subprograms

<PACKAGE NAME>.<VARIABLE NAME>

To reference procedures we have to use the syntax as follows:

EXECUTE <package name>.<procedure name(variables)>; Removing a Package


A package can be dropped from the database just like any other table or database
object. The exact syntax of the command to be used for dropping a package is:
DROP PACKAGE <PACKAGE NAME>;

 11) Explain Triggers in PL/SQL?


A trigger is an action which can be performed automatically whenever the data manipulations are
applied on the table
or
1. A database trigger is a stored procedure
2. That is fired when an insert, update or delete statement is issued against the associated table.

Syntax:

CREATE [OR REPLACE] TRIGGER trigger-name

BEFORE (OR AFTER)

INSERT OR UPDATE OR DELETE [OF COLUMNS]

ON tablename

[FOR EACH ROW [WHEN (condition)]]

BEGIN

Trigger action;

END;

 Types of PL/SQL Triggers


There are two types of triggers based on the which level it is triggered.
1. Row level trigger –
a. An event is triggered for each row upated, inserted or deleted.

2. Statement level trigger –


a. An event is triggered for each sql statement executed.

In trigger two types of pseudo (artificial) (fake) column are available they are
On the Basis of Type of Trigger/Firing or Triggering Transaction

– BEFORE Triggers
– AFTER Triggers

– INSTEAD OF

BEFORE Triggers

BEFORE triggers execute the trigger action before the triggering statement is executed. It is used to
derive specific column values before completing a triggering DML, DDL statement or to determine
whether the triggering statement should be allowed to complete.

Example

We can define a BEFORE trigger on the passengers detail table that gets fired before deletion of any
row. The trigger will check the system date and if the date is Sunday, it will not allow any deletion on
the table.
The trigger can be created in Oracle The trigger action can be shown. As soon as we try to delete a
record from passenger detail table, the above

trigger will be fired and due to SUNDAY EXP fired, all the changes will be rolled back or

undone and the record will not be deleted.

AFTER Triggers

AFTER triggers execute the trigger action after the triggering statement is

executed. AFTER triggers are used when we want the triggering statement to complete before
executing the trigger action, or to execute some additional logic to the before trigger action

You might also like