Information: Database Management System Unit - 1
Information: Database Management System Unit - 1
UNIT – 1
Information
INPUT
PROCESS OUTPUT
(DATA)
(INFORMATION)
DATABASE
Information Processing
Information processing is acquisition, storage, organization, retrieval, display and
distribution of information.
Few decades back, when the computers were not invented, data processing was done
manually.
But manual processing can be done only when the amount of information is very less.
Now in companies, the amount of data has been increased.So manual processing takes
a lot of time to complete the work.
After inventing the computers, the information processing was done within seconds.
The information processing using computers were clear and accurate.
Also, the information will be processed within the needed time frame.
For this information processing, we need a large amount of data.
So, Now-a-days we started to use the data base approach. That is, database means a
large amount of data.
Information and Enterprise
An enterprise is the group of people with a common goal, which has certain resources
to achieve this goal.
In traditional approach, the organization is divided into different units like production
department, sales department, etc.
Each of these department has different goals and objectives.
So, each department functions in isolation.
So, the information created by various departments are available only to the top
management. But no other department can access the information.
TRADITIONAL APPROACH
But in modern approach, the enterprise is considered as one system and all the
departments as subsystem.
So, the information about all the aspects of the organization are stored centrally and
made available to all the departments.
FINANCIAL MARKETING
CENTRAL DATABASE
PRODUCTION DISTRIBUTION
SALES R&D
MODERN APPROACH
Why a database?
(Characteristics of Database)
1. Redundancy can be reduced: In non-database system, each department has its own private
files. So, storage space is wasted. But in database systems, by having a centralized database,
Redundancy can be reduced.
2. Inconsistency can be avoided: Two different entries regarding same data will be avoided in
database.
3. Data can be shared in a database.
4. Standards can be enforced by a Database Administrator (DBA).
5. Security restrictions can be applied to a database by a DBA.
6. Integrity i.e., Accuracy of data can be maintained in a database.
7. Conflicting requirements can be balanced by creating a best database design.
8. Persistence: Data in a database exist permanently until deleted by the user.
9. Independence: The three levels of schema should be independent of each other.
DatabaseManagement System
A DBMS is a collection of programs that helps to store, modify, retrieve information from
database.
There are various DBMS software like oracle, Access, database, foxbase etc.,
A DBMS software is used in many applications like:
Computerized library systems.
Railway Reservation systems.
Banking systems.
Government database like E-services.
Smart card systems.
Postal system.
Types of DBMS
A database model is an approach that specifies particular mechanism for data storage and
retrieval. The different database model is:
a) Hierarchical Model
b) NetworkModel
c) RelationalModel
d) Object orientedModel
e) ObjectrelationalModel
f) DeductiveModel
a) Hierarchical Model:
It is one of the oldest database models.
Information management system [IMS] was the first hierarchical database.
It was developed by North American Rockwell company and IBM.
This database model is organized into a tree like structure.
It has parent and child relationship.
It has one parent record and many children.
For e.g.:
Advantages:
The design of hierarchical database is very simple.
Hierarchical model gives security for the database.
This promotes parent and child relationship. Therefore, it has data integrity.
This model is considered as very efficient.
Disadvantages:
This model was easy to design but difficult to implement.
Maintaining a database in hierarchical model was difficult.
It has programming complexity.
Only one to one and one to many relationships was possible but many to
many relationships can’t be implemented in hierarchical model.
(b) Network model:
This database model is organized as a graph.
This model has the ability to handle many to many relationships.
It allows a record to have more than one parent.
It has owner-member relationship.
Suppose an employee works in more than one company.
Advantages:
Network model was conceptually simple and easy to design.
This model can have one to one, one to many and many to many relationships.
This model promotes data integrity because it has owner member relationships.
Changes in data do not require changes in application programs.
Network model is based on standards formulated by DBTG (Data Base Task Group).
Disadvantage:
This model was easy to design but difficult to implement.
This model has difficulty in making structural changes in database.
(c) Relational Model:
This model is organized as a table.
Each table is called as entity and each row is called as an instance.
This is the most popular database model.
Advantages:
This model is conceptually simple.
Database design, implementation, maintenance and usage were much easier
than other models.
It has very powerful, flexible and easy to use query capabilities.
Database Structures do not affect the data access.
Disadvantages:
Relational database system needs more powerful hardware to run smoothly.
Relational database easy to design but sometimes this easiness leads to a bad
design.
Since relational database was easy to design so many people or departments
create their own database.
(d) Object-oriented Model:
A data model that closely represents the real world.
Both data and relationships are contained in single structure called object.
An object is a real-world entity.
Attributes describe the properties of an object.
Methods describe the object’s behavior.
For e.g.: An object called PERSON includes the attributes like name, date of
birth, Aadhar ID etc.
Any type of data can be stored in OODBMS such as data, text, picture, voice and
video.
Advantages:
This object-oriented model can have large number of the different datatypes.
This model combines the object-oriented programming concept with database
technology.
Object oriented features like inheritance and dynamic binding improves productivity.
Disadvantages:
Object oriented database have greater challenge in handling schema migration.
This object-oriented model was not suited for all applications.
Advantages:
New data types and methods can be added in this model.
This model allows the use of inheritance that is reuse and sharing.
Polymorphism in ORDBMS allows same methods names to have different
meanings.
Disadvantages:
Programming in object relational model was difficult.
This model was expensive.
UNIT-2
Entity Relationship Modeling
ER Model
(1) Entities:
Publishes
PUBLISHER BOOK
Ternary Relationship:
TEACHER
Teaches
SUBJECT STUDENT
Quaternary Relationship:
TEACHER
Studies
SUBJECT COURSE-MATERIAL
STUDENT
(ii) Connectivity:
1 N
Has
DEPARTMENT EMPLOYEES
N N
Joins
EMPLOYEE COURSE
(iii) Cardinality:
Expresses the specific number of entity occurrence associated with the occurrence of the
related entity.
For e.g.:
Has
DEPARTMENT EMPLOYEES
(1, 100) (1,1)
One department can have a minimum of one employee and a maximum of 100 employees.
(iv) Participation:
If an entity’s occurrence requires the occurrence of another entity, then it is called total
participation.
If an entity’s occurrence doesn’t require the occurrence of another entity, then it is
called partial participation.
For e.g.:
Enrolled in
COURSES
STUDENT
Partial Total
(v) Dependency:
For e.g.
Borrows
CUSTOMER LOAN
ER Diagram Conventions
Entities are reprresented by a rectangular box.
CUSTOMER
Attributes are represented by an ellipse.
Cust_name
Entities names are written in upper case letters.
STUDENT
Attributes names are written in lower case letters.
Address
Roll no.
Age
Relationship can be classified as one to one, one to many and many to many.
1 1
manages DEPARTMENT
MANAGER
1 N
Has
DEPARTMENT EMPLOYEES
Joins
EMPLOYEE COURSE
N N
RDBMS Terminology
Attributes
Tuples
E0101 M.hari 32 Production
E0102 R.kumar 36 operation
E0103 S.pooja 31 human resoruce
E0104 N.varsha 34 production
Domain
DEGREE
The data in RDBMS is stored as tables & this tables are called as relations.
Every table is broken up into columns called attributes.
A tuple is row of data. In this table, we have 4 employee records that is 4 tuples.
Number of attributes in a relation is called degree.
A relation with one degree is called unary relation. A relation with two degree is called
binary relation, etc.
Number of tuples in a relation is called cardinality.
Most of the relations have an attibute which can uniquely identify each tuple in the
relation. This attribute is callled as primary key.
In some cases, there can be more than one attribute which can uniquely identify each
tuple in the relation. These attributes are called as canidate keys.
One candiate key is designated as primary key and other candiates keys are called
alternate keys.
A foregin key is a field in a table that refers to the primary key of another table.
Foregin key act as a cross_referance between the tables.
For eg:
Whenever one of these operations are applied, integrity constraints specified on the relational
database schema must never be violated.
Insert Operation
The insert operation gives values of the attribute for a new tuple which should be inserted into
a relation.
Update Operation
You can see that in the below-given relation table CustomerName= 'Apple' is updated from
Inactive to Active.
Query: Update table customer set Status=’active’ where CustomerName=’Apple’;
Delete Operation
To specify deletion, a condition on the attributes of the relation selects the tuple to be deleted.
Query:
Delete from customer where CustomerName=’Apple’;
In the above-given example, CustomerName= "Apple" is deleted from the table.
The Delete operation could violate referential integrity if the tuple which is deleted is
referenced by foreign keys from other tuples in the same database.
Select Operation
Domain Constraints:
All the values that appear in a column of a relation(table) must be taken from the same
domain. A domain is a set of values that may be assigned to an attribute.
A domain consists of the following components:
a) Domain Name
b) Meaning
c) Data type
d) Size of Length
e) Allowable values or Allowable range
Entity Integrity:
This rule is designed to assure that every relation has a primary key that the data values for
that primary key are all valid, no null value enter for the primary key. Every primary key
attribute is non-null.
Null value occurs in two situations:
1. There is no applicable data value. Example: If we don’t have a fax machine, we don’t
have the fax number.
2. Applicable data value is not known when the values are assigned. Example: If we don’t
know the melting point of Nickel, but it has value.
Referential Integrity:
Referential integrity constraints are based on the concept of Foreign Keys. A foreign key
is an important attribute of a relation which should be referred to in other relationships.
A foreign key is matching with the primary key.
Referential integrity constraint state happens where relation refers to a key attribute of
a different or same relation. However, that key element must exist in the table.
Operational Constraints:
These are the constraints enforced in the database by the business rules or real
worldlimitations.
Example: I the retirement age of the employees in an organization is 60, then the age column of
the employee table can have a constraint “Age should be less than or equal to 60”.
These kinds of constraints, enforced by the business and the environment are called
operational constraints.
Codd’s Rules
Rule 1: Information Rule
The data stored in a database, may it be user data or metadata, must be a value of some table
cell. Everything in a database must be stored in a table format.
Rule 2: Guaranteed Access Rule
Every single data element (value) is guaranteed to be accessible logically with a combination of
table-name, primary-key (row value), and attribute-name (column value). No other means, such
as pointers, can be used to access data.
Rule 3: Systematic Treatment of NULL Values
The NULL values in a database must be given a systematic and uniform treatment. This is a very
important rule because a NULL can be interpreted as one the following − data is missing, data is
not known, or data is not applicable.
Rule 4: Active Online Catalog Based on the Relational Model
The structure description of the entire database must be stored in an online catalog, known as
data dictionary, which can be accessed by authorized users. Users can use the same query
language to access the catalog which they use to access the database itself.
Rule 5: Comprehensive Data Sub-Language Rule
A database can only be accessed using a language having linear syntax that supports data
definition, data manipulation, and transaction management operations. This language can be
used directly or by means of some application. If the database allows access to data without
any help of this language, then it is considered as a violation.
Rule 6: View Updating Rule
All the views of a database, which can theoretically be updated, must also be updatable by the
system.
Rule 7: High-Level Insert, Update and Delete Rule
A database must support high-level insertion, updation, and deletion. This must not be limited
to a single row, that is, it must also support union, intersection and minus operations to yield
sets of data records.
Rule 8: Physical Data Independence
The data stored in a database must be independent of the applications that access the
database. Any change in the physical structure of a database must not have any impact on how
the data is being accessed by external applications.
Rule 9: Logical Data Independence
The logical data in a database must be independent of its user’s view (application). Any change
in logical data must not affect the applications using it. For example, if two tables are merged or
one is split into two different tables, there should be no impact or change on the user
application. This is one of the most difficult rule to apply.
Rule 10: Integrity Independence
A database must be independent of the application that uses it. All its integrity constraints can
be independently modified without the need of any change in the application. This rule makes a
database independent of the front-end application and its interface.
Rule 11: Distribution Independence
The end-user must not be able to see that the data is distributed over various locations. Users
should always get the impression that the data is located at one site only. This rule has been
regarded as the foundation of distributed database systems.
Rule 12: Non-Subversion Rule
If a system has an interface that provides access to low-level records, then the interface must
not be able to subvert the system and bypass security and integrity constraints.
Unit 3
Normalization
Normalization divides the larger table into the smaller table and links them using
relationship.
The normal form is used to reduce redundancy from the database table.
Normal Description
Form
1NF A relation is in 1NF if it contains an atomic value. The multi-valued
attributes should be removed, that is elimination of repeating groups.
2NF The partial functional dependencies have to be removed, that is
elimination of redundant data.
3NF The transitive dependencies have to be removed, that is
eliminatingcolumns not dependent on the key.
BCNF The remaining anomalies that result from functional dependencies are
removed.
4NF Multi-valued dependencies are removed, that is isolation of
independentmultiple relationships.
5NF Any remaining anomalies are removed. In this normal form, we isolate
semantically related multiplerelationships.
EMPLOYEE Table:
The decomposition of the EMPLOYEE table into 1NF has been shown below:
o In the second normal form, all non-key attributes are fully functional dependent on the
primary key
Example:Suppose a school wants to store the data of teachers and the subjects they teach.
They create a table that looks like this: Since a teacher can teach more than one subjects, the
table can have multiple rows for a same teacher.
TEACHER Table
The table is in 1 NF because each attribute has atomic values. However, it is not in 2NF because
non prime attribute teacher_age is dependent on teacher_id alone which is a proper subset of
candidate key. This violates the rule for 2NF.
To convert the given table into 2NF, we decompose it into two tables:
TEACHER_DETAIL Table:
TEACHER_ID TEACHER_AGE
25 30
47 35
83 38
TEACHER_SUBJECT Table:
TEACHER_ID SUBJECT
25 Chemistry
25 Biology
47 English
83 Math
83 Computer
Third Normal Form (3NF)
An attribute that is a part of one of the candidate keys is known as prime attribute.
An attribute that is not part of any candidate key is known as non-prime attribute.
In other words 3NF can be explained like this: A table is in 3NF if it is in 2NF and for each
functional dependency X-> Y at least one of the following conditions hold:
X is a super key of table
Y is a prime attribute of table
Example:
EMPLOYEE_DETAIL Table:
{EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_PIN}
Non-prime attributes: In the given table, all attributes except EMP_ID are non-prime.
EMPLOYEE Table:
EMPLOYEE_PINTable:
Example: Let's assume there is a company where employees work in more than one
department.
EMPLOYEE Table:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
To convert the given table into BCNF, we decompose it into three tables:
EMP_COUNTRY Table:
EMP_ID EMP_COUNTRY
264 India
364 UK
EMP_DEPT Table:
EMP_DEPT DEPT_TYPE EMP_DEPT_NO
Designing D394 283
Testing D394 300
Stores D283 232
Developing D283 549
EMP_DEPT_MAPPING Table:
EMP_ID EMP_DEPT
D394 283
D394 300
D283 232
D283 549
Functional dependencies:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
Now, this is in BCNF because left side part of both the functional dependencies is a key.
o A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-valued
dependency.
o For a dependency A → B, if for a single value of A, multiple values of B exists, then
the relation will be a multi-valued dependency.
Example :
STUDENT Table:
In the STUDENT relation, a student with STU_ID, 21 contains two courses, Computer and
Math and two hobbies, Dancing and Singing. So there is a Multi-valued dependency on
STU_ID, which leads to unnecessary repetition of data.
So to make the above table into 4NF, we can decompose it into two tables:
STU_ID HOBBY
21 Dancing
21 Singing
34 Dancing
74 Cricket
59 Hockey
STUDENT_COURSESTUDENT_HOBBY
STU_ID COURSE
21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics
o A relation is in 5NF if it is in 4NF and not contains any join dependency and joining
should be lossless.
o 5NF is satisfied when all the tables are broken into as many tables as possible in order
to avoid redundancy.
o 5NF is also known as Project-join normal form (PJNF).
Example
In the above table, John takes both Computer and Math class for Semester 1 but he doesn't
take Math class for Semester 2. In this case, combination of all these fields required to
identify a valid data.
Suppose we add a new Semester as Semester 3 but do not know about the subject and who
will be taking that subject so we leave Lecturer and Subject as NULL. But all three columns
together acts as a primary key, so we can't leave other two columns blank.
So to make the above table into 5NF, we can decompose it into three relations P1, P2 & P3:
P1 P2
SUBJECT LECTURER
SEMESTER SUBJECT
Computer Anshika
Semester 1 Computer Computer John
Semester 1 Math Math John
Semester 1 Chemistry Math Akash
Semester 2 Math Chemistry Praveen
P3
SEMESTER LECTURER
Semester 1 Anshika
Semester 1 John
Semester 1 John
Semester 2 Akash
Semester 1 Praveen
Unit 4
TABLES
Tables are the basic building blocks in any database system. They contain the rows and columns
of data. We can create, modify and delete tables using sql commands.
Creating a Table
Creating a table involves table name, column definitions and each column's data type. The
CREATE TABLE statement is used to create a new base table.
The CREATE TABLE statement has two formats.
Format1 :
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
Primary Key definition,
Alternate Key definitions,
Foreign Key definitions
);
Format2 :
CREATE TABLE table-name LIKE base-table-name;
Example :
CREATE TABLE CATALOG LIKE BOOK;
This statement will create a table called CATALOG with the same structure as BOOK.
Modifying a Table
The ALTER TABLE command is used to add, delete or modify columns in an existing table.
Deleting a Table
The DROP TABLE statement is used to delete a table. The basic syntax of this DROP TABLE
statement is as follows:
JOINS
Join is a query in which data is retrieved from more than one table.
Join has the capability of retrieving data from multiple tables.
It is one of the most powerful and useful feature in RDBMS.
Why do we need Joins?
For data analysis, we must assemble data from several tables.
Joins are used to retrieve data from more than one table.
Use of Aliases
Giving aliases to tables can make this job easier. Using aliases improves the readability of the
SQL. Aliases can be letters, numbers or combination.
Example:
Select Name, Pay from Employee E, Salary S
Where E.empid=S.empid;
Qualities of a Good Join
Use of primary key and foreign key makes a good join.
Columns compared in joins should have similar values.
Different Types of SQL JOINs
1. INNER JOIN: Returns records that have matching values in both tables.
2. LEFT JOIN: Returns all records from the left table, and the matched records from the
right table.
3. RIGHT JOIN: Returns all records from the right table, and the matched records from
the left table.
4. FULL OUTER JOIN: Returns all records when there is a match in either left or right
table.
Theta Joins, EquiJoins and Non-EquiJoins
Theta Join is a join query using comparison operators. (=, > =, < =, >, <, <>)
If the comparison operator is equality, then the join is called an equijoin.
If the comparison operator is not the equal sign, then the join is called annon equijoin.
Natural Join :
The equijoin produce a result containing two identical columns. But a natural join produce
a result that does not contain identical columns.
Self Join :
If a table is joined to itself, then it is called self-join.
UNIONS
The Union is used to combine two separate select statements and produce the result as a
union of both the select statements.
The fields to be used in both the select statements must be in same order, same number
and same data type.
The UNION produces distinct values in the result.
The UNIONALL produces the duplicate values.
UNION Syntax
The UNION operator selects only distinct values by default.
SELECTcolumn_name(s)FROMtable1
UNION
SELECTcolumn_name(s)FROMtable2;
SELECTcolumn_name(s)FROMtable1
UNIONALL
SELECTcolumn_name(s)FROMtable2;
City
Chennai
Coimbatore
Madurai
Trichy
City
Chennai
Trichy
Madurai
Madurai
Chennai
Coimbatore
INDEXES
What is an Index?
An index is a structure that provides faster access to the rows of a table based on the
values of one or more columns.
An index is a pointer to data in a table.
An index in a database is similar to an index in the book.
The RDBMS can quickly search the index to find a particular data value.
Creating an Index
Indexes are created using the CREATE INDEX statement. The general form is :
Example :
Types of Indexes
1. Composite Indexes
2. Unique Indexes
3. Clustered Indexes
4. Non Clustered Indexes
Composite Indexes
When an index is made up of more than one column, it is called a composite index.
Example:
Unique Indexes
A unique index is an index in which no duplicate values are allowed. Unique indexes are usually
created based on the primary key.
Example:
Clustered Indexes
Clustered Index is an index in which the rows of a table will be in the same order as that of the
index.
Clustered Index is an index in which the rows of a table will not be in the same order as that of
the index.
Dropping an Index
Once the command is executed, the Index1 is removed from the catalog.
Uses of Indexes
If there are no indexes for a table, the RDBMS process the query sequentially row by
row.
For large tables containing millions of records, the processing of a query without an
index takes a lot of time.
Indexes speed up the execution of SQL statements.
AGGREGATE FUNCTIONS
The aggregate functions greatly enhance the power of sql statements. It helps us to summarize
the data from the tables.
1. COUNT()
2. COUNT(*)
3. SUM()
4. AVG()
5. MAX()
6. MIN()
1. COUNT()
2. COUNT(*)
3. SUM()
Example: Find the total basic pay for all the employees
Example: Find the total basic pay for all the employees in the 'HR' department
4. AVG()
Example: Find the average basic pay for all the employees in the 'HR' department
5. MAX()
6. MIN()
The SQL SELECT statement is used to retrieve records from one or more tables in your SQL
database. The records retrieved are known as a result set.
Syntax:
SELECT expressions
FROM tables
[WHERE conditions]
Expressions :The columns or calculations that you wish to retrieve. Use * if you wish to select
all columns.
Tables :The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions :Optional. The conditions that must be met for the records to be selected. If
no conditions are provided, then all records will be selected.
ORDER BY expression :Optional. The expression used to sort the records in the result set. If
more than one expression is provided, the values should be comma separated.
ASC :Optional. ASC sorts the result set in ascending order by expression. This is the default
behavior, if no modifier is provider.
DESC :Optional. DESC sorts the result set in descending order by expression.
Example:
CUSTOMER TABLE
SELECT Statement:
Output:
SELECT with OR
The following SQL statement selects all fields from "Customers" where country is "Germany"
OR "Spain":
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
SUBQUERIES
Syntax:
SELECT column_name
FROM table_name
WHERE column_name comparison operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );
Sample Table:
DATABASE Table
NAME ROLL_NO LOCATIO PHONE_NUMBER
N
Ram 101 Chennai 9988775566
Raj 102 Coimbatore 8877665544
Sasi 103 Madurai 7766553344
Ravi 104 Salem 8989898989
Sumathi 105 Kanchipura 8989856868
m
STUDENT Table
NAME ROLL_NO SECTION
Ravi 104 A
Sumathi 105 B
Raj 102 A
Sample Queries
Explanation :
First subquery executes “ SELECT ROLL_NO from STUDENT where SECTION=’A’ ” returns
ROLL_NO from STUDENT table whose SECTION is ‘A’.
Then outer-query executes it and return the NAME, LOCATION, PHONE_NUMBER from the
DATABASE table of the student whose ROLL_NO is returned from inner subquery.
Output:
NULLS
The SQL NULL is the term used to represent a missing value.
A NULL value in a table is a value in a field that appears to be blank.
A field with a NULL value is a field with no value.
Syntax:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) NULL ,
SALARY DECIMAL (18, 2) NULL,
PRIMARY KEY (ID));
We use the IS NULL or IS NOT NULL operators to check for a NULL value.
Example:
VIEWS IN SQL
Views in SQL are considered as a virtual table. A view also contains rows and columns.
To create the view, we can select the fields from one or more tables present in the
database.
A view can either have specific rows based on certain condition or all the rows of a table.
Example:
Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Raja Madurai
Student_mark
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Raja 90 20
5 John 96 18
Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single
table or multiple tables.
Syntax:
1. CREATE VIEW view_name AS
2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;
Creating View from a single table
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
1. CREATE VIEW DetailsView AS
2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. WHERE STU_ID < 4;
Just like table query, we can query the view to view the data.
1. SELECT * FROM DetailsView;
Output:
NAMEADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
3. Creating View from multiple tables
View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
Query:
1. CREATE VIEW MarksView AS
2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
3. FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView:
1. SELECT * FROM MarksView;
NAMEADDRESS MARKS
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
1. DROP VIEW view_name;
Example:
If we want to delete the View MarksView, we can do this as:
1. DROP VIEW MarksView;
PL/SQL Cursor
Cursor - Introduction
When an SQL statement is processed, Oracle creates a memory area known as context
area.
A cursor is a pointer to this context area.
It contains all information needed for processing the statement.
In PL/SQL, the context area is controlled by Cursor.
A cursor contains information on a select statement and the rows of data accessed by it.
A cursor is used to referred to a program to fetch and process the rows returned by the
SQL statement, one at a time.
There are two types of cursors:
1. Implicit Cursors
2. Explicit Cursors
1) Implicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is executed.
These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.
Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML
operations.
Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
Attribute Description
%FOUND Return value is TRUE if SELECT statement returned one or
more rows.
%NOTFOUND Return value is TRUE if SELECT statement return no rows.
%ISOPEN Always returns FALSE for implicit cursors.
%ROWCOUNT Returns number of rows returned by a SELECT statement.
2) Explicit Cursors
The Explicit cursors are defined by the programmers.
These cursors should be defined in the declaration section.
It is created on a SELECT statement which returns more than one row.
Example
Customers Table
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000
DECLARE
total_rowsnumber(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Output:
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 25000
2 Suresh 22 Kanpur 27000
3 Mahesh 24 Ghaziabad 29000
4 Chandan 25 Noida 31000
5 Alex 21 Paris 33000
6 Sunita 20 Delhi 35000
PL/SQL Trigger
Triggers - Introduction
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.
Trigger is stored into database and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some event
occurs.
Triggers are written to be executed in response to any of the following events.
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Advantages of Triggers
Trigger generates some derived column values automatically
Enforces referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
Creating a Trigger:
CREATE TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT | UPDATE | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
PL/SQL Trigger Example:
In this example, we are using the following CUSTOMERS table:
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
PL/SQL Procedure
Introduction to Procedures
Exception
What is Exception?
An error occurs during the program execution is called Exception in PL/SQL.
PL/SQL facilitates programmers to catch such conditions using exception block in the program
and an appropriate action is taken against the error condition.
There are two type of exceptions:
System-defined Exceptions
User-defined Exceptions
Syntax for Exception Handling:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example of Exception Handling
CUSTOMERS table
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
DECLARE
c_idcustomers.id%type := 8;
c_namecustomers.name%type;
c_addrcustomers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
The above program should show the name and address of a customer as result whose ID is given.
But there is no customer with ID value 8 in our database, so the program raises the run-time
exception NO_DATA_FOUND, which is captured in EXCEPTION block.
Following is a list of some important pre-defined exceptions:
Exception Description
LOGIN_DENIED It is raised when s program attempts to log on to the database
with an invalid username or password.
NO_DATA_FOUND It is raised when a select into statement returns no rows.
PROGRAM_ERROR It is raised when PL/SQL has an internal problem.
ROWTYPE_MISMATC It is raised when a cursor fetches value in a variable having
H incompatible data type.
STORAGE_ERROR It is raised when PL/SQL ran out of memory or memory was
corrupted.
TOO_MANY_ROWS It is raised when a SELECT INTO statement returns more than
one row.
VALUE_ERROR It is raised when an arithmetic, conversion, truncation, or size-
constraint error occurs.
ZERO_DIVIDE It is raised when an attempt is made to divide a number by zero.