4th Sem BSC Dbms
4th Sem BSC Dbms
“DBMS”
Bsc(CS)
CLASS – BCA IV SEMESTER
Introduction:- DBMS stands for Database Management System. We can break it like this
DBMS = Database + Management System. Database is a collection of data and Management System is a set of
programs to store and retrieve those data. Based on this we can define DBMS like this: DBMS is a collection of
inter-related data and set of programs to store & access those data in an easy and effective manner.
Database systems are basically developed for large amount of data. When dealing with huge amount of data,
there are two things that require optimization: Storage of data and retrieval of data.
Storage: According to the principles of database systems, the data is stored in such a way that it acquires lot less
space as the redundant data (duplicate data) has been removed before storage.
Fast Retrieval of data: Along with storing the data in an optimized and systematic manner, it is also important that
we retrieve the data quickly when needed. Database systems ensure that the data is retrieved as quickly as possible.
The main purpose of database systems is to manage the data. Consider a university that keeps the data of
students, teachers, courses, books etc. To manage this data we need to store this data somewhere where we can add
new data, delete unused data, update outdated data, retrieve data, to perform these operations on data we need a
Database management system that allows us to store the data in such a way so that all these operations can be
performed on the data efficiently.
Explain about the objectives of DBMS.
Database management system has made a revolution in all the industries that handles lots of data. All these
organizations are making a huge profit just because of database management system. This is why because DBMS
provides a lot benefits to all these companies and there are lots of objectives of using a database management system.
The following are the various Objectives of Database Management System.
Mass Storage :-DBMS can store a lot of data in it. So for all the big firms, DBMS is really ideal technology to use.
It can store thousands of records in it and one can fetch all that data whenever it is needed.
Removes Duplicity :-If you have lots of data then data duplicity will occur for sure at any instance. DBMS guarantee
it that there will be no data duplicity among all the records. While storing new records, DBMS makes sure that same
data was not inserted before.
Multiple Users Access :- No one handles the whole database alone. There are lots of users who are able to access
database. So this situation may happen that two or more users are accessing database. They can change whatever they
want, at that time DBMS makes it sure that they can work concurrently.
Data Protection:-Information such as bank details, employee’s salary details and sale purchase details should always
be kept secured. Also all the companies need their data secured from unauthorized use. DBMS gives a master level
security to their data. No one can alter or modify the information without the privilege of using that data.
Data Back up and recovery :- Sometimes database failure occurs so there is no option like one can say that all the
data has been lost. There should be a backup of database so that on database failure it can be recovered. DBMS has
the ability to backup and recover all the data in database.
Everyone can work on DBMS :- There is no need to be a master of programming language if you want to work on
DBMS. Any accountant who is having less technical knowledge can work on DBMS. All the definitions and
descriptions are given in it so that even a non-technical background person can work on it.
Integrity :- Integrity means the data is authentic and consistent. DBMS has various validity checks that make your
data completely accurate and consistence.
Platform Independent :- One can run dbms at any platform. No particular platform is required to work on database
management system.
FILES AND FILE SYSTEMS
FILES
A file is a collection of bytes. All data is stored as a file with a file name that is unique within the disk. The
structure of a file is known to the software that manipulates it.
In early processing systems, an organization’s information was stored as groups of records in separate files.
These file processing systems consist of few data files and many application programs. Programmers use
programming languages such as COBOL, C and C++ to write applications to access files to perform data management.
As systems became more complex, file processing system had little flexibility and difficult to maintain.
Basic File terminology:
Data: Data are raw facts, such as student number, marks etc. Data have little meaning unless they have been
processed properly. The smallest piece of data that can be recognized by the computer is a single character, such as
an alphabet, digit or symbol. A single character requires 1 byte of computer storage.
Field: A character or group of characters (alphabetic or numeric) that has a specific meaning. A .field is used to
define and store data.
Record: A set of one or more fields that describes a person, place, or thing. For example, the fields that constitute a
record for a student may consist of name, address, phone number, date of birth, etc.
File: A collection of related records is called a file. For example, a file might contain data about students of a
college, or a file might contain the records for the customers of a bank etc.
ADVANTAGES:
1. The data files can be easily located in memory devices.
2. They occupy less space in memory devices.
3. They can be opened in any editor like any other text files.
Metadata: Meta data means data about data. It provides detailed description of characteristics or properties of
other data. It contains details like data type, field size, and allowable values. For example the Meta data for a
student database is
Colum Name Data type Width Min value Max value Description
STNO Number 5 1 199 Student
Number
STNAME Varchar2 20 ---- ----- Student Name
SUBI Number 3 0 100 Subject 1 Marks
SUB2 Number 3 0 100 Subject2 Marks
DBMS: DBMS means database management system. It is a collection of programs that manage the
database structure and control access to the data stored in the database. It provides user to store,
modify and extracts information from a database.
ADVANTAGES OF THE DATABASE MANGEMENT SYSTEMS
The database management system has number of advantages as compared to file based processing system.
They are
Program-data independency
In database system, the data descriptions are stored in a central location called “data dictionary”. The
application programs are stored separately in database system. The changes in the data do not require
changes in the programs. Hence the program and data are independent to each other.
1. Avoids data redundancy
The database system does not allow the repeated data into the database. The reduction of duplicated data
minimizes memory wastage. Hence consistent data can also be maintained in the database.
2. Easily accessing data
In database system, the end users without programming knowledge can easily access data from the database
using query languages.
4. No recovery problems
When a failure occurs in database system, it is easily restoring the data to the consistent state that existed prior
to the failure.
5. No Lengthy Development
Use of languages like SQL and PL|SQL, database approach takes less time to develop the application programs.
Each and every change does not require changes in all application programs.
6. Integrity can be maintained
In data base systems, integrity can be maintained easily by defining various constraints... So the data in the
database is always accurate
7.Data can be shared
In data base system, the database is shared among several users. Each user can access the required information
of the database at any time.
8.Prevents unauthorized access
In database system, there is a centralized control system for accessing database information. So it is provide
better securities to the database. The Database Administrator controls and manages database by using security
standards.
The DBMS supports many users to access the database information at a time. Database systems are designed
to manage large organizations’ like banks, universities, railways etc.
THE DATABASE SYSTEM ENVIRONMENT OR COMPONENTS OF A DATA BASE SYSTEM
A database management system (DBMS) consists of several components. Each component plays very important
role in the database management system environment. The major components of database management system
are:
1. Hardware
2. Software
3. People
4. Procedures
5. Data
1. HARDWARE: It refers to all the physical devices. For example, computers (micro, mainframe, super), storage
devices, printers, Input / Output devise, network devices, and other devices.
2. SOFTWARE: The working of the database system fully, it requires three types of software. They are operating
system soft ware, DBMS software, and application software.
a) Operating system Software: It manages all hardware components and makes it possible for all other
software to run on the computers. Examples of OS are Microsoft Windows, Unix, Linux etc.,
b) DBMS Software: It manages the database within the database system. Examples of DBMS software are
MS.Access, Oracle etc.,
c) Application Software: These are used to access and manipulate data in the DBMS. Examples are SQL,
PL/SQL, and other programming languages.
3. PEOPLE: The uses are the people who manage the databases and perform different operations on the
database.
i) Database Administrators (DBA): A person manages the overall database management system is
called Database Administrator
ii) Programmers are the persons, who design and imp0lement the application programs. They create
the data entry screens, reports and procedures through which end users access and manipulate
database’s data
iii) End Users: The end-users are the people who interact with database management system to insert,
update, delete and view data. They are also called data entry operators.
4. PROCEDURES: Procedures refer to the instructions and rules that help to design the database and to use the
database system.
5. DATA: Data is the most important component of the DBMS. The collection of “war facts” is called data. It
does not have any specific meaning. The data may be numeric, text, audio, video etc. The data can be
processed to get information.
Ansi/Spark Data Model (American National Standard Institute/ Standards Planning and
Requirements Committee) (Or)Explain Degree of Data abstraction.(Or)Explain the levels of Data
abstraction.(Or)Explain three schema architecture
1. In the early 1970s the (American National Standards Institute) ANSI (standards planning and
Requirements committee) SPARC defined a framework for data modeling based on degrees of
data abstraction.
2. The ANSI/SPARC architecture defines three levels of data abstractions:
a. External,
b. conceptual and
c. Internal.
3. The ANSI/SPARC framework has been expanded with the addition of a physical model to
explicitly address physical level implementation address physical level implementation details
of the internal model.
The different levels of data abstraction are:
1. Internal Level
o The internal level has an internal schema which describes the physical storage structure of
the database.
o The internal schema is also known as a physical schema.
o It uses the physical data model. It is used to define that how the data will be stored in a block.
o The physical level is used to describe complex low-level data structures in detail.
2. Conceptual Level
o The conceptual schema describes the design of a database at the conceptual level.
Conceptual level is also known as logical level.
o The conceptual schema describes the structure of the whole database.
o The conceptual level describes what data are to be stored in the database and also
describes what relationship exists among those data.
o In the conceptual level, internal details such as an implementation of the data structure
are hidden.
o Programmers and database administrators work at this level.
3. External Level
o At the external level, a database contains several schemas that sometimes called as
subschema. The subschema is used to describe the different view of the database.
o An external schema is also known as view schema.
o Each view schema describes the database part that a particular user group is interested
and hides the remaining database from that user group.
The view schema describes the end user interaction with database systems.
8) Database System versus File System
DBMS File Processing System
DATA MODELS:
Hierarchical Data Model: Mid 1960s Rockwell collaborates with IBM to create the Information Management System
(IMS), IMS lead the mainframe database market in 70’s and early 80’s.
In this model, files are related in a parent/child manner, with each child file having at most one parent file.
Advantages Limitations
4.
Advantages Limitations
Data Integrity
Data Independence
5. Object Oriented Database Model:
Advantages Limitations
Objects with complex behaviors are easy to An OODBMS is typically tied to a specific
handle using inheritance and polymorphism etc. programming language and an API; this reduces
its flexibility.
Reduces the large number of relations by Ad-hoc queries are difficult to implement as one
creating objects. cannot join two classes as one can join two
tables in RDBMS. Therefore, queries depend
upon the design of the system.
Advantages Limitations
Defines the basic structure of the database i.e. how It is the set of Information stored at a
the data will be stored in the database. particular time.
UNIT-II
(ENTITY RELATIONAL DATA MODEL)
RELATIONAL DATABASE MODEL
The relational model was introduced by Dr.E.F.Codd in 1970. It is a conceptual theory of data based on the
mathematical theory of relations.
In a relation model, data is stored in tables. Three key items are used frequently in
Relational database
Models: relations, attributes, and domains.
6. A relation is a table with columns and rows.
7. The named columns of the relation are called attributes.
8. The domain is the set of values of the attributes.
LOGICAL VIEW OF DATA
The relational models allow users to view the data logically rather than physically. The logical view of the relational is
database is facilitated by the creation of data relationships through a table.
A Table of dimensional structure contains rows & columns. The data is stored in these rows & columns. A
table is also called relation.
For example: student table shown as
HTNO STNAME MARKS
101 AAA 90
102 BBB 20
103 CCC 80
ATTRIBUTES: An attribute is a property or a characteristic of an entity. Each entity is associated with a set of
attributes. The attributes are also called as fields.
It represents as
RELATIONSHIPS: A relationship describes an association between entities. Data models use 3 types of relationships.
It represents as
1. One – to – one Relationship: An entity instance is associated to only one instance of another entity.
Example: One employee can join only in one department.
2. One– to–many Relationship: An entity is associated to many instances of another entity.
Example: One employee can join in many departments.
3. Many– to–many Relationship: Many entity instances are associated to many instances of other
entity.
Example: Many employees can join in many departments.
CONSTRAINTS: A constraints is a condition or rule that is placed on the data. Constraints are more important to
maintain data integrity. The constraints can be domain, entity and referential.
Example: 1. An employee`s salary must not exceed than 3000.
2. A student`s marks must be between 0 to 100.
Explain about different types of entity sets in ER-Model.
An entity is a thing or an object which is distinguishable from other objects in the real world. Collection of entities of
same type is called as an ‘entity set’.
Ex:- STUDENT, EMPLOYEE, CAR, FAN, etc.
Entity sets can be classified in to two types. They are: (1). Strong Entity Set.
(2). Weak Entity Set.
(1). Strong Entity Set:- An entity set which has a key attribute(primary key or composite key) or identifier that
uniquely identifies each and every entity in an entity set can be denoted by the symbol ‘Rectangle’
Ex:-
Sno Sname
STUDENT
Address
Telephone
DOB
Empno Ename
EMPLOYEE
Address
Salary
DOJ
In the above example ‘Sno’ attribute is key attribute in ‘STUDENT’ entity set and ‘empno’ is the key attribute in
‘EMPLOYEE’ entity set.
(2). Weak Entity Set:- An entity set which does not have any key attribute or identifier is called as ‘Weak entity set’.
In ER-Model weak entity set is denoted by the symbol ‘Double Rectangle’
Dependent_Nam address
e
DEPENDENT
age Relationship
In the above example there is no unique identifier or key attribute for ‘DEPENDENT’ entity set. So, it is
considered as Weak entity set.
2.Multi-Valued attribute
3.Simple attribute
4.Composite attribute
5.Stored attribute
6.Derived attribute
(1) Single-Valued attribute:- A Single-Valued attribute can have only one value for a given entity occurrence.
Ex:- sno, sname, empno, ename, etc.
Telephone_no
(3).Simple attribute:- The attribute which cannot be divided further is called as simple attribute.
Ex:-
empno
(4).Composite attribute:- The attribute which can be sub-divided further is called composite attribute.
Ex:- mname
streeet city
fname lname
name address
state pincode
country
(5).Stored attribute:- A stored attribute is an attribute about which the database designer wants to store data in the
database.
Ex:-
DOB
(6).Derived attribute:- A derived attribute is an attribute whose value can be computed from other stored attribute.
Ex:-
4. Explain about relationship degree and classification in ER-Model.
Relationship is an association among several entity sets. The degree of a relationship indicates that the number of
entities or entity sets that participate in that relationship. The following are the different types of relationship degrees.
1.Unary Relationship
2.Binary Relationship
3.Ternary Relationship
1.Unary Relationship:- The association is maintained with only one entity set then that relationship is called as unary
relationship. Ex:-
PERSON Marrie
d to
STUDENT COURSE
learn
s
Fig : Binary Relationship
3. Ternary Relationship:- When there is an association is maintained among 3-entity sets in a relationship then it is
called ternary relationship.
EER Model:
EER is a high-level data model that incorporates the extensions to the original ER model.
It is a diagrammatic technique for displaying the following concepts
Sub Class and Super Class
Specialization and Generalization
Union or Category
Aggregation
These concepts are used when the comes in EER schema and the resulting schema diagrams called
as EER Diagrams.
Features of EER Model
EER creates a design more accurate to database schemas.
It reflects the data properties and constraints more precisely.
It includes all modeling concepts of the ER model.
Diagrammatic technique helps for displaying the EER schema.
It includes the concept of specialization and generalization.
It is used to represent a collection of objects that is union of objects of different of different entity types.
A. Sub Class and Super Class
Sub class and Super class relationship leads the concept of Inheritance.
The relationship between sub class and super class is denoted with symbol.
1. Super Class
Super class is an entity type that has a relationship with one or more subtypes.
An entity cannot exist in database merely by being member of any super
class.
For example: Shape super class is having sub groups as Square, Circle, Triangle.
2. Sub Class
Sub class is a group of entities with unique attributes.
Sub class inherits properties and attributes from its super
class.
For example: Square, Circle, Triangle are the sub class of Shape super class.
1. Generalization
Generalization is the process of generalizing the entities which contain the properties of all the
generalized entities.
It is a bottom approach, in which two lower level entities combine to form a higher level entity.
Generalization is the reverse process of Specialization.
It defines a general entity type from a set of specialized entity type.
It minimizes the difference between the entities by identifying the common
features.
For example:
D. Aggregation
Aggregation is a process that represent a relationship between a whole object and its component parts.
It abstracts a relationship between objects and viewing the relationship as an object.
It is a process when two entity is treated as a single entity.
In the above example, the relation between College and Course is acting as an Entity in Relation with Student.
2) ISA Relationship and Attribute Inheritance
IS A relationship supports attribute inheritance and relationship participation. In the EER
inheritance is the property by which subclass entities inherit values for all attributes of
In this example the superclass is EMPLOYEE and the subclasses are CLERK,
A subclass with more than one superclass is called a shared subclass. A subclass inherits attributes
not only of its direct superclass, but also of all its predecessor superclass, that is it has multiple
inheritance from its super classes. In multiple inheritance a subclass can be subclass of more than
one superclass.
Constraints on Specialization and Generalization
The constraints on specialization and generalization can be broadly classified into
disjointness and completeness. The dis jointness constraint allows us to specify whether an
instance of a super type may simultaneously be a member of two or more subtypes. In dis
jointness we have two categories (1) Overlap and
(2) Disjoint. In completeness we have two categories
Overlap Constraint
Overlap refers to the fact that the same entity instance may be a member of more than one
subclass of the specialization
Example of Overlap Constraint
Consider the example of ANIMAL entity, which can be further subdivided into
LAND ANIMAL and WATER ANIMAL. Consider the example of Frog and Crocodile
which can live in both land and water hence the division of
ANIMAL into LAND and WATER animals is an example of overlap constraint.
Disjoint Constraint
Disjoint refers to the fact that the same entity instance may be a member of only one subclass of the
specialization.
Example of Di jointness Constraint
Consider the example of CATALOGUE. The CATALOGUE is a superclass,
which can be further subdivided into BOOKS, JOURNALS, and PERIODICALS. This falls under disjoint Ness
because a BOOK entity can be neither JOURNAL nor PERIODICAL.
Total Specialization
Total completeness refers to the fact that every entity instance in the superclass must be a member of
some subclass in the specialization. With total specialization, an instance of the supertype must be a
member of at least one subtype.
Partial Specialization
Partial completeness refers to the fact that an entity instance in the superclass need not
be a member of any subclass in the specialization. With partial specialization, an instance
of a supertype may or may not be a member of any subtype.
Example of Partial Specialization
Consider the PERSON specialization into EMPLOYEE and STUDENT. This
is an example of partial specialization because there can be a person who is
unemployed and does not study.
Advantages OF ER Modeling:-
1. SIMPLE : It is simple to draw an ER diagram when we know entities and relationships.
2. EFFECTIVE : It is an effective communication tool.
3. EASY TO UNDERSTAND : The design of ER is very logical and hence they are easy to design and
understand.They show database capabilities like how tables, keys and columns are used to find a
solution to the given question.
4. INTEGRATED : The ER Model can be easily integrated with relational model.
5. USEFUL IN DECISION MAKING : Since some of the entities in the database are analyzed by an ER-Diagram,
So by drawing an ER-Diagram we come to know what kind of attributes and relationship exist between them.
6. EASY CONVERTION : It can be easily converted to other type of models.
7. DATABASE TROUBLESHOOTING : ER diagrams are used to analyze existing databases to find and resolve the
key issues in logic or deployment. Drawing the diagram should reveal where it’s going wrong.
8. FLEXIBLE: ER models are flexible and can be modified easily to accommodate changes in the database design
or structure.
9. MINIMIZES DATA REDUNDANCY: ER models help minimize data redundancy by identifying and eliminating
duplicate data entries.
10. SCALABILITY: ER models can be used for databases of varying sizes, from small to large.
11. VISUAL REPRESENTATION: ER models provide a visual representation of the database structure, making it
easier for stakeholders to understand and provide feedback.
12. DOCUMENTATION: ER models provide useful documentation for future reference, making it easier to
maintain and update the database in the long run.
UNIT-III
RELATIONAL DATABASE MODEL
The relational model was introduced by Dr.E.F.Codd in 1970. It is a conceptual theory of data based on the
mathematical theory of relations.
In a relation model, data is stored in tables. Three key items are used frequently in
Relational database
Models: relations, attributes, and domains.
1. A relation is a table with columns and rows.
2. The named columns of the relation are called attributes.
3. The domain is the set of values of the attributes.
A key is an attribute (also known as column or field) or a combination of attributes that is used to uniquely
identify records. They are also called Identifier Attributes.
1. Super Key: A super key is once or more attributes that identify the records uniquely. Any Unique key
with Non Unique key combination is called a super key of the relationship. A table con have many
Super Keys.
Example: Consider the relation.
Student (HTNO, Stname, Course, Address)
The super keys are
i. (HTNO)
ii. (HTNO, Stname)
iii. (HTNO, Stname, Course)
iv. (HTNO, Stname, Course, Address)
2. Candidate Key:
A candidate key can be defined as minimal Super Key. It is a set of one or more attributes that uniquely
identify a record in a relation.
For example, consider the relation
Student (HTNO, Stname, Course, Address)
The super keys are
The super keys are
1. (HTNO) -
2. (HTNO, Stname)
3. (HTNO, Stname, Course)
4. (HTNO, Stname, Course, Address)
3. Primary key: The key is one or more attributes that identify a row uniquely in a table. Any candidate key is a
primary key of a table. It is chosen by database designer while creating a table.
Example :{ HTNO}
4. Foreign key: A foreign key is an attribute in a table holds the values of an attribute of another or same
table. It is present in child table.
For example,
Student (HTNO, Stname, Course, Address) Here, HTNO is the Primary key.
Marks (HTNO, sub1, sub2) Here, HTNO is the Foreign key
EXPLAIN DIFFERENT TYPES OF CONSTRAINTS.
1. Constraint is a rule that can be applied on a table or a column of a table.
2. Constraints can also be used to prevent (check) mistakes in data entry.
3. Constraints can be categorized into following,
3. Referential Constraint
a. Foreign key
Domain Integrity constraints
1. Not Null:
1. By default all columns in a table allow NULL values.
2. When a NOT NULL constraint is enforced on a column in a table,
3. It will not allow NULL values into that column.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> NOT NULL);
Example:
Create table tab (no number(3) constraint C NOT NULL);
2. Check constraint
1. These are rules govern logical expressions or Boolean expressions.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> check
(column name with condition));
Example:
Ex1: Create table stud (marks number (5) constraint c1 check (marks>35));
Ex2: alter table emp add constraint ck_emp check (sal + comm <10000);
Entity Integrity Constraints
1. Unique Constraint:
1. This constraint allows only unique values to be stored in the column.
2. Oracle rejects duplication of records when the unique key constraint is used.
3. It can also allow NULL values. Since two NULL values are not allowed because it is
duplicate.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> unique
(column name));
Ex:
Create table JDC (sno number(10) , sname varchar2(10), sphno number(15)
unique);
2. Primary key constraint:
1. It avoids duplication of rows and does not allow NULL values.
Primary key is the combination of NOT NULL and UNIQUE.
1. It is also used to set the relations between the tables. 4.
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> primary key);
Ex:
Create table student(sno number(10) constraint P primary key, sname
varchar2(10));
3. Default constraint:
1. Its read automatically value when user not enter value
Syntax:
Create table <table name> (<Column name> <data type>
<Default> <value>)
Ex:
CREATE TABLE Persons (id number (3), name varchar2 (20) default
‘abhyudaya’);
Referential Integrity Constraints
1. Foreign key Constraint
1. The referential integrity constraints enforce (impose) the relationship between the tables
2. Tables are used primary key
3. It helps in creating a parent child relation ships between the tables.
4. A referential integrity constraint assigns a column as a foreign key.
5. Child table primary key is called foreign key
6. Parent table primary key is called referenced key is called parent table.
Syntax:
Create table <table name> (<column name> <data type>,
constraint <constraint name> references
<table name> (column name));
Ex:
Create table emp1 (eno number(3) constraint P1 primary key, ename
varchar2(20));
r ∪ s = { t | t ∈ r or t ∈ s}
Notation − r U s
Where r and s are either database relations or relation result set (temporary relation).
For a union operation to be valid, the following conditions must hold −
r, and s must have the same number of attributes.
Attribute domains must be compatible.
Duplicate tuples are automatically eliminated.
r Χ s = { q t | q ∈ r and t ∈ s}
σauthor = 'tutorialspoint'(Books Χ Articles)
Output − Yields a relation, which shows all the books and articles written by tutorialspoint.
o Universal Quantifiers: The universal quantifier denoted by ∀ is read as for all which means that in a given set
of tuples exactly all tuples satisfy a given condition.
o Existential Quantifiers: The existential quantifier denoted by ∃ is read as for all which means that in a given
set of tuples there is at least one occurrences whose value satisfy a given condition.
Before using the concept of quantifiers in formulas, we need to know the concept of Free and Bound Variables.
A tuple variable t is bound if it is quantified which means that if it appears in any occurrences a variable that is not
bound is said to be free.
Free and bound variables may be compared with global and local variable of programming languages.
Types of Relational calculus:
TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and Universal Quantifiers (∀).
For example:
connectives ∧ (and), ∨ (or) and ┓ (not). It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable. The
uses the domain of attributes. Domain relational calculus uses the same operators as tuple calculus. It uses logical
3. Example:
4. Consider a table with two columns Employee_Id and Employee_Name.
5. {Employee_id, Employee_Name} → Employee_Id is a trivial functional dependency as
6. Employee_Id is a subset of {Employee_Id, Employee_Name}.
7. Also, Employee_Id → Employee_Id and Employee_Name → Employee_Name are trivial dependencies
7. Explain about functional dependencies: Functional dependency (FD) is a constraint between any two
attributes or any two sets of attributes. For example consider two attributes ‘A’ and ‘B’, the functional dependency
between two attributes ‘A’ and ‘B’ is denoted by A B. This notation can be read as ‘A’ functionally determines
‘B’ (or) ‘A’ uniquely determines ‘B’ (or) ‘B’ is functionally dependent on ‘A’.
Left hand side of the arrow of the functional dependency are called as determinants and right hand side of the
arrow are called as dependents. The attributes that are part of the determinants are called as key attributes and
attributes that are part of the dependents are called as non-key attributes.
Ex:- Table (or) Relation : BOOK
Attributes : book_id, book_title, author, publisher.
Functional Dependencies:-
FD1 : book_id book_title,author,publisher
FD2 : book_id,book_title author,publisher
FD3 : book_id,book_title,author publisher
8. Write about basic normal forms (or) Write about 1NF, 2NF and 3NF.
First Normal Form (1NF):- A relation is said to be in first normal form (1NF), if it does not contain any multi-valued
attributes, i.e all the values of columns in a relation are atomic.
Ex:- Consider the following Relation (or) Table.
EMPNO ENAME SAL COURSE_NAME DATE_COMPLETED
100 SMITH 25000 C 05-OCT-2019
C++ 10-NOV-2019
101 CLARK 36000 JAVA 11-JAN-2020
ORACLE 15-FEB-2020
The above relation is not in first normal form (1NF), because the relation having multiple values of a column.
But every column must contains atomic values only. So, we have to convert the above relation into 1NF and is given
below:
EMPNO ENAME SAL COURSE_NAME DATE_COMPLETED
100 SMITH 25000 C 05-OCT-2019
100 SMITH 25000 C++ 10-NOV-2019
101 CLARK 36000 JAVA 11-JAN-2020
101 CLARK 36000 ORACLE 15-FEB-2020
Hence the above relation is in First Normal Form (1NF).
First Normal Form(1NF) : As per First Normal Form, no two Rows of data must contain repeating group of
information i.e each set of column must have a unique value, such that multiple columns cannot be used to
fetch the same row.
The primary key for the above table was made up of attributes are (PROJ_NUM, EMP-NUM)
Functional dependencies:-
1. (PROJ_NUM, EMP-NUM ) NO_HOUR
2. EMP-ID ENAME,JOB,CHG_HRS
3. PROJ_NUM PROJ_NAME
4. JOB CHG_HRS
The attribute CHG-HRS is depending functionally on JOB and JOB is depending on EMP-ID
then we can say transitive dependence exist between EMP-ID, JOB & CHG- HOUR
Second Normal Form (2NF):- A relation is said to be in second normal form (2NF), if it satisfies the following
properties:
Ex:-
COURSE
EMPNO COURSE_NAME DATE_COMPLETED
CUSTOMER
CUST_ID CUST_NAME SALESPERSON_ID
Hence the above two relations are in third normal form (3NF).
UNIT-IV
Structured Query Language(SQL)
Introduction:
Structured Query Language (SQL) is the standard set of commands used to access data within the
relational database. All tasks related to relational data management such as creating tables, querying the
database for information, modifying the data in the database, deleting them, granting access to users and
so on can be done using SQL.
SQL is a high level language that provides a greater level of abstraction than procedural languages.
It is so designed that the programmer can specify what data is needed but need not specify how to retrieve it.
SQL allows the end-users and systems personnel to deal with a number of database management
systems where it is available.
Applications written in SQL can be easily ported across systems.
SQL as a language is independent of the way it is implemented internally. It means, a query returns the
same result regardless of whether optimizing has been done with indexes or not.
The language while being simple and easy to learn can handle complex situations.
The SQL has strong theoretical base and there is no ambiguity. Hence the results to be expected are
well defined.
All SQL operations are performed at a set level. It means, one SELECT statement can retrieve multiple
rows, one UPDATE statement can modify multiple rows. This set-at-a-time feature of the SQL makes it
powerful than the record-at-a-time processing techniques used in languages like COBOL.
1. What is SQL? What are different types of SQL commands?
SQL stands for “Structured Query Language”, it is used to perform all operations in a relational database.
The different types of SQL commands are:
SQL
3.Explain different types of DDL commands. (what a table using with DDL)
A table is one of the objects of Oracle database. It is the basic unit of data storage in a relational database
management system. Every table has a table name and a set of columns (fields) and rows (records) in which
the data is stored. Each column is identified by a column name and it is given a data type and width.
DDL commands are used to define the structure of the database. The following are the different types
of DDL commands.
(1) create (2) alter (3) truncate (4) drop.
(1) create:- This command is used to create the structure of the table.
Syntax:- create table <tablename> (column1 <data type1>,column2 <data type2>,column3 <data type3>,------------
--------------,columnN <data typeN>);
Ex:- create table student(sno number(2),sname char(20),address varchar(20));
(2) alter:- This command is used to modify or change the structure of the table.
Syntax:- alter table <table name> add (column1 <data type1>,column2 <data type2>,-----------------);
alter table <table name> modify (column1 <new_datatype>(width),column2 <new_ data type>(width),------------);
alter table <table name> drop column <columnName>;
alter table <table name> drop (column1,column2,column3,---------------);
Ex:- 1.alter table student add(dob date,telephone number(10));
2.alter table student modify(sname varchar(20));
3.alter table student drop column telephone;
(3) truncate:- This command is used to remove all the records from the table but it does not remove the structure of
the table.
Syntax:- truncate table<table name>;
Ex:- truncate table student;
(4) drop:- This command is used to remove both the records and the structure of the table.
Syntax:- drop table <table name>;
Ex:- drop table student;
SQL OPERATORS:
An operator is a special character used to perform arithmetic and logical operations. In SQL, these
operators are classified into four types. They are arithmetic, relational, logical and set operators.
1. Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations like addition, subtraction etc.
These are as follows:
Operator Meaning
+ Addition
Subtraction
* Multiplication
/ Division
|| Concatenation
2. Relational Operators:
These are used to compare two values and to get the result either true or false. These are as follows:
Operator Meaning
> Greater than
< Less than
= Equal to
>= Greater than or equal to
<= Less than or equal to
<> , != Not equal to
Operator Meaning
IN Equal to any member of the list
IS Test for nulls
LIKE Test for pattern
BETWEEN Test for range of values
ALL Compares every value of a suquery
ANY or SOME Compares each value of a subquery
EXISTS True if subquery returns at least one row
3. Logical Operators
These operators are used to combine two or more conditions or to negate the result of a condition.
These are as follows:
Operator Meaning
AND Returns true if both conditions are true
OR Returns true if either conditions are true
NOT Negates the result of a condition
4. Set Operators:
Set operators are used to combine the results of two separate queries into a single result. These are as
follows:
Operator Meaning
UNION Returns all distinct rows from both queries
UNION ALL Returns all rows from both queries
INTERSECT Returns only common rows of both queries
MINUS Returns all distinct rows of the first query but not in the second one.
(3) delete:- This command is used to remove records from the table.
Syntax:- delete from <table name> where <condition>;
5. What is a query? Explain it with examples. (or) Explain about ‘select’ queries with examples.
A query is a statement requesting that the information retrieval . ‘SELECT’ command is used to retrieve or
access the data values from the database. The statements that are built by using ‘SELECT’ command are called as
‘Select Queries”.
Syntax:- select <column list> from <tablename> [where <condition>];
Ex:- 1. select * from student;
2. select sno,sname,dob from student;
3. select sno,sname,dob from student where sno<=20;
Selecting unique values:-
To retrieve unique values of a column ‘DISTINCT’ clause is used in the select command.
Syntax:- SELECT DISTINCT <COLUMN NAME> FROM <TABLE NAME>;
Ex:- 1. select distinct sname from student;
2. select distinct ename from emp;
Selecting ordered data:- To retrieve the data values of a table in a specified order(ascending/descending) the ‘ORDER
BY’ clause is used in the SELECT command.
Syntax:- select <column list> from <table name> order by <column list> asc/desc;
Ex:-1. select sno,sname,dob from student order by sname asc;
2. select * from emp order by sal desc;
1) sum( )
2) avg( )
3) min( )
4) max( )
5) count( )
6) count(*)
1) sum() :- This function calculates sum or total of all values for the given columns.
Ex:- select sum(sal) from emp;
2) avg() :- This function calculate the average of all values for the given columns.
Ex:- select avg(sal) from emp;
3) min() :- This function finds the minimum of all values for the given columns.
Ex:- select min(sal) from emp;
4) max() :- This function finds the maximum of all values for the given columns.
Ex:- select max(sal) from emp;
5) count() :- This function counts the total number of records for the given table.
Ex:- select count(*) from emp;
count function can also be used to count the non-null values of a column for the given table.
Ex:- select count(comm) from emp;
6) COUNT(*): This function counts the number of rows present in the specified table.
Eg: 1. Select count(*) from emp;
Write about relational set operators in SQL. Set operators combine the result of two component queries into
a single resultant table. SQL supports the following types of set operators.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
1. UNION:- This operator is used to display all the records selected by either query. This operation produces
distinct rows or records as the result.
Ex:- Consider the following two tables ‘X’ and ‘Y’
Table : X Table : Y
Item code Item name
Item name
1 Powder
2 Soap
4 Pen
Item code
2 Soap
3 Cream
4 Pencil
4. MINUS:- This operator is used to display all the distinct rows selected by the first query but which are not in
the second query.
Query:- select * from X minus select * from Y;
Output:-
Item code Item name
1 Powder
4 Pen
8.Write about sub queries or nested queries in SQL.
A query within another query is called a sub query. The statement containing a sub query is called a parent
query or outer query and the query inside the statement is called a child query or inner query. There are two different
types of sub queries. They are: (1) Single row sub queries
(2) Multiple row sub queries
(1) Single row Sub queries:- The sub queries that return only one row are called single row sub queries.
Ex:- select ename,deptno,sal from emp where sal=(select max(sal) from emp);
Output:-
ENAME DEPTNO SAL
KING 10 5000
(2) Multiple row Sub queries:- Sub queries that return more than one row are called multiple row sub queries.
To perform multiple row sub queries the following operators are used.
In operator
Any operator
All operator
Exists operator
In operator:- In operator checks if the value of the outer query is equal to any of the values in the inner query.
Query:- select ename,deptno,sal from emp where sal in (select max(sal) from emp group by deptno);
Output:-
All operator:- The all operator is used to check for all the values returned by the sub query. The condition is
checked for all the values and the records that catch all the values are displayed.
Query:- select ename,sal,deptno from emp where sal>=all(select avg(sal) from emp group by deptno);
Exists:- When this operator is used, the outer query is executed if inner query evaluates to true.
Query:- select deptno,dname,loc from dept where exists(select * from emp);
Output:-
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
QUERIES(SELECT QUERIES)
The query is a process that retrieves required information from the database. The SELECT command is used to
query the database. A query can be used for the following purposes:
To retrieve data from one or more tables
To sort the data on multiple columns either in ascending or descending order
To filter data using conditions
To group the rows based on multiple columns
To join multiple tables together
SELECT command:
It is also a DML command used to retrieve data from one or more system tables, user-defined tables, views
or synonyms. It is a powerful statement for querying the data.
Syntax:
SELECT [DISTINCT] */columnlist
FROM tablename1 [, tablename2, ……]
[WHERE condition]
[GROUP BY columnlist]
[HAVING condition]
[ORDER BY column [DESC],……] ;
Here, the table names are the existing tables. The ‘*’ represents all columns of the table and ‘columnlist’ indicates
the specified columns from table. When the SELECT command is used without optional clauses, it displays all
the rows from the specified tables.
Eg:
1. SELECT * FROM employee;
It displays all rows and columns of the table employee.
2. SELECT empname, job FROM employee;
It displays all rows of the columns empname and job of the table employee
The DISTINCT clause eliminates duplicate values in the output. It displays unique values from among them.
Simply this clause displays only one value from the duplicates.
Eg:
1. SELECT DISTINCT job FROM employee;
The WHERE clause is used to display the rows based on the condition. When it is used, it displays all the rows
that match the given condition.
Eg:
1. SELECT * FROM emp WHERE salary < 5000;
2. SELECT * FROM emp WHERE job=’CLERK’ AND salary BETWEEN 2000 AND 4000;
The GROUP BY clause is used to combine a group of rows based on particular column(s).
Eg:
1. SELECT JOB, COUNT(*) FROM employee GROUP BY job;
2. SELECT SUM(salary) FROM employee GROUP BY deptno, job;
The HAVING clause is used to specify a condition using group functions.
Eg:
SELECT JOB, COUNT(*) FROM employee GROUP BY job HAVING COUNT(*) > 3;
The ORDER BY clause is used to display rows either in ascending or descending order based on the specified
columns. The DESC is used to display rows in descending order. If it is omitted, SELECT command displays rows
in ascending order.
Eg:
1. SELECT * FROM employee ORDER BY empname;
2. SELECT * FROM employee ORDER BY job, empname;
3. SELECT * FROM employee ORDER BY salary DESC;
EXISTS: This operator returns true if the subquery returns atleast one row.
Eg.: SELECT * FROM EMP WHERE EXISTS (SELECT * FROM D
TABLES
(DDL Commands)
A table is one of the objects of Oracle database. It is the basic unit of data storage in a relational database
management system. Every table has a table name and a set of columns (fields) and rows (records) in which the data
is stored. Each column is identified by a column name and it is given a data type and width.
SQL DATA TYPES
The data type is the characteristic nature of a column in a table. It specifies what type of data to be entered
into the column of a table. The following are different data types available in SQL. They are
NUMBER
CHAR
VARCHAR / VARCHAR2
LONG
DATE
RAW
LONG RAW
1. NUMBER(L, D):
This data type allows numeric values only.
L specifies the length and D specifies the number of decimal places within the length
The length should be in the range from 1 to 38 digits.
The length is optional and if we omit, it takes 38 digits as default length.
2. CHAR(size):
This data type stores fixed length character strings.
The ‘size’ indicates maximum number of characters allowed in each cell of column
The ‘size’ must be in the range from 1 to 255 bytes.
The ‘size’ is optional and if we omit, the default length is 1 character.
3. VARCHAR(size) / VARCHAR2(size):
This data type stores variable length character strings.
The ‘size’ indicates maximum number of characters allowed in each cell of column
The ‘size’ must be in the range from 1 to 2000 bytes.
4. LONG:
This data type is used to store variable length character strings.
We can store upto 2 Giga Bytes of data in each cell.
We should not specify size for this data type
5. DATE:
This data type used to enter date and time values
This data type occupies 7 bytes in the memory
By default, we must enter date values in ‘DD-MON-YY’ format.
The date values must be in the range from ‘1-JAN-4712 B.C.’ to ’31-DEC-4712 A.D.’
6. RAW(size):
It is used to store binary or hexadecimal data.
The ‘size’ must be in the range from 1 to 255 bytes.
It is useful to store multimedia information like images, audio and video files.
7. LONG RAW:
This data type is also used to store binary or hexadecimal data.
We can store images upto 2 Giga Bytes
We should not specify size for this data type
It is useful to store multimedia information like images, audio and video files.
TYPES OF SQL COMMANDS(SQL SUB COMMANDS)
When an instruction is executed at SQL prompt then it is called SQL command.
The SQL commands are classified into the following categories.
1.Data definition Language(DDL) commands
2.Data Manipulation Language(DML) commands
3.Data Control Language(DCL) Commands
4.Transaction Control Language(TCL) commands
1.Data definition Language(DDL) commands:-
The DDL commands are used to create, alter and drop various database objects i.e tables, views and indexes.
The commands that begin with CREATE, ALTER,DROP are referred as DDL commands. These are auto commit
commands, because they process and save objects automatically in the database.
Ex:- CREATE TABLE, CREATE USER,
ALTER TABLE, ALTER USER,
DROP TABLE , DROP USER etc.
2.Data Manipulation Language(DML) commands:-
The DML commands are used to manipulate data within the database objects. The commands
INSERT,UPDATE,DELETE and SELECT are treated as DML commands. They are used to insert, modify, delete and
retrieve data in the database objects. These are not auto commit commands.
EX:- 1. INSERT INTO STUDENT VALUES(100,’XYZ’);
2.UPDATE STUDENT SET ROLLNO=100;
3.DELETE FROM STUDENT;
4.SELECT * FROM STUDENT;
3.Data Control Language(DCL) commands:-
The DML commands are used to control user access to the database objects. These are used to provide authorisation
to the users to protect the database. GRANT and REVOKE are referred as DCL commands. They used to Grant or
Remove various privileges and roles to users.
EX:- 1. GRANT ALL TO USER1;
2.REVOKE ALL FROM USER1;
4.Trasaction Control Language(TCL) commands:-
The TCL commands a re used to Manage the changes made by DML commands. These Commands are used
to save or Cancel the process of DML commands. COMMIT,ROLLBACK and SAVEPOINT commands are referred as TCL
commands.
EX:- 1.COMMIT;
2.ROLLBACK;
Data definition Language(DDL) commands:-
The DDL commands are used to create, alter and drop various database objects i.e tables, views and indexes.
The commands that begin with CREATE, ALTER,DROP are referred as DDL commands. These are auto commit
commands, because they process and save objects automatically in the database.
EMPNO NAME DESIGNATION SALARY
ROWS
The DISTINCT clause eliminates duplicate values in the output. It displays unique values from among them. Simply
this clause displays only one value from the duplicates.
Eg:
2. SELECT DISTINCT job FROM employee;
3. SELECT DISTINCT * FROM employee;
The WHERE clause is used to display the rows based on the condition. When it is used, it displays all the rows that
match the given condition.
Eg:
3. SELECT * FROM emp WHERE salary < 5000;
4. SELECT * FROM emp WHERE job=’CLERK’ AND salary BETWEEN 2000 AND 4000;
The GROUP BY clause is used to combine a group of rows based on particular column(s).
Eg:
3. SELECT JOB, COUNT(*) FROM employee GROUP BY job;
4. SELECT SUM(salary) FROM employee GROUP BY deptno, job;
EXISTS: This operator returns true if the subquery returns atleast one row.
Eg.: SELECT * FROM EMP WHERE EXISTS (SELECT * FROM DEPT);
AGGREGATE FUNCTIONS
The aggregate functions are also known as group functions. They perform a task on a group of items and
produce a single value for the entire group. There are 6 different functions used in SQL. They are
COUNT(*):
This function counts the number of rows present in the specified table.
Eg: 1. Select count(*) from emp;
2. Select count(*) from emp where job=’CLERK’;
COUNT( ):
This function counts the number of values present in the specified column by ignoring null values. It can be
used for any datatype column.
Syntax: COUNT([DISTINCT/ALL] column)
Eg-1: Select count(salary) from emp;
This example counts the no. of values present in salary column by ignoring nulls.
Eg-2: Select count(distinct sal) from emp;
This example counts the no. of values present in salary column by ignoring null and duplicate values.
SUM( ):
This function returns the sum of values of the specified column by ignoring null values. It must be used for
number datatype columns only.
Syntax: SUM([DISTINCT/ALL] column)
Eg-1: Select sum(salary) from emp;
This example returns the sum of values of salary column by ignoring nulls.
Eg-2: Select avg(distinct sal) from emp;
This example returns the sum of values of salary column by ignoring null and duplicate values.
AVG( ):
This function returns the average of values of the specified column by ignoring null values. It must be used for
number datatype columns only.
Syntax: AVG([DISTINCT/ALL] column)
Eg-1: Select avg(salary) from emp;
This example returns the average of values of salary column by ignoring nulls.
Eg-2: Select avg(distinct sal) from emp;
This example returns the average of values of salary column by ignoring null and duplicate values.
MAX( ):
This function returns the maximum value from the values of the specified column by ignoring null values. It
can be used for any datatype column.
Syntax: MAX([DISTINCT/ALL] column)
Eg: Select MAX(salary) from emp;
This example returns the maximum value of salary column by ignoring nulls.
MIN( ):
This function returns the minimum value from the values of the specified column by ignoring null values. It
can be used for any datatype column.
Syntax: MIN([DISTINCT/ALL] column)
Eg-1: Select MIN(salary) from emp;
This example returns the minimum value of salary column by ignoring nulls.
SUB-QUERIES OR CO-RELATED QUERIES
A query within another query is called sub-query. It is also known as nested query. It is a technique used
to process multiple tables that involves placing an inner query (SELECT…FROM…WHERE) within WHERE or
HAVING clause of another (outer) query. The inner query provides values for the condition of the outer query.
An outer query or inner query can have multiple sub-queries.
Output:-
ENAME DEPTNO SAL
KING 10 5000
(2) Multiple row Sub queries:- Sub queries that return more than one row are called multiple row sub queries.
To perform multiple row sub queries the following operators are used.
In operator
Any operator
All operator
Exists operator
In operator:- In operator checks if the value of the outer query is equal to any of the values in the inner query.
Query:- select ename,deptno,sal from emp where sal in (select max(sal) from emp group by deptno);
Output:-
All operator:- The all operator is used to check for all the values returned by the sub query. The condition is
checked for all the values and the records that catch all the values are displayed.
Query:- select ename,sal,deptno from emp where sal>=all(select avg(sal) from emp group by deptno);
Exists:- When this operator is used, the outer query is executed if inner query evaluates to true.
Query:- select deptno,dname,loc from dept where exists(select * from emp);
Output:-
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Eg-1:
Select Ename, Job, Emp.Deptno, Dept.Deptno, Dname From Emp, Dept Where Emp.Deptno=Dept.Deptno;
Natural Join:
It is as same as equi join except that one of the duplicate columns is eliminated in the result table. It is the
most commonly used join operation.
For example, if equi join is written as
Select Ename, Job, Emp.Deptno, Dept.Deptno, Dname From Emp, Dept Where Emp.Deptno=Dept.Deptno;
Then, it displays same values for emp.deptno and dept.deptno in the result table. Hence to eliminate
such duplicate columns, the natural join is written as follows:
Select Ename, Job, Emp.Deptno, Dname From Emp, Dept Where Emp.Deptno=Dept.Deptno;
Outer Join:
It is an extension of equi or natural join. An outer join displays rows in the result table that don’t have
matching values in the common columns. It means if a row in one table doesn’t have a matching row in the other
table then it is also included in the output.
This type of join is performed by placing outer join operator i.e. (+) in the join condition. This operator must
be used only one side of the condition. Normally, it is placed for child table’s column.
Eg:
Select Ename, Job, Emp.Deptno, Dept.Deptno, Dname From Emp, Dept Where Emp.Deptno(+)=Dept.Deptno;
Self Join:
A self join is a join of a table to itself. That is each row of a table combined with a row of the same table.
The self join can be viewed as joining of two copies of the same table.
To perform self join, a table appears twice in the FROM clause and is followed by different alias.
Oracle combines and returns the rows of the table that satisfies the join condition.
Cartesian Join:
When multiple tables are joined without join condition then it is called Cartesian join. It combines all
rows of one table with every row of the other table. As a result, it returns the Cartesian product. For example, if
a table contains 10 rows and other contains 5 rows then the Cartesian product is 50 rows.
Eg:
Select * from Emp, Dept;
UNIT-V
9. Explain about different types of literals in SQL or PL/SQL.
A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier. For example,
TRUE, 786, ‘dbms’ are all literals of type Boolean, number, or string. PL/SQL, literals are case-sensitive. PL/SQL
supports the following kinds of literals −
Numeric Literals
Character Literals
String Literals
BOOLEAN Literals
Date and Time Literals
The following table provides examples from all these categories of literal values.
S.No Literal Type & Example
Numeric Literals
String Literals
3 'Hello, world!'
'Degree Students'
'19-NOV-12'
4 BOOLEAN Literals
To embed single quotes within a string literal, place two single quotes next to each other as shown in the following
program −
DECLARE
message varchar2(30):= 'This is a class room.';
BEGIN
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
This is a class room.
2) PL/SQL Language Elements:-
There are different elements
1. Character Set
2. Lexical Units
a. Delimiters
b. Identifiers
c. Literals
d. Comments
1. Character Set
1. A PL/SQL program consists of text having specific set of characters.
2. Character set may include the following characters:
a. Alphabets, both in upper case [A–Z] and lower case [a–z]
B. Identifiers
a. Identifiers are used in the PL/SQL programs
b. To name the PL/SQL program items
i. Like constants, variables, cursors, cursor variables, subprograms, etc.
c. Identifiers can consists of alphabets, numerals, dollar signs,
underscores, and number signs only.
d. Any other characters like hyphens, slashes, blank spaces, etc.
C. Literals
a. A literal is an explicitly defined character, string, numeric, or Boolean value,
D. Comments
1. Comments are used in the PL/SQL program
2. It used to improve the readability and understandability of a program.
3. A comment can appear anywhere in the program code.
4. The compiler ignores comments.
5. Generally, comments are used to describe the purpose and use of each code
segment.
Ex: /* Hello World! This is an example of multiline comments in PL/SQL */
3) What are the data types available in PL/SQL?
1. Comparison operators
2. Logical operators
3. Special operators
1. Comparison operators:- These operators are used to compare the column data with specific values in a condition.
The following are the different types of comparison operators.
Comparison operators Description
= Equal to
< > , != Not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Ex:- 1. Select * from emp where sal>=20000;
2. select ename,deptno from emp where sal<=10000;
2. Logical operators:- These operators compare two or more than two conditions at a time to determine whether a
row can be selected for the output. These operators are given below:
Logical operators Description
OR For the row to be selected at least one of the conditions must be true
AND For the row to be selected all the specified conditions must be true
NOT For the row to be selected the specified condition must be false
Ex:- 1. select ename from emp where job=’analyst’ or job=’salesman’;
2. select ename from emp where job=’clerk’ and deptno=20;
3.Special operators:- These operators are used to enhance the search capabilities of a SQL query. These are given
below
Special operators Description
LIKE Matching a pattern from a column . Column value is similar to specified character(s).
IN Checking a value in a set. Column value is equal to any one of a specified set of values.
BETWEEN Checking a value with in a range. Column value is between two values, including the end
values specified in the range.
Ex:- 1. select ename from emp where ename like ‘S%’;
2. select ename,sal from emp where sal between 10000 and 30000;
1. Explain about the features of PL/SQL or Write about the advantages of PL/SQL.
Procedural Language SQL(PL/SQL) is a block structured language. The basic unit of PL/SQL is called a block
which contains declarative statements, executable statements and error handling statements.
Features of PL/SQL :- Following are the features of PL/SQL :
1. Allows users to embed(extend) one or more ‘SQL’ statements together and execute as a single SQL unit.
2. Allows declaration of variables and constants.
3. Allows usage of conditional control statements and iterative control statements.
4. Allows programming of error handling using exceptions.
5. Allows Row-by-Row processing of data using cursors.
6. Allows triggers to be created and fired.
1. Declaration part
2. Executable part
3. Error handling part
1) Declaration part :- This is the first section of a PL/SQL block. This section is used to declare variables,
constatnts,cursors,etc.
2) Executable part :- This part contains all the SQL and PL/SQL statements which are used for querying and
processing the data. ‘BEGIN’ is used to mark the beginning of the block and ‘END’ ends the block. There must
be at least one executable statement with in a set of ‘BEGIN’ and ‘END’ statements.
3) Error handling part :- This part is called exception handling part and it contains the error handling statements.
begin
exception
End;
dbms_output.put_line(‘Demo on PL/SQL’);
end;
(2) declare
X number;
begin
X := &X;
end;
1) IF .. THEN
2) IF .. THEN .. ELSE
3) IF .. THEN .. ELSE IF
1) IF .. THEN :- The sequence of statements are executed only if the given condition evaluates ‘TRUE’.
EX :- Example:
DECLARE
a number:=&a;
BEGIN
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if;
END;
IF .. THEN .. ELSE :- The sequence of statements will be executed when the given condition is true otherwise
another set of statements will be executed.
2) IF .. THEN .. ELSE IF :- Conditions are evaluated one-by-one from top to bottom. If any condition is
evaluated as ‘TRUE’ its associated sequence of statements will be executed.
1. Loop
2. While Loop
3. For Loop
1.Loop:- Sequence of statements will be executed repeatedly until the condition has been satisfied. The condition is
specified inside the loop statement.
Syntax:- LOOP
<Sequence of statements>;
END LOOP;
Ex:- declare
A number := &A;
begin
loop
dbms_ouput.put_line(A);
A := A+1;
if A > 20 then
exit;
end if;
end loop;
end;
2. While Loop :- The sequence of statements will be executed continuously until the condition in the while loop is
satisfied.
Syntax:- WHILE <condition> LOOP
<Sequence of statements>;
END LOOP;
Ex:- declare
I number := 1;
S number :=0;
begin
while I < = 20 loop
S := S + I;
I := I + 1;
end loop;
dbms_output.put_line(‘ The sum of 20 numbers=’||S);
end;
3. For Loop:- For loop is used to iterate the sequence of statements over a specified range of integers.
Syntax :- FOR variable IN lowerbound .. upperbound LOOP
<Sequence of statements> ;
END LOOP;
Ex:- declare
S number;
E number;
begin
S:=&start;
E:=&end;
for X in S..E loop
if mod(X,2)=0 then
dbms_output.put_line(X);
end if;
end loop;
end;
5. Explain about cursors in PL/SQL (or) What is a cursor? Write the steps to create a cursor.
When a query inside a PL/SQL block returns more than one record oracle requires the place holder to place the
values. The variable provided in the INTO clause can contain only one value at a time. Inorder to process multiple
records cursors are used.Whenever a SQL statement is issued the database server opens an area of memory in which
the command is parsed and executed. This area is called a ‘cursor’. Each cursor has 4-attributes, which are given
below:
Subprograms
1. Subprogram is a program unit/module
2. That performs a particular task. It also called block.
3. These subprograms are combined to form larger programs.
4. This is basically called the 'Modular design'. A
5. Subprogram can be invoked by another subprogram or program which is called the calling
program
6. Subprograms can be created at the schema level, inside the package, and inside block
7. They are two types of sub programs
1. Procedures
2. Functions
Parameter Modes in PL/SQL Subprograms
User create a Procedure or function, you have to define this three parameters.
1. In
2. Out
3. In out
1. IN
a. IN parameter is referenced to the procedure or function.
b. Input parameter only, the value passed is input only.
c. And value of parameter in not overwritten
2. OUT
a. OUT parameter is referenced to the procedure or function.
b. Output only.
c. And value of parameter is overwritten allow.
3. IN OUT
a. IN OUT parameter is referenced to the procedure or function.
b. Both input and output.
c. And value of parameter is both overwritten allow or not allow.
1. Procedures
These subprograms do not return a value directly, mainly used to perform an action.
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name (procedure parameters)
{IS | AS}
BEGIN
< procedure_body >
END;
Example:
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
END;
dbms_output.put_line('Hello World!');
/
Procedure created.
Execute:
When above code is executed using SQL prompt, it will produce the following
result:
World
Or
You might call the procedure in a PL/SQL Block.
BEGIN
greetings;
END;
Hello World
PL/SQL procedure successfully completed.
2. Functions
1. These subprograms return a single value, mainly used to compute and return a value.
2. A PL/SQL function is same as a procedure except that it returns a value.
Syntax:
CREATE OR REPLACE
FUNCTION function_name (function_params) RETURN return_type IS
BEGIN
function_body
RETURN something_of_return_type;
END;
Ex1:
CREATE OR REPLACE FUNCTION ADD_TWO (A INT,B INT) RETURN INT IS
BEGIN
RETURN (A + B);
END;
END;
DBMS_OUTPUT.PUT_LINE(’RESULT IS: ’ || ADD_TWO(12,34));
/
RESULT IS: 46
Advantages of Packages
Packages offer a lot of advantages. They are as follows.
1. User can create package to store all related functions and procedures are grouped together
into single unit called packages.
2. Package is reused.
3. All function and procedure within a package can share variable among them
4. Packages are support overloading to overload functions and procedures.
5. Package are improve the performance to loading the multiple object into memory at once,
therefore, subsequent calls to related program doesn't required to calling physically I/O.
6. Packages are reduced the traffic because all block execute all at once.
7. Packages enable the organization of commercial applications into efficient modules.
8. Each package is easily understood
9. Packages interfaces between packages are simple, clear and well defined.
10.Packages allow granting of privileges efficiently.
11. Packages promote code reuse through the use of libraries
12. That contain stored procedures and functions, thereby reducing redundant coding . 13.Each
package is easy to understand, and the interfaces between packages are simple,
clear, and well defined.
14. Easier Application Design it stored programs and subprograms
15. Packages can specify which types, items, and subprograms are public (visible and accessible)
or private (hidden and inaccessible).
16. For example, if a package contains four subprograms, three might be public and one private.
17. The package hides the implementation of the private subprogram so that only the package
(not your application) is affected if the implementation changes.
18. They can be shared by all subprograms that execute in the environment.
19. To maintain data across transactions without having to store it in the database. 20.User call a
packaged subprogram for the first time, the whole package is loaded into
memory.
21. To related subprograms in the package require no disk I/O.
22. Packages stop cascading dependencies and thereby avoid unnecessary recompiling. 23.Change
the implementation of a packaged function
Units of Packages
As described earlier, a package is used to store together, the logically related PL/SQL units.
1. Procedures
2. Functions
3. Triggers
4. Cursors
5. Variables
Parts of Package
A Package has two parts. They are:
1. Package specification
2. Package body
1. Package Specification
1. The specification declares the types, variables, constants, exceptions, cursors, and
subprograms
2. These are public and thus available for use outside the package.
3. In case in the package specification declaration there is only types, constants, exception,
or variables,
4. Then there is no need for the package body because package specification are sufficient
for them.
5. Package body is required when there is subprograms like cursors, functions, etc.
2. Package Body
1. The package body fully defines subprograms such as cursors, functions, and procedures.
2. All the private declarations of the package are included in the package body.
3. It implements the package specification.
4. A package specification and the package body are stored separately in the database.
5. This allows calling objects to depend on the specification only, not on both.
6. Oracle invalidates the calling object if the package specification is changed.
Creating a Package
1. A package consists of package specification and package body.
2. Creation of a package involves creation of the package specification and then creation
of the package body.
3. The package specification is declared using the CREATE PACKAGE command.
Syntax:
CREATE [OR REPLACE] PACKAGE <package name> [AS/IS]
1. All the procedures, sub programs, cursors declared in the CREATE PACKAGE command
2. They are described and implemented fully in the package body along with private
members.
Syntax:
Syntax:
ON tablename
BEGIN
Trigger action;
END;
In trigger two types of pseudo (artificial) (fake) column are available they are
On the Basis of Type of Trigger/Firing or Triggering Transaction
– BEFORE Triggers
– AFTER Triggers
– INSTEAD OF
BEFORE Triggers
BEFORE triggers execute the trigger action before the triggering statement is executed. It is used to
derive specific column values before completing a triggering DML, DDL statement or to determine
whether the triggering statement should be allowed to complete.
Example
We can define a BEFORE trigger on the passengers detail table that gets fired before deletion of any
row. The trigger will check the system date and if the date is Sunday, it will not allow any deletion on
the table.
The trigger can be created in Oracle The trigger action can be shown. As soon as we try to delete a
record from passenger detail table, the above
trigger will be fired and due to SUNDAY EXP fired, all the changes will be rolled back or
AFTER Triggers
AFTER triggers execute the trigger action after the triggering statement is
executed. AFTER triggers are used when we want the triggering statement to complete before
executing the trigger action, or to execute some additional logic to the before trigger action