DBMS Complete Notes
DBMS Complete Notes
DBMS Complete Notes
UNIT-1
Overview Of Database Management System
INTRODUCTION:
Data:
Data is defined as a collection of raw facts or data items placed in a file.
Example: Student marks details (rno,name,marks), employee details(empno, name, salary) .
Information:
Information is the result of processing raw data to reveal its meaning. Processed data is called
information or result of data processing.
Example: students who get 70 marks in computers.
Field:
A character or group of characters that has a specific meaning. A field is used to define and store
data. It is also called attribute.
Example:
Record:
A record can be defined as collection of fields or attributes.
Example:
File:
A File can be defined as collection of records.
End Users:
The users who should process daily operations of an organization using database application
program.
1|Page
Database Management System
Meta Data:
Meta Data is nothing but Data about Data. It helps fastest data accessing mechanism.
It provides a description of data characteristics and set of relationships that link the data found within
the database (self describing data called meta data)
Example: Index of the text book.
Database:
a. A Database can be defined as collection of inter related files.
b. It is a shared-integrated computer structure that stores both end users data and meta data.
c. In database the data is independent of programs. In database data sharing refers multi users and
programs processing done simultaneously.
Example: Student marks system, Employee salary System
DBMS:
a. DBMS is a collection of programs that are used to manage the database structure and controls the
access of information stored in the Database.
b. A DBMS is a collection of database, database utilities ( DBMS software ) operated by end users or
application programmers and finally administered by DBA.
c. A DBMS works as an interface between end-users and database.
d. DBMS is a software package that can be used to define, construct, manipulating the database using
efficient query language.
DBMS performs several important functions that guarantee the integrity and consistency of data in the
Database.
The word data dictionary refers data standards, relationships defined in between Database and the
Database constraints.
The responsibility of DBMS the data dictionary should functioning in efficient manner.
The functioning of the data dictionary is under the control of DBA.
2|Page
Database Management System
Data Storage Management
The DBMS create and manages complex structure for the data storage with desired memory address.
Whenever the memory address is sufficient the end users access files randomly at any time.
The database application programs support strong passwords and syntactical rules.
The database stores not only database tables but also data entry forms, reports, the DBMS provides
security.
DBMS provides security to user programs, system programs.
It is important in multi-user database systems where many users can access the database
simultaneously.
DBMS supports data backups and recovery with the help of replicated server and DBA.
Recovery of data from bad sector (or) power failures.
In DBMS more than one user can access and update more than one file at a time that is called
concurrent access.
DBMS supports multiple users simultaneously access files without loss of any data.
The DBMS transforms the entered data to the data structures that are required to store the data.
Based on the query processing the data will be communicated i.e., transfer, displaying, returned data
efficiently in between user and database server.
The DBMS accepts request from the end users by using user interface.
This request will be processed and then results will be displayed to the user in a understandable
format.
DBMS supports well defined program languages like Structured Query Language (SQL) , PL/SQL.
These are used to access and process queries with the help of query processor.
3|Page
Database Management System
EVOLUTION OF DBMS:
1. In early 1960s Charles Bachman created the first general purpose DBMS that uses network data
model.
2. In late 1960s IBM developed Information Management System that uses hierarchical data model.
3. In 1970s EF Codd from IBM created Relational Data Model.
4. In 1976 Peter Chen presented Entity-Relationship Model that is used in database design.
5. In 1980s SQL was developed by IBM and became the standard query language for database.
6. In 1990s IBM, Oracle and others developed powerful DBMS.
CLASSIFICATION OF DBMS:
a. SINGLE USER:
Single user database supports only one user at a time.
b. MULTI USER:
It supports multiple users at the same time. When the database is used by the entire organization and
supports many users across many departments, these database is known as enterprise database.
a. CENTRALIZED DATABASE:
A Database that supports data located at a single site is called as Centralized Database.
b. DISTRIBUTED DATABASE:
A Database that supports data distributed across several different sites is called as Distributed
Database.
According to the Data Model databases are classified into three categories.
5|Page
Database Management System
UNIT-II
In the conventional file processing system each and every subsystem maintains same files.
These will be duplication (redundancy) of data between various subsystems of the information
system.
The concept of the conventional file processing system is shown below, which consists of the 3
applications namely App1, App2, App3.
The different inputs and outputs of these applications are summarized below. Some files are
duplicated in different subsystems in conventional file processing System.
Name of the
Input Output
Application
Application-1 File1 and File2 Report1, Report2, Report3
Application-2 File1 , File3 and File2 Report4, Report5
Application-3 File 2 and File 5 Report6
In File Processing System, there is the possibility to place the common files on different sub systems.
It causes the problem of data redundancy.
The following are the drawbacks of File management System.
2. Inconsistency of data:
a. The uncontrolled redundancy of data will permit same data available in many different
subsystems across the organization, so the inconsistency of data increased.
b. While performing basic data processing operations like deletion, updating, retrieve etc this
inconsistency will give misleading results.
DBMS receives all the application requests and translate them into Database understandable format
to fulfill the user request.
The following are the benefits/advantages of DBMS.
1. Reduced Data Redundancy
2. Consistency of Data
3. Flexibility of Data Processing
4. Better enforcement of standards
5. High Programming Productivity
6. Enhanced Data sharing
7. Improved Data Security
8. Reduced Program maintenance
9. Supports Adhoc queries
10. Supports Concurrent access
8|Page
Database Management System
c. The end users have the rights to share and access any file at any time. There is no limitation of
data access and sharing in DBMS.
7. Improved Data Security
a. DBMS provides high security for files by using usernames and strong passwords.
b. All files are under the control of DBA (Database Administrator).
c. DBA should provide different access permissions to different types of users.
d. Unauthorized persons cannot access data.
8. Reduced program maintenance
a. DBMS follows both graphical and virtual representation of data.
b. It needs a less number of programs for maintaining the files in DBMS.
c. Different applications are developed under the coordination of the DBA.
9. Support Adhoc Queries
a. DBMS follows strong syntactical query language.
b. So it is easy for data accessing, retrieving and data modifications.
c. So DBMS follows Adhoc query language rules.
10. Supports Concurrent Access
a. Concurrent access means multiple users can access their information at the same time.
b. DBMS supports parallel accessing as well as concurrent access.
DATA MODELS
A Data Model represents data structures and their characteristics, relations, constraints,
transformations, and other constructs with the purpose of supporting a specific problem domain.
A Data Model can be defined as the blueprint of the database structure.
9|Page
Database Management System
NETWORK DATAMODEL:
The network data model was developed to overcome the limited scope of hierarchical model.
Network data model can be used to design complex database structure.
In network data model, multiple parent-child relationships are used.
The network data model uses a network structure, which is a data structure consisting of nodes and
branches.
In network data model the database files can be divided into two parts.
3. Owner part
4. Member part
A relationship defined between any two files is named as SET.
The first implemented network database application program is IBM mainframe computers.
Network data model includes DDL (Data Definition Language) and DML (Data Manipulation
Language) in DBMS.
The main difference of network model with hierarchical model is that a network model permits a
child to have more than one parent, where as hierarchical model not allows a child to have multiple
parents.
In network data model data access is more flexible.
ADVANTAGES:
Network data model is simple and easy to implement.
Network data model can handle one-to-one and many-to-many associations.
There is always a link between the parent and child segments in this data model.
DISADVANTAGES:
Since all the records use pointers, database structure becomes more complex.
10 | P a g e
Database Management System
Insertion, updating and deletion operations more complex in this model.
In this data model structural independence is not present.
RELATIONAL DATAMODEL:
It is one of the most popular data model implemented by E.F.Codd.
Relational data model supports all kinds of associations.
The structure of the database in relational data model is in the form of table.
A table can be defined as collection of rows and columns.
The rows are called records or tuple and columns are called fields or attributes.
Relational data model could not support data redundancy. So two tables or two fields could not have
the same name.
There is no restriction for creating tables.
Every relational database table having at least one unique field called “key field”.
In relational data model the data is fully independent that is the modifications applied on one data
item/value/table/field could not affect other data item/value/field/table.
It supports all kinds of database constraints.
The first implemented relational database application program is “ORACLE”. It is the combination
of both SQL and PL/SQL.
ADVANTAGES:
Relational data model is simpler than hierarchical and network data models.
Changes in the structure do not affect the data access.
Relational data model achieves both data independence and structural independence.
Ad hoc query capability is based on SQL.
DISADVANTAGES:
Relational database system need more powerful hardware computers and data storage devices.
Setting up and maintaining the relational database is more expensive. To set up a relational database,
you need to purchase special software.
Ease of design can lead to bad design.
1. Data
2. Procedures
3. People
4. Computer ( Software + Hardware )
11 | P a g e
Database Management System
DATA:
Data is a collection of interrelated files specific to an organization. Data is the root entity of any
database system. In database terminology data is raw facts. Depending on access mechanism data is
available in two modes.
1. Shared Mode
2. Integrated Mode
SHARED MODE:
If a single piece of information is accessed by multiple application users then we say that data is in
the shared mode.
In railway database system information regarding the trains may be accessed by multiple counter clerks
from various locations.
INTEGRATED MODE:
If multiple pieces of information is accessed by single application user then we say that the data is in
integrated mode.
In a school database system a senior clerk preparing progress report by combining the various files such as
personal details, marks details, attendance details and etc.
PROCEDURES:
A Program is a collection of well defined instructions. Database utilities like Oracle, Sybase, IDMS,
IMS used as database languages.
Procedures are the instructions and rules that govern the design and use of the database system.
It gives the information about the data standards assigned to the database fields, storage structure and
also specifies the data entry screens and reports.
COMPUTER:
A Computer is a collection of physical components of the system which are integrated together.
Hardware includes secondary storage devices, communication channels (data cables), power cables,
processor, mother board and other devices.
Software is a collection of application programs includes strategies like inserting data, retrieving data,
updating data, deleting data. Usually application programs developed by application programmers to help
end users to perform their data manipulations.
PEOPLE:
This is the last component of the information system. People are classified into three categories.
End Users
Application Programmers
DBA (Database Administrator)
System Administrator
12 | P a g e
Database Management System
Database Designer
END USER:
He is the third class user of database system to perform tail-end operations. He is the responsible user
for various data manipulations such as insertion, updating, deletion and etc. With the help of application
programs, end user will access data from the database system.
APPLICATION PROGRAMMER:
He is the intermediate user responsible to develop variety of application programs which always
helps the end user to interact with the database, to perform various operations.
Application programs develop utility programs with the help of components in the database system.
He is the apex body of the database system. Being a supervisor of an organization, he has several
responsibilities.
SYSTEM ADMINISTRATOR
The system administrator controls and coordinates the functioning in between the hardware
component and the system programs of DBMS. He is responsible to oversee the database system is general
operations.
DATABASE DESIGNER
These people design the database structure. The database designer gives the information about the
growing new dimensions and the responsibilities of newly implemented database application programs.
↪ The degree of data abstraction specifies the frame work of Data model.
↪ The database can also be viewed from different levels of abstraction to reveal different levels of
details.
13 | P a g e
Database Management System
↪ From a bottom-up manner, we may find that there are three levels of abstraction in the database.
EXTERNAL LEVEL:
1. In this database view, maximum details about the database will be hidden from the user.
2. Only the restricted portion of the database is available to end users, because an end user does not
need to know everything about the structure of the entire database.
3. This model purely related to end user only.
4. It implements highest level of data abstraction.
5. E-R Diagrams will be used to represent the external views.
CONCEPTUAL LEVEL:
1. This view will provide some more details about the database to the user like structure or schema
details of the database.
2. Conceptual level describes what type of data is stored in the database and what relationships exist
among those data.
3. In this level a user know the information about the attributes of each table, the common attributes in
the different tables.
4. It implements middle level of data abstraction.
INTERNAL LEVEL:
1. This level is concerned with the physical storage of the data.
2. It also describes what data is stored in tables.
3. It implements lowest level of data abstraction.
4. Both internal level and physical level is considered as a single level, but the difference is physical
level is managed by operating system under the direction of DBMS, while the internal level is
managed by DBMS.
14 | P a g e
Database Management System
UNIT-III
Entity – Relationship Model
INTRODUCTION:
1. Entity – Relationship model is a high level conceptual model developed by Peter Chen in 1976 to
facilitate database design.
2. The E-R Model is the generalization of the earlier available models like hierarchical and the network
model.
3. Entity-Relationship model consists of set of objects called entities and relationships among the entity
sets.
4. A basic component of the E-R model is the Entity-Relationship diagram which is used to visually
represent data objects and the relationships between them.
5. The E-R Diagram used for representing E-R model can be easily converted into relations (tables) in
relational model.
6. It is a top-down approach to database design.
7. It is very simple and easy to understand by various types of users and designers.
8. It provides an easily understood pictorial map for the database design.
TYPES OF ENTITIES:
Entities are classified into two types.
1. WEAK ENTITY:
If the existence of an entity is depends upon another entity such an entity is said to be weak entity. In
other words an entity that does not has an attribute that act as a primary key is called as weak entity.
It is represented by using double rectangle.
15 | P a g e
Database Management System
2. STRONG ENTITY:
If the existence of an entity does not depend up on another entities such an entity is said to be strong
entity. In other words an entity that has an attribute that act as a primary key is called as strong
entity. It is represented by using single rectangle.
TYPES OF ATTRIBUTES:
The following are the various types of attributes.
1. Simple attribute
2. Composite attribute
3. Multi valued attribute
4. Derived attribute
SIMPLE ATTRIBUTE:
An attribute that consist of a single atomic value is called simple attribute and it cannot be sub
divided.
For example the field name in a STUDENT or EMPLOYEE entity can be divided into First-Name, Middle-
Name and Last-Name.
MULTI VALUED ATTRIBUTE:
An attribute that consists of multiple values is called as multi valued attribute. For example a
STUDENT may have multiple phone numbers or email IDs.
DERIVED ATTRIBUTE:
An attribute that’s value is derived form a stored attribute is called as derived attribute. For example
the attribute age, its value is derived from the stored attribute Date_of_Birth.
16 | P a g e
Database Management System
DEGREE PF REALTIONSHIP:
The degree of a relationship is the number of entities associated with the relationship. The degree of
relationship is also called as “cardinality”.
ONE-TO-ONE RELATIONSHIP:
Only one entity of the first set is related to only one entity of the second set, such a relationship is
called one-to-one relationship.
For example a teacher teaches student. Only one teacher is teaching to only one student.
17 | P a g e
Database Management System
DEVELOPING E-R DIAGRAMS:
1. The name of the entity must be in upper case characters.
2. The relationship must and should have an identification ( name of relation ).
3. The relationship identification may be either in active voice or passive voice.
4. The relationship in the diagram either may be in single or double direction and this direction
represents relationship type.
Let us consider 3 entities with fields as follows:
Entity – 1 : STUDENT ( StdNum , SName , Branch )
Entity – 2 : SUBJECT ( SubCode, SubName, BookName )
Entity – 3 : FACULTY ( FacCode, FacName, SubName )
18 | P a g e
Database Management System
Specialization:
1. A group of entities are divided into sub-groups based on their characteristics is called as
specialization.
2. IS A relationship supports attribute inheritance and relationship participation.
3. The sub class relationship is represented by IS A relationship.
4. Attribute inheritance is the property by which sub class entities inherit values for all attributes of
super class.
5. Specialization is the top-down process of identifying lower level entity subtypes from a higher level
entity supertype.
The relation between CENTER and COURSE entities is acting as a single entity in relation with entity
VISITOR.
Composition:
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is
called as composition.
When an object contains the other object, if the contained object cannot exist without the existence
of container object, then it is called composition.
For example
1. A class contains students. A student cannot exist without a class. There exists composition
between class and student.
2. A room does not exist separate to a house.
19 | P a g e
Database Management System
CODD’s RULES:
1. In 1985, Dr. E.F.Codd published a list of 12 rules to define a relational database system.
2. An RDBMS product has to satisfy at least 6 of the 12 rules to be accepted as a full-fledged RDBMS.
3. There is no RDBMS package available that satisfies all the 12 rules.
4. The following are the Codd’s rules.
a. INFORMATION RULE: All information in a relational database must be logically represented as
column values in rows within tables.
b. GUARANTEED ACCESS: Every value in a table is guaranteed to be accessible through a
combination of table name, primary key and column name.
c. SYSTEMATIC TREATMENT OF NULL VALUES: Null values must be represented and treated
in a systematic way, independent of data type.
d. DYNAMIC ONLINE CATALOG BASED ON THE RELATIONAL MODEL: The meta data
must be stored and managed as ordinary data, that is in tables within database. Such data must be
available to authorized users using the standard database relational language.
e. COMPREHENSIVE DATA SUBLANGUAGE: The relational database must support one well
defined, declarative language for data definition, view definition, data manipulation, integrity
constraints, authorization and transaction management.
f. VIEW UPDATING: Any view that is theoretically updatable must be updatable through system.
g. HIGH LEVEL INSERT, UPDATE AND DELETE: The database must support set-level insert,
update and delete.
h. PHYSICAL DATA INDEPENDENCE: Application programs and ad hoc facilities are logically
unaffected when physical access methods or storage structure are changed.
i. LOGICAL DATA INDEPENDENCE: Application programs and ad hoc facilities are logically
unaffected when changes are made to the table structure that is changing order of columns and
inserting new columns.
j. INTEGRITY INDEPENDENCE: All relational integrity constraints must be definable in the
relational language and stored in the system catalog, not at the application level.
k. DISTRIBUTION INDEPENDENCE: The end users and application programs are unaware and
unaffected by the data location.
l. NO-SUBVERSIONS: If the system supports low-level access to the data, users must not be allowed
to bypass the integrity rules of the database.
RELATIONAL INTEGRITY:
1. The responsibility of Database Administrator is to maintain the integrity of the database and prevent
it from becoming corrupted.
2. Database integrity means the completeness, correctness and consistency of data.
3. In relational data model data integrity can be achieved using integrity rules or constraints.
4. Integrity constraints are divided into three main categories.
a. Domain integrity
b. Entity integrity
c. Referential integrity
DOMAIN INTEGRITY
1. Domain integrity rules are associated with maintaining the correctness of attribute values.
2. It deals with the entries of the data values.
3. We can achieve domain integrity by using data type, NOT NULL and CHECK constraints.
20 | P a g e
Database Management System
4. NOT NULL constraint is used to verify the data value of field is not null.
5. CHECK constraint is used to verify the range and data types of data values.
ENTITY INTEGRITY
1. Entity integrity rule specifies that each entity should be identified uniquely.
2. Entity integrity is a constraint on primary key value.
3. PRIMARY KEY doesn’t have repeated data and null values and used to identify an entity uniquely.
REFERENTIAL INTEGRITY:
1. Referential integrity is achieved through FOREIGN KEY CONSTRAINT.
2. A Foreign Key is an attribute within one relation that matches the primary key in another relation.
3. In relational database sometimes it requires to ensure that a value that appears in one relation field is
also available for some other field in another relation. This is known as referential integrity and is
expressed in terms of foreign key.
21 | P a g e
UNIT-IV
STRUCTURED QUERY LANGUAGE
Introduction to SQL:
1. SQL stands for Structured Query Language. It is a special purpose language used to define, access and
manipulate data in RDBMS.
2. SQL provides a set of statements for storing and retrieving data to and from a relational database.
3. All modern RDBMS like Microsoft SQL-Server, Microsoft Access, Oracle, DB2, Sybase, MySQL use
SQL as standard database language.
4. SQL is different form other programming languages like C, C++ etc.
5. It is a English like language that processes data in groups of records rather than one record at a time.
Advantages of SQL:
1. SQL can retrieve data from a database.
2. SQL can execute queries against a database.
3. SQL can insert records in a database.
4. SQL can update records in a database.
5. SQL can delete records form a database.
6. SQL can create new databases, new tables in a database.
SQL Commands:
SQL commands are instructions used to communicate with the database to perform specific task that
work with data. SQL commands are grouped into five major categories:
Data Query Language (DQL)
SQL commands used to retrieve data from database. DQL commands in SQL are SELECT.
Data Definition Language (DDL)
DDL commands are used to create, modify and drop structure of database objects. DDL
commands are CREATE, ALTER, DROP, RENAME, TRUNCATE.
Data Manipulation Language (DML)
DML commands are used to insert, update and delete records form a database. DML commands
are INSERT, UPDATE, DELETE.
Transaction Control Language (TCL)
These commands are used to save the changes made to the database. TCL commands are
COMMIT, ROLLBACK and SAVEPOINT.
Data Control Language (DCL)
These commands are used to provide security to the database. DCL commands are GRANT and
REVOKE.
Data Types in SQL:
1) NUMBER:- This data type is used to store Fixed Point (numeric’s) or Floating point Numbers.
Maximum precision range 1 to 38 and scale range : -84 to 127
Ex: -160, 45, 3.45, -5.67
Syntax: field-name NUMBER(P, S); (p=precision, S=scale(total length)
Number Subtypes:
o DEC , DECIMAL, NUMBER: They are used to declare fixed point numbers with Precision
range 1 to 38 decimal digits.
o FLOAT :- FLOAT is used to declare floating point numbers with precision range 1 to 126
binary digits. Ex:- avg FLOAT(3);
o INT, INTEGER, SMALLINT:- They are used to declare integers with precision range 1 to
38 Decimal digits.
2) CHAR:- CHAR data type use to store fixed length character data maximum storage 2000 bytes.
Syntax: field-name CHAR(size);
Example:- Sname CHAR(20);
Note :- if you store 10 chars then remaining 10 spaces are left unused.
4) DATE:- It is used to store fixed length date times in the format of DD-MON-YY. Valid range
January – 1- 4712 BC to December-31-9999 AD. The size of date data type 7 bytes.
Syntax: field-name DATE;
6) BLOB:- BLOB(Binary Length Object) It refers binary length object. The range from 8TB to 128
TB (Tera byte)
Data Definition Language:
It is the subset of SQL commands to create, modify and destroy database objects like tables,
indexes, views etc.
There are 6 types of DDL commands
1) CREATE
2) ALTER (Advanced Data Definition Commands)
3) TRUNCATE
4) RENAME
5) DROP
1) CREATE :- This command can be used to create the physical structure of the database table.
Syntax:
create table table_name
(
Example1 :-
create table STUDENT
( Sno NUMBER(3) PRIMARY KEY,
Sname VARCHAR2(20),
Spec VARCHAR2(10),
Dob DATE
);
Example2 :- SQL/> CREATE TABLE MARKS(HNO NUMBER(12) PRIMARY KEY, SNO NUMBER(12)
REFERENCES STUDENT, SUB VARCHAR2(12), MARKS NUMBER(12, 2) NOT NULL);
2) ALTER:- ALTER TABLE statement is used to modify the table structure by modifying the
definition of its columns.
There are 4 options are available in Alter command
A) ADD :- To add a column
B) MODIFY :- To change the column characteristics.
C) DROP :- To delete a column from a table.
D) ADD / DROP Constraints.
A) Adding a Column:-
Using ALTER ADD command to adding one or more columns to an existing table.
Syntax: ALTER TABLE table_name ADD column_name datatype;
Example:- ALTER TABLE STUDENT ADD mobile_no NUMBER(10);
B) Modifying a Column Data Type, Length:-
Using ALTER MODIFY to modify the column data type or length of the column.
Syntax: ALTER TABLE table_name MODIFY column_name datatype;
Example:- ALTER TABLE STUDENT MODIFY Sname VARCHAR2(25);
C) Dropping a Column:-
Using ALTER DROP command you can drop (delete) the existing column of a table.
Syntax: ALTER TABLE table_name DROP COLUMN Sname;
Example:- ALTER TABLE STUDENT DROP COLUMN Sname;
3. TRUNCATE:- Using TRUNCATE command to delete all records in a table. But not delete
structure of the table. Never get back record using ROLL BACK.
Syntax:- TRUNCATE table table_name; Example:- TRUNCATE table EMP3;
4. RENAME :- Using RENAME TABLE statement to rename an existing table in any database
schema.
Syntax:- RENAME oldtable_name TO new_table_name; Example:- RENAME emp TO employee;
5. DROP:- Using DROP TABLE statement removes the table from the database server
permanently. Once the table dropped it never be roll backed.
Syntax: DROP table Table-name; Example: DROP table EMP;
AGGREGATE FUNCTIONS :-
Aggregate functions also called Group functions are built-in SQL functions that operate on groups of
rows and return one value for the entire group or table. They are used to produce summarized results.
Types of Aggregate functions :
i. COUNT ( )
ii. SUM ( )
iii. AVG ( )
iv. MAX ( )
v. MIN ( )
i) COUNT ( ) :- This function returns the number of rows in the table that satisfies the condition
specified in the WHERE clause with SELECT statement. It counts non-null values of an attribute
also.
Example 1:-
SELECT COUNT ( * ) AS Total_Employees FROM EMP WHERE deptno = 10;
Output:- Total Employees
3
Example 2:-
SELECT COUNT ( * ) AS Total_Employees FROM EMP;
Output:- Total Employees
10
Example 2:-
SELECT COUNT ( DISTINCT DEPTNO) FROM DEPT;
Output:- 3
ii) SUM ( ) :- This function is used to get the sum of a numeric column.
Example 1:- To get the total salary given out to the employees.
SELECT SUM (SAL) AS Total_Salary FROM EMP;
Output:- Total Salary
355000
iii) AVG ( ) :- This function is used to get the average of a numeric column.
Example 1:- To get the average salary, the query would be like.
SELECT AVG (SAL) AS Average_Salary FROM EMP;
Output:- Average_Salary
1500.234
iv) MAX ( ) :- This function is used to get the maximum value from a numeric column.
Example 1:- To get the maximum salary drawn by an employee, the query would be like.
SELECT MAX (SAL) AS Maximum_Salary FROM EMP;
Output:- Maximum_Salary
33000
v) MIN ( ) :- This function is used to get the minimum value from a numeric column.
Example 1:- To get the minimum salary drawn by an employee, the query would be like.
SELECT MIN (SAL) AS Minimum_Salary FROM EMP;
Output:- Minimum_Salary
10000
(1) INSERT :- (Adding table rows) The INSERT statement is used to insert new rows or records into a
table. We can insert single record or multiple records at a time.
1) Inserting single record:
Syntax: INSERT INTO tablename VALUES ( value1, value2,…. valueN);
Example: INSERT INTO Student VALUES(1, ‘murthy’, ‘bca’, ’25-jan-09’);
Output: 1 row created.
(2) UPDATE:- (Updating table rows) The UPDATE statement is used to modify data in a table. Changing
a single value or multiple values or single record or multiple records in a table.
(3) DELETE:- (Deleting table rows) The DELETE statement is used to delete a single record or
multiple record or all records in a database table.
Syntax: DELETE FROM tablename WHERE condition;
Examples:-
a. Delete all records from STUDENT table;
Example:- DELETE FROM student;
Output:- SQL\> 5 rows deleted
Imposition of Constraints:
SQL uses integrity constraints to prevent invalid data entry into the tables of the database. Constraints
are a part of a table definition.
The constraints can be specified immediately after the column definition. This is called column level
constraints.
The constraints can be specified after all the columns are defined. This is called table level constraints.
The following are the various SQL constraints.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
NOT NULL:
By default, a table column can hold null values. The NOT NULL constraint enforces a column to not
accept NULL values. The constraint is placed immediately after the data type of a column.
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3) NOT NULL,
NAME CHAR(30),
MARKS NUMBER(5,2) );
UNIQUE:
The UNIQUE constraint uniquely identifies each and every record in a database. It ensures that the
values entered into a column are unique, i.e., no two rows of a table have duplicate values.
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3) UNIQUE,
NAME CHAR(30),
MARKS NUMBER(5,2) );
PRIMARY KEY:
A PRIMARY KEY constraint is used to identify a record uniquely from a table and it doesn’t allow
duplicate records and null values. It can be defined as a column level or table level.
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3) PRIMARY KEY.
NAME CHAR(30),
MARKS NUMBER(5,2) );
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3),
NAME CHAR(30),
MARKS NUMBER(5,2), PRIMARY KEY(RNO) );
FOREIGN KEY:
The FOREIGN KEY or referential Integrity identifies any column referencing the PRIMARY KEY in
another table. It establishes a relationship between two columns in the same table or between different tables.
Example:
CREATE TABLE PRODUCT ( PID NUMBER(3) PRIMARY KEY,
PNAME CHAR(30),
UNITPRICE NUMBER(4) );
CREATE TABLE CUSTOMER ( CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID),
QTY NUMBER(3) );
On delete Cascade: By using this option, whenever a parent row is deleted then all the corresponding child rows
are deleted from the child table.
CREATE TABLE CUSTOMER
(
CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID) ON DELETE CASCADE,
QTY NUMBER(3)
);
On Delete Set Null: By using this option, all the foreign key column values set to null when the parent value is
removed.
CREATE TABLE CUSTOMER
(
CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID) ON DELETE SET NULL,
QTY NUMBER(3)
);
CHECK:
The CHECK constraint defines a condition that each row must satisfy. It is used to limit the value range
that can be placed in a column.
CREATE TABLE CUSTOMER
(
CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID) ON DELETE CASCADE,
QTY NUMBER(3),
GENDER CHAR(1) CHECK( GENDER IN(‘M’,’F’)
);
Set operations:
Relational SET OPERATORS (Relational Algebra)
In Oracle database SQL supports 8 types of relational algebra and relational SET operators.
SET operators are used to combine information of similar types from one or more than one table.
SQL joins tends to combine columns from different tables, whereas SQL SET operators combine rows
from different queries.
o Before apply set operators on 2 or more tables, these tables must satisfies “union compatibility”
relation.
o Union compatibility:- Two or more tables must and should have same field names, same data type
and approximate field length.
Types of SET operators:-
1) UNION
2) INTERSECT
3) MINUS (difference)
4) DIVIDE
1) UNION:-
The UNION operators joins the outputs of two or more queries(SELECT statement) into a single set
of rows and columns having distinct(unique) records.
The UNON operator combines the output of two selected queries without include duplicate records.
Syntax:- SELECT column list FROM table1
UNION
SELECT column list FROM table2 [Order by clause];
ADMISSION table
STUDENT table Admsno Spec Fee
Stdno Sname Spec Fee 1 BSC 12000
1 Sailu BSC 12000 2 BCOM 10000
2 Mounika BCOM 10000 3 BCA 20000
3 Ramya BCA 20000 4 BBM 15000
4 Indu BA 8000
Apply UNION operator on both tables. Output :-
Spec Fee
Example:- SELECT spec, fee FROM STUDENT BSC 12000
UNION BCOM 10000
SELECT spec, free FROM ADMISSION; BCA 20000
BA 8000
2) INTERSECT :- BBM 15000
The INTERSECT operator returns the rows that are common between two
sets of rows. It returns the records that appear in the both the tables.
4) DIVIDE :-
This operator specifies table1 is DIVIDE by table2 to produce table3 whenever both tabl1 & table2
using a common field.
The DIVIDE operation uses one single column table (i.e. columna) as the divisor and 2 column
table(i.e. column a & b) as the dividend.
The table must have a common column (i.e.column a)
Table A
Table B The output of a Table Output
Sname Avg
Sname A divided by Table B :-
Xyz 70
Xyz is. Avg
abc 60 DIVID
Pqr The only value 50
pqr 50 E associated with both
xyz 50 ‘xyz’ & ‘pqr’ is 50
Pqr 90 only.
UNIT-V
PL/SQL
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation
Pl/SWL BLOCK STRUCTURE
PL/SQL is a block-structured language. This means that programs can be divided into logical bocks
1) Declaration: It is used to declare variables, constants, cursors etc.
2) Executable : This section starts with BEGIN and ends with END. It contains program logic.
3) Exception handling: This section starts with the EXCEPTION keyword. It can be used to
handle errors.
PL/SQL ARCHITECTURE
DECLARE
<declarations>
EXCEPTOIN
<executable statements>
END;
Compound symbols
Symbol Meaning
!= Relational operator
|| Concatenation operator
-- Single line comment
/* */ Multiline comment
:= Assignment operator
VARIABLE: Variables are storage areas used to hold the data values that can change through the
PL/SQL block.
Variable declaration:
DECLARE
Rno number(2):=10;
Sname VARCHAR2(30):=’bharat’;
Avg NUMBER(9,2);
basic CONSTANT number(3):=10; /* constant declaration */
a) IF-THEN-END IF:- If the condition is TRUE, the statements get executed, and if the condition is
FALSE or NULL, then the IF statement does nothing.
Syntax:-
IF condition THEN
Satements;
END IF;
b) IF-THEN-ELSE-END IF:- If the condition is TRUE, then if bock executes other wise execute the
else block. DECLARE
a number(2) := 10;
Syntax:- b number(2) := 20;
IF condition THEN
Satement1; BEGIN
ELSE IF( a > b ) THEN
Satement2; dbms_output.put_line('a is big');
ELSE
END IF; dbms_output.put_line('b is big');
END IF;
END;
/
DECLARE
b) WHILE loop:- Repeats a statement or N NUMBER := &N;
group of statements while a given condition F NUMBER := 1;
is true. It tests the condition before executing I NUMBER := 1;
the loop body. BEGIN
WHILE (I<=N) LOOP
Syntax F := F * I;
WHILE condition LOOP I:= I + 1;
Statment1; END IF;
END LOOP;
Statment2;
dbms_output.put_line(‘Factorial is‘|| F);
END LOOP; END;
/
Otupt:-
Enter value for N : 5
Factorial is 120
c) FOR loop:- A FOR LOOP is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
DECLARE
i number(2);
Syntax:-
BEGIN
FOR counter IN [REVERSE] FOR i in 10 .. 20 LOOP
<initial_value> .. <final_value> LOOP dbms_output.put_line('value of i:'|| i);
Statment1; END LOOP;
Statment2; END;
/ Example: Reverse Order
----
END LOOP; Output:- FOR a IN REVERSE 10 ..
value of i: 10 20 LOOP
value of i: 11
……………………………….
PROCEDURES in PL/SQL
Procedures:
A procedure or stored procedure is a named PL/SQL block that can accept parameters
and to be invoked. But not return any value.
Procedures − These subprograms do not return a value directly; mainly used to perform
an action.
Creating a Procedure:
A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter1 [mode1] datatype1,
Procedure
parameter2 [mode2] datatype2,…) ] Specification
IS / AS
BEGIN
Procedure
< procedure_body > Body
END procedure_name;
/
Note:-
BEGIN
greetings;
END;
/
Output: Hello World
Dropping a Procedure
A function is a named PL/SQL block like procedure that can accept parameters and be
invoked. Generally a function is mainly used to compute a value.
Function must return a value to the calling environment.
Creating a Function:
Syntax:
CREATE [OR REPLACE] FUNCTION function_name
[ (parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,…) ] RETURN datatype
IS / AS
[ local declaration ]
BEGIN
< function_body >
END function_name;
/
Note:-
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
Parameter: Name of the PL/SQL variable whose value is passed to the function.
Mode :- Type of argument
o IN, OUT, IN OUT
Data type: Data type of argument. It can be of %TYPE, %ROWTYPE or any data type.
Return data type: Data type of the return value.
Dropping a Function:
CURSORS in PL/SQL
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.
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed.
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area.
S.No Attribute & Description Example
%FOUND
1 Cursor_name %FOUND
Return TRUE, if fetch statement returns at
least one row otherwise returns FALSE
%NOTFOUND
2 Cursor_name %NOTFOUND
Return TRUE, if fetch statement doesn’t
return a row. Otherwise returns FALSE
%ISOPEN
3 Cursor_name %ISOPEN
Returns TRUE, if the cursor is already open in
the program. Otherwise returns false.
%ROWCOUNT
4 Cursor_name %ROWCOUNT
Return the number of rows fetched by the
fetch statement.
DECLARE
4) Closing the Cursor ENO EMP.EMPNO%TYPE;
Closing the cursor NAME EMP.ENAME%TYPE;
SALARY EMP.SAL%TYPE;
means releasing CURSOR c1 IS
the allocated SELECT EMPNO, ENAME, SAL FROM EMP WHERE SAL>5000;
BEGIN
memory. OPEN c1;
Syntax: LOOP
FETCH c1 INTO ENO, NAME, SALARY;
CLOSE <cursor_name>; EXIT WHEN c1 % NOTFOUND;
dbms_output.put_line(EMPO || ' ' || NAME || ' ' || SALARY);
Example: END LOOP;
CLOSE c1;
CLOSE c_customers; END;
/
CURSOR FOR LOOP:-
The cursor FOR LOOP implicitly declares its loop index as a record of type %ROWTYPE,
opens a cursor, repeatedly fetches rows of the values form the active set into fields in the
record.
DECLARE
Syntax: - CURSOR cr IS
SELECT * FROM EMP WHERE deptno=20;
FOR <INDEX> IN < CURSOR_NAME> LOOP BEGIN
OPEN cr;
<STATEMENTS>; LOOP
FOR I IN cr LOOP
END LOOP;
dbms_output.put_line(I.ENAME || ‘ ‘ ||I.sal);
END LOOP;
CLOSE cr;
END;
/
TRIGGERS in PL/SQL
Trigger is a named PL/SQL block stored in a database and executed(fired) implicitly
(automatically) when triggering specific event occurs.
A trigger event is a DML is INSERT, UPDATE, DELETE statement executed against a
Database Table.
Syntax:
CREATE OR REPLACE TRIGGER trigger_name
[ BEFORE / AFTER ] [ INSERT / UPDATE / DELETE OF column_name] ON table_name
[FOR EACH ROW]
[WHEN condition]
DECLARE
Declaration statements;
BEGIN
Pl/SQL instructions; (trigger action)
……………………………………
END;
Advantages of Triggers:
Maintaining complex security rules.
Automatically generating values for derived columns
Preventing invalid transactions
Providing value auditing.
BEFORE TRIGGERS:
Here triggers fire BEFORE any transactions are implemented.
o BEFORE INSERT , BEFORE UPDATE , BEFORE DELETE
AFTER TRIGGERS:
Here triggers fire AFTER any transactions are implemented.
o AFTER INSERT , AFTER UPDATE , AFTER DELETE
Types of Triggers:-
1) Statement-level Trigger
2) Row-level Trigger
3) BEFORE Trigger
4) AFTER Trigger
1) Statement-level Trigger:- A statement trigger is fired once for the triggering statement.
In this model number of rows affected by the triggering statement.
Example:-
CREATE OR REPLACE TRIGGER stmt_level
Execute Trigger: BEFORE UPDATE ON EMP
DECLARE
SQL> update emp set sal=10000
MSG VARCHAR2(30):=’Statement-level Trigger Fired’;
where deptno=20; BEGIN
DBMS_OUTPUT.PUT_LINE(MSG);
Statement-level Trigger Fired
END;
5 rows updated. /
SQL> Output:- Trigger Created.
2) Row-Level Trigger:- A row-level trigger is fired each time the table is affected by the triggering
statement. CREATE OR REPLACE TRIGGER row_level
Execute Trigger: BEFORE UPDATE ON DEPT
FOR EACH ROW
SQL> update dept set loc=’USA’ DECLARE
where dname=’FINANCE’; MSG VARCHAR2(30):=’Row-level Trigger Fired’;
BEGIN
Row-level Trigger Fired DBMS_OUTPUT.PUT_LINE(MSG);
Row-level Trigger Fired END;
2 rows updated. / Output:- Trigger Created.
EXCEPTIONSin PL/SQL
Exception Description
INVALID_CURSOR Invalid cursor
INVALID_NUMBER Invalid number
NO_DATA_FOUND It is raised when a SELECT INTOstatement returns no
rows.
ZERO_DIVIDE It is raised when an attempt is
made to divide a number by zero.
VALUE_ERROR numeric or value error
CURSOR_ALREADY_OPEN Cursor already open
User-defined Exceptions:
PL/SQL allows you to define your own exceptions according to the need of your program.
A user-defined exception must be declared and then raised explicitly, using either a RAISEstatement
or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
o Step1: Declaring an exception
o Step2. Raising an exception
o Step 3: Handling an exception
Step 1: Declaring an Exception:-
Syntax:- DECLARE
exception-identifier EXCEPTION;
Step 2: Raising an Exception:-
Packages:-
A package is a database object that contains groups of pl/sql objects such as
procedures, functions, variables, cursor, type declarations into a single unit.
This reduces the unnecessary disk I/O and network traffic.
o A Package usually has two parts;
1) Package specification
2) Package body
1) Package specification:- The package specification contains information about
variable, exceptions, cursors, procedure, function. These all objects are accessible
from other applications.
Syntax:-
CREATE OR REPLACE PACKAGE package_name[IS/AS]
procedure_specification.
function_specification;
exception_declaration;
cursor_declaration;
END package_name;
This package contain procedure called fire it used to delete employee who has been fired. It has function
dispsalwhich accepts employee number and returns the salary.
Example:-
SQL> CREATE OR REPLACE PACKAGE fire_dispsal
AS
PROCEDURE fire(pnoNUMBER);
FUNCTIONdispsal(fno NUMBER) RETURN number;
END ;
2) Package Body:-A package bodycontains the actualexecutable code for the objects
described in the package specification. It fully defines cursors, procedures, and
functions declared in the package specification. To create package body use the
CREATE PACKAGE BODY statement.
Syntax:- CREATE OR REPLACE PACKAGE BODY package_name [ IS / AS ]
procedure_definitioin.
function_definitioin;
BEGIN
Executable_statements;
[EXCEPTION
Exception_handlers]]
END package_name;
Example:-
SQL> CREATE PACKAGE BODY fire_dispsal AS
PROCEDURE fire(pno NUMBER) is
Begin
DELETE FROMempWHEREempno=pno;
End fire;
FUNCTION dispsal(fno NUMBER) RETURN NUMBER IS
s NUMBER;
begin
SELECT salINTO s FROM empWHEREempno=fno;
return s;
enddispsal;
end;
Accessing Packages:-
Package_name.procedure_name(parameter);
Package_name.function_name(parameter);
Example:-
SQL> CALL fire_dispsal.fire(101);
Example:-
SQL> declare
R number;
Begin
fire_dispsal.fire(101);
r:=fire_dispsal.dispsal(102);
dbms_output.put_line(r);
end;
/
Advantages of Packages:
1) Modularity
2) Easier application design
3) Information hiding
4) Better performance.