DBMS & Data Structure_BCA
DBMS & Data Structure_BCA
UNIT-1
UNIT-2
The Relational Database Model: Various Data Models, Relational Database Model, Keys used in Relational
model, Relational Data Integrity, Relational set operators, Relationships within the Relational Database,
Codd‟s relational database rules.
Entity-Relationship Model: Introduction, The components of an Entity Relationship model, entities, attributes
relationships, Classification of Entity sets, Attribute Classification, Relationship Degree, and Relationship
Classification.
UNIT-3
Introduction to SQL: Structured Query Language (SQL)-Introduction-SQL data types-SQL Literals, SQL
operators: Arithmetic Operators- Comparison Operators-Logical Operators- Set Operator Precedence.
Types of SQL Commands: DDL, DML, TCL, DCL
Tables: Creating tables – Altering tables – dropping tables – displaying structure of table – Inserting, updating,
and deleting: INSERT statement-bulk inserts of data – UPDATE statement – DELETE statement
UNIT-4
UNIT-5
PL/SQL: Introduction, Structure of PL/SQL program, PL/SQL Data Types, operators used in PL/SQL, variables,
declaring variables in PL/SQL, Creating and running a PL/SQL Program, Control structures: Conditional Control
statements, Iterative Control statements, Cursors: types of cursors, Steps to create a cursor, are using cursors in
PL/SQL program.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
2
Zenex Vision Degree College DBMS –BCA- SEM-II
UNIT-1
1. What is Data, Information , Database, and Database Management System? Explain in detail.
DATA: The collection of “raw facts" is called data. It does not provide any specific meaning. The data may be
numeric, text, audio, video etc.,
Ex 2: 16 Ravi 9000
29 Balu 8000 raw facts (data)
13 Suresh 8000
INFORMATION: The collection of processed data is called as information. The information has a specific
meaning. The information can be in a table format or graphical format.
Timely information is the key to good decision making. Timely and useful information requires accurate data.
Hence, such data must be generated properly, and it must be stored in a format that is easy to access and process.
Data management is a procedure that focuses on the proper generation, storage, and retrieval of data. So various
database management systems are developed to help data management.
DATABASE:
Database is a collection of related data and data is a collection of facts and figures that can be processed to
produce information.
A Database is the collection of logically interrelated data about a particular organization. It is a shared, integrated
computer structure that store end user data and metadata. A database is developed to quickly retrieve needed data.
For example, Employee database, publisher database, student database, Bank database, hospital database, library
database and so on.
3
Zenex Vision Degree College DBMS –BCA- SEM-II
A Database is a shared, integrated computer structure that stores a collection of END USER DATA and META
DATA.
Meta data:-Meta data means data about data (or) the data that describes the properties (or) characteristics of other
data is called "meta data". In which the end user data is integrated and managed.
The meta data provides a description of the data characteristics like data type, field size , allowable values and
descriptions. for example, the meta data for a student database is
File-based System
2. What is a File?
FILE:
A file is a collection of bytes. All data is stored as a file with a file name within the disk. It stores data in the form
of records. A record is a collection of fields. The structure of a file is known to the software that manipulates it.
3. What is a File System or File-Based System? Advantages and drawbacks of file-based system?
FILE SYSTEM:
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 using 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.
4
Zenex Vision Degree College DBMS –BCA- SEM-II
Data: data are raw facts. The data can be 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 is also called column.
Record: A set of one or more fields that describes a person, place, or thing, for example, the fields that represent
record for a student consists of name, address, phone number, date of birth, etc is also called row.
File: A collection of related records is called a file. For example, a file may contain data about students of college
etc.
ADVANTAGES:
1. Easy to use
2. The data files can be easily located in memory devices.
3. Inexpensive
4. They occupy less space in memory devices.
5. Faster performance
6. Suitable for personal data management
7. They can be opened in any editor like any other text files.
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. Sothe
programs and data are dependent to each other.
2. Data redundancy and inconsistency: In file systems, the same information may be duplicated inseveral
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 problem: 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. It doesn‟t provide backup and recovery of data if
it is lost.
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 systems, it is difficult to maintain integrity constraints. Hence
invalid data can be entered into the 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. Soit is
not possible to provide better securities to the data files.
9. Limited capacity: Only one user can access data at a time.
10. Limited functionality: There is no efficient query processing in the file system.
Note: These file systems are used to handle a single or multiple files and are not very efficient.
5
Zenex Vision Degree College DBMS –BCA- SEM-II
A database management system stores data in such a way that it becomes easier to retrieve, manipulate, and
produce information. (or)
A database management system (DBMS) refers to the technology for creating and managing databases. DBMS is
a software tool to organize (create, retrieve, update, and manage) data in a database. (or)
Database Management System (DBMS) is software for storing and retrieving users‟ data while considering
appropriate security measures. It consists of a group of programs which manipulate the database. The DBMS
accepts the request for data from an application and instructs the operating system to provide the specific data.
MySQL
Microsoft Access
Oracle
Dbase
PostgreSQL
FoxPro
IBM DB2
LibreOffice Base
Microsoft SQL Server
MariaDB etc.
ADVANTAGES:
Redundancy problem can be solved: In the File System, duplicate data is created in many places because
all the programs have their own files which created data redundancy resulting in wastage of memory. In
database system, all the files are integrated in a single database. So there is no chance of duplicate data.
The data descriptions are stored in a central location called ”Data Dictionary”. The application programs
are stored separately in a database system. The changes in the data do not require changes in the programs.
Hence the program and data are independent to each other.
Has a very high security level: Data security level is high by protecting your precious data from
unauthorized access. Only authorized users should have the grant to access the database with the help of
credentials.
Avoidance of inconsistency: Data consistency is nothing but if you want to update data in any files then
all the files should not be updated again. In DBMS, data is stored in a single database so data becomes
more consistent in comparison to file processing systems . 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.
Presence of Data integrity: Data integrity makes unification of so many files into a single file. DBMS
allows data integrity which makes it easy to decrease data duplicity Data integration and reduces
redundancy as well as data inconsistency.
Support multiple users: DBMS allows multiple users to access the same database at a time without any
conflicts.
Shared data: Data can be shared between authorized users of the database in DBMS. All the users have
their own right to access the database. Admin has complete access to the database. He has a right to assign
users to access the database.
Any unauthorized access is restricted: Unauthorized persons are not allowed to access the database
because of security credentials.
6
Zenex Vision Degree College DBMS –BCA- SEM-II
Enforcement of standards: As DBMS have central control of the database. So, a DBA can ensure that all
the applications follow some standards such as format of data, document standards etc. These standards
help in data migrations or in interchanging the data.
Provide backup of data: Data loss is a big problem for all the organizations. In the file system users
have to back up the files in regular intervals which lead to waste of time and resources. DBMS solves this
problem of taking backup automatically and recovery of the database.
DISADVANTAGES:
1. High Cost
The high cost of software and hardware is the main disadvantage of the database management system.
Database users require a high-speed processor and huge memory size to use the database on the DBMS.
Sometimes, users require costly machines for maintaining databases.
Organizations need a trained and highly paid technical database administrator for using and maintaining the large
database systems.
2. Huge Size
The size of the database is not big at the initial state, but when the user stores a large amount of data, then it creates
many problems. Due to the huge data, database systems do not provide good results and do not run efficiently.
That's why the size is another limitation of the database systems.
3. Database Failure
In the database systems, all the data or information of an organization is stored in one centralized database. If the
database of that organization fails, then the data is lost, and the organization will collapse. So, database failure is a
big problem with the database management system.
4. Complexity
Database management system (DBMS) is so complex for non-technical users. So, it isn't easy to manage and
maintain database systems. Therefore, training for the designers, users, and administrators is necessary to
efficiently run the database systems.
5. Increased Staff Cost
DBMS requires an educated and skilled staff for managing and maintaining the databases. So, we need to spend a
lot of money to get this level of trained and experienced staff.
6. Requirement of Technical Staff
A non-technical people can't understand the complexity of the database. So, the technical staff is required for
maintaining and handling the database management system.
7. Cost of Data Conversion
It is one of the big disadvantages of the database management system because the cost of data conversion is very
high. There is a requirement for trained, skilled, and experienced database administrators for converting the data
smoothly.
8. Performance
Performance is another big disadvantage of database systems because the speed of the database systems for small
firms and organizations is very slow. Hence, the performance of the database systems in small organizations is
poor.
7
Zenex Vision Degree College DBMS –BCA- SEM-II
A database model describes the database structure of DBMS. The structure of database refers to the data types,
constraints and relationships used on the data.
The data model also describes the basic operations of retrieving the data from a database and updating the data in
the database. There are mainly four data models. They are…
Hierarchical Database System Structure was developed by IBM in the early 1960s.
In hierarchical data model, data is organized in a tree-line structure. The tree structure consists of hierarchy of
parent and child data segments.
This type of database management software allows one-to-one and one-to-many relationships, i.e., a parent node
can have one or multiple child nodes, whereas the children node can only have one parent node.
It is simple but inflexible due to the parent-child one-to-many relationship. They are mostly used in Banking and
Telecommunications industries to build high performance and manage applications.
The relational model was introduced by Dr. E. F. Codd. It is a conceptual theory of data that is based on the
mathematical theory of relations.
In a relational model, the data is stored in tables. There are three main terms used frequently in relational database
models. They are relations, attributes, and domains. A relation is a table with columns and rows. The name
columns of the relation are called attributes, and the domain in the set of values of the attributes.
The properties of a relation (table) in a relational model are as follows. Each row can contain a single value for
each of its attributes. Same field
8
Zenex Vision Degree College DBMS –BCA- SEM-II
Order Items
The network model is also called CODASYL (Conference On Data Systems Language) model. It recognizes data
using set constructs. Each set consists of an owner (parent) record type and a member (child) record type.
In this model, a record may be an owner in any number of sets, and a member in any number of sets. So this model
has ability to handle many-to-many (N:N) relationships. Thus it allows a record more than one parent.
TurboIMAGE, Integrated Database Management System (IDMS), Integrated Data Store (IDS)
Object oriented data model is based upon real world situations. These situations are represented as objects, with
different attributes. All these objects have multiple relationships between them.
The object-oriented model consists of a collection of objects. It supports OOP concepts like objects, classes,
inheritance, polymorphism etc. in the query language.
An object-oriented data model allows us to store different types of data. It is suited for multimedia applications as
well as with complex relationships. It allows fully integrated databases that hold data such as text, pictures, audio
and video. SHAPE
getArea() getPerimeter()
Eg:
Shape, Circle, Rectangle and Triangle are all objects in this model.
Circle has the attributes Center and Radius, Rectangle has the attributes Length and Breadth, and Triangle has the
attributes Base and Height.
9
Zenex Vision Degree College DBMS –BCA- SEM-II
TYPES OF DATABASES
A database is a shared, integrated computer structure that stores a collection of end user and metadata. A DBMS
can support different types of databases. The databases can be classified as follows.
DATABASES
Based on Users
a). Single User Database: A single use database support only one user at a time. A single user database that runs on
a personal computer is called personal or desktop database. There is no sharing of data in single user database.
b). Multi User Database: A multi user database support multi users at the same time. When the multiuser database
Databa
supports few users (less than 50) then it is called workgroup database. When the database supportssemany users
User
(more than 50) then it is called enterprise database. System
User 1 Databa
User User
se
System
Based on Location:
User
a). Centralized Database: A database that supports data located at a single site (location) is called a centralized
database. This location is most often a central computer or database system that can be a desktop or server CPU, or
a mainframe computer.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
b). Distributed Database: A distributed database is a database in which data is stored across different physical
locations. It may be stored in multiple computers located in the same physical location.
A distributed database is a database that consists of two or more files located in different sites either on the same
network or on entirely different networks. Portions of the database are stored in multiple physical locations and
processing in distributed among multiple databases nodes.
Operational Database: A database that is designed to support a company‟s day-to-day operations is called an operation
Data warehouse: A data warehouse is a large storage space. It collects data from various sources on locations. The data wa
7. What are the functions and services of DBMS?
A DBMS performs several important functions that guarantee integrity and consistency of data in the database. Most of the
i) Data Storage Management: It provides a mechanism for management of permanent storage of the data. The internal sch
manager interfaces with the operating system to access the physical storage.
(ii) Data Manipulation Management: A DBMS furnishes users with the ability to retrieve, update and delete
existing data in the database.
(iii) Data Definition Services: The DBMS accepts the data definitions such as external schema, the conceptual
schema, the internal schema, and all the associated mappings in source form.
(iv) Data Dictionary/System Catalog Management: The DBMS provides a data dictionary or system catalog
function in which descriptions of data items are stored and which is accessible to users.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
(v) Database Communication Interfaces: The end-user's requests for database access are transmitted to DBMS in
the form of communication messages.
(vi) Authorization / Security Management: The DBMS protects the database against unauthorized access, either
international or accidental. It furnishes mechanism to ensure that only authorized users an access the database.
(vii) Backup and Recovery Management: The DBMS provides mechanisms for backing up data periodically and
recovering from different types of failures. This prevents the loss of data,
(viii) Concurrency Control Service: Since DBMSs support sharing of data among multiple users, they must
provide a mechanism for managing concurrent access to the database. DBMSs ensure that the database kept in
consistent state and that integrity of the data is preserved.
(ix) Transaction Management: A transaction is a series of database operations, carried out by a single user or
application program, which accesses or changes the contents of the database. Therefore, a DBMS must provide a
mechanism to ensure either that all the updates corresponding to a given transaction is made or that none of them is
made.
(x) Database Access and Application Programming Interfaces: All DBMS provide interface to enable
applications to use DBMS services. They provide data access via Structured Query Language (SQL). The DBMS
query language contains two components: (a) a Data Definition Language (DDL) and (b) a Data Manipulation
Language (DML).
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 (H/W):-It refers to all of the system's physical devices like micro computers ,main frames ,work
stations, storage devices , printers, I/O channels, network devices etc., It is impossible to implement the DBMS
without the hardware devices. In a network, a powerful computer with high data processing speed and a storage
device with large storage capacity is required as database server.
2. Software (S/W):-To make the database system function fully ,3 types of software are required for a database
system. They are:-
a. operating system s/w
b. DBMS s/w
c. application programs and utility s/w
1
Zenex Vision Degree College DBMS –BCA- SEM-II
Operating System S/W:-It manages all hardware components and makes it possible for all other software to run
on the computers. Examples of operating system s/w are Microsoft windows, UNIX, LINUX etc.,
DBMS S/W:-It manages the database within the database system. Examples of DBMS s/w are Microsoft access
and SQL Server, Oracle, IBM's DB2 etc.,
Application Programs and Utility S/W:-These are used to access and manipulate data in the DBMS and to
manage the computer environment in which data access and manipulation take place.
(or)
Application programs developed in programming languages such as C++, Visual Basic that are used to to access
database in database management system. Each program contains statements that request the DBMS to perform
operation on database. The operations may include retrieving, updating, deleting data etc . The application program
may be conventional or online workstations or terminals.
Utilities are the s/w tools used to help manage the database system's computer components.
3. People:- The users are the people who manage the databases and perform different operations on the databases
in the database system. Based on their job, the users are classified into 5 types. They are:-
i. System administrators
v. End users
i. SYSTEM ADMINISTRATORS: They are the persons who supervise the database system's generaloperations.
ii. DATABASE ADMINISTRATORS: A person who is responsible for managing the overall database
management system is called database administrator or simply DBA.
iii. DATABASE DESIGNERS: Database designers are the persons, who can design the database structure. For
success of an organization, a good database design is most important.
v. END USERS: The end-users are the people who interact with database management system to perform
different operations on database such as retrieving, updating, inserting, deleting data etc.
4. PROCEDURES: Procedures refer to the instructions and rules that help to design the database and to use the
DBMS/database system. The users that operate and manage the DBMS require documented procedures on hot use
or run the database management system. These may include.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
5. DATA: Data is the most important component of the DBMS. The main purpose of DBMS is to process the data.
The processed data is called information. In DBMS, databases are defined, constructed and then data is stored,
updated and retrieved to and from the databases. The database contains both the actual (or operational) data and the
metadata (data about data or description about data). What data should be stored in a database and how the data is
to be organized in a database is a database designer's job.
A database environment is a collective system of components that comprise and regulates the group of data,
management, and use of data, which consist of software, hardware, people, techniques of handling database, and
the data also.
Here, the hardware in a database environment means the computers and computer peripherals that are being used
to manage a database, and the software means the whole thing right from the operating system (OS) to the
application programs that include database management software like M.S. Access or SQL Server. Again the
people in a database environment include those people who administrate and use the system. The techniques are
the rules, concepts, and instructions given to both the people and the software along with the data with the group of
facts and information positioned within the database environment.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
UNIT-2
INTRODUCTION: The relational data model was developed in 1970 by prof .E. F. Codd. This data model
organizes the data in the form of tables. The tables are also called as relations. The relational data model consists of
mainly 3 components. They are:
1. Data structure
2. Data manipulation
3. Data integrity
I.DATA STRUCTURE: It defines organization of data in the form of tables containing rows & columns.
2. DATA MANIPULATION: It performs various operations like insert, delete, update, and so on in the database.
3. DATA INTEGRITY: It provides facilities to specify rules that maintain the integrity of data when they
are manipulated.
The relational models enable you to view the data logically rather than physically. The logical view of the
relational database is facilitated by the creation of data relationships based on the logical construct called as a
"table".
A table is a two dimensional structure contains rows & columns. In these rows & columns, the data is stored.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
Key is an attribute (also known as column or field) or a combination of attributes that is used to identify
records. They are also called Identifier Attributes.
1. Super Key: A super key is one or more attributes that identify the records uniquely. Any Unique key
with N Unique key combination is called a super key of the relationship. A table can have many Super
Keys.
Example: Consider relation
A table can have many Super Keys.
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
1. Super Key: A super key is one or more attributes that identify the records uniquely. Any Unique key will
Unique key combination is called a super key of the relationship. A table can have many Super Keys. Example:
Consider the relation,
Student (HTNO, Stname, Course, Address)
The super keys are
i. {HTNOY
ii. ii. {HTNO, Stname}
iii. iii. {HTNO, Stname, Course}
iv. 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 unique identify a
record in a relation.
For example, consider the relation
Student (HTNO, Stname, Course, Address) The super keys are
i. {HTNO} → It is Candidate Key. Because it contains minimal (only one) attributes. Isi.{HTNO, Stname}
iii. {HTNO, Stname, Course},
iv. {HTNO, Stname, Course, Address
3. Primary key: The primary 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 present in child table.
For example,
Student(HTNO, Stname, Course, Address) Heře
HTNO is the Primary Key Marks (HTNO, Sub1, Sub2) Here, HTNO is the Foreign Key.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
Relational database integrity rules are very important to good database design .Many RDBM'S enforce integrity
rules automatically.
An integrity constraint is a condition used to prevent invalid data entity into the table. It enforces rules of the
columns in a table. Constraints are use d to maintain relational data integrity. A constraint can be specified while
creating or altering table structure.
The columnconstraint and tableconstraints can be any type of data integrity constraints.
Types of Constraints:
There are three types of constraints in SQL to maintain integrity while inserting or updating data of a table
1. Domain Integrity Constraints: Domain constraints allow only specified values into a column, NOT NULL
and CHECK constraints are the domain constraints.
a). NOT NULL: It doesn‟t allow null values. It must be used as only column constraint.
b). CHECK: This constraint provides a condition so that a value entered into the table has to satisfy
the condition. It can be used as columnconstraint or tableconstraint.
Entity Integrity ensures that there are no duplicate rows in a table. They maintain uniqueness in a table UNIQUE
and PRIMARY KEY are the entity integrity constraints.
a) UNIQUE: This constraint prevents duplicate values in the specified columns. However , it allows number
values in the column. It can be used as columnconstraint or tableconstraint.
Eg: CREATE TABLE student(Rollno number(6) UNIQUE);
b) PRIMARY KEY: This constraint prevents duplicate and null values in the specified column. However ,
only one primary key can be created for each table. It can be used as columnconstraints or
tableconsraint.
The referential integrity constraint is a validation rule between two columns of same or different tables. It
allows values of a column into another column. It can be used as columnconstraint or tableconstraint.
1
Zenex Vision Degree College DBMS –BCA- SEM-II
Child Table(Tableconstraint)
CREATE TABLE Fee(Rollno number(4), Amount number(8,2)),
FOREIGN KEY(Rollno) REFERENCES student(Rollno));
Relationships are used to represent association between 2 entities (or) more entities .In the design of relational
database, we can use different types of relationships. they are:-
1. One-To-One Relationship:-In this relationship one instance of an entity is related to the one instance of
another entity.
Is
marrie
d to
PERSO
N
2. One-To-Many Relationship:-In this relationship, one instance of an entity is related to many instances
of another entity.
PAINTER PAINTINGS
Paints
1
Zenex Vision Degree College DBMS –BCA- SEM-II
3. Many-To-Many (m:m) relationship:-In this relationship, many instances of an entity is related to the
many instances of another entity.
STUDENT COURSE
join
1
Zenex Vision Degree College DBMS –BCA- SEM-II
The Entity Relationship model is a detailed logical representation of the data for an organization. An E-R
model is normally expressed through E-R diagrams, which is a graphical representation of an E-R model. The E-R
model is expressed in terms of entities, relationships among these entities. Each entity has a set of attributes.
Derived attribute
Weak Entity
Relation ship
Associative entity
type Identifying relation ship
Composit
s a high level conceptual data model that shows graphical representation of entities, attributes and their relationships. It is developed by Pet
hey are
1. Entities
2. Attributes
3. Relationships
1. ENTITIES:- The fundamental unit in any data model is the entity. An entity is a person, object, place, thing or
event and so on about which the organisation wishes to maintain data. Each entity has set of attributes. We will
use rectangle symbol to define entity in database environment.
for example:-
Entity type/Entity set:-An entity type is a collection of entities, that can share common properties (or)
characteristics. Each entity type in an E-r model is given a name with capital letters and in singular form .
2
Zenex Vision Degree College DBMS –BCA- SEM-II
For example:-
Entity type:-STUDENT
Attributes:- Sno,Sname,Address,Fee...
1. Strong entity
2. Weak entity
3. Associative entity
Strong Entity: In an organization, most of the entity types are classified as strong entity types. A strong entity is
an entity, it has one primary key(identifier attribute) and that does not depends up on other entity. In E-R diagrams
strong entities are represented by rectangle symbol.
Weak Entity: A weak entity is an entity, It has no primary key and that depends up on other entity. In E-R
diagrams weak entities are represented by double lined rectangle symbol. For example „DEPARTMENT‟ doesn‟t
contain a primary key. The weak entity has partial identifier attribute. It depends on the strong entity
„EMPLOYEE‟ called OWNER.
EMPLOYEE
hhaass DEPARTMENT
2
Zenex Vision Degree College DBMS –BCA- SEM-II
Associative entity:-An associative entity is nothing but an entity with relationship containing identifier attribute
(or ) not containing identifier attribute. It is represented by using the symbol
for example:-
associative entity
2.Attributes:-Each entity type is associated with a set of attributes. An attribute is nothing but a property (or) a
characteristic of an entity type. Each attribute is associated with a set of values called domain. We will use the
oval symbol to define an Attribute
EMPLOYEE
entity
[NOTE:The attributes are represented by giving a name with "initial capital letter" followed by lower case letters
with in the "ellipse symbol". If an attribute name consists of more than one word, we can use underscore symbol to
connect these words and we can start each word with a capital letter.]
4.Multi-valued attribute
Simple Attribute: A simple attribute is an attribute that cannot be divided into smaller components is called
simple attribute. These attributes are represented by using ellipse symbol. For example, „Eno‟ is an attribute
cannot be divided into different components.
Composite Attribute: A composite attribute is an attribute that can be divided into smaller components is called
composite attribute. These.
For example, „Address‟ is an attribute can be divided into different components like Street, City, Pin etc. attributes
are represented by.
for example:-
2
Zenex Vision Degree College DBMS –BCA- SEM-II
EMPLOYEE
Address Composite attribute
Smaller components
Single valued Attribute: A single valued attribute is an attribute that have only one value of the entity instance.
For example, the entity type „EMPLOYEE‟ has an attribute „Salary‟, it takes only one value for a given entity
instance. So „Salary‟ is a single valued attribute. Single value attributes are represented by using ellipse symbol.
Multi valued Attribute: A multi valued attribute is an attribute that takes more than one value for a given entity
instance. In E-R diagrams multi valued attributes are represented by using double ellipse symbol.
Eno Ename
Salary Attributes
EMPLOYEE Skills
Derived Attributes: A derived attribute is an attribute whose values can be calculated from other attribute values.
In E-R diagrams the derived attributes are represented by using dashed ellipse symbol. For example, the „Service‟
can be calculated from his „DOJ‟ .
Identifier Attribute: An identifier attribute is an attribute that uniquely identifies individual entity instance of an
entity. It is represented by ellipse symbol, inside with single underlined. For example,
2
Zenex Vision Degree College DBMS –BCA- SEM-II
Composite identifier attribute:-An identifier that consists of a composite attribute is called the composite
identifier attribute. It is represented by ellipse symbol, inside with double underlined.
Far
No_of_seat
3. Relationships:-A relationship is an association between two entities. In E-R diagram, the relationships are
represented by a diamond symbol containing the name of the relationship. In case of relationship between
strong and weak entities, we can use a diamond symbol with double line. For example:
Completes
STUDENT COUR
SE
Types of Relationships:- Relationships are classified by their degree, connectivity, cardinality, existence. A
relationship between entities is described in terms of degree, connectivity, existence dependency, and cardinality.
Based on the degree, cardinalities, the relationships are mainly classified into two types. They are:-
Degree of relationship:-The degree of a relationship is the number of entity types that participate in a relationship.
There are three types of relationship degrees in an E-R model. They are
1. Unary relationship
2. Binary relationship
3. Ternary relationship
Unary Relationship: An entity is associated itself is called unary relationship (or) recursive relationship. Its
degree=1.
Eno
Salary
Binary Relationship: A relationship between two entities is called binary relationship. It is the most commonly
used relationship type in E-R model. Its degree=2.
2
Zenex Vision Degree College DBMS –BCA- SEM-II
EMPLOYEE COURSE
teaches
Ternary Relationship: A relationship between three entities is called ternary relationship. Its degree=3.
SUBJEC
Teaches STUDENT
TEACHE
Connectivity of Relationship: The connectivity describes the relationship classification. The relationship is
classified into one-to-one, one-to-many, many-to-many or many-to-one. The E-R diagram indicates the
relationship‟s connectivity by placing a 1, M or N near the related entities.
Connectivity refers to the number of entity instances. An entity instance is a particular occurrence of an entity.
There are 4 types of connectivity. They are one-to-one, one-to-many, many-to-many or many-to-one. The E-R
diagram indicates the relationship‟s connectivity by placing a 1, M or N near the related entities. For example, let
us assume X and Y are two entity sets then the relationship connectivity is as follows:
One-to-one Relationship :In this type, an entity in X is associated with at most one entity in Y, and an entity in Y
is associated with at most one entity in X.
Example:
1 1
EMPLOY Join DE
EE
The above relationship indicates that one employee has to join in only one department.
One-to-many Relationship: In this type, an entity in X is associated with any number of entities in Y. However,
an entity in Y is associated with at most one entity in X.
Eg:
DEP 1 N EMPLOYE E
Ha
2
Zenex Vision Degree College DBMS –BCA- SEM-II
The above relationship indicates that one department has many employees.
Many-to-one Relationship: In this type, an entity in X is associated with at most one entity in Y. However, an
entity in Y can be associated with any number of entities in X.
Eg:
EMPLOYEE N 1 DEP T
Joi
The above relationship indicates that many employees can join in only one department.
Many-to-many Relationship: In this type, an entity in X is associated with any number of entities in Y and an
entity in Y is associated with any number of entities in X.
Eg:
N N
TEACHE Teac STUDEN
The above relationship connectivity indicates that many teachers teach many students.
2
Zenex Vision Degree College DBMS –BCA- SEM-II
UNIT-3
INTRODUCTION TO ORACLE
ORACLE means “Oak Ridge Automated Computing Logical Engine”. Oracle is an Object Relational Database
Management System (ORDBMS) package. It offers capabilities of both relational and object-oriented database
system. The oracle provides various tools (or) products based on a technology called Client-Server technology. In
this technology, the server performs database activities and client help the user to interact with the database
application.
Tools of ORACLE: The oracle provides various tools. They are
1. SQL *PLUS
2. PL/SQL
3. FORMS
4. REPORTS
Here SQL *PLUS and PL/SQL are back-end tools(SERVER)
FORMS and REPORTS are front-end tools(CLIENT).
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.
History of SQL:
The language, Structured English Query Language (SEQUEL) was developed by IBM to use E.F.Codd’s
relational model. SEQUEL later became SQL. In 1979, Oracle Corporation introduced the first commercially
available implementation of SQL.
The American National Standards Institute (ANSI) and the International Standards Organization
(ISO) have accepted SQL as the standard language for relational databases. Today, SQL is widely accepted
standard RDBMS language. The SQL consists of a set of facilities for defining, accessing and managing relational
databases.
Characteristics (Features) of SQL:
1. SQL usage by its nature is extremely flexible. It uses a free form syntax that gives the user the ability
to write SQL statements in a easy way.
2. Each SQL command is analyzed by the RDBMS before execution, to check for proper syntax and
to process the command.
3. The SQL commands are very simple to write and easy to understand.
SQL LITERALS
A literal is a fixed value. It doesn‟t change its value. It is also called constant. In SQL, literals are classified
as follows:
LITERALS
INTEGER FLOATING
2
Zenex Vision Degree College DBMS –BCA- SEM-II
Integer Literals:
Any number without fractional part is called an integer constant. The integer numbers can contain digits (0..9)
and sign (+ or -). An integer constant must not contain commas and spaces.
Eg: 3 -3 15 -15 2500 -9700 etc.
Text Literals:
A sequence of one or more characters enclosed within single quotes is called text literal. These are also known as
string literals or character strings;
Eg:
„Nellore‟
„SQL-99‟
„Vikrama Simhapuri University‟
Date Literals:
Any date value enclosed within single quotes is called date literal. The date literals must be in the format „DD-
MON-YYYY‟.
Eg: ‟12-JUL-2022‟
SQL OPERATORS
An operator is a symbol or keyword used to perform arithmetic and logical operations. In SQL, operators are
classified into the following types. They are
1 Arithmetic operators
2 Relational (comparison)
operators 3 Logical operators
4 Set operators
5 Special relational operators
1 Arithmetic Operators: Arithmetic operators are used to perform mathematical operations likeaddition,
subtraction etc.
Operator Meaning Example Result
+ Addition 10+3 13
- Subtraction 10-3 7
* Multiplication 10*3 30
/ Division 10/3 3.333
10 | | 30 1030
|| Concatenation
10 | | „AB‟ 10AB
2 Relational (comparison) Operators: The relational operators compare two values and give the result either
true or false. These are used to form simple conditions.
Operator Meaning Example Result
> Greater than 50>40 T
< Less than 50<40 F
= Equal to 50=40 F
>= Greater than or equal to 50>=40 T
<= Less than or equal to 50<=40 F
!= Not equal to 50!=40 T
Logical Operators: The logical operators combine two conditions or to negate the result of a condition and give
the result either true or false. These are used to form compound conditions.
2
Zenex Vision Degree College DBMS –BCA- SEM-II
4 Set Operators:
Set operators are used to combine the output of two queries. These are used to form union queries.
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 rows of the first query but not in the second query
Operator Meaning
IN Compares equal to any value in the list of values
BETWEEN Compares range of values
IS Compares nulls
LIKE Compares string patterns
ALL Compares all values within the list
ANY or SOME Compares any or some of values in the list
The data type is the characteristic of a column in a table. It specifies the type of data to be entered into the column
of a table. The data types are used in creating a table structure. SQL data types are as follows
1 NUMBER data type: This data type allows numeric values
only. Syntax: NUMBER (L,D)
L indicates length i.e. number of digits. D indicates the number of decimal places within the length
The length should be in the range from 1 to 38 digits. The length is optional. If it is omitted, it takes
38 digits as default length.
2
Zenex Vision Degree College DBMS –BCA- SEM-II
3 VARCHAR2 data type: This data type allows any type of character i.e. alphabet, digit, or symbol. It
stores variable length strings.
syntax: VARCHAR(size)
The „size‟ indicates maximum number of characters allowed in each cell of column
The „size‟ must be in the range from 1 to 4000
bytes Eg: varchar2(20)
4 LONG data type: This data type allows any type of character i.e. „alphabet, digit, or symbol. It stores
variable length strings. It can store upto 2 Giga Bytes in each cell.
Syntax: LONG
Eg: long
5 DATE data type: This data type allows date values. Date values must be entered in „DD-MON-YYYY‟
format. Syntax: DATE
Eg: date
6 RAW data type: It is used to store small size multimedia information like images, audio and video. It stores
data in binary or hexadecimal format
Syntax: RAW(size)
The „size‟ must be in the range from 1 to 255
bytes Eg: raw(100)
7 LONG RAW data type: It is used to store large size multimedia information like images, audio and video.
It stores data in binary or hexadecimal format.
Syntax: LONG RAW
Eg: long raw
3
Zenex Vision Degree College DBMS –BCA- SEM-II
TCL commands:
Transaction Control language(TCL) commands manage changes made by Data Manipulation Language
commands. These commands are used to save or cancel the process of DML commands. COMMIT, ROLLBACK
and SAVEPOINT commands are treated as TCL commands.
TABLES
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.
COLUMNS
Create Table: In SQL, the database primary object is table. To create that tables we can use create table
command.
Syntax:
CREATE TABLE <table-name> (column data-type (size),...);
Ex:
SQL> CREATE TABLE books ( isbn number(3), bname varchar2(21), aname varchar2(21),price number(7,2));
SQL> CREATE TABLE product ( pcode varchar2(11), pname varchar2(21), mfd date);
SQL> create table empl ( eid number(5),ename varchar2(31), job varchar2(21),salary number(8,2), doj date);
NOTE:
Create Table Rules:
1. While naming a table the first letter must be an alphabet.
2. Oracle reserved words can't be used to name a table or column.
3
Zenex Vision Degree College DBMS –BCA- SEM-II
Alter Table: The alter table command is used to change the structure of a database object(for ex: table).That
means you can add, modify, drop and rename columns of a table by using ALTER TABLE command. It is also
used to add constraints and remove constraints from the table.
Syntax: ALTER TABLE <table-name> [ADD | MODIFY] (Column data-type (size)...);
ALTER TABLE <table-name> DROP (column-names);
Adding new columns to a table:-
Ex: SQL> ALTER TABLE empl ADD(JOB VARCHAR2(11));
SQL> alter table books add(pubname varchar2(21),address varchar2(20));
Removing existing columns from a table:-
Ex: SQL> alter table empdet drop(doj); (or) sql>alter table empdet drop column doj;
SQL> alter table empdet drop(job,sal);
Modifying data type and width of existing columns in a
table:- Ex: SQL> alter table books modify (bname
varchar2(28));
SQL> alter table product modify(pcode number(5),pname char(20));
Changing the existing column name into new name:(works in sql 10g)
Syntax: alter table tablename rename column oldcolumnname to newcolumnname;
Ex: sql>alter table empl rename column eid to empid;
Rules for Adding Column:
1. You can't specify where the column is to appear. The new column becomes the last column in the table.
2. If a table already contains rows when a column is added, then the new column is initially null for all therows.
Rules for Drop Column:
1. The column may or may not contain data.
2. The table must have at least one column remaining in it after it is altered.
4. Once a column is dropped, it can't be recovered.
Rules Modify Column:
1. You can increase the width or precision of a numeric column.
2. You can increase the width of numeric or character column size.
3. You can decrease the width of a column only if the column contains null values or if the table has no rows.
4. You can change the data type only if the column contains null values (no values).
DROP TABLE Command:
The DROP TABLE command is used to remove (or) drop a table. When you drop a table, the database
loses the table and table data as well as the indexes associated with it.
Syntax:
DROP TABLE <table-name>;
Ex: SQL> drop table books;
Note: Once table is dropped can't be recovered.
TRUNCATE TABLE Command: It is used to remove all the data permanently but not the structure.
Syntax: truncate table tablename;
Ex: sql> truncate table bonus;
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 either table, view or synonym name which must be present in the
database. Eg: sql> DESCRIBE employee; (or) sql>DESC employee;
3
Zenex Vision Degree College DBMS –BCA- SEM-II
DML COMMANDS
The DML(Data Manipulation Language) commands are used to manipulate data within the ORACLE database.
They are used to insert, delete, update, and query the data in the database objects. The DML commands supported
by SQL are
1. INSERT Command
2. UPDATE Command
3. DELETE Command
4. SELECT Command
1. 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.
Method-1: Inserting Single Row:
INSERT INTO tablename VALUES ( values-list );
Here, the „tablename‟ specifies the name of the existing table. The „values-list‟ specifies the values that
are inserted into the table. The number and order (data type) of values in the „values-list‟ must match with the
number and order of columns of the table. All the values in the „values-list‟ must be separated by commas.
Eg:sql> INSERT INTO employee VALUES ( 1001,‟KUMAR‟,‟MANAGER‟,4500);
Method-2: Inserting values into particular columns: We can also insert values into the table in the specified
columns .
Syntax: INSERT INTO tablename ( column-list ) VALUES ( values-list );
Here, the „column-list‟ indicates the column names of the table. We can specify column names in
any order. The number and order (data type) of values in the „values-list‟ must match with the number and
order of columns in „column-list‟.
Eg: Sql>INSERT INTO employee (Empname, Joindate ) VALUES („XYZ‟, ‟12-JUN-89‟ );
Sql>insert into books values(&isbn,‟&bname‟,‟‟,&price);
Method-3: Inserting Multiple (bulk) Rows:
Syntax insert into tablename values(columnslist);
EX: sql> insert into books values (&isbn,‟&bname‟,‟&aname‟,&price );
[ NOTE:We can also insert multiple rows by retrieving records from another table using SELECT statement as
follows:
Method-1: INSERT INTO tablename query;
In the above syntax, the „tablename‟ is the name of the existing table in which we want to insert
the records. The „query‟ retrieves one or more rows from another table.
The number and order of columns in „query‟ must match to the number and order of columns of
the specified table.
Eg:
1. Sql>INSERT INTO sample SELECT * FROM employee;
2. Sql>INSERT INTO sample SELECT * FROM employee WHERE
job=‟CLERK‟; Method-2: INSERT INTO tablename(column-list) query;
In the above syntax, the „tablename‟ is the name of the existing table in which we want to insert
the records. The „query‟ retrieves one or more rows from another table.The number and order of columns
in „query‟ must match to the number and order of columns in the „column-list‟.
Sql>INSERT INTO newemp (ename, job) SELECT Empname, Job FROM emp;
Sql> INSERT INTO newemp (ename, job) SELECT Empname, Job FROM emp
WHERE sal>5000; ]not compulsory
3
Zenex Vision Degree College DBMS –BCA- SEM-II
2. UPDATE command:You can modify existing row or rows by using the UPDATE
command. Syntax: UPDATE <table-name> SET column1 = value1,… [WHERE
<condition>];
Ex: SQL> update EMP set ename='SURESH' where empno=7790;
Sql> update books set bname=‟oracle‟;
SQL> update student set total=cpp+vb+oracle;
SQL> update student set aveg=total/3;
SQL> update student set result='Pass' where result is null;
SQL> update student set result='Pass' where cpp>=35 and vb>=35 and
oracle>=35; SQL> update empdata set job=null where eid=102;
Note: The UPDATE statement modifies specific row or rows if the 'WHERE clause' is specified otherwise
modified all rows.
3. 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. Sql>DELETE FROM student;
It deletes all rows from „student‟ table.
2. Sql> DELETE FROM student WHERE result =
„FAIL‟; It deletes rows from student table whose result
is „FAIL‟.
3. Sql>DELETE FROM employee WHERE job = „CLERK‟ and Joindate<‟12-MAR-89‟;
It deletes rows from employee who are joined before ‟12-MAR-89‟ and job is
„CLERK‟.
3
Zenex Vision Degree College DBMS –BCA- SEM-II
UNIT-4
QUERIES
The query is a process that retrieves required information from the database. The SELECT command is used to
query the database.
Uses of Queries:
1 To retrieve required data from one or more tables
2 To sort the data on multiple columns
3 To group the rows based on columns
4 To join data of multiple tables together
5 To find result of various expressions or
functions 6 To perform union operations
4. SELECT Command: It is also called as Query language command. It is used to display (or )query( or)
retrieve data from the table.
Syntax:
Select specific columns /* from tablename [where condition];
Here * means all columns.
Ex:1 sql>select *from books;
It displays all columns and all rows of a specified table.
Ex:2 sql>select *from books where bname=‟oracle‟;
It displays all columns and specific rows of a specified table.
Ex:3 sql>select isbn,bname from books ;
It displays specific columns and all rows of a specified table.
Ex:4 sql>select isbn,bname from books where price=200 ;
It displays specific columns and specificl rows of a specified table.
DISTINCT Clause: It eliminates duplicate values in the output. It displays only one value from the
duplicates. Eg: SELECT DISTINCT job FROM emp;
WHERE Clause: It is used to specify a condition using non-group values. When it is used, it retrieves all the
rows that match the given condition.
Eg: SELECT * FROM emp WHERE job=‟CLERK‟ AND salary<5000;
GROUP BY Clause: It is used to combine a group of rows based on the values of specified column(s). Eg:
SELECT JOB,COUNT(*) FROM employee GROUP BY job;
HAVING Clause: It is used to specify a condition using aggregate(group)functions.
Eg: SELECT JOB, COUNT(*) FROM employee GROUP BY job HAVING COUNT(*)>3;
ORDER BY Clause: It is used to display rows either in ascending or descending order based on the specified
columns. The keyword DESC is used to display rows in descending order. If it is omitted,
SELECT command displays rows in ascending order.
Eg:
1. SELECT * FROM emp ORDER BY salary;
2. SELECT * FROM emp ORDER BY salary DESC;
3
Zenex Vision Degree College DBMS –BCA- SEM-II
An integrity constraint is a condition used to prevent invalid data entry into the table. It enforces rules for
the columns in a table.
Syntax to define constraints:
CREATE TABLE tablename ( column datatype(size) [CONSTRAINT constraintname] constrainttype, ….);
Where „constrainttype‟ is one of the following:
NOT NULL,CHECK,UNIQUE,PRIMARY KEY,FOREIGN KEY…REFERENCES
The „constraintname‟ is a user-defined word which is used to give name to the above constraints. If it is
omitted, SQL gives default constraint name starting with SYS_C followed by a number like SYS_C00123. These
constraint names are used to drop constraints.
Types of Constraints:
There are three types of constraints in SQL to maintain integrity.
1. Domain Integrity Constraints
2. Entity Integrity Constraints
3. Referential Integrity (Foreign Key) Constraints
1. Domain Integrity Constraints: Domain Integrity enforces valid entries for a given column by restricting
the format or the range of possible values. NOT NULL and CHECK constraints are the domain constraints.
NOT NULL: This constraint enforces that the column will not accept null values. By default, all the columns in a
table allow null values. It must be used only at column level.
Eg:
SQL>CREATE TABLE student ( Rollno Number(5) CONSTRAINT rno NOT NULL,
Stname Varchar2(25) NOT NULL, Course Varchar2(4) );
In the above example, the columns Rollno and Stname do not allow null values, but Course column allows
null values.
CHECK: This constraint provides a condition so that a value entered into the table has to satisfy the condition
before it is stored. The CHECK constraint consists the keyword CHECK followed by a condition within
parenthesis. While insert or update, any invalid value entered then this constraint will give an error.
Eg:
SQL> CREATE TABLE student( Rollno Number(4),Stname Varchar2(25) NOT NULL,
Course Varchar2(4) CHECK (Course IN(„BCOM‟,‟MSCS‟)));
2. Entity Integrity Constraints: These are used to prevent duplicate rows in a table.UNIQUE and PRIMARY
KEY are the entity integrity constraints.
UNIQUE:
This constraint prevents duplicate values while inserting or updating the values in the specified set of
columns. However, it allows null values into the column. It can be used to more than one column. It can be
specified for a maximum of 16 columns. This constraint can be used at column or table level.
Eg-1:(Column Level)
Sql>CREATE TABLE student( Rollno Number(4) UNIQUE,Stname Varchar2(25) NOT NULL, Course
Varchar2(4) );
Eg-2:(Table Level)
Sql>CREATE TABLE student( Rollno Number(4),
stname Varchar2(25) NOT NULL,Course Varchar2(4),UNIQUE(Rollno));
We can use UNIQUE constraint for multiple columns only at table level.
Eg: sql>CREATE TABLE student( Rollno Number(4), Stname Varchar2(25) NOT
NULL, Course Varchar2(4),UNIQUE(Rollno, Course));
3
Zenex Vision Degree College DBMS –BCA- SEM-II
PRIMARY KEY: This constraint prevents duplicate and null values while inserting or updating the values in the
specified set of columns. Every table should have a primary key constraint to uniquely identify each row.
However, only one primary key constraint can be created for each table.
The Primary Key constraint can be used for a single column at column or table level or for multiple
columns at table level. When Primary Key constraint is specified for multiple columns then it is said to be
composite primary key. It can contain a maximum of 16 columns.
Eg-1:(Column Level)
Sql>CREATE TABLE student( Rollno Number(4) PRIMARY KEY,
Stname Varchar2(25) NOT NULL, Course Varchar2(4) );
Eg-2:(Table Level)
SQL>CREATE TABLE student( Rollno Number(4), Stname Varchar2(25) NOT NULL,
Course Varchar2(4), PRIMARY KEY(Rollno));
Eg-3:(Composite Primary Key)
SQL>CREATE TABLE student( Rollno Number(4),
Stname Varchar2(25) NOT NULL,Course Varchar2(4),PRIMARY KEY(Rollno, Course));
3
Zenex Vision Degree College DBMS –BCA- SEM-II
Dropping Constraints: ALTER TABLE command 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.Sql>ALTER TABLE employee DROP CONSTRAINT SYS_C00235 ;
Sql>ALTER TABLE student DROP CONSTRAINT fk_stno;
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.
Sql>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.
Sql>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
Sql>Select * From Emp Where salary > any (Select salary from emp where job=‟manager‟);
2. Correlated sub-query : It is a subquery, that executes once for each row in the outer query. The execution of
correlated subquery is similar to the execution of the nested loop in a programming language.
For EX: for(i=1;i<=2;i++) outer loop
For(j=1;j<=3;j++) inner loop
Printf(“i=%d j=%d”,I,j);
3
Zenex Vision Degree College DBMS –BCA- SEM-II
Operator Meaning
IN Equal to any member of the list
IS null 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
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.sql> 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.: sql>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. Sql>SELECT * FROM EMP WHERE ENAME LIKE „SM%‟
2. Sql>SELECT * FROM EMP WHERE ENAME LIKE „_ _ A
%‟ IS null: This operator is used to compare null values only.
Eg:sql> 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: sql>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:sql> SELECT * FROM EMP WHERE SAL > ALL(SELECT SAL FROM EMP WHERE JOB=‟MANAGER‟)
3
Zenex Vision Degree College DBMS –BCA- SEM-II
EXISTS: This operator returns true if the subquery returns atleast one row.
Eg.:SQL> SELECT * FROM EMP WHERE EXISTS (SELECT * FROM DEPT);
3. Logical Operators (or) Compund 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 (or) union 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.
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. The group functions supported by SQL are
SUM()
AVG()
MAX()
MIN()
COUNT()
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: SQL>Select sum(salary) from emp;
This example returns the sum of values of salary column by ignoring nulls.
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: SQL>Select avg(salary) from emp;
This example returns the average of values of salary column by ignoring nulls.
Eg-2: SQL>Select avg(distinct sal) from emp;
This example returns the average of values of salary column by ignoring null and duplicate values.
4
Zenex Vision Degree College DBMS –BCA- SEM-II
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: SQL>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: SQL>Select MIN(salary) from emp;
This example returns the minimum value of salary column by ignoring nulls.
COUNT():
This function is used to count number of values. It is used in 3 ways.
They are COUNT(*)
COUNT(COLUMNNAME)
COUNT(DISTINCT COLUMNNAME)
COUNT(*):-This function counts the number of rows present in the specified table including duplicates and nulls.
Eg:SQL> Select count(*) from emp;
COUNT(columnname):-This function counts the number of values present in the specified column by ignoring null
values. It can be used for any datatype column.
Eg-1:SQL> Select count(salary) from emp;
This example counts the no. of values present in salary column by ignoring nulls.
COUNT(DISTINCT COLUMNNAME):It counts the number of values without including nulls and
duplicates.That means counts the distinct values of the specified column.
Eg-1: Select count(distinct sal) from emp;
This example counts the no. of values present in salary column by ignoring null and duplicate
values.
The set operators are used to combine the output of multiple queries into a single result. There are 4 types
of set operators used in SQL. They are UNION, UNION ALL, INTERSECT and MINUS.
While working with set operators, the following points should be remembered.
1. The queries that are combined by the set operator must have same number and order of columns.
2. The queries must not contain Long datatype columns.
3. The first query labels (headings) are displayed as column headings in the output.
Syntax:
Query1 SetOperator Query2 SetOperator Query3 …….;
Let us assume EXAM1 and EXAM2 contain data as follows:
4
Zenex Vision Degree College DBMS –BCA- SEM-II
EXAM1 EXAM2
RNO NAME MARKS RNO NAME MARKS
101 A 40 101 A 80
102 B 80 103 C 90
104 D 90 105 E 58
105 E 75 107 G 85
106 F 95 108 H 95
UNION Operator:
This operator returns all the distinct rows selected by both queries. The output contains sorted data based
on the selected columns in the query.
Eg:
Sql>Select RNO, NAME from EXAM1 UNION Select RNO, NAME from EXAM2;
Output:
RNO NAME
101 A
102 B
103 C
104 D
105 E
106 F
107 G
108 H
4
Zenex Vision Degree College DBMS –BCA- SEM-II
INTERSECT Operator:
This operator returns only common rows selected by both queries including duplicate rows.
Eg:
Sql>Select RNO, NAME from EXAM1 INTERSECT Select RNO, NAME from EXAM2;
Output:
RNO NAME
101 A
105 E
MINUS Operator:
This operator returns all the distinct rows selected by first query, but not contain in the second query.
Eg:
1. Sql>Select RNO, NAME from EXAM1 MINUS Select RNO, NAME fromEXAM2;
2. Sql>Select RNO, NAME from EXAM2 MINUS Select RNO, NAME from EXAM1;
A join is a relational operation (query) that combines data of two or more tables into single result table using a
common column. It is the most frequently used relational operation to process multiple tables.
Types of Joins: There are several types of joins used in relational databases. Some of them are:
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOCATION
1001 RAJESH 20 10 ACCOUNTS DELHI
1002 JESSIE 10 20 RESEARCH CHENNAI
1003 VANI 10 30 SALES BANGALORE
1004 KAVITHA 40
4
Zenex Vision Degree College DBMS –BCA- SEM-II
1) CARTESIAN JOIN:
When multiple tables are joined without any condition then it is called Cartesian join. It is also called
Cross 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.
Syntax:
SELECT */columnlist FROM table1 CROSS JOIN table2;
2 NATURAL JOIN:
It returns rows of two tables that are having matching values in the matching columns. It eliminates duplicate
columns in the result. The matching columns must have the same names and data types. But if there are no
common columns then it returns cross product.
Output:
3 INNER JOIN: An inner join returns all rows matching the join condition. It returns rows of two tables that
are having matching values in the specified columns of the join condition. It is like natural join but it is useful
when there are no common in the tables.
Eg:
4
Zenex Vision Degree College DBMS –BCA- SEM-II
Output:
4. OUTER JOINS:
An outer join returns all matching and non-matching rows. There are three types of outer joins. They are
LEFT OUTER JOIN, RIGHT OUTER JOIN and FULL OUTER JOIN.
i) LEFT OUTER JOIN: The left outer join returns all matching rows followed by non-matching rows
of left side table.
Syntax: SELECT */columnlist FROM table1 LEFT OUTER JOIN table2 ON joinconditon;
Eg: SELECT * FROM emp LEFT OUTER JOIN dept ON emp.deptno = dept.deptno;
Output:
ii) RIGHT OUTER JOIN: The right outer join returns all matching rows followed by non-matchingrows
of right side table.
Syntax: SELECT */columnlist FROM table1 RIGHT OUTER JOIN table2 ON joincondition;
Eg: SELECT * FROM emp RIGHT OUTER JOIN dept ON emp.deptno= dept.deptno;
Output:
4
Zenex Vision Degree College DBMS –BCA- SEM-II
iii) FULL OUTER JOIN: The full outer join returns all matching rows followed by non-matching rows of
either side table.
Syntax: SELECT */columnlist FROM table1 FULL OUTER JOIN table2 ON joincondition;
Output:
SQL FUNCTIONS
A function is a predefined formula that returns a value using its parameters. In SQL, the functions are classified as
follows:
DATE FUNCTIONS:
3). LAST_DATE() it returns a date of the last day of the month given in a date.
4). MONTHS_BETWEEN() it returns the number of months between the given two
NUMERIC FUNCTIONS:
2 . POWER(number1,number2)
4
Zenex Vision Degree College DBMS –BCA- SEM-II
STRING FUNCTIONS
LOWER(string)
UPPER (string)
CONVERSATION FUNCTIONS: These are used to convert a value in one data type into another data type.
Format codes:
Code Meaning
9 Digit
0 Leading Zero
, Comma
$ Dollar Sign
Eg: SELECT TO_CHAR („$9,999.99‟) FROM DUAL; output: $2,650.00
2.TO_NUMBER (): it is used to convert a formatted number from a character string using a given format or
to convert a character value into number value.
4
Zenex Vision Degree College DBMS –BCA- SEM-II
VIEWS
A view is a database object which is created from a query that uses one or more base tables. The views are also
known as virtual or logical or derived tables. Using SQL queries, views are created using base table‟s data.
A view doesn‟t contain data; instead it derives its data from the base tables. A view can also be used in the same
way as base table is used. But the changes are made in their base tables.
Merits:
Demerits:
Types of Views:
They are two types of views namely Updatable and Non-Updatable views
Updatable Views: The views that allow data manipulation then they are called Updatable Views. If any DML
operation performed on view will affect to its base table. But, some rules must be followed to create updatable
views.
Non-Updatable Views: The views that do not allow data manipulation then they are called Non-Updatable
Views.
Creation of views: The DDL command CREATE VIEW is used to create views.
Syntax:
CREATE [OR REPLACE] VIEW viewname AS query;
Eg:
1. CREATE VIEW clerkinfo AS SELECT * FROM emp WHERE job=’CLERK’;
2. CREATE OR REPLACE VIEW clerkinfo AS SELECT * FROM emp WHERE job=’CLERK’;
DML operations on Views:
Once a view is created, we can do various DML operations on views. Any DML operation performed on
view will affect to its base table.
Eg:
1. INSERT INTO clerksinfo VALUES(1001,’XYZ’,’CLERK’,3000);
2. UPDATE clerksinfo SET sal=4000 WHERE sal=3000;
3. DELETE FROM clerksinfo;
4. SELECT * FROM clerkinfo;
Dropping Views:
DROP VIEW command is used to remove views from the database. When a view is dropped, it doesn’t
affect to the base table data.
Syntax: DROP VIEW
viewname; Eg: DROP VIEW
clerkinfo;
4
Zenex Vision Degree College DBMS –BCA- SEM-II
DCL COMMANDS
Data Control Language commands are used to control user access to the database objects. These are used to
provide authorization to protect the data in the database. Authorization is permission given to user to access an
object. This can be done by granting or removing various privileges or roles.
PRIVILEGES: A privilege is a permission to execute an SQL statement or to access another user’s object. The
user can access objects based on the privileges they received.
Eg: INSERT, SELECT, UPDATE etc (DML).
ROLES: A role is a named set of privileges given to users. Roles are defined to manage the privileges for a user
group.
Eg: CONNECT, RESOURCE, DBA etc.
4
Zenex Vision Degree College DBMS –BCA- SEM-II
UNIT-5
PL/SQL
In PL/SQL, the code is not executed in single line format, but it is always executed by grouping the code into a
single element called Blocks.
PL/SQL is the procedural approach to SQL in which a direct instruction is given to the PL/SQL engine about
how to perform actions like storing/fetching/processing data. These instructions are grouped together
called Blocks.
Blocks contain both PL/SQL as well as SQL instruction. All these instruction will be executed as a whole rather
than executing a single instruction at a time.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are different sections of
PL/SQL blocks
1. Declaration section
2. Execution section
3. Exception-Handling section
5
Zenex Vision Degree College DBMS –BCA- SEM-II
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is the section in which the
declaration of variables, cursors, exceptions, subprograms, instructions and collections that are needed in the block
will be declared. Below are few more characteristics of this part.
This particular section is optional and can be skipped if no declarations are needed.
This should be the first section in a PL/SQL block, if present.
This section starts with the keyword 'DECLARE' for triggers and anonymous block. For other
subprograms this keyword will not be present, instead the part after the subprogram name definition
marks the declaration section.
This section should be always followed by execution section.
Execution Section
Execution part is the main and mandatory part which actually executes the code that is written inside it. Since the
PL/SQL expects the executable statements from this block this cannot be an empty block, i.e., it should have at
least one valid executable code line in it. Below are few more characteristics of this part.
Exception-Handling Section:
The exceptions are unavoidable in the program which occurs at run-time and to handle this Oracle has provided an
Exception-handling section in blocks. This section can also contain PL/SQL statements. This is an optional section
of the PL/SQL blocks.
5
Zenex Vision Degree College DBMS –BCA- SEM-II
This is the section where the exception raised in the execution block is handled.
This section is the last part of the PL/SQL block.
Control from this section can never return to the execution block.
This section starts with the keyword 'EXCEPTION'.
This section should be always followed by the keyword 'END'.
Data Type: Data Type specifies the type of the data which can be stored in the specified variable. PL/SQL
supports the same data types of SQL and its supports some other data types. They are
Scalar types
Scalar data type haven't internal components. It is like a linear data type. Scales data type divides into four
different types character, numeric, boolean or date/time type.
5
Zenex Vision Degree College DBMS –BCA- SEM-II
5
Zenex Vision Degree College DBMS –BCA- SEM-II
LONG data type used to store variable string data within predefined
LONG length, This data type used for backward compatibility. Please use 32760 bytes
LONG data to the CLOB type.
LONG RAW data type same as LONG type used to store variable
string data within predefined length, This data type used for
LONG RAW 32760 bytes
backward compatibility.
Use LONG RAW data type for storing BLOB type data.
Boolean data type stores logical values. Boolean data types don’t take any parameters.
Boolean data type store either TRUE or FALSE. Also store NULL, Oracle treats NULL
Boolean
as an unassigned boolean variable.
You can not fetch boolean column value from another table.
Date/time variable can holds value, we can say date/time data type. PL/SQL automatically converts character value in to d
BLOB data type is same as BFILE data type used to store Size: 8 TB to 128 TB
BLOB
unstructured binary object into Operating System file
5
Zenex Vision Degree College DBMS –BCA- SEM-II
CLOB data type is used to store large blocks of character data into Size: 8 TB to 128 TB
CLOB
Database.
This data type is used to store value unknown data type column in a table. Column is
identified by %type data type.
Eg. emp.eno%type
%Type
emp name is table,
eno is a unknown data type column and
%Type is data type to hold the value.
This data type is used to store values unknown data type in all columns in a table. All
columns are identified by %RowType datatype.
%RowType Eg. emp%rowtype
emp name is table,
all column type is %rowtype.
User-Defined Subtypes
PL/SQL gives you the control to create your own sub data type that are inherit from predefined base type. Sub
types can increase reliability and provide compatibility with ANSI/ISO type. Several predefined subtypes are in
STANDARD package.
PL/SQL Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulation. PL/SQL
language is rich in built-in operators and provides the following types of operators −
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
5
Zenex Vision Degree College DBMS –BCA- SEM-II
Here, we will understand the arithmetic, relational, comparison and logical operators one by one. The String
operators will be discussed in a later chapter − PL/SQL - Strings.
Arithmetic Operators
Following table shows all the arithmetic operators supported by PL/SQL. Let us assume variable A holds 10
and variable Bholds 5, then −
Show Examples
Relational Operators
Relational operators compare two expressions or values and return a Boolean result. Following table shows all the
relational operators supported by PL/SQL. Let us assume variable A holds 10 and variable B holds 20, then −
Show Examples
!=
5
Zenex Vision Degree College DBMS –BCA- SEM-II
Comparison Operators
Comparison operators are used for comparing one expression to another. The result is always either TRUE,
FALSE or NULL.
Show Examples
If x = 10 then, x between
The BETWEEN operator tests
5 and 20 returns true, x
whether a value lies in a specified
BETWEEN between 5 and 10 returns
range. x BETWEEN a AND b means
true, but x between 11 and
that x >= a and x <= b.
20 returns false.
5
Zenex Vision Degree College DBMS –BCA- SEM-II
Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these operators work on Boolean
operands and produce Boolean results. Let us assume variable A holds true and variable B holds false, then −
Show Examples
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE, BETWEEN,
5
Zenex Vision Degree College DBMS –BCA- SEM-II
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
comparison
AND conjunction
OR inclusion
Control Structures
PL/SQL Control Structures are used to control flow of execution. PL/SQL provides different kinds of statements
to provide such type of procedural capabilities. These statements are almost same as that of provided by other
languages.
The flow of control statements can be classified into the following categories:
Conditional control statements: Sequence of statements can be executed based on some condition is called
conditional control statements
There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.
1. if then:-
Syntax: if<condition> then
statements;
end if;
5
Zenex Vision Degree College DBMS –BCA- SEM-II
working : The sequence of statements is executed only if the condition is TRUE. If the condition is FALSE or
NULL, the IF statement does nothing. In either case, control passes to the next statement.
2. if then else:-
syntax: if<condition>then
statements;
else
statements;
end if;
working: If the condition is true then the statements associated with the if block will be executed otherwise the
statements associated with else block will be executed.
3. if then elseif:-
syntax: if<condition>then
statements;
elsif<condition>then
statements;
elsif<condition>then
statements
end if;
working: It allows you to choose between several alternatives. If the condition is true it executes sequence of
statements under if block otherwise it will check the next condition and so on…
The sequence of statements can be executed any number of times using loops.Loops in PL/SQL can be broadly
classified as
1. Simple loop
2. While loop
3. For loop
1. Simple loop:
A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates.
An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of
iterations. When the EXIT condition is satisfied the process exits from the loop.
Syntax :
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
These are the important steps to be followed while using Simple Loop.
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN condition,
the statements in the loop is executed only once.
6
Zenex Vision Degree College DBMS –BCA- SEM-II
2) While Loop:
A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The condition
is evaluated at the beginning of each iteration. The iteration continues until the condition becomes false.
Syntax :
WHILE <condition>
LOOP statements;
END LOOP;
3) FOR Loop:
A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration occurs between
the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter
reaches the value of the end integer.
Syntax :
FOR counter IN val1..val2
LOOP statements;
END LOOP;
Cursors
Oracle creates a memory area, known as the context area, for processing an SQL statement, which contains all the
information needed for processing the statement; for example, the number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the
rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no
explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it. The
6
Zenex Vision Degree College DBMS –BCA- SEM-II
Implicit cursors do not have any declarations i.e opening, fetching, closing statements. The implicit cursors will fetch
the records from database to a host variable by using “into” keyword.
The following table provides the description of the most used attributes –
%FOUND
%NOTFOUND
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL statement.
%ROWCOUNT
Ex:
Declare
rec emp%rowtype;
begin
select *into rec from emp where empno:=&empno;
dbms_output.put_line(rec.empno||‟ „ rec.ename||‟ „ ||rec.sal);
end;
Explicit Cursors:
The cursor which is used to hold (store) multiple records at a time is called explicit.
6
Zenex Vision Degree College DBMS –BCA- SEM-II
These cursors are manipulated by user explicitly in the PL/SQL code block. The explicit cursors follow the below
declarations
For example −
CURSOR c IS
Opening the Cursor
SELECT id, name, address FROM customers;
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the
SQL statement into it. For example, we will open the above defined cursor as follows −
Eg:
CLOSE c;
Declare
rec emp%rowtype;
6
Zenex Vision Degree College DBMS –BCA- SEM-II
Begin
dbms_output.put_line ('Hello World');
end;
declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('Sum of ' || a || ' and ' || b || ' is ' || c);
DECLARE
no NUMBER (3) := &no;
a NUMBER (4);
b NUMBER (2);
6
Zenex Vision Degree College DBMS –BCA- SEM-II
BEGIN
FOR i IN 2..no - 1
LOOP
a := no MOD i;
IF a = 0
THEN
GOTO out;
END IF;
END LOOP;
<>
IF a = 1
THEN
DBMS_OUTPUT.PUT_LINE (no || ' is a prime number');
ELSE
DBMS_OUTPUT.PUT_LINE (no || ' is not a prime number');
END IF;
END;
Solution:
declare
n number;
i number;
f number:=1;
begin
n:=&n;
for i in
1..n loop
f:=f*i;
end loop;
dbms_output.put_line(n||'! = '||f);
end;
Output:
6
Zenex Vision Degree College DBMS –BCA- SEM-II
Solution:
declare
N number;
S NUMBER := 0;
R NUMBER;
K number;
begin
N := &N;
K := N;
loop
exit WHEN N = 0;
S := S * 10;
R := MOD(N,10);
S := S + R;
N := TRUNC(N/10);
end loop;
dbms_output.put_line('THE REVERSED DIGITS OF '||K||' = '||
S); end;
Output:
Solution:
declare
a number := &a;
b number := &b;
c number := &c;
begin
if a>b and a>c then
dbms_output.put_line(a||' is greatest.');
elsif b>a and b>c then
dbms_output.put_line(b||' is greatest.');
else
dbms_output.put_line(c||' is greatest.');
end if;
end;
Output:
6
Zenex Vision Degree College DBMS –BCA- SEM-II
value for c: 4
6
Zenex Vision Degree College DBMS –BCA- SEM-II
old 4: c number :=
&c; new 4: c number
:= 4;
6 is greatest.
PL/SQL procedure successfully completed.
Q: Write a PL/SQL code block to generate Fibonacci series.
Solution:
declare
a number:= 0 ;
b number:= 1;
c number;
begin
dbms_output.put(a||' '||b||' ');
for i in 3..10 loop
c := a + b;
dbms_output.put(c||' ');
a := b;
b := c;
end loop;
dbms_output.put_line(' ');
end;
Output:
0 1 1 2 3 5 8 13 21 34
PL/SQL procedure successfully completed.
Q: Write a PL/SQL code block to find sum of digits of a number.
Solution:
declare
N number ;
S number:=0;
R number;
begin
N:=&N;
WHILE N<>0 LOOP
R := MOD(N,10);
S := S + R;
N := TRUNC(N/10);
end loop;
dbms_output.put_line('THE SUM OF THE DIGITS = '||S);
end;
Output:
6
DATA STRUCTURES
ZENEX DEGREE COLLEGE,
Data Structures
UNIT –
I
UNIT – II
UNIT – III
UNIT – V
SORTING: Definition, Sorting methods - Bubble Sort, Selection Sort, Quick Sort,
InsertionSort, Merge Sort.
SEARCHING: Definition, searching methods - Linear or Sequential Search, Binary Search.
1
ZENEX DEGREE COLLEGE,
UNIT I
Concept of Abstract Data Types (ADTs)
1. Define
Data may be data structures.
organized List various
in many different ways. Thetypes
logicalof(or)
data structures.
mathematical model of a
(OR) Write short notes on Primitive and Non-primitive data
particular organization of a data is called data structure. It is a collection of values and
possible operations.
Structural representation of data items, storage & retrieval operations efficiently.
2
ZENEX DEGREE COLLEGE,
data item.
Arrays, Lists and Files come under this category.
Array: An array is a collection of memory locations which can share same data
name and same data type values.
List: An order set containing variable number of elements is called as lists.
o The list is a sequential data structure.
o Lists are a way to store many different values under a single variable.
o Every item in this list is numbered with an index.
File: A file is a collection of logically releated inforation. It can be viewed as
large list of records consisting of various fields.
A Non- primitive data type is further divided into linear and Non- linear
data strucutre.
⬧ Linera data stucture: A data structure is said to be linear if its elements form a
sequence or a linear list. Example: array, stacks, queues and linked lists come under
this category.
⬧ Non- Linear data strucutres: A data structure is said to be non linear if its elements
form a hierarchical classification where, data items appear at various levels.Trees and
Graphs are widely used non-linear data structures.
Data Type: Data type defines what type of value to stored on a variable.(or)A data type
defines a set of values and the allowable operations on those values. Different data types
include:
1. Abstract data types (ADT )
2. Composite types
3. Primitive types
Abstract data types (ADT ) : Abstract data types are mathematical models ofa
set of data values or information that share similar behaviors. Abstract data types
are used in algorithms and also data items.(OR)
ADT is a user defined data type which encapsulates a range of data values and
their functions. (OR)
An abstract data type is a definition of new type, describes its properties and
operations.
Ex: ―Stack‖ is a ADT which contains push( ), pop( ) operations.
―Linked List‖ is a ADT which contains insert( ), delete( ) operations etc.
In an ADT, we encapsulate the data and the operations on data and we hide
them from the user.An abstract data type consists of
i) Declaration of data
ii) Declaration of operations
Advantages:
⬧ Code is easier to understand.
3
ZENEX DEGREE COLLEGE,
⬧ Implementations of ADTs can be changed without requiring changes to
4
ZENEX DEGREE COLLEGE,
Integer numbers
An integer number can hold a whole number, but no fraction. Integers may be
either signed (allowing Negative values) or unsigned (non negative values only).
Floating-point numbers
A floating-point number represents a real number that may have a fractional
part. These numbers are stored internally in scientific notation, they also called
decimal number. Floating point number contains integer, decimal point(.) and
exponent notation(‗e‘).
Examples of floating-point literals are: 20.0005 , 99.9 , −5000.12 , 6.02e23
Boolean: A boolean type is a single-bit type that can be either true (1) or
false (0).
Characters and strings: A character type (typically called "char") may contain
5
ZENEX DEGREE COLLEGE,
6
ZENEX DEGREE COLLEGE,
Topographical Structures:
Diplom
Circular structure:
⬧ Tree: a tree can be defined as finite set of data items(nodes) in which data
items are arranged in branches and sub branches according to requirement.
⬧ Trees consist of nodes connected by edge, the node presented by circle and
edge lives connecting to circle.
⬧ Graph: Graph is a collection of nodes (information) and connecting edges(
Logical relation) between nodes.
⬧ A tree can be viewed as a restricted graph.
⬧ Graphs have many types.
o Un- directed graph
o Directed graph
o Mixed graph
o Multi graph
o Simple graph
o Null graph
o Weighted graph
Linear
Diference Data structure
between linear and Non linearNon Linear
data data structure
structures:
Every item is related to the previous Every item is attached with many
and time other items.
7
ZENEX DEGREE COLLEGE,
8
ZENEX DEGREE COLLEGE,
Arrays
Definition:
Physical Representation
Eg: Let M=4560 and w=1,calculate the address of A[0], A[2], A[7]
9
ZENEX DEGREE COLLEGE,
Traversing: It is used to access each data item exactly once so that it can be
processed.
Searching: It is used to find out the location of the data item if it exists in the
given collection of data items.
Insertion: It is used to add a new data item in the given collection of data
items.
Deletion: It is used to delete an existing data item from the given collection of
data items.
Sorting: It is used to arrange the data items in some order i.e. in ascending or
descending order in case of numerical data and in dictionary order in case of
alphanumeric data.
Merging: It is used to combine the data items of two sorted files into single file
in the sorted.
Multi-Dimensional arrays and their address mapping and operations
Definition:An array is a finite, ordered and collection of homogeneous data
elements. An array is finite because it contains only a limited number of
elements, ordered as all the elements are stored one by one in contiguous
locations of the computer memory in a linear order. As homogeneous all the
elements of an array are of the same data type.
Eg: Consider an array of size mxn, here m is the no.of rows and n is the no.of
columns as follows.
1
ZENEX DEGREE COLLEGE,
1. Row-Major Order
2. Column-Major Order
Memory Representation
Row-Major Order:
Address(aij) = (i-1)xn+j
If the base address is M, then the above formula can be modified as follows.
1
ZENEX DEGREE COLLEGE,
Address(aij) = M+(i-1)xn+j-1
= 4560+2x3+2-1
=4560+6+2-1 = 4567
Column-Major Order:
Address(aij) = (j-1)xm+j
If the base address is M, then the above formula can be modified as follows.
Address(aij) = M+(j-1)xm+i-1
= 4560+3+3-1
=4560+3+2 = 4565
A sparse matrix is a two – dimensional array where the majority of the elements have
the value null.
Input : An array a with two- Another array spm with two multiplied by 3.`
SparseMatrix:Two columns mxn . There may be situation in ins Non-Zero values. Such
matrix is non-zero values, that is majority of values non-zero values. So, to represent those
6 values, we are we can represent the sparse matrix by using Triplet - dimensions containing
elements, most of the elements are zeros two-dimensions whose size is equal to no.of non-
dimensional array.
The above matrix contains 5 rows and 6 columns. Then the total number of
elements are 5x6=30. If each element requires 4 Bytes of memory, then we need
totally 120 Bytes of memory. But if we observe the matrix, it has very few non-zero
values, that is majority of values are zeros. We have only 6 non-zero
1
ZENEX DEGREE COLLEGE,
Sparse matrices are used by scientists and engineers when solving partial
differential equations. For example, a measurement of a matrix's sparsity can
be useful when developing theories about the connectivity of computer
networks. When using large sparse matrices in a computer program, it is
important to optimize the data structures and algorithms to take advantage
of the fact that most of the values will be zero.
1
ZENEX DEGREE COLLEGE,
Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two
parts.Each node consists of its own data and the address of the next node and
forms a chain.Linked Lists are used to create trees and graphs.
1
ZENEX DEGREE COLLEGE,
Singly Linked List : Singly linked lists contain nodes which have a data part as
well as an address part i.e. next, which points to the next node in sequenceof
nodes. The operations we can perform on singly linked lists are insertion,
deletion and traversal.
Doubly Linked List : In a doubly linked list, each node contains two links the first link points to the previ
in the sequence.
Circular Linked List : In the circular linked list the last node of the list contains
the address of the first node and forms a circular chain.
1
ZENEX DEGREE COLLEGE,
Single Linked List: In single linked list, each node contains only one link which
points to the next node in the list. We maintain a pointer called Headptr to
point the very first node of the list.
In the above example, we have five nodes from N1 to N5. The first node is
called as Head Node and last node is called as Tail Node. First node points to
second, second points to third and so on. Tail Node always points to null which
indicates there no more node in the list. In single-linked list, we can travel only in
direction that is from Head Node to Tail Node. We can move only to the next
node not to the previous node of the list. That is why it is called as one way list.
Operations:
addNewNode (data): This operation adds a new node to the list with the given
data.
delete (index): This operation deletes an existing node from the list at given
index position.
size(): This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.
traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.
1
ZENEX DEGREE COLLEGE,
Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two parts.
Each node consists of its own data and the address of the next node and forms
a chain.Linked Lists are used to create trees and graphs.
Insertion: : Insertion is used to add a new data item. A node can be inserted in various positions.
Inserting at the front ( as a first element)
Inserting at end ( as a last element)
Inserting at any position.
Steps for inserting an element in the beginning of a list
Create a new node
Make the next part of new node point to the first node
Make the START pointer point to new node
Algorithm
new_nodenext=START; START =new_node;
1
ZENEX DEGREE COLLEGE,
while(pnext!=NULL)
{
p=pnext;
}
pnext=new_node; new_nodenext=NULL;
while(p!=insert_position)
{
P=pnext;
}
store_next=pnext;
pnext=new_node; new_nodenext=store_next;
1
ZENEX DEGREE COLLEGE,
Deleting a node from a list: It is used to delete an existing data item from the
given collection of data items. There three ways to delete element.
1
ZENEX DEGREE COLLEGE,
2
ZENEX DEGREE COLLEGE,
Example:
In the above example, we have four nodes from N1 to N4. The first node is
called as Head Node and last node is called as Tail Node. First node points to
second, second points to third and so on. The left link of head node and right
link of tail node points to null. It indicates that there is no previous node
tohead and no next node to tail node. In double-linked list, we can travel
ineither directions that is from Head Node to Tail Node and Tail Node to Head
Node. That is why it is called as two-way list.
2
ZENEX DEGREE COLLEGE,
Operations:
addNewNode (data):This operation adds a new node to the list with the given
data.
delete (index):This operation deletes an existing node from the list at given
index position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.
traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.
Define double linked list. Explain how to insert and delete an
element at the end of the list.
In double linked list, each node contains two links one points to the next node
another points to the previous node in the list. We maintain a pointer called
Headptr to point the very first node of the list.
Steps for inserting in the beginning of a doubly linked list
1. Create a new node
2. Make the next part of new node equal to START
3. Make the previous part of new node equal to NULL
4. Make the previous part of the node pointed by START to new node
5. Make START point to new node
Algorithm for insert a node at the start
new_nodenext=head;
headprev=new_node;
new_nodeprev=NULL;
head=new_node;
2
ZENEX DEGREE COLLEGE,
2
ZENEX DEGREE COLLEGE,
1. Deletion at beginnning
2. Deletion at middle
3. Deletion at end
Algorithm:
p=head;
head=headnext;
headprev=NULL;
delete(p);
2
ZENEX DEGREE COLLEGE,
P=pnext;
}
store_next=pnext;
store_prev=pprev;
store_nextprev=store_prev;
store_prevnext=store_next;
delete(p);
Make the next part of the previous node equal to next of the node to be deleted
Make the TAIL equal to the previous part of the node to be deleted
2
ZENEX DEGREE COLLEGE,
CircularLinked List: A linked list where the last node points the header node
is called the ‗Circular Linked List‘. A circular list doesn't have definite head and
definite tail nodes. Any Node in the list can be chosen as Head and node before
that as Tail. If there are more than one Node in the list, then every Node will
have next Node. If there is only one Node in the list that itself is the head and
tail. The tail Node in the circular list points to the head Node.
Operations:
addNewNode (data):This operation adds a new node to the list with the given data.
delete (index):This operation deletes an existing node from the list at given index
position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given index
position with a givendata value.
traversal():This operation gathers data from each node in the list starting from head to
tail node and displays the data.
2
ZENEX DEGREE COLLEGE,
1. In SLL the list will be traversed in 1. In DLL the list will be traversed
only one way i.e., in forward in two ways either in forward (or)
direction. Backward directions.
2. In SLL the node contains only one 2. In DLL each node contains two Link
link field. fields.
4. Every node contains the address 4. Every node contains the address of
of next node. next node as well as the address of the
previous node.
2
ZENEX DEGREE COLLEGE,
UNIT-II
STACKS
1. What is a Stack? Write a short notes on Stack?
A Stack is a linear list in which insertions and deletions take place at the same end. The
end through which items are added and deleted is called the Top End. The other end of the
list is called the Bottom End.
Stack data structure allows addition and deletion of items through only one end. Addition of
items onto a Stack is called ‘Push’ operation and deletion of items from a Stack is called
‘Pop’ operation. A stack is a Las-In-First-Out (LIFO) data structure. Each Stack has a definite
size called Maximum Size of the Stack. In a stack the item that is added last will be taken
out first. So this data structure is called as LIFO data structure. Stack data structures are
used when the item that is added last need to be served first. A stack can be visualized as a
vertical structure where bottom is sealed and top is opened.
Structure of Stack data structure:
Example:
2
ZENEX DEGREE COLLEGE,
A Stack data structure can be represented using arrays. We perform stack operations
Push and Pop by maintaining the top value to point to the topmost element position of the
stack. Abstract Class :
AbstractDataType Stack
{ Instances
Linear list of elements: one end is called the bottom the other is the top.
Operations
isEmpty() : Return True if stack is empty, return False otherwise.
isFull() : Return True if stack is full, return False otherwise
push(x) : Add element x to the stack
pop(x) : Delete top element from stack and put it in x.
}
Operations:
push(x) : Adding items to the stack is called as Push operation. Here x is the data item that
is being added onto the stack.
pop(x) : Deleting items from the stack is called as Pop operation. Here x is the data item
that is being deleted from the stack.
isFull( ) :This function verifies whether the stack is full or not. If stack is full, it returns
true, otherwise return false.
isEmpty():
This function verifies whether the stack is empty or not. If stack is empty, it returns
true, otherwise it returns false.
Algorithm
Stack Operations: Basically, there are two operations performed on the stack.
Push: Push is the term used to insert the element on the top of stack.
Pop: Pop is the term used to delete the elements from top of the stack.
Algorithm: push(s, top, x):[This algorithm inserts the elements.]
Step: 1 [check for the stack over flow]
If (top > = max-1) then write (“stack over flow”)
Return;
Step: 2 [increment top by 1]
top top+1;
Step: 3 [insert element]
s[top] x;
Step: 4 [finished]
Return;
2
ZENEX DEGREE COLLEGE,
Algorithm pop(s, top): [this algorithm deletes the top element from the stack]
Step: 1 [check for the stack under flow]
if (top= = -1) then write (“stack underflow”)
Return;
Step: 2 [assign top element to x]
X s[top];
Step: 3 [decrement top by 1]
top top-1;
Step: 4 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = -1) then write (“stack Empty”)
Step: 2.[finished]
Return;
Example :
3
ZENEX DEGREE COLLEGE,
The implementation of isFull() method is not necessary because the only way to
know whether we can add an element on to the stack or not is to see whether enough
space exists to create a node of type Node. This check can be done by invoking new.
Abstraction of Stack:
Data Objects:
Node :-consisting of two parts data and address.
headptr :-always points to the address of first node in the list
next :- used to store next node address
Methods :
isEmpty():
This method verifies that the stack is empty or not. If the stack is empty it returns
true, otherwise it returns false.
push(x):
This method adds a data item x onto the stack. If the operation executed
successfully it returns true, otherwise it returns false.
pop(x):
This method pops a data item from the stack and places it in x. If the operation
executed successfully it returns true, otherwise it returns false.
Algorithms
Algorithm: push_LL (s, top, x):[This algorithm inserts the elements.]
Step: 1[Create new node ]
New=Getnew(Node);
Step: 2 [inserting Values]
New Data=Item
Step3: [palcing reference]
New link=top
Top=new
Step: 4 [top is assigns to stack head]
Stack_Headlink=top
3
ZENEX DEGREE COLLEGE,
Step:5 [Finish]
Return;
Algorithm pop_LL(s, top): [this algorithm deletes the top element from the stack]
Step: 1 [check for the stack under flow]
PTR= Stack_Headlink;
if (PTR=NULL) then write (“stack underflow”)
Return;
Step: 2 [assign top element to x]
X PTR[top]; [Display x]
Step: 3 [Assign top to next node]
top = ptr link;
Step: 4[Assign head_ptr to top]
Stack_Head=top;
Step: 5 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = null) then write (“stack Empty”)
Step: 2.[finished]
Return;
5. Implementations of Stacks?
Implementation of Recursion Process:
Recursion is a process by which a function calls itself repeatedly. In the recursion
process, a function is repeated endlessly or until some specified condition has
been satisfied. Recursion is used for repetitive computations in which each
action is started in terms of a previous result.
For Example, to find factorial of 5, it can be recursively computed as follows:
5! = 5 x 4!
4! = 4 x 3!
3! = 3 x 2!
2! = 2 x 1!
1! = 1
In the same way, the factorial of n is recursively defined as,
N! = N * (N-1)! if N > 1
= 1 if N <=1
3
ZENEX DEGREE COLLEGE,
3
ZENEX DEGREE COLLEGE,
2. Move(N-1,ORG,DES,INT)
3. ORG=DES(Move from ORG to DES)
4.Move(N-1,INT,ORG,DES)
5. End if
6.stop
3
ZENEX DEGREE COLLEGE,
3
ZENEX DEGREE COLLEGE,
Parenthesis Problem: In this problem we are to match the left and right parenthesis in
a character string. We observe that if we scan the input string from left to right, then each
right parenthesis is matched to the most recently seen unmatched left parenthesis. For this
we save the position of left parenthesis on a stack as they are encountered in a left-to-right
scan. When a right parenthesis is encountered then it is matched to the left parenthesis at
the top of the stack. The matched left parenthesis is deleted from the stack.
QUEUES
1. What is a Queue?
Definition:Queue is a data structure where items are added through one end and deleted
through another end. The end through which items are added is called as “Rear End” and
the end through which items are deleted is called as “Front End”.
The Queue data structure is used in situations where first added item need to be
served first. That is why this data structure is known as First-In-First-Out (FIFO) data
structure.
3
ZENEX DEGREE COLLEGE,
While adding items to a Queue, the Rear End of the Queue increases and while
deleting items from the Queue the Front End increases. Addition of items to a Queue is
possible only when the Queue is not full.
Deletion of items from a Queue is possible only when the Queue is not empty.
Queue data structures can be implemented by using either Arrays or Linked structure.
Each queue has a definite capacity called maximum size of the queue.
3
ZENEX DEGREE COLLEGE,
Algorithms
Algorithm: Q.insert (Q,F,R,X): [ Given F,R are pointers to the first and last elements of the
queue ‘Q’. ‘Q’ consisting of maximum element initially F & R have been set to -1]
Step: 1 [check for overflow]
If (R>=max-1) then write queue overflow
Return
Step: 2 [increment R]
R R+1;
Step: 3 [insert ‘x’ at ‘R’ in queue]
Q[R] x;
Step: 4 [if F property set]
If (F= = -1) then F 0;
Step: 5 [finish]
Return;
Algorithm: Q.delete(Q, F, R, X): [Q is a queue represented in memory for F and R are two
variables are first and last elements in a queue. This algorithm deletes and assigns the first
element of the queue to the variable x]
Step: 1 [check underflow]
if (F= =-1) then write (“queue underflow”)
Return
Step: 2 [assigns the deleted value to x]
3
ZENEX DEGREE COLLEGE,
X Q[F];
Step: 3 [updates F pointer]
If (F= = R) then F -1 [set F and R values to -1]
R -1
Else
F F+1[increment F value by 1]
Step: 4 [finish]
Return;
Abstract datatype:
AbstractDataType LinkedLinerQueue
{ Instances:
An ordered list of elements; one end is called front end and another end is called
rear end.
Operations:
isEmpty() : Returns true if the Queue is empty
first() : Returns the first element in the Queue
last() : Returns the last element in the Queue
add(x) : Adds the data element x to the Queue
delete() : Deletes an element from the Queue
}
4.Explain about CIRCULAR QUEUE?
In a general queue once an element is deleted the front pointer will be updated. So,
the memory cell from which the element is deleted will be useless. To avoid this wasteful of
3
ZENEX DEGREE COLLEGE,
memory there is another technique, is called a circular queue. This is a more suitable
method of representing a queue which prevent an excessive use of memory by arranging
the elements
Q[1], Q[2],Q[3]…….Q[N] in a circular fashion.
The logical view of a circular queue is shown as
REAR
FRONT
4
ZENEX DEGREE COLLEGE,
A B C
When an element ‘C’ is inserted into circular queue F=1, R=3.
FIG-5
F=1 A B C D
WheRn=4an element ‘D’ is inserted into circular queue F=1, R=4.
FIG-6
F=1 A B C D E
R=5 When an element ‘E’ is inserted into circular queue F=1, R=5.
Circular queue is completely filled up. I.e. the over flow condition is
being satisfied we can’t insert any more elements into the circular queue.
FIG-7
F B C D E
R=4 In the above diagram when we deleted the first element A from the circular
queue. The Front point=2 and we can observe that there is a memory cell existing freely in
the first location. So, we can insert an element an element F into the first location by
setting the value of the Rear pointer to 1.This is possible because we have arranged the
4
ZENEX DEGREE COLLEGE,
Deletio
Deletion
Insertio Insertion
40
ZENEX DEGREE COLLEGE,
The Deque can be used as a stack as well as a queue.The Deque is represented by using
double linked list or a circular array.
OPERATIONS ON A DEQUE:
1.push_DQ(ITEM): To insert ITEM at the FRONT end of deque.
2.Pop_DQ(): To remove the FRONT item from a deque.
3.Inject(ITEM):To insert ITEM at the REAR end of a deque.
4.Eject_DQ():To remove the REAR ITEM from a deque.
The above operations are described for a deque using circular array of length N. Let array
be DQ[1…….N]
Algorithm for push _DQ(ITEM): The ITEM to be inserted at FRONT.
1. if (FRONT=1) then // if FRONT is at extreme left
2. ahead=N
3. Else // if FRONT is at extreme right or the deque is empty
4. If (FRONT=N) or (FRONT=0) then
5. ahead=1
6. Else
7. ahead=FRONT-1 //FRONT is an intermediate position
8. Endif
9. If (ahead=REAR) then
Display “Deque is full or underflow” Exit
10. Else
11. FRONT=ahead
12. DQ[FRONT]=ITEM //push an ITEM
13. Endif
14. Endif
15. stop
Algorithm for Pop _DQ(): Remove FRONT item from a deque.
This algorithm is same as algorithm for Dequeue_CQ (that is deleting an element from the
circular queue)
Algorithm for Inject(): Insert an item at REAR end of a deque.
This algorithm is same as algorithm for Enqueue_CQ (that is inserting an element in to a
circular queue)
Algorithm for Eject _DQ(): Remove REAR ITEM from a deque.
1. If (FRONT=0) then
2. Display “Deque is empty or underflow”
3. Exit
4. Else
5. If (FRONT=REAR)then //the deque contains a single element
a. ITEM=DQ[REAR]
b. FRONT=REAR=0 //deque becomes empty
6. Else
a. If (REAR=1)then //REAR is extreme left
i.ITEM=DQ[REAR]
ii.REAR=N
b. Else
c. If (REAR=N)then //REAR is extreme right
i.ITEM=DQ[REAR]
ii.REAR=1
4
ZENEX DEGREE COLLEGE,
4
ZENEX DEGREE COLLEGE,
Deletion algorithm:
check the REAR and FRONT same or not
if (REAR=FRONT)
Print” Queue Under flow”
2. Other wise we can delete the front end element.
4
ZENEX DEGREE COLLEGE,
11. exit
12. Else
13. If(ptr->PRIORITY=P)then
14. ptr1=ptr->LLINK
15. ptr2=ptr->RLINK
16. If (ptr=REAR) //if the last node to be deleted
17. REAR=ptr1
18. ptr1->RLINK=NULL
19. Else //other than last node deleted
20. ptr1->RLINK=ptr2
21. ptr2->LLINK=ptr1
22. Endif
23. Endif
24. Endif
25. ITEM=ptr->DATA
26. Returnnode(item)//remove ITEM
27. Endif
28. Stop
4
ZENEX DEGREE COLLEGE,
3. Queues are also used in multi-programming operating system (o.s) in which it is used to
hold a set of programs ready for execution. Queues are used in BFT of a graph.
Important Questions:
1.How to represent Stack using Linked List and explain their operations?
2.Implementations of Stacks?
3. CONVERSION OF AN INFIX EXPRESSION TO POSTFIX EXPRESSION?
4. How to represent Linear Queue using Linked
Representation? 5.Explain about CIRCULAR QUEUE?
6. What is DOUBLY ENDED QUEUE ( DEQUES) and explain their operations?
7. How to implement Priority Queue using Linked
Lists? 8.DIFFERENCES BETWEEN STACK AND QUEUE?
4
ZENEX DEGREE COLLEGE,
UNIT –III
TREES
1.What is a Tree and explain?
Tree is a non-linear data structure. In which the items(elements) are not organized in a
linear order. That means the items are organized in a hierarchical form like a tree
structure.
Definition: A tree is a collection of nodes. The collection can be empty or non-empty. If not
empty, a tree consists of a distinguished node R (the root), and zero or more nonempty
subtrees T1, T2, ...., Tk, each of whose roots are connected by a directed edge from R. There
is a specially designed node called a Root node. The remaining nodes are partitioned into
n>=0 disjoint sets called T1, T2, T3------------------------------TN. Where each of these sets is a
tree. Here T1, T2 ,…TN can be called as sub trees.`
For example:-
Root node
The above figure represents a simple tree. In this figure root node is A, and the remaining
three sub trees rooted at B, C and D. Sub tree D is a leaf node, as are the remaining nodes
E,F,G,H and I. the node C has a single child I, where as E,F,G and H have the same parent B.
Tree Terminology:
Root: The root is a specially designated node ,which has no parent. In the above example
4
ZENEX DEGREE COLLEGE,
Parent: It is the immediate predecessor of a node. In the above figure A is the parent of B
,C,D and B is the parent of E,F,G.
Child: If the immediate predecessor of a node is the parent of the node then all immediate
successors of a node are called as child’s. In the above example The nods B,C,D are the
Childs of node A.
Degree of a node: The maximum number of children that exists for a node is called
the degree of the node.
Degree of a tree: The maximum degree of the nodes in a tree is called degree of a tree.
4
ZENEX DEGREE COLLEGE,
children, i.e. the maximum degree of any node is =2. A binary tree can be defined as a
finite set of nodes ,such that
(i) Tree (T) is empty(called the empty binary tree) or
(ii) Tree(T) contains a specially designated node called the root of T, and the remaining
nodes of T form two disjoint binary trees t1 and t2 which are called the left sub-tree and
the right sub-tree, respectively.
Examples:
Complete binary tree: A binary tree is a tree is said to a complete binary tree if all its
levels, except possibly the last level, have the maximum number of possible nodes, and all
the nodes in the last level appear as far left as possible.
Example:
4
ZENEX DEGREE COLLEGE,
The maximum no.of nodes possible in a binary tree of height h is 2h+1 -1.
The minimum no.of nodes possible in a binary tree of height h is h+1.
The number of internal nodes in a perfect binary tree of height h = 2h – 1
The height of the complete binary tree with n no.of nodes is [ log2( 𝑛 + 1)].
For any non empty binary tree, if n is the no.of nodes and e is the no.of edges then n=e-1.
4
ZENEX DEGREE COLLEGE,
particular item is returned, otherwise the search continues till the end of the data
collection.
Algorithm:-
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
LINKED LIST REPRESENTATION :
The most popular and practical way of representing a binary tree is using linked list(or
pointers). In linked list, every element is represented as nodes. A node consists of three
fields such as :
a) Left Child (LChild)
(b) Information of the Node (Info)
5
ZENEX DEGREE COLLEGE,
5
ZENEX DEGREE COLLEGE,
BST Operations
The basic operations that can be performed on a binary search tree data structure, are the
following –
Insert − Inserts an element in a tree/create a tree.
Delete-Delete an element from a tree.
Search − Searches an element in a tree.
Preorder Traversal − Traverses a tree in a pre-order manner.
Inorder Traversal − Traverses a tree in an in-order manner.
Postorder Traversal − Traverses a tree in a post-order manner.
Insertion: This operation is used to insert a new node into the binary tree. The insertion
procedure contains two-steps.
Step-1: First we search for the existence of a node
in the given binary tree.
Step-2: Next we insert a node by establish a link for
the new node.
The following Figure shows how a new node G to a leaf
node containing data content E.
Deletion:
This operation is used to delete any node from any non-empty binary tree. The deletion
operation also varies from one kind of binary tree to another. Consider the case of deletion
of a leaf node in any binary tree. The following Figure shows how a leaf node containing
data G can be deleted from a binary tree.
Search Operation
Whenever an element is to be searched, start searching from the root node, then if the
data is less than the key value, search for the element in the left subtree. Otherwise,
5
ZENEX DEGREE COLLEGE,
search for the element in the right subtree. Follow the same algorithm for each node.
Algorithm:-
If root.data is equal to
search.data return root
else
while data not found
If data is greater than
node.data goto right subtree
else
goto left
subtree If data
found return
node endwhile
return data not
found end if
In-order Traversal:
In this traversal method, the left child is visited first, then the parent and later the right
child. The output of in-order traversal of this tree will be : D → B → E → A → F → C → G
Algorithm:
5
ZENEX DEGREE COLLEGE,
Let BT be a Binary Tree. ROOT points to the root node, LC is the link to left child and RC is
the link to right child.
1. Start
2. If (ROOT=NULL) then
3. Print “ Tree is empty”
4. Else
5. Inorder(ROOT.LC)
6. Visit(ROOT)
7. Inorder(ROOT.RC)
8. Endif
9. Stop
Pre-order Traversal:
In this traversal method, the parent(root) node is visited first, then the left child and finally
the right child. The output of pre-order traversal of this tree will be: A → B → D → E → C → F
→G
Algorithm:
Let BT be a Binary Tree. ROOT points to the root node, LC is the link to left child and RC is
the link to right child.
1. Start
2. If (ROOT=NULL) then
3. Print “ Tree is empty”
4. Else
5. Visit(ROOT)
6. Preorder(ROOT.LC)
7. Preorder(ROOT.RC)
8. Endif
9. Stop
Post-order Traversal:
In this traversal method, the left child is visited first, then right child is visited and last
parent is visited. The output of inorder traversal of this tree will be : D → E → B → F → G →
C→A
Algorithm:
5
ZENEX DEGREE COLLEGE,
Let BT be a Binary Tree. ROOT points to the root node, LC is the link to left child and RC is
the link to right child.
1. Start
2. If (ROOT=NULL) then
3. Print “ Tree is empty”
4. Else
5. Postorder(ROOT.LC)
6. Postorder(ROOT.RC)
7. Visit(ROOT)
8. Endif
9. Stop
In the array representation of binary trees, we use an array to store the nodes of a binary
tree. The nodes stored in an array of memory can be accessed sequentially.
In this representation, the nodes are stored level by level, starting from the zero level
where only the root node is present. The root node is stored in the first memory location (as
the first element in the array).
Following rules can be used to decide the location of any node of a tree in the array
(assuming that they array index starts from 1):
1. The root node is at location 1.
2. For any node with index i, 1 < i ≤ n (for some n):
a. PARENT(i) = [i/2]
For the node when i = 1, there is no parent.
b. LCHILD(i) = 2 * i
If 2 * i > n, then i has no left child.
c. RCHILD = 2*i+1
If 2 * i + 1 > n, then I has no right child.
Suppose a binary tree T of depth d. Then at most 2d – 1 nodes can be there in T(i.e., SIZE
= 2d–1). So we require the array of size “SIZE” to represent the binary tree.
Consider binary trees as shown below. The first binary tree has three elements (A, B, and
C), and the second has five elements (A, B, C, D, and E). White circles represent missing
elements. Dark circles contains element.
5
ZENEX DEGREE COLLEGE,
The above two binary tree has degree 3 then SIZE=23 – 1=7.
Therefore, we require an array A[7] to hold nodes. The white boxes
in the array represent missing nodes and gray boxes represent nodes in the binary tree.
Here, LC and RC are the two link fields used to store the addresses of left child and right
child of a node; DATA is the information content of the node. With this representation, if we
know the address of the root node then from it any other node can be accessed.
The following figure shows the linked representation of a binary tree containing ten nodes.
Structure of a node in
linked representation.
Each LC and RC link fields in a node store the addresses of left child and right child of a
node. The LC and RC link fields in a leaf node are NULL.
5
ZENEX DEGREE COLLEGE,
Important Questions:
1. What is Binary tree and what are the types of Binary
Tress? 2.Briefly discuss about ADT: Binary Trees ?
3.What are the Applications of trees?
4.Explain about Binary Search Tree Traversals?
5.What is Binary Search tree(BST) and explain their operations?
5
ZENEX DEGREE COLLEGE,
UNIT – IV
GRAPHS
Introduction
Graph is a non linear data structure which contains a set of points known as nodes (or
vertices) and set of links known as edges (or Arcs) which connects the vertices.
A Graph is a collection of vertices and arcs which connects vertices in the graph. Graph is a
collection of nodes and edges which connects nodes in the graph.
Generally, a graph G is represented as G = (V, E), where V is set of vertices and E is set of
edges.
G=(V,E)
V(G)={v0,v1,v2…..vn-1}
E(G)={e1,e2….en)
Example
The following is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = (V, E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}
Directed Graph
A graph with only directed edges is said to be directed graph.
5
ZENEX DEGREE COLLEGE,
Degree
Total number of edges connected to a vertex is said to be degree of that vertex.
In-degree
Total number of incoming edges connected to a vertex is said to be in-degree of that
vertex.
Out-degree
Total number of outgoing edges connected to a vertex is said to be out-degree of that
vertex.
Path
A path is a sequence of alternating vertices and edges that starts at a vertex and ends at a
vertex such that each edge is incident to its predecessor and successor vertex.
Adjacent
If there is an edge between vertices A and B then both A and B are said to be adjacent. In
other words, Two vertices A and B are said to be adjacent if there is an edge whose end
vertices are A and B.
Mixed Graph
A graph with undirected and directed edges is said to be mixed graph.
Origin
If an edge is directed, its first endpoint is said to be origin of it.
Destination
If an edge is directed, its first endpoint is said to be origin of it and the other endpoint is
said to be the destination of the edge.
Cyclic graph:- A graph that has cycles is called cyclic graph.
Acyclic graph:- a graph that has no cycles is called an acyclic graph.
Isolated graph:- if a node has no edges connected with any other node then it’s degree
will be o and it will be called isolated graph.
Self-loop
An edge (undirected or directed) is a self-loop if its two endpoints coincide.
Multi graph:- a graph which has loop or multiple edges can be described as multi graph.
In this representation, graph can be represented using a matrix of size total number of
vertices by total number of vertices. Adjacency matrix is the matrix, which keeps the
information of adjacency nodes. The adjacency matrix A of a graph G=(V,E) with n nodes is
5
ZENEX DEGREE COLLEGE,
That means if a graph with 4 vertices can be represented using a matrix of 4X4 class. In
this matrix, rows and columns both represent vertices. This matrix is filled with either 1 or
0. Here, 1 represents there is an edge from row vertex to column vertex and 0 represents
there is no edge from row vertex to column vertex.
2) Adjacency List(liked Representation)
In adjacency list representation of graph, we will maintain two lists. First list will keep track
of an nodes in the graph and second list will maintain a list of adjacent nodes for each
node. It is more efficiency of than adjacency matrix.
Example: Consider the following directed graph representation implemented using linked
list
6
ZENEX DEGREE COLLEGE,
6
ZENEX DEGREE COLLEGE,
We choose B, mark it as
visited and put onto the
5. stack. Here B does not
have any unvisited
adjacent node. So, we
pop B from the stack.
6
ZENEX DEGREE COLLEGE,
As C does not have any unvisited adjacent node so we keep popping the stack until we find
a node that has an unvisited adjacent node. In this case, there's none and we keep popping
until the stack is empty.
1. Initialize the
queue.
6
ZENEX DEGREE COLLEGE,
We start from
visiting S starting
2. nodestartingnode
, and mark it as
visited.
We then see an
unvisited adjacent
node from S. In this
example, we have
3. three nodes but
alphabetically we
choose A, mark it
as visited and
enqueue it.
6
ZENEX DEGREE COLLEGE,
From A we
have D as unvisited
7. adjacent node. We
mark it as visited
and enqueue it.
At this stage, we are left with no unmarked unvisitedunvisited nodes. But as per the
algorithm we keep on dequeuing in order to get all unvisited nodes. When the queue gets
emptied, the program is over.
A Spanning tree is a sub-graph of G that has the same set of vertices of G and is a tree.A
Minimum spanning tree of a weighted connected graph G is its spanning tree of the
smallest weight, where the weight of a tree is defined as the sum of the weights on all its
edges. The total number of edges in Minimum spanning tree is V – 1 where V is the number
of vertices.
5. What are the algorithms to find minimal spanning Tree and
explain? Minimal Spanning tree Algorithms:
There are two algorithms for finding Minimum spanning tree
1) Prim’s algorithm
2) Kruskal’s algorithm
1) Prim’s algorithm
Prim's algorithm to find minimum cost spanning tree uses the greedy approach. Prim's
algorithm shares a similarity with the shortest path first algorithms.
Algorithm
1) One node is picked as a root node (u) from the given connected graph.
2) At each stage choose a new vertex v from u, by considering an edge (u, v) with
minimum cost among all the edges from u, where u is already in the tree and v is not in
the tree.
3) The Prim’s algorithm table is constructed with three parameters. They are:
Known – Vertex is added in the tree or not.
6
ZENEX DEGREE COLLEGE,
2) Kruskal’s algorithm
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for
a connected weighted graph. This means it finds a subset of the edges that forms a tree
that includes every vertex, where the total weight of all the edges in the tree is minimized.
If the graph is not connected, then it finds a minimum spanning forest (a minimum
spanning tree for each connected component). Kruskal's algorithm is an example of a
greedy algorithm.
Algorithm:
1) Start by selecting the two nodes with the minimal costing link.
2) Select any two nodes with the minimal costing link. Your selection is not bound by any
requirement to
select nodes connected to previously selected nodes. Any two nodes we can select, as
long as it the
minimal cost.
3) Repeat steps 1 and 2 until all nodes have been selected / connected.
Example:
6
ZENEX DEGREE COLLEGE,
Solution:
6
ZENEX DEGREE COLLEGE,
6
ZENEX DEGREE COLLEGE,
UNIT – V
Sorting & Searching
Sorting terminology
Sorting is one of the most important and fundamental operations performed in
computer science. It is the task of rearranging data in an order such as Ascending,
Descending or Lexicographic order. Here the data may be of any type like numerical,
alphabetical or alphanumeric. The task sorting is done more frequently in the world of
computer science. Sorting is important for the following reasons.
1. How to rearrange a given set of data?
2. What kind of data structures are suitable to store data prior to their sorting?
3. How fast can the sorting be achieved?
4. How to sort various types of data values?
Basic Terminology
Internal Sorting: When a set of data to be stored in small enough such that the entire
sorting can be performed in a computer’s internal storage(primary memory) then the
sorting is called ‘Internal Sort’.
External Sort: Sorting of a large set of data, which is stored in external memory(such as
hard disk) is called ‘External Sorting’.
6
ZENEX DEGREE COLLEGE,
The operation of sorting is the most common task performed by computers today. Sorting is
used to arrange names and numbers in meaningful ways.
Let A be a list of n elements A 1, A2, ....... An in memory. Sorting of list A refers to the operation of
rearranging the contents of A so that they are in increasing (or decreasing) order (numerically or
lexicographically); A1 < A2 < A3 < < An.
For example, suppose an array A contains 5 elements 20, 40, 50, 30, 10. The elements of an
array can be sorted in any specified order i.e., either in ascending order (10, 20, 30, 40, 50) or
descending order (50, 40, 30, 20, 10).
Sorting can be performed in many ways. There are several methods (or algorithms) for sorting data.
The following are the most common and popular sorting algorithms.
a) Bubble sort d) Quick sort
b) Selection sort e) Merge sort
c) Insertion
1. Bubble Sort:
Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in
which each pair of adjacent elements is compared and the elements are swapped if they are not in
order. This algorithm is not suitable for large data sets.
Algorithm:
Let A be a linear array of n numbers. Temp is a temporary variable for swapping (or interchange) the
position of the numbers.
Steps:
1. Start.
2. Input n numbers of an array A.
3. Repeat for i = 0 to (i < n)
4. Repeat for j = 0 to (j < n – i – 1)
5. If (A[j] > A[j + 1]) then swap(A[j], A[j+1]).
(a) Temp = A[j]
(b) A[j] = A[j + 1]
(c) A[j + 1] = Temp
6. End if
7. End for
8. Display the sorted numbers of array A.
9. Exit.
Example:
7
ZENEX DEGREE COLLEGE,
Consider an unsorted array, -2, 45, 0, 11, -9. This array is sorted using Bubble Sort as shown below,
2. Selection Sort:
The
selection sort algorithm is a very important sorting technique based on the principle of Selection. A
selection sort has two important operations. They are,
1. Select : Selection of the item from the input list.
2. Swap : Interchange two items in the list.
Selection sort uses above two operations repeatedly and sorts the given array by finding and
selecting the minimum element from the unsorted array and placing it at the beginning of the array.
Algorithm:
Let A be a linear array of n numbers. Temp is a temporary variable for swapping (or interchange) the
position of the numbers.
Steps:
1. Start.
2. Input n numbers of an array A.
3. Repeat for i = 0 to (i < n)
4. Repeat for j = i+1 to (j < n)
5. If (A[i] > A[j]) then swap(A[i], A[j]).
(a) Temp = A[i]
(b) A[j] = A[j]
(c) A[j] = Temp
6. End If and For
7. Display the sorted numbers of array A.
8. Exit.
7
ZENEX DEGREE COLLEGE,
o Then, again compare first element and third element compare A[1] and A[3], if A[1] >
A[3] then swap A[1] and A[3]. Continue the process until first and last element of an
array is compared A[1] with A[N]. This completes the first step of selection sort.
Step-2: In second step, we start comparison from second element because after first phase,
the sorted number is automatically placed at the first position of the array.
Step-3: Similarly, in third phase, we start comparison from third element and so on.
Step-4: If the array has n elements, then we must repeat above process (n -1) times. After (n
-1) step, the array will be a sorted array in ascending order.
Example:
Consider an unsorted array 20, 12, 10, 15,2. The array is sorted using Selection Sort as shown below,
3.
Insertion Sort:
The insertion sort algorithm is a very simple and efficient sorting technique based on the principle of
Insertion. The insertion sort algorithm finds the minimum element from the unsorted array and finds
the location it belongs within the sorted list, and inserts it there. It repeats this process until all the
elements are arranged in sorted order.
Algorithm:
Let A be a linear array of n numbers. Temp is a temporary variable for swapping (or interchange) the
position of the numbers.
Steps:
1. Start.
2. Input n numbers of an array A.
3. Repeat for i = 0 to (i < n)
4. Key=a[i]
5. Set j = i-1
6. Repeat while ((key<a[j] && (j>=0) )
a. A[j+1]=A[j]
b. Set j=j-1
7. End while
8. A[j+1] = key;
9. End for
7
ZENEX DEGREE COLLEGE,
Example:
Consider an unsorted array 12, 3, 1, 5, 8. The array is sorted using Insertion Sort as shown below,
7
ZENEX DEGREE COLLEGE,
4. Merge Sort:
Merge sort is a sorting technique based on divide and conquer technique. In this algorithm, we break
down the list into several sub-lists until each sub-list consists of a single element and merge these
sub-lists in a manner that they are in a sorting order.
Merge Sort perform the following three tasks recursively. They are,
1. Divide
2. Conquer
3. Combine
Let a list of n elements to be sorted with l and r being the position of leftmost and rightmost
𝑛
Partition the list midway, that is, at [ ] ] elements in
elements in the list. The three tasks in this divide – and - conquer technique are stated as follows.
𝒍+
𝒓
2
𝟐 [
Divide:
each. If n is even or [ ] .
𝑛
into two sub-lists with
2
[ ]
𝑛
2
If n is odd -1
Conquer: Sort the two lists recursively using the merge sort.
Combine: Merge the sorted sub-lists to obtain the sorted output.
Algorithm: MergeSort
Let A be a linear array of n to be sorted with l and r be the lower and upper end indexes of A. TEMP
be temporary array.
Steps:
1. Start
2. If (r≤l) then return.
3. Else
4. mid = (low + high)/2; // Divide
7
ZENEX DEGREE COLLEGE,
Algorithm: Merge
1. Start
2. i = low, j = mid;
3. Repeat for k = 0 to k < N
4. if (i == mid) then
5. TEMP[k] = a[j++];
6. else if (j == high) then
7. TEMP [k] = a[i++];
8. else if (a[j]<a[i]) then
9. TEMP [k] = a[j++];
10. else
11. TEMP [k] = a[i++];
12. Endif
13. Endfor
14. Repeat for k = 0 to k < N
15. A[low + k] = TEMP[k];
16. Endfor
17. Stop
Merge Sort Working:
Let A be a linear array of N numbers. Sorting of A means rearranging the elements of A in ascending
or descending order. Suppose A[1], A[2],.................A[N] are N elements of an array A. Let us sort Array
in ascending order. i.e., A[1] < A[2] < A[3] <..........A [N].
1. First divide the list of unsorted elements into two parts. Left half and Right half.
2. Apply the merge sort again and divide the left part elements in to sub lists until it become
single element.
3. Similarly divide right half of array or list of elements in to sub lists until it becomes one
element in list.
4. After dividing all elements in two parts in to single entity.
5. Merge the elements by comparing lesser element will be first. Apply same at right half.
6. Merge all the elements in the left and right parts until it become a single sorted list.
Example:
Consider an unsorted array 6, 2, 4, 5, 1, 3. The array is sorted using Merge Sort as shown below,
7
ZENEX DEGREE COLLEGE,
5. Quick Sort:
Quick Sort is
sorting
techniques based on divide and conquers technique. In this algorithm, first we select the breaking
point and we break down the list into several sub-lists until each sub-list consists of a single element
and sorts the each part and simply combines to generate a sorted array.
Quick Sort performs the following tasks recursively. They are,
1. Choose a pivot value: First we choose an element as pivot value. This value can be first or
middle or last element.
2. Divide: Rearrange elements in such a way, that all elements which are lesser than the pivot
gos to the left part of the array and all elements greater than the pivot, go to the right part of
the array. Values equal to the pivot can stay in any part of the array.
3. Conquer: Sort the two lists by apply Quick Sort algorithm recursively to the left and the right
parts.
4. Combine: Since the sub-arrays are sorted in the place, there is no need to combine.
7
ZENEX DEGREE COLLEGE,
8. temp = A[i];
9. A[i] = A[j];
10. A[j] = temp;
11. i++; j--;
12. Endif
13. [Recursively sort lower half]
if (low < j) QuickSort(A, low, j);
14. [Recursively sort upper half ]
if (i < high) QuickSort(A, i, high);
15. End
Example:
7
ZENEX DEGREE COLLEGE,
Consider an unsorted array 55, 88, 22, 99, 44, 11, 66, 77, 33. The array is sorted using Quick Sort
as shown below,
Searching
What is searching? Write about sequential or linear search?
Searching is a process of checking and finding a required element in a list of
elements. Let A be a collection of data elements, i.e., A is a linear array of say n elements. If we want
to find the presence of an element “data” in A, then we have to search for it. The search is
successful if data does appear in A and unsuccessful if otherwise. There are several types of
searching techniques; one has some advantage(s) over other. Following are the important searching
techniques:
1. Linear or Sequential Searching
2. Binary Searching
7
ZENEX DEGREE COLLEGE,
8. If (loc≠ 0) then
Print “Key Element found in the list.”
9. Else
Print “Key Element found in the list.
10. Stop
Binary Search:
Binary search is an extremely efficient algorithm when it is compared to linear search. Binary search
technique searches “Key” in minimum possible comparisons. Suppose the given array is a sorted
one, otherwise first we have to sort the array elements. Then apply the following conditions to search
a “data”.
1. Find the middle element of the array (i.e., n/2 is the middle element if the array or the sub-
array contains n elements).
2. Compare the middle element with the search element key, then there are following
three cases.
(a) If the middle element is the desired element, then search is successful.
(b) If it is less than desired data, then search only the first half of the array, i.e., the
elements which come to the left side of the middle element.
(c) If it is greater than the desired data, then search only the second half of the array, i.e.,
the elements which come to the right side of the middle element.
3. Repeat the same steps until an element are found or exhaust the search area.
Steps:
1. Start
2. Input an array A of n element.
3. Input Key value.
4. Initialize loc =0.
5. Repeat for i=0 to i<n
6. l=0, h=n-1,loc=0;
7. Repeat while(l<=h)
8. mid =(l+h)/2;
9. if(key==a[mid])
a. loc=mid;
b. break;
10. else if(key<a[mid]) h=mid-1;
11. else l=mid+1;
12. endif.
13. Endwhile
14. If (loc≠ 0) then
Print “Key Element found in the list.”
15. Else
7
ZENEX DEGREE COLLEGE,
What are the Key differences between Linear Search and Binary
1. Linear search is iterative in nature and uses sequential approach. On the other hand,
Binary search implements divide and conquer approach.
2. The time complexity of linear search is O(N) while binary search has O(log2N).
3. The best case time in linear search is for the first element i.e., O(1). As against, in
binary search, it is for the middle element, i.e., O(1).
4. In the linear search, worst case for searching an element is N number of comparison.
In contrast, it is log2N number of comparison for binary search.
5. Linear search can be implemented in an array as well as in linked list whereas binary
search can not be implemented directly on linked list.
6. As we know Binary search requires the sorted array that is reason It requires
processing to insert at its proper place to maintain a sorted list. On the contrary
linear search does not require sorted elements, so elements are easily inserted at
the end of the list.
7. Linear search is easy to use, and there is no need for any ordered elements. On the
other hand, Binary search algorithm is however tricky, and elements are necessarily
arranged in order.
Important Questions:
1.What are the representations of Graphs in memory
explai? 2.Write about Depth First Search (DFS) Traversal?
3. Write about Breadth First Search (BFS) Traversal?
4. What are the algorithms to find minimal spanning Tree and explain?
Important Questions:
1. Write an algorithm for Booble Sort and analyze with an
example? 2.Write an algorithm for Merge Sort and analyze with an
example? 3.Write an algorithm for Quick Sort and analyze with an
example? 4.What is searching?Write about sequential or linear
search?
5.What are the Key differences between Linear Search and Binary Search?