RDBMS Notes
RDBMS Notes
Relational Model was proposed by E.F. Codd to model data in the form of relations or
tables. After designing the conceptual model of Database using ER diagram, we need to
convert the conceptual model in the relational model which can be implemented using any
RDBMS languages like Oracle SQL, MySQL etc. So we will see what Relational Model is.
What is Relational Model?
Relational Model represents how data is stored in Relational Databases. A relational
database stores data in the form of relations (tables).
Relational data model is the primary data model, which is used widely around the world for
data storage and processing. This model is simple and it has all the properties and capabilities
required to process data with storage efficiency.
Key constraints
Domain constraints
Referential integrity constraints
Key Constraints
There must be at least one minimal subset of attributes in the relation, which can identify a
tuple uniquely. This minimal subset of attributes is called key for that relation. If there are
more than one such minimal subsets, these are called candidate keys.
Key constraints force that −
in a relation with a key attribute, no two tuples can have identical values for key
attributes.
a key attribute can not have NULL values.
Key constraints are also referred to as Entity Constraints.
Domain Constraints
Attributes have specific values in real-world scenario. For example, age can only be a
positive integer. The same constraints have been tried to employ on the attributes of a
relation. Every attribute is bound to have a specific range of values. For example, age cannot
be less than zero and telephone numbers cannot contain a digit outside 0-9.
Referential integrity Constraints
Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key
attribute of a relation that can be referred in other relation.
Referential integrity constraint states that if a relation refers to a key attribute of a different or
same relation, then that key element must exist.
Introduction
Relational Query Languages – So far we have seen what a database is, what is the features of
database, how to gather requirements and how to put them in ER diagrams, how to convert
them into tables and their columns, set their constraints etc. Once we have database ready
users will start using them. But how will they access the database? Most of the time they
access the data by using some applications. These applications will communicate to database
by SQL and DBMS is responsible for managing the application and SQL intact. SQL has its
own querying methods to interact with database. But how these queries work in the database?
These queries work similar to relational algebra that we have in mathematics. In database we
have tables participating in relational algebra.
Relational Query Languages
Relational query languages use relational algebra to break the user requests and instruct the
DBMS to execute the requests. It is the language by which user communicates with the
database. These relational query languages can be procedural or non-procedural.
Relational Algebra
Relational algebra is a procedural query language, which takes instances of relations as input
and yields instances of relations as output. It uses operators to perform queries. An operator
can be either unary or binary. They accept relations as their input and yield relations as their
output. Relational algebra is performed recursively on a relation and intermediate results are
also considered relations.
The fundamental operations of relational algebra are as follows −
Select
Project
Union
Set different
Cartesian product
Rename
We will discuss all these operations in the following sections.
Select Operation (σ)
It selects tuples that satisfy the given predicate from a relation.
Notation − σp(r)
Where σ stands for selection predicate and r stands for relation. p is prepositional logic
formula which may use connectors like and, or, and not. These terms may use relational
operators like − =, ≠, ≥, < , >, ≤.
For example −
σsubject = "database"(Books)
Output − Selects tuples from books where subject is 'database'.
σsubject = "database" and price = "450"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" and price = "450" or year > "2010"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those
books published after 2010.
Project Operation (∏)
It projects column(s) that satisfy a given predicate.
Notation − ∏A1, A2, An (r)
Where A1, A2 , An are attribute names of relation r.
Duplicate rows are automatically eliminated, as relation is a set.
For example −
∏subject, author (Books)
Selects and projects columns named as subject and author from the relation Books.
Union Operation (∪)
It performs binary union between two given relations and is defined as −
r ∪ s = { t | t ∈ r or t ∈ s}
Notation − r U s
Where r and s are either database relations or relation result set (temporary relation).
For a union operation to be valid, the following conditions must hold −
Set intersection
Assignment
Natural join
Relational Calculus
In contrast to Relational Algebra, Relational Calculus is a non-procedural query language,
that is, it tells what to do but never explains how to do it.
Relational calculus exists in two forms −
Tuple Relational Calculus (TRC)
Filtering variable ranges over tuples
Notation − {T | Condition}
Returns all tuples T that satisfies a condition.
For example −
{ T.name | Author(T) AND T.article = 'database' }
Output − Returns tuples with 'name' from Author who has written article on 'database'.
TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀).
For example −
{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}
Output − The above query will yield the same result as the previous one.
Domain Relational Calculus (DRC)
In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as
done in TRC, mentioned above).
Notation −
{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where a1, a2 are attributes and P stands for formulae built by inner attributes.
For example −
{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}
Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is
database.
Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also
involves relational operators.
The expression power of Tuple Relation Calculus and Domain Relation Calculus is
equivalent to Relational Algebra.
Data models define how the logical structure of a database is modeled. Data Models are
fundamental entities to introduce abstraction in a DBMS. Data models define how data is
connected to each other and how they are processed and stored inside the system.
The very first data model could be flat data-models, where all the data used are to be kept in
the same plane. Earlier data models were not so scientific, hence they were prone to introduce
lots of duplication and update anomalies.
Entity-Relationship Model
Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships
among them. While formulating real-world scenario into the database model, the ER Model
creates entity set, relationship set, general attributes and constraints.
ER Model is best used for the conceptual design of a database.
ER Model is based on −
Entities and their attributes.
Relationships among entities.
These concepts are explained below.
Data modelling is the first step in the process of database design. This step is sometimes
considered to be a high-level and abstract design phase, also referred to as conceptual design.
The aim of this phase is to describe:
The data contained in the database (e.g., entities: students, lecturers, courses, subjects)
The relationships between data items (e.g., students are supervised by lecturers; lecturers
teach courses)
The constraints on data (e.g., student number has exactly eight digits; a subject has four or
six units of credit only)
In the second step, the data items, the relationships and the constraints are all expressed using
the concepts provided by the high-level data model. Because these concepts do not include
the implementation details, the result of the data modelling process is a (semi) formal
representation of the database structure. This result is quite easy to understand so it is used as
reference to make sure that all the user’s requirements are met.
The third step is database design. During this step, we might have two sub-steps: one
called database logical design, which defines a database in a data model of a specific DBMS,
and another called database physical design, which defines the internal database storage
structure, file organization or indexing techniques. These two sub-steps are database
implementation and operations/user interfaces building steps.
In the database design phases, data are represented using a certain data model. The data
model is a collection of concepts or notations for describing data, data relationships, data
semantics and data constraints. Most data models also include a set of basic operations for
manipulating data in the database.
Normalization
Normalization is the process of organizing data in a database. This includes creating tables
and establishing relationships between those tables according to rules designed both to
protect the data and to make the database more flexible by eliminating redundancy and
inconsistent dependency.
Normalization
A large database defined as a single relation may result in data duplication. This repetition of
data may result in:
o Making relations very large.
o It isn't easy to maintain and update data as it would involve searching many records in
relation.
o Wastage and poor utilization of disk space and resources.
o The likelihood of errors and inconsistencies increases.
So to handle these problems, we should analyze and decompose the relations with redundant
data into smaller, simpler, and well-structured relations that are satisfy desirable properties.
Normalization is a process of decomposing the relations into relations with fewer attributes.
What is Normalization?
o Normalization is the process of organizing the data in the database.
o Normalization is used to minimize the redundancy from a relation or set of relations.
It is also used to eliminate undesirable characteristics like Insertion, Update, and
Deletion Anomalies.
o Normalization divides the larger table into smaller and links them using relationships.
o The normal form is used to reduce redundancy from the database table.
Why do we need Normalization?
The main reason for normalizing the relations is removing these anomalies. Failure to
eliminate anomalies leads to data redundancy and can cause data integrity and other problems
as the database grows. Normalization consists of a series of guidelines that helps to guide you
in creating a good database structure.
Normalization is the process of minimizing redundancy from a relation or set of relations.
Redundancy in relation may cause insertion, deletion, and update anomalies. So, it helps to
minimize the redundancy in relations. Normal forms are used to eliminate or reduce
redundancy in database tables.
Functional Dependency
Functional dependency (FD) is a set of constraints between two attributes in a relation.
Functional dependency says that if two tuples have same values for attributes A1, A2,..., An,
then those two tuples must have to have same values for attributes B1, B2, ..., Bn.
Functional dependency is represented by an arrow sign (→) that is, X→Y, where X
functionally determines Y. The left-hand side attributes determine the values of attributes on
the right-hand side.
Armstrong's Axioms
If F is a set of functional dependencies then the closure of F, denoted as F +, is the set of all
functional dependencies logically implied by F. Armstrong's Axioms are a set of rules, that
when applied repeatedly, generates a closure of functional dependencies.
Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha
holds beta.
Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds.
That is adding attributes in dependencies, does not change the basic dependencies.
Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds,
then a → c also holds. a → b is called as a functionally that determines b.
Trivial Functional Dependency
Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X,
then it is called a trivial FD. Trivial FDs always hold.
Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a
non-trivial FD.
Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to
be a completely non-trivial FD.
Normalization
If a database design is not perfect, it may contain anomalies, which are like a bad dream for
any database administrator. Managing a database with anomalies is next to impossible.
Update anomalies − If data items are scattered and are not linked to each other
properly, then it could lead to strange situations. For example, when we try to update
one data item having its copies scattered over several places, a few instances get
updated properly while a few others are left with old values. Such instances leave the
database in an inconsistent state.
Deletion anomalies − We tried to delete a record, but parts of it was left undeleted
because of unawareness, the data is also saved somewhere else.
Insert anomalies − We tried to insert data in a record that does not exist at all.
Normalization is a method to remove all these anomalies and bring the database to a
consistent state.
First Normal Form
First Normal Form is defined in the definition of relations (tables) itself. This rule defines that
all the attributes in a relation must have atomic domains. The values in an atomic domain are
indivisible units.
Each attribute must contain only a single value from its pre-defined domain.
Second Normal Form
Before we learn about the second normal form, we need to understand the following −
Prime attribute − An attribute, which is a part of the candidate-key, is known as a
prime attribute.
Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be
a non-prime attribute.
If we follow second normal form, then every non-prime attribute should be fully functionally
dependent on prime key attribute. That is, if X → A holds, then there should not be any
proper subset Y of X, for which Y → A also holds true.
We see here in Student_Project relation that the prime key attributes are Stu_ID and Proj_ID.
According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent
upon both and not on any of the prime key attribute individually. But we find that Stu_Name
can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently. This
is called partial dependency, which is not allowed in Second Normal Form.
We broke the relation in two as depicted in the above picture. So there exists no partial
dependency.
Third Normal Form
For a relation to be in Third Normal Form, it must be in Second Normal form and the
following must satisfy −
o A is prime attribute.
We find that in the above Student_detail relation, Stu_ID is the key and only prime key
attribute. We find that City can be identified by Stu_ID as well as Zip itself. Neither Zip is a
superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there
exists transitive dependency.
To bring this relation into third normal form, we break the relation into two relations as
follows −
Key Points –
BCNF is free from redundancy.
If a relation is in BCNF, then 3NF is also satisfied.
If all attributes of relation are prime attribute, then the relation is always in
3NF.
A relation in a Relational Database is always and at least in 1NF form.
Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.
If a Relation has only singleton candidate keys( i.e. every candidate key consists
of only 1 attribute), then the Relation is always in 2NF( because no Partial
functional dependency possible).
Sometimes going for BCNF form may not preserve functional dependency. In
that case go for BCNF only if the lost FD(s) is not required, else normalize till
3NF only.
There are many more Normal forms that exist after BCNF, like 4NF and more.
But in real world database systems it’s generally not required to go beyond
BCNF.
Oracle 9i database
Oracle9i offers the most secure internet platform available to protect company information
with multiple layers of security for data, users, and companies.
Oracle is fundamentally just like SQL Server and every other relational database system. Its
database architectural principles are the same and it operates with SQL (Structured Query
Language), plus Oracle's own PL/SQL extensions. It's relatively easy to learn — as long as
you have a good handle on Linux and SQL.
Definition
Personal database system is the local database system which is only for one user to store and
manage the data and information on their own personal system. There are number of
applications are used in local computer to design and managed personal database system.
Simple design
Design in database management system has much importance for storing and controlling the
data. In personal database management system, there is simple design to store data and
information.
Higher security
Data is stored in personal computer does not need any special security arrangement for
authorization of data.
In client-server architecture many clients connected with one server. The server is
centerlines.it provides services to all clients. All clients request to the server for different
Service. The server displays the results according to the client’s request.
Client/server architecture is a computing model in which the server hosts (computer), send
and manages most of the resources and works to be required by the client. In this type of
architecture has one or more client computers attached to a central server over a network.
This system shares different resources.
Client/server architecture is also called as a networking computing model and client-server
network because all the requests and demands are sent over a network.
SQL IN Clause
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
WHERE CONDITION
GROUP BY column_name;
GROUP BY column_name
HAVING (arithematic function condition);
SQL
SQL is Structured Query Language, which is a computer language for storing, manipulating
and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational Database
Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres
and SQL Server use SQL as their standard database language.
Also, they are using different dialects, such as −
Query Dispatcher
Optimization Engines
Classic Query Engine
SQL Query Engine, etc.
A classic query engine handles all the non-SQL queries, but a SQL query engine won't
handle logical files.
Following is a simple diagram showing the SQL Architecture −
SQL Commands
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into the
following groups based on their nature −
DDL - Data Definition Language
S.No. Command & Description
1 CREATE Creates a new table, a view of a table, or other object in the database.
3 DROP Deletes an entire table, a view of a table or other objects in the database.
SQL Data Type is an attribute that specifies the type of data of any object. Each column,
variable and expression has a related data type in SQL. You can use these data types while
creating your tables. You can choose a data type for a table column based on your
requirement.
SQL Server offers six categories of data types for your use which are listed below −
Tinyint 0 255
Bit 0 1
Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute
accuracy.
Character Strings Data Types
Sr.No DATA TYPE & Description
.
1 sql_variant Stores values of various SQL Server-supported data types, except text,
ntext, and timestamp.
2 Timestamp Stores a database-wide unique number that gets updated every time a row
gets updated
Constraints are the rules enforced on the data columns of a table. These are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in
the database.
Constraints could be either on a column level or a table level. The column level constraints
are applied only to one column, whereas the table level constraints are applied to the whole
table.
Following are some of the most commonly used constraints available in SQL. These
constraints have already been discussed in SQL - RDBMS Concepts chapter, but it’s worth to
revise them at this point.
NOT NULL Constraint − Ensures that a column cannot have NULL value.
DEFAULT Constraint − Provides a default value for a column when none is specified.
UNIQUE Constraint − Ensures that all values in a column are different.
PRIMARY Key − Uniquely identifies each row/record in a database table.
FOREIGN Key − Uniquely identifies a row/record in any of the given database table.
CHECK Constraint − The CHECK constraint ensures that all the values in a column
satisfies certain conditions.
INDEX − Used to create and retrieve data from the database very quickly.
Constraints can be specified when a table is created with the CREATE TABLE statement or
you can use the ALTER TABLE statement to create constraints even after the table is
created.
Dropping Constraints
Any constraint that you have defined can be dropped using the ALTER TABLE command
with the DROP CONSTRAINT option.
For example, to drop the primary key constraint in the EMPLOYEES table, you can use the
following command.
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;
Some implementations may provide shortcuts for dropping certain constraints. For example,
to drop the primary key constraint for a table in Oracle, you can use the following command.
ALTER TABLE EMPLOYEES DROP PRIMARY KEY;
Some implementations allow you to disable constraints. Instead of permanently dropping a
constraint from the database, you may want to temporarily disable the constraint and then
enable it later.
Integrity Constraints
Integrity constraints are used to ensure accuracy and consistency of the data in a relational
database. Data integrity is handled in a relational database through the concept of referential
integrity.
There are many types of integrity constraints that play a role in Referential Integrity (RI).
These constraints include Primary Key, Foreign Key, Unique Constraints and other
constraints which are mentioned above.
The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".
GROUP BY Syntax
SELECT column_name(s) FROM table_name WHERE condition
GROUP BY column_name(s) ORDER BY column_name(s);
Group functions are mathematical functions to operate on sets of rows to give one result per
set. The types of group functions (also called aggregate functions) are:
AVG, that calculates the average of the specified columns in a set of rows,
COUNT, calculating the number of rows in a set.
MAX, calculating the maximum,
MIN, calculating the minimum,
STDDEV, calculating the standard deviation,
SUM, calculating the sum,
VARIANCE, calculating the variance.
The general syntax for using Group functions is :
SELECT <column, ...>, group_function(column) FROM <table> WHERE <condition>
[GROUP BY <column>] [ORDER BY <column>]
Note that the column on which the group function is applied must exist in the SELECT
column list.
For example, the following selects the maximum salary from the employee table.
SQL> SELECT dept, MAX(sal) FROM employee;
Using Having-Clause
To exclude some group results, use Having-clause.
For example,
SQL> SELECT dept, MAX(sal) FROM employee GROUP BY dept HAVING MAX(sal) > 2000;
Note that you CANNOT use WHERE clause to restrict groups. For example, the following is
illegal:
SQL> SELECT dept, MAX(sal) FROM employee WHERE MAX(sal) > 2000 GROUP BY dept;
This is because the group function cannot be used in WHERE clause.
A SQL left outer join will return all the records from the left table in the join clause,
regardless of matching records in the right table. The left SQL outer join includes rows where
the condition is met plus all the rows from the table on the left where the condition is not met.
Fields from the right table with no match will be displayed as null values.
A right outer join will return all the records in the right table in the join clause, regardless of
matching records in the left table. Using the right SQL outer join includes all the rows from
the table on the right. The right SQL outer join is considered a special case and many
databases don’t support right joins. Generally, a SQL right join can be rewritten as a SQL left
join by simply changing the order of the tables in the query. In this instance, fields from the
left table with no match will display null values
A SQL outer join, as you might expect by now, will return all the rows in both tables. When
rows don’t have a match in one of the tables, the field will display a null value. A full SQL
outer join combines the effects of the SQL left joins and SQL right joins. Many databases do
not support the implementation of full SQL outer joins
Set Operators
Operator Returns
UNION ALL All rows selected by either query, including all duplicates
MINUS All distinct rows selected by the first query but not the second
Set operators combine the results of two component queries into a single result. Queries
containing set operators are called compound queries. They are fully described, including
examples and restrictions on these operators, in "The UNION [ALL], INTERSECT, MINUS
Operators".
Set operators are used to join the results of two (or more) SELECT statements.The SET
operators available in Oracle 11g are UNION,UNION ALL,INTERSECT,and MINUS.
The UNION set operator returns the combined results of the two SELECT
statements.Essentially,it removes duplicates from the results i.e. only one row will be listed
for each duplicated result.To counter this behavior,use the UNION ALL set operator which
retains the duplicates in the final result.INTERSECT lists only records that are common to
both the SELECT queries; the MINUS set operator removes the second query's results from
the output if they are also found in the first query's results. INTERSECT and MINUS set
operations produce unduplicated results.
All the SET operators share the same degree of precedence among them.Instead,during query
execution, Oracle starts evaluation from left to right or from top to bottom.If explicitly
parentheses are used, then the order may differ as parentheses would be given priority over
dangling operators.
Points to remember -
Same number of columns must be selected by all participating SELECT
statements.Column names used in the display are taken from the first query.
Data types of the column list must be compatible/implicitly convertible by oracle.
Oracle will not perform implicit type conversion if corresponding columns in the
component queries belong to different data type groups.For example, if a column in
the first component query is of data type DATE, and the corresponding column in the
second component query is of data type CHAR,Oracle will not perform implicit
conversion, but raise ORA-01790 error.
Positional ordering must be used to sort the result set. Individual result set ordering is
not allowed with Set operators. ORDER BY can appear once at the end of the query.
For example,
UNION and INTERSECT operators are commutative, i.e. the order of queries is not
important; it doesn't change the final result.
Performance wise, UNION ALL shows better performance as compared to UNION
because resources are not wasted in filtering duplicates and sorting the result set.
Set operators can be the part of sub queries.
Set operators can't be used in SELECT statements containing TABLE collection
expressions.
The LONG, BLOB, CLOB, BFILE, VARRAY,or nested table are not permitted for
use in Set operators.For update clause is not allowed with the set operators.
NESTED QUERY
A nested query is a query that has another query embedded within it. The embedded query is
called a subquery.
A subquery typically appears within the WHERE clause of a query. It can sometimes appear
in the FROM clause or HAVING clause.
select E.ename from employee E where E.eid IN (select S.eid from salary S where
S.regno=103);
When a query is included inside another query, the Outer query is known as Main Query, and
Inner query is known as Subquery. In Nested Query, Inner query runs first, and only
once. Outer query is executed with result from Inner query.
A database object is any defined object in a database that is used to store or reference
data.Anything which we make from create command is known as Database Object.It can
be used to hold and manipulate the data.Some of the examples of database objects are :
view, sequence, indexes, etc.
Table – Basic unit of storage; composed rows and columns
View – Logically represents subsets of data from one or more tables
Sequence – Generates primary key values
Index – Improves the performance of some queries
Synonym – Alternative name for an object
Different database Objects :
1. Table – This database object is used to create a table in database.
Syntax :
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);
Example :
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));
Output :
DESCRIBE dept;
2. View – This database object is used to create a view in database.A view is a logical
table based on a table or another view. A view contains no data of its own but is like a
window through which data from tables can be viewed or changed. The tables on which
a view is based are called base tables. The view is stored as a SELECT statement in the
data dictionary.
Syntax :
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
Example :
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
Output :
SELECT *
FROM salvu50;
VIEWS
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a
real table in the database. We can create a view by selecting fields from one or more tables
present in the database. A View can either have all the rows of a table or specific rows
based on certain condition.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
SEQUENCE
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database
systems to produce unique values on demand.
A sequence is a user defined schema bound object that generates a sequence of numeric
values.
Sequences are frequently used in many databases because many applications require
each row in a table to contain a unique value and sequences provides an easy way to
generate them.
The sequence of numeric values is generated in an ascending or descending order at
defined intervals and can be configured to restart when exceeds max_value.
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
sequence_name: Name of the sequence.
INDEX
An index is a schema object. It is used by the server to speed up the retrieval of rows by
using a pointer. It can reduce disk I/O(input/output) by using a rapid path access method to
locate data quickly. An index helps to speed up select queries and where clauses, but it
slows down data input, with the update and the insert statements. Indexes can be created or
dropped with no effect on the data. In this article, we will see how to create, delete, and
uses the INDEX in the database.
For example, if you want to reference all pages in a book that discusses a certain topic, you
first refer to the index, which lists all the topics alphabetically and is then referred to one or
more specific page numbers.
Creating an Index:
Syntax:
CREATE INDEX index
ON TABLE column;
where the index is the name given to that index and TABLE is the name of the table on
which that index is created and column is the name of that column for which it is applied.
OBJECT PRIVILEGE
System privileges—A system privilege gives a user the ability to perform a particular action,
or to perform an action on any schema objects of a particular type. ...
Object privileges—An objectprivilege gives a user the ability to perform a particular action
on a specific schema object.
System privileges allow users to CREATE, ALTER, or DROP the database objects. An
object privilege is a privilege to perform a specific action on a particular table, function,
or package. For example, the right to delete rows from a table is an object privilege.
PL/SQL
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s
as procedural extension language for SQL and the Oracle relational database. Following are
certain notable facts about PL/SQL −
PL/SQL is a completely portable, high-performance transaction-processing language.
PL/SQL provides a built-in, interpreted and OS independent programming
environment.
PL/SQL can also directly be called from the command-line SQL*Plus interface.
Direct call can also be made from external programming language calls to database.
PL/SQL's general syntax is based on that of ADA and Pascal programming language.
Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM
DB2.
Features of PL/SQL
PL/SQL has the following features −
Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL
programs are divided and written in logical blocks of code. Each block consists of three sub-
parts −
Declarations
1 This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory
2 section. It consists of the executable PL/SQL statements of the program. It should have at
least one executable line of code, which may be just a NULL command to indicate that
nothing should be executed.
Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within
other PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL
block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
The 'Hello World' Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from the SQL command
line, you may need to type / at the beginning of the first blank line after the last line of the
code. When the above code is executed at the SQL prompt, it produces the following result −
Hello World
Delimiter Description
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
=> Association operator
|| Concatenation operator
** Exponentiation operator
.. Range operator
PL/SQL block
Function
Package
Package body
Procedure
Trigger
Type
Type body
The PL/SQL variables, constants and parameters must have a valid data type, which specifies
a storage format, constraints, and a valid range of values. We will focus on the SCALAR and
the LOB data types in this chapter. The other two data types will be covered in other
chapters.
Scalar
1
Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN.
Composite
3 Data items that have internal components that can be accessed individually. For example,
collections and records.
Reference
4
Pointers to other data items.
Numeric
1
Numeric values on which arithmetic operations are performed.
Character
2
Alphanumeric values that represent single characters or strings of characters.
Boolean
3
Logical values on which logical operations are performed.
Datetime
4
Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype
called INTEGER. You can use the subtypes in your PL/SQL program to make the data types
compatible with data types in other programs while embedding the PL/SQL code in another
program, such as a Java program.
PL/SQL Numeric Data Types and Subtypes
Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −
PLS_INTEGER
1
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARY_INTEGER
2
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number
NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130 to (but not
including) 1.0E126. A NUMBER variable can also represent 0
DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits
DECIMAL(prec, scale)
7
IBM specific fixed-point type with maximum precision of 38 decimal digits
NUMERIC(pre, secale)
8
Floating type with maximum precision of 38 decimal digits
DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)
FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)
INT
11
ANSI specific integer type with maximum precision of 38 decimal digits
INTEGER
12
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
SMALLINT
13
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)
Following is the detail of PL/SQL pre-defined character data types and their sub-types −
S.No Data Type & Description
CHAR
1
Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes
RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted
by PL/SQL
NCHAR
4
Fixed-length national character string with maximum size of 32,767 bytes
NVARCHAR2
5
Variable-length national character string with maximum size of 32,767 bytes
LONG
6
Variable-length character string with maximum size of 32,760 bytes
LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted
by PL/SQL
ROWID
8
Physical row identifier, the address of a row in an ordinary table
UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)
MONTH 01 to 12 0 to 11
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
Table Created
Let us now insert some values in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
PL/SQL provides the following types of loop to handle the looping requirements. Click the
following links to check their detail.
1 In this loop structure, sequence of statements is enclosed between the LOOP and the
END LOOP statements. At each iteration, the sequence of statements is executed and
then control resumes at the top of the loop.
EXIT statement
1
The Exit statement completes the loop and control passes to the statement immediately
after the END LOOP.
CONTINUE statement
2
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
GOTO statement
3
Transfers control to the labeled statement. Though it is not advised to use the GOTO
statement in your program.
PL/SQL
By extending SQL, PL/SQL offers a unique combination of power and ease of use. You can
manipulate Oracle data flexibly and safely because PL/SQL fully supports all SQL data
manipulation statements (except EXPLAIN PLAN), transaction control statements, functions,
pseudo columns, and operators. PL/SQL also conforms to the current ANSI/ISO SQL
standard.
Data Manipulation
To manipulate Oracle data you can include DML operations, such as INSERT, UPDATE,
and DELETE statements, directly in PL/SQL programs, without any special notation. You
can also include the SQL COMMIT statement directly in a PL/SQL program.
Transaction Control
Oracle is transaction-oriented; that is, Oracle uses transactions to ensure data integrity. A
transaction is a series of SQL data manipulation statements that does a logical unit of work
You use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION commands
to control transactions. COMMIT makes permanent any database changes made during the
current transaction. ROLLBACK ends the current transaction and undoes any changes made
since the transaction began. SAVEPOINT marks the current point in the processing of a
transaction. Used with ROLLBACK, SAVEPOINT undoes part of a transaction. SET
TRANSACTION sets transaction properties such as read-write access and isolation level.
SQL Functions
SQL Pseudocolumns
PL/SQL recognizes the SQL pseudo columns CURRVAL, LEVEL, NEXTVAL, ROWID,
and ROWNUM. However, there are limitations on the use of pseudo columns, including the
restriction on the use of some pseudo columns in assignments or conditional tests.
CURRVAL and NEXTVAL – CURRVAL returns the current value in a specified
sequence. A reference to NEXTVAL stores the current sequence number in CURRVAL.
NEXTVAL increments the sequence and returns the next value. To get the current or
next value in a sequence, use dot notation:
sequence_name.CURRVAL
sequence_name.NEXTVAL
SQL Operators
Comparison Operators
Set Operators
Set operators combine the results of two queries into one result. INTERSECT returns all
distinct rows selected by both queries. MINUS returns all distinct rows selected by the first
query but not by the second. UNION returns all distinct rows selected by either query.
UNION ALL returns all rows selected by either query, including all duplicates.
Row Operators
Row operators return or reference particular rows. ALL retain duplicate rows in the result of
a query or in an aggregate expression. DISTINCT eliminates duplicate rows from the result
of a query or from an aggregate expression. PRIOR refers to the parent row of the current
row returned by a tree-structured query.
Transaction processing with PL/SQL using SQL COMMIT, SAVEPOINT, and ROLLBACK
statements that ensure the consistency of a database.
COMMIT – The COMMIT statement ends the current transaction, making any changes
made during that transaction permanent, and visible to other users.
ROLLBACK – The ROLLBACK statement ends the current transaction and undoes
any changes made during that transaction. If you make a mistake, such as deleting the
wrong row from a table, a rollback restores the original data. If you cannot finish a
transaction because an exception is raised or a SQL statement fails, a rollback lets you
take corrective action and perhaps start over.
SAVEPOINT – SAVEPOINT names and marks the current point in the processing of a
transaction. Savepoints let you roll back part of a transaction instead of the whole
transaction. The number of active savepoints for each session is unlimited.
PL/SQL EXCEPTION
An exception is an error condition during a program execution. PL/SQL supports
programmers to catch such conditions using EXCEPTION block in the program and an
appropriate action is taken against the error condition. There are two types of exceptions −
System-defined exceptions
User-defined exceptions
Syntax for Exception Handling
The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others
THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE. Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
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 RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule
is violated by a program. For example, the predefined exception NO_DATA_FOUND is
raised when a SELECT INTO statement returns no rows. The following table lists few of the
important pre-defined exceptions −
Oracle SQLCOD
Exception Description
Error E
PL/SQL - Cursors
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.
A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the
cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the
rows returned by the SQL statement, one at a time. There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the data that needs
to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with
the FORALL statement. The following table provides the description of the most used
attributes −
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.
2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned no rows.
Otherwise, it returns FALSE.
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.
Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer by 500
and use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It
is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
Declaring the cursor for initializing the memory
Opening the cursor for allocating the memory
Fetching the cursor for retrieving the data
Closing the cursor to release the allocated memory
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Opening the Cursor
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it. For example, we will open the above defined
cursor as follows −
OPEN c_customers;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;
Closing the Cursor
Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows −
CLOSE c_customers;
Implicit_cursor_attribute :
Explicit cursor
An explicit cursor is a named pointer to a private SQL area that stores information for
processing a specific query or DML statement—typically, one that returns or affects multiple
rows. You can use an explicit cursor to retrieve the rows of a result set one at a time.
Before using an explicit cursor, you must declare and define it. You can either declare it first
(with cursor_declaration) and then define it later in the same block, subprogram, or package
(with cursor_definition) or declare and define it at the same time (with cursor_definition).
An explicit cursor declaration and definition are also called a cursor
specification and cursor body, respectively.
PROCEDURE
A subprogram is a program unit/module that performs a particular task. These subprograms
are combined to form larger programs. This is basically called the 'Modular design'. A
subprogram can be invoked by another subprogram or program which is called the calling
program.
A subprogram can be created −
Declarative Part
1 It is an optional part. However, the declarative part for a subprogram does not start with
the DECLARE keyword. It contains declarations of types, cursors, constants, variables,
exceptions, and nested subprograms. These items are local to the subprogram and cease
to exist when the subprogram completes execution.
2 Executable Part
This is a mandatory part and contains statements that perform the designated action.
3 Exception-handling
This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT
represents the parameter that will be used to return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on
the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result
−
Procedure created.
Executing a Standalone Procedure
A standalone procedure can be called in two ways −
Using the EXECUTE keyword
Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
The above call will display −
Hello World
FUNCTION
A function is same as a procedure except that it returns a value. Therefore, all the discussions
of the previous chapter are true for functions too.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the
parameter that will be used to return a value outside of the procedure.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
function-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.
Calling a Function
While creating a function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task. When a program
calls a function, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or
when the last end statement is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function
name and if the function returns a value, then you can store the returned value. Following
program calls the function totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers
Triggers can be written for the following purposes −
PACKAGES
Packages are schema objects that groups logically related PL/SQL types, variables, and
subprograms.
A package will have two mandatory parts −
Package specification
Package body or definition
Package Specification
The specification is the interface to the package. It just DECLARES the types, variables,
constants, exceptions, cursors, and subprograms that can be referenced from outside the
package. In other words, it contains all information about the content of the package, but
excludes the code for the subprograms.
All objects placed in the specification are called public objects. Any subprogram not in the
package specification but coded in the package body is called a private object.
The following code snippet shows a package specification having a single procedure. You
can have many global variables defined and multiple procedures or functions inside a
package.
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
When the above code is executed at the SQL prompt, it produces the following result −
Package created.
Package Body
The package body has the codes for various methods declared in the package specification
and other private declarations, which are hidden from the code outside the package.
The CREATE PACKAGE BODY Statement is used for creating the package body. The
following code snippet shows the package body declaration for the cust_sal package created
above. I assumed that we already have CUSTOMERS table created in our database as
mentioned in the PL/SQL - Variables chapter.
CREATE OR REPLACE PACKAGE BODY cust_sal AS