Final Rdbms Notes
Final Rdbms Notes
UNIT-I
Data
Data is nothing but facts and statistics stored or free flowing over a
network, generally it's raw and unprocessed. For example: When you
visit any website, they might store you IP address, that is data, in
return they might add a cookie in your browser, marking you that you
visited the website, that is data, your name, it's data, your age, it's
data.
Database
A Database is a collection of related data organised in a way that data
can be easily accessed, managed and updated. Database can be
software based or hardware based, with one sole purpose, storing
data.
During early computer days, data was collected and stored on tapes,
which were mostly write-only, which means once data is stored on it, it
can never be read again. They were slow and bulky, and soon
computer scientists realised that they needed a better solution to this
problem.
Larry Ellison, the co-founder of Oracle was amongst the first few,
who realised the need for a software based Database Management
System.
DBMS
MySql
Oracle
SQL Server
IBM DB2
PostgreSQL
Amazon SimpleDB (cloud based) etc.
1. Data stored into Tables: Data is never directly stored into the
database. Data is stored into tables, created inside the database.
DBMS also allows to have relationships between tables which
makes the data more meaningful and connected. You can easily
understand what type of data is stored where by looking at all the
tables created in a database.
2. Reduced Redundancy: In the modern world hard drives are very
cheap, but earlier when hard drives were too expensive,
unnecessary repetition of data in database was a big problem. But
DBMS follows Normalisation which divides the data in such a
way that repetition is minimum.
3. Data Consistency: On Live data, i.e. data that is being
continuosly updated and added, maintaining the consistency of
data can become a challenge. But DBMS handles it all by itself.
4. Support Multiple user and Concurrent Access: DBMS allows
multiple users to work on it(update, insert, delete data) at the
same time and still manages to maintain the data consistency.
5. Query Language: DBMS provides users with a simple Query
language, using which data can be easily fetched, inserted,
deleted and updated in a database.
6. Security: The DBMS also takes care of the security of data,
protecting the data from un-authorised access. In a typical DBMS,
we can create user accounts with different access permissions,
using which we can easily secure our data by restricting user
access.
7. DBMS supports transactions, which allows us to better handle
and manage data integrity in real world applications where multi-
threading is extensively used.
Advantages of DBMS
Disadvantages of DBMS
It's Complexity
Except MySQL, which is open source, licensed DBMSs are
generally costly.
They are large in size.
Components of DBMS
The database management system can be divided into five major
components, they are:
1. Hardware
2. Software
3. Data
4. Procedures
5. Database Access Language
Let's have a simple diagram to see how they all fit together to form a
database management system.
Data is that resource, for which DBMS was designed. The motive
behind the creation of DBMS was to store and utilise data.
User can create new databases, tables, insert data, fetch stored data,
update data and delete the data using the access language.
Users
For the end user, the GUI layer is the Database System, and the end
user has no idea about the application layer and the DBMS system.
If you have used MySQL, then you must have seen PHPMyAdmin, it
is the best example of a 3-tier DBMS architecture.
Types of Database Model
A Database model defines the logical design and structure of a database. It defines how
data will be stored, accessed, and updated in a database management system.
As per your application's requirement, you can use a database model to define
your database.
The database model sets the rule, relationships, constraints, etc. to define how
data is stored in the database.
There are different types of Database models and each one has its own set of
features.
You can define how you want to structure the application data using a database
model.
In this tutorial you will learn about the 7 database model that are popularly used.
1. Hierarchical Model
2. Network Model
3. Entity-relationship Model
4. Relational Model
5. Object-oriented Model
6. NoSQL Model
7. Graph Model
Let's learn about the different types of database models along with their main features
and when should you use them.
1. Hierarchical Model
The hierarchical database model organizes data into a tree-like structure, with
a single root, to which all the other data is linked.
The hierarchy starts from the Root data, and expands like a tree,
adding child nodes to the parent nodes.
In this model, a child node will only have a single parent node.
This model efficiently describes many real-world relationships like the index of a
book, etc.
Here are a few points to mark the advantages and disadvantages of the Hierarchical
database model:
2. Network Model
The Network Model is an extension of the Hierarchical model.
In this model, data is organized more like a graph, and allowed to have more than
one parent node.
In the network database model, data is more related as more relationships are
established in this database model.
Also, as the data is more related, hence accessing the data is also
easier and fast.
This was the most widely used database model before Relational Model was
introduced.
The implementation of the Network model is complex, and it's very difficult to
maintain it.
You may want to explore this if you are developing some social networking
applications, although the Graph Database model is new and is far better than the
Network Database model.
Advantages of the Network Model
3. Entity-relationship Model
In this database model, relationships are created by dividing objects of interest
into entities and their characteristics into attributes.
This model is good to design a database, which can then be turned into tables in a
relational model (explained below).
Relationships can also be of different types. You can learn about ER Diagrams in
detail if you want to learn about entities and relationships.
4. Relational Model
In this model, data is organized in two-dimensional tables and the relationship is
maintained by storing a common field.
This model was introduced by E.F Codd in 1970, and since then it has been the
most widely used database model.
The basic structure of data in the relational model is tables. All the information
related to a particular type is stored in rows of that table.
3. It supports SQL using which you can easily query the data.
5. Object-oriented Model
In this model, data is stored in the form of objects.
This database model is not mature enough as compared to the relational database
model.
6. NoSQL Model
The NoSQL database model supports an unstructured style of storing data.
The documents look more like JSON strings or Key-value based object
representations.
The support for data querying is limited in the NoSQL database model.
This database model is well-suited for Big data applications, real-time analytics,
CMS (Content Management systems), etc.
Advantages of the NoSQL Model
7. Graph Model
The Graph database model is based on more real-world like relationships.
If your application has simple data requirements, then you should not use the
graph database model.
1. In the modern world where there is so much data and the data has to be related in
different ways, the graph database model is very useful.
The main data objects are termed as Entities, with their details defined
as attributes, some of these attributes are important and are used to
identity the entity, and different entities are related using
relationships.
ER Model: Attributes
1. Simple attribute: The attributes with values that are atomic and
cannot be broken down further are simple attributes. For
example, student's age.
2. Composite attribute: A composite attribute is made up of more
than one simple attribute. For example, student's address will
contain, house no., street name, pincode etc.
3. Derived attribute: These are the attributes which are not
present in the whole database management system, but are
derived using other attributes. For example, average age of
students in a class.
4. Single-valued attribute: As the name suggests, they have a
single value.
5. Multi-valued attribute: And, they can have multiple values.
ER Model: Keys
If the attribute roll no. can uniquely identify a student entity, amongst
all the students, then the attribute roll no. will be said to be a key.
1. Super Key
2. Candidate Key
3. Primary Key
We have covered Keys in details here in Database Keys tutorial.
ER Model: Relationships
For example, in the below diagram, anyone can see and understand
what the diagram wants to convey: Developer develops a website,
whereas a Visitor visits a website.
Components of ER Diagram
Entitiy, Attributes, Relationships etc form the components of ER
Diagram and there are defined symbols and shapes to represent each
one of them.
Entity
Simple rectangular box represents an Entity.
Weak Entity
ER Diagram: Entity
An attribute can also have their own attributes. These attributes are
known as Composite attributes.
ER Diagram: Relationship
1. Binary Relationship
2. Recursive Relationship
3. Ternary Relationship
The above example describes that one student can enroll only for one
course and a course will also have only one Student. This is not what
you will usually see in real-world relationships.
The above diagram represents that one student can enroll for more
than one courses. And a course can have more than 1 student enrolled
in it.
*************************************unit-1 completed*******************************
UNIT-2
Relational database model:
The Relational Model organizes data using tables (relations) consisting of rows and
columns. Each column represents a specific attribute with a unique name, while each
row holds data about a real-world entity or relationship. As a record-based model, it
stores data in fixed-format records with defined attributes.
Introduced by E.F. Codd, the relational model transforms conceptual designs from ER
diagrams into implementable structures. These structures are used in relational
database systems like Oracle SQL and MySQL.
What is the Relational Model?
The relational model represents how data is stored and managed in
Relational Databases. Data is organized into tables, each known as a relation,
consisting of rows (tuples) and columns (attributes).
Each row represents an entity or record, and each column represents a
particular attribute of that entity. A relational database consists of a collection of tables
each of which is assigned a unique name.
1. Primary Key:
A Primary Key uniquely identifies each tuple in a relation. It must contain unique
values and cannot have NULL values. Example: ROLL_NO in the STUDENT table is the primary
key.
2. Candidate Key
A Candidate Key is a set of attributes that can uniquely identify a tuple in a relation.
There can be multiple candidate keys, and one of them is chosen as the primary key.
3. Super Key
A Super Key is a set of attributes that can uniquely identify a tuple. It may contain
extra attributes that are not necessary for uniqueness.
4. Foreign Key
A Foreign Key is an attribute in one relation that refers to the primary key of another
relation. It establishes relationships between tables. Example: BRANCH_CODE in
the STUDENT table is a foreign key that refers to the primary key BRANCH_CODE in
the BRANCH table.
5. Composite Key
A Composite Key is formed by combining two or more attributes to uniquely identify a
tuple. Example: A combination of FIRST_NAME and LAST_NAME could be a composite key if
no one in the database shares the same full name.
The video below covers all about the different keys in an RDBMS.
Now to fetch any particular record from such dataset, you will have to
apply some conditions, but what if there is duplicate data present and
every time you try to fetch some data by applying certain condition,
you get the wrong data. How many trials before you get the right data?
To avoid all this, Keys are defined to easily identify any row of data in
a table.
Let's try to understand about all the keys using a simple example.
student_id name phone age
1 Akon 9876723452 17
2 Akon 9991165674 19
3 Bkon 7898756543 18
4 Ckon 8987867898 19
5 Dkon 9990080080 17
Super Key
Next comes, (student_id, name), now name of two students can be same,
but their student_id can't be same hence this combination can also be a
key.
Candidate keys are defined as the minimal set of fields which can
uniquely identify each record in a table. It is an attribute or a set of
attributes that can act as a Primary Key for a table to uniquely identify
each record in that table. There can be more than one candidate key.
In our example, student_id and phone both are candidate keys for
table Student.
A candiate key can never be NULL or empty. And its value should
be unique.
There can be more than one candidate keys for a table.
A candidate key can be a combination of more than one
columns(attributes).
Primary Key
For the table Student we can make the student_id column as the
primary key.
Composite Key
Key that consists of two or more attributes that uniquely identify any
record in a table is called Composite key. But the attributes which
together form the Composite key are not a key independentely or
individually.
In the above picture we have a Score table which stores the marks
scored by a student in a particular subject.
In this table student_id and subject_id together will form the primary key,
hence it is a composite key.
The candidate key which are not selected as primary key are known as
secondary keys or alternative keys.
Non-key Attributes
Non-prime Attributes
1. Select
2. Project
3. Union
4. Set Different
5. Cartesian product
6. Rename
Syntax: σ (r) p
This will fetch the tuples(rows) from table Student, for which age will
be greater than 17.
You can also use, and, or etc operators, to specify two conditions, for
example,
σage > 17 and gender = 'Male' (Student)
It will only project or show the columns or attributes asked for, and will
also remove duplicate data from the columns.
For example,
∏Name, Age(Student)
Above statement will show us only the Name and Age columns for all
the rows of data in Student table.
Syntax: A ∪ B
∏Student(RegularClass) ∪ ∏Student(ExtraClass)
This operation is used to find data present in one relation and not
present in the second relation. This operation is also applicable on two
relations, just like Union operation.
Syntax: A - B
Syntax: A X B
For example, if we want to find the information for Regular Class and
Extra Class which are conducted during morning, then, we can use the
following operation:
σtime = 'morning' (RegularClass X ExtraClass)
This operation is used to rename the output relation for any query
operation which returns result like Select, Project etc. Or to simply
rename a relation(table)
Natural Join
Outer Join
Theta join etc.
Normalization in DBMS
Normalization in DBMS is a technique using which you can organize the data in the
database tables so that:
It is a multi-step process that puts data into tabular form, removes duplicate data, and
set up the relationship between tables.
Normalization helps in keeping data consistent by storing the data in one table
and referencing it everywhere else.
Storage optimization although that is not an issue these days because Database
storage is cheap.
Breaking down large tables into smaller tables with relationships, so it makes the
database structure more scalable and adaptable.
This video will give you a good overview of Database Normalization. If you want you can skip the video, as
the concept is covered in this tutorial as well - Normalization in DBMS (YouTube Video).
Insertion, Updation, and Deletion Anomalies are very frequent if the database is not
normalized.
In the
table rollno name branch hod office_tel
As we can see, data for the fields branch, hod(Head of Department), and office_tel are
repeated for the students who are in the same branch in the college, this is Data
Redundancy.
Suppose for a new admission, until and unless a student opts for a branch, data of
the student cannot be inserted, or else we will have to set the branch information
as NULL.
Also, if we have to insert data for 100 students of the same branch, then the
branch information will be repeated for all those 100 students.
If you have to repeat the same data in every row of data, it's better to keep the
data separately and reference that data in each row.
So in the above table, we can keep the branch information separately, and just use
the branch_id in the student table, where branch_id can be used to get the
branch information.
2. Updation Anomaly in DBMS
What if Mr. X leaves the college? or Mr. X is no longer the HOD of the computer
science department? In that case, all the student records will have to be updated,
and if by mistake we miss any record, it will lead to data inconsistency.
This is an Updation anomaly because you need to update all the records in your
table just because one piece of information got changed.
In our Student table, two different pieces of information are kept together,
the Student information and the Branch information.
So if only a single student is enrolled in a branch, and that student leaves the
college, or for some reason, the entry for the student is deleted, we will lose the
branch information too.
So never in DBMS, we should keep two different entities together, which in the
above example is Student and branch,
The solution for all the three anomalies described above is to keep the student information and
the branch information in two different tables. And use the branch_id in the student table to reference
the branch.
As you can see in the table above, the student_id column is a primary key because
using the student_id value we can uniquely identify each row of data, hence
the remaining columns then become the non-key attributes.
Types of DBMS Normal forms
Normalization rules are divided into the following normal forms:
4. BCNF
Let's cover all the Database Normal forms one by one with some basic examples to help
you understand the DBMS normal forms.
For a table to be in the First Normal Form, it should follow the following 4 rules:
Watch this YouTube video to understand First Normal Form (if you like videos) - DBMS First Normal
Form 1NF with Example
If we have an Employee table in which we store the employee information along with
the empl oyee
skillset, the table
will look like this:
emp_id emp_name emp_mobile emp_skills
The above
table has 4
columns:
1 John Tick 9999957773 Python, JavaScript
All the
columns
have
different
2 Darth Trader 8888853337 HTML, CSS, JavaScript names.
All the
columns
hold
3 Rony Shark 7777720008 Java, Linux, C++ values of
the same
type like emp_name has all the names, emp_mobile has all the contact
numbers, etc.
But the emp_skills column holds multiple comma-separated values, while as per
the First Normal form, each column should have a single value.
Hence the above table fails to pass the First Normal form.
So how do you fix the above table? There are two ways to do this:
1. Remove the emp_skills column from the Employee table and keep it in some
other table.
2. Or add multiple rows for the employee and each row is linked with one skill.
this,
emp_id emp_skill
Python
JavaScript
emp_id emp_skill
HTML
CSS
JavaScript
Java
Linux
C++
If you want to learn about the First Normal Form in detail, check out DBMS First
Normal Form tutorial.
Watch this YouTube video to understand Second Normal Form (if you like videos) - DBMS Second
Normal Form 2NF with Example
Let's take an example to understand Partial dependency and the Second Normal Form.
If we have two tables Students and Subjects, to store student information and
information related to subjects.
student_id student_name branch
1 Akon CSE
2 Bkon Mechanical
subject_id subject_name
1 C Language
2 DSA
3 Operating System
Student table:
Subject Table:
And we have another table Score to store the marks scored by students in any subject
like this,
1 1 70 Miss. C
1 2 82 Mr. D
2 1 65 Mr. Op
student_id subject_id marks teacher_name
Now in the above table, the primary key is student_id + subject_id, because both
these information are required to select any row of data.
But in the Score table, we have a column teacher_name, which depends on the subject
information or just the subject_id, so we should not keep that information in
the Score table.
The column teacher_name should be in the Subjects table. And then the entire system
will be Normalized as per the Second Normal Form.
C Language Miss. C
DSA Mr. D
To understand what is Partial Dependency and how you can normalize a table to 2nd
normal form, jump to the DBMS Second Normal Form tutorial.
1. It satisfies the First Normal Form and the Second Normal form.
Watch this YouTube video to understand the Third Normal Form (if you like videos) - DBMS Third Normal
Form 3NF with Example
What is Transitive Dependency?
In a table we have
some column
that acts student_id subject_id marks exam_type total_marks as the
primary key and
other columns
depends on this
column. But what
1 1 70 Theory 100
if a column
that is not the
primary key
depends on
another column
1 2 82 Theory 100
that is also not a
primary key or
part of it? Then we
have Transitive
2 1 42 Practical 50
Let's take an example. We had the Score table in the Second Normal Form above. If we
have to store some extra information in it, like,
1. exam_type
2. total_marks
To store the type of exam and the total marks in the exam so that we can later calculate
the percentage of marks scored by each student.
o and based on that they may have different exam types for different subjects.
o The CSE students may have both Practical and Theory for Compiler Design,
o whereas Mechanical branch students may only have Theory exams for
Compiler Design.
But the column total_marks just depends on the exam_type column. And
the exam_type column is not a part of the primary key. Because the primary key
is student_id + subject_id, hence we have a Transitive dependency here.
1 Practical 50 45
We have created a new table ExamType and we have added more related information
in it like duration(duration of exam in mins.), and now we can use the exam_type_id in
the Score table.
Here is the DBMS Third Normal Form tutorial. But we suggest you first study the
second normal form and then head over to the third normal form.
Boyce and Codd Normal Form is a higher version of the Third Normal Form.
This form deals with a certain type of anomaly that is not handled by 3NF.
A 3NF table that does not have multiple overlapping candidate keys is said to
be in BCNF.
You can also watch our YouTube video to learn about BCNF - DBMS BCNF with Example
Here is the Fourth Normal Form tutorial. But we suggest you understand other normal
forms before you head over to the fourth normal form.
The fifth normal form is also called the PJNF - Project-Join Normal Form
Using Fifth Normal Form you can fix Join dependency and reduce data
redundancy.
*******************unit-2 completed****************************
UNIT-3
Introduction to SQL
Structure Query Language(SQL) is a database query language used for storing and managing data in Relational
DBMS. SQL was the first commercial language introduced for E.F Codd's Relational model of database.
Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) use SQL as the standard database
query language. SQL is used to perform all types of data operations in RDBMS.
SQL Command
SQL defines Command Description following ways to
manipulate data stored in an RDBMS.
DML commands are used for manipulating the data stored in the table and not the table itself.
DML commands are not auto-committed. It means changes are not permanent to database, they can be rolled
back.
Command Description
These commands are to keep a check on other commands and their affect on the database. These commands can
annul changes made by other commands by rolling the data back to its original state. It can also make any
temporary change permanent.
Command Description
Data control language are the commands to grant and take back authority from any database user.
Command Description
Data query language is used to fetch data from tables based on conditions that we can easily apply.
Command Description
DDL
SQL: create command
create is a DDL SQL command used to create a table or a database in
relational database management system.
Creating a Database
Copy
Copy
The above command will create a database named Test, which will be
an empty schema without any table.
Creating a Table
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
);
Copy
create table command will tell the database system to create a new
table with the given table name and column information.
student_id INT,
name VARCHAR(100),
age INT);
Copy
The above command will create a new table with name Student in the
current database with 3 columns, namely student_id, name and age.
Where the column student_id will only store integer, name will hold upto
100 characters and age will again store only integer value.
If you are currently not logged into your database in which you want to
create the table then you can also add the database name along with
table name, using a dot operator .
student_id INT,
name VARCHAR(100),
age INT);
Copy
Here we have listed some of the most commonly used datatypes used
for columns in tables.
Dataty
Use
pe
VARCHA used for columns which will be used to store characters and
R integers, basically a string.
CHAR used for columns which will store char values(single character).
used for columns which will store text which is generally long in
length. For example, if you create a table for storing profile
TEXT
information of a social networking website, then for about
me section you can have a column of type TEXT.
column_name datatype);
Copy
Here is an Example for this,
address VARCHAR(200)
);
Copy
The above command will add a new column address to the
table student, which will hold data of type varchar which is nothing but
string, of length 200.
Using ALTER command we can even add multiple new columns to any
existing table. Following is the syntax,
column_name1 datatype1,
column-name2 datatype2,
column-name3 datatype3);
Copy
Here is an Example for this,
father_name VARCHAR(60),
mother_name VARCHAR(60),
dob DATE);
Copy
The above command will add three new columns to the student table
);
Copy
Here is an Example for this,
);
Copy
The above command will add a new column with a preset default value
to the table student.
ALTER Command: Modify an existing Column
ALTER command can also be used to modify data type of any existing
column. Following is the syntax,
column_name datatype
);
Copy
Here is an Example for this,
address varchar(300));
Copy
Remember we added a new column address in the beginning? The
above command will modify the address column of the student table,
to now hold upto 300 characters.
old_column_name TO new_column_name;
Copy
Here is an example for this,
address TO location;
Copy
The above command will rename address column to location.
ALTER Command: Drop a Column
column_name);
Copy
Here is an example for this,
address);
Copy
The above command will drop the address column from the
table student.
TRUNCATE command
TRUNCATE command removes all the records from a table. But this
command will not destroy the table's structure. When we
use TRUNCATE command on a table its (auto-increment) primary key is
also initialized. Following is its syntax,
Copy
Here is an example explaining it,
Copy
The above query will delete all the records from the table student.
In DML commands, we will study about the DELETE command which is
also more or less same as the TRUNCATE command. We will also learn
about the difference between the two in that tutorial.
DROP command
Copy
Here is an example explaining it,
Copy
The above query will delete the Student table completely. It can also
be used on Databases, to delete the complete database. For example,
to drop a database,
Copy
The above query will drop the database with name Test from the
system.
RENAME query
RENAME command is used to set a new name for any existing table.
Following is the syntax,
Copy
Here is an example explaining it.
DML
Using INSERT SQL command
Data Manipulation Language (DML) statements are used for managing
data in database. DML commands are not auto-committed. It means
changes made by DML command are not permanent to database, it
can be rolled back.
INSERT command
Copy
Lets see an example,
Copy
The above command will insert a new record into student table.
We can use the INSERT command to insert values for only some specific
columns of a row. We can specify the column names along with the
values to be inserted like this,
Copy
The above SQL query will only insert id and name values in the newly
inserted record.
Both the statements below will insert NULL value into age column of
the student table.
Copy
Or,
Copy
The above command will insert only two column values and the other
column is set to null.
101 Adam 15
102 Alex
Copy
101 Adam 15
102 Alex
103 chris 14
Suppose the column age in our tabel has a default value of 14.
Also, if you run the below query, it will insert default value into the age
column, whatever the default value may be.
Let's learn about the syntax and usage of the UPDATE command.
UPDATE command
UPDATE command is used to update any record of data in a table.
Following is its general syntax,
Copy
WHERE is used to add a condition to any SQL query, we will soon study
about it in detail.
Lets take a sample table student,
101 Adam 15
102 Alex
103 chris 14
Copy
101 Adam 15
102 Alex 18
103 chris 14
In the above statement, if we do not use the WHERE clause, then our
update query will update age for all the columns of the table to 18.
Updating Multiple Columns
Copy
The above command will update two columns of the record which
has s_id 103.
101 Adam 15
102 Alex 18
103 Abhi 17
Copy
As you can see, we have used age = age + 1 to increment the value of
age by 1.
Let's study about the syntax and the usage of the Delete command.
DELETE command
Copy
101 Adam 15
102 Alex 18
103 Abhi 17
Copy
The above command will delete all the records from the
table student.
Delete a particular Record from a Table
Copy
The above command will delete the record where s_id is 103 from the
table student.
101 Adam 15
102 Alex 18
Before moving forward with TCL commands, check these topics out
first:
DML commands
DDL COMMAND
These are used to manage the changes made to the data in a table by
DML statements. It also allows statements to be grouped together into
logical transactions.
COMMIT command
When we use any DML command like INSERT, UPDATE or DELETE, the
changes made by these commands are not permanent, until the
current session is closed, the changes made by these commands can
be rolled back.
COMMIT;
Copy
ROLLBACK command
If we have used the UPDATE command to make some changes into the
database, and realise that those changes were not required, then we
can use the ROLLBACK command to rollback those changes, if they were
not commited using the COMMIT command.
ROLLBACK TO savepoint_name;
Copy
SAVEPOINT command
SAVEPOINT savepoint_name;
Copy
In short, using this command we can name the different states of our
data in any table and then rollback to that state using
the ROLLBACK command whenever required.
id name
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.
COMMIT;
SAVEPOINT A;
SAVEPOINT B;
SAVEPOINT C;
Copy
NOTE: SELECT statement is used to show the data stored in the table.
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Now let's use the ROLLBACK command to roll back the state of data to
the savepoint B.
ROLLBACK TO B;
Copy
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of
data to the savepoint A
ROLLBACK TO A;
Copy
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
Copy
To allow a user to create tables in the database, we can use the below
command,
Copy
Copy
The above command will alter the user details and will provide it
access to unlimited tablespace on system.
Copy
Copy
As the title suggests, if you want to allow user to drop any table from
the database, then grant this privilege to the user,
Copy
To take back Permissions
And, if you want to take back the privileges from any user, use
the REVOKE command.
Copy
SELECT
column_name1,
column_name2,
column_name3,
...
column_nameN
FROM table_name;
Copy
Copy
The above query will fetch information of s_id, name and age columns of
the student table and display them,
101 Adam 15
102 Alex 18
103 Abhi 17
104 Ankit 22
As you can see the data from address column is absent, because we did
not specif it in our SELECT query.
Select all records from a table
Copy
The above query will show all the records of student table, that
means it will show complete dataset of the table.
Copy
Copy
When we specify a condition using the WHERE clause then the query
executes only for those records for which the condition specified by
the WHERE clause is true.
Here is how you can use the WHERE clause with a DELETE statement, or
any other statement,
Copy
The WHERE clause is used at the end of any SQL query, to specify a
condition for execution.
Now we will use the SELECT statement to display data of the table,
based on a condition, which we will add to our SELECT query
using WHERE clause.
Let's write a simple SQL query to display the record for student
with s_id as 101.
SELECT s_id,
name,
age,
address
Copy
Following will be the result of the above query.
SELECT s_id,
name,
age,
address
Copy
Following will be the result of the above query.
Operator Description
= Equal to
!= Not Equal to
Wildcard operators
There are two wildcard operators that are used in LIKE clause.
101 Adam 15
102 Alex 18
103 Abhi 17
Copy
The above query will return all records where s_name starts with
character 'A'.
101 Adam 15
102 Alex 18
103 Abhi 17
Using _ and %
Copy
The above query will return all records from Student table
where s_name contain 'd' as second character.
s_id s_Name age
101 Adam 15
Using % only
Copy
The above query will return all records from Student table
where s_name contain 'x' as last character.
102 Alex 18
Syntax of Order By
SELECT column-list|* FROM table-name ORDER BY ASC | DESC;
Copy
Copy
The above query will return the resultant data in ascending order of
the salary.
Copy
The above query will return the resultant data in descending order of
the salary.
SELECT query
WHERE clause
LIKE clause
Group BY clause
Having clause
SQL Group By Clause
Group by clause is used to group the results of a SELECT query
based on one or more columns. It is also used with SQL functions
to group the result from one or more tables.
Syntax for using Group by in a statement.
SELECT column_name, function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
Copy
name age
Rohan 34
Shane 29
Anu 22
Example of Group by in a Statement with WHERE clause
Consider the following Emp table
name salary
Rohan 6000
Shane 8000
Scott 9000
You must remember that Group By clause will always come at the
end of the SQL query, just like the Order by clause.
SQL HAVING Clause
Having clause is used with SQL Queries to give more precise
condition for a statement. It is used to mention condition in Group
by based SQL queries, just like WHERE clause is used
with SELECT query.
Syntax for HAVING clause is,
SELECT column_name, function(column_name)
FROM table_name
WHERE column_name condition
GROUP BY column_name
HAVING function(column_name) condition
Copy
The main objective of the above SQL query was to find out the
name of the customer who has had a previous_balance more
than 3000, based on all the previous sales made to the customer,
hence we get the first row in the table for customer Alex.
DISTINCT keyword
The distinct keyword is used with SELECT statement to retrieve
unique values from the table. Distinct removes all the duplicate
records while retrieving records from any table in the database.
sala
ry
5000
8000
1000
0
AND operator
AND operator is used to set multiple conditions with the WHERE clause,
alongside, SELECT, UPDATE or DELETE SQL queries.
SELECT * FROM Emp WHERE salary < 10000 AND age > 25
The above query will return records where salary is less
than 10000 and age greater than 25. Hope you get the concept here.
We have used the AND operator to specify two conditions
with WHERE clause.
OR operator
When we use AND to combine two or more than two conditions, records
satisfying all the specified conditions will be there in the result.
Example of OR operator
The above query will return records where either salary is greater
than 10000 or age is greater than 25.
SQL JOIN
SQL Join is used to fetch data from two or more tables, which is joined
to appear as single set of data. It is used for combining column from
two or more tables by using values common to both tables.
JOIN Keyword is used in SQL queries for joining two or more tables.
Minimum required condition for joining table, is (n-1) where n, is
number of tables. A table can also join to itself, which is known as, Self
Join.
Types of JOIN
Inner
Outer
Left
Right
This type of JOIN returns the cartesian product of rows from the tables
in Join. It will return a table which consists of records which combines
each row from the first table with each row of the second table.
SELECT column-name-list
FROM
Copy
ID NAME
1 abhi
2 adam
4 alex
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
SELECT * FROM
Copy
The resultset table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 1 DELHI
4 alex 1 DELHI
1 abhi 2 MUMBAI
2 adam 2 MUMBAI
4 alex 2 MUMBAI
1 abhi 3 CHENNAI
2 adam 3 CHENNAI
4 alex 3 CHENNAI
As you can see, this join returns the cross product of all the records
present in both the tables.
Copy
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
Copy
The resultset table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
Natural JOIN
SELECT * FROM
Copy
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
Copy
The resultset table will look like,
ID NAME Address
1 abhi DELHI
2 adam MUMBAI
3 alex CHENNAI
OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins
subdivide further into,
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join
The left outer join returns a resultset table with the matched
data from the two tables and then the remaining rows of the left table
and null from the right table's columns.
ON table-name1.column-name = table-name2.column-name;
Copy
To specify a condition, we use the ON keyword with Outer Join.
Copy
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
Copy
The resultset table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
The right outer join returns a resultset table with the matched
data from the two tables being joined, then the remaining rows of
the right table and null for the remaining left table's columns.
ON table-name1.column-name = table-name2.column-name;
Copy
Right outer Join Syntax for Oracle is,
table-name1, table-name2
ON table-name1.column-name(+) = table-name2.column-name;
Copy
Example of Right Outer Join
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
Right Outer Join query will be,
Copy
The resultant table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
The full outer join returns a resultset table with the matched data of
two table then remaining rows of both left table and then
the right table.
Copy
Example of Full outer join is,
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
Copy
The resultset table will look like,
Now that
we ID NAME ID Address have
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
learned SQL JOIN, you can check these SQL topics as well and their
usage:
SQL function
SQL Alias
SQL SET operation
SQL Views
SQL Constraints
SQL Constraints are rules used to limit the type of data that can go
into a table, to maintain the accuracy and integrity of the data inside
table.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
age int
);
Copy
The above query will declare that the s_id field of Student table will
not take NULL value.
If you wish to alter the table after it has been created, then we can use
the ALTER command for it:
Copy
UNIQUE Constraint
Here we have a simple CREATE query to create a table, which will have
a column s_id with unique values.
name varchar(60),
);
Copy
The above query will declare that the s_id field of Student table will
only have unique values and wont take NULL value.
If you wish to alter the table after it has been created, then we can use
the ALTER command for it:
Copy
The above query specifies that s_id field of Student table will only
have unique value.
Age int);
Copy
Foreign Key is used to relate two tables. The relationship between the
two tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
To understand FOREIGN KEY, let's see its use, with help of the below
tables:
Customer_Detail Table
Order_Detail Table
10 Order1 101
11 Order2 103
12 Order3 102
If you try to insert any incorrect data, DBMS will return error and will
not allow you to insert the data.
);
Copy
Copy
Behaviour of Foriegn Key Column on Delete
There are two ways to maintin the integrity of data in Child table, when
a particular record is deleted in the main table. When two tables are
connected with Foriegn key, and certain data in the main table is
deleted, for which a record exits in the child table, then we must have
some mechanism to save the integrity of data in the child table.
CHECK Constraint
Age int
);
Copy
The above query will restrict the s_id value to be greater than zero.
Copy
Related Tutorials:
SQL function
SQL Join
SQL Alias
SQL SET operation
SQL Sequences
SQL Views
UNIT-4
PL/SQL BASICS
In this article, we’ll cover PL/SQL basics, including its core features, PL/SQL block structure, and practical
examples that demonstrate the power of PL/SQL. We’ll also explore the differences between SQL and
PL/SQL, how variables and identifiers work, and how the PL/SQL execution environment operates within
Oracle.
What is PL/SQL?
PL/SQL is a combination of SQL and procedural programming constructs, enabling developers to write code
that performs database operations efficiently. It was developed by Oracle to enhance SQL’s capabilities and
allow for advanced error handling, complex calculations, and programmatic control over database operations.
Handle exceptions, ensuring the program runs smoothly even when errors occur
1. Block Structure: PL/SQL can execute a number of queries in one block using single command.
2. Procedural Constructs: One can create a PL/SQL unit such as procedures, functions, packages, triggers,
and types, which are stored in the database for reuse by applications.
3. Error Handling: PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known
as exception handling block.
4. Reusable Code: Create stored procedures, functions, triggers, and packages, which can be executed
repeatedly.
5. Performance: Reduces network traffic by executing multiple SQL statements within a single block
Typically, each block performs a logical action in the program. A block has the following structure:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
PL/SQL code is written in blocks, which consist of three main sections:
Declare section starts with DECLARE keyword in which variables, constants, records as cursors can be
declared which stores data temporarily. It basically consists definition of PL/SQL identifiers. This part
of the code is optional.
Execution section starts with BEGIN and ends with END keyword.This is a mandatory section and here
the program logic is written to perform any task like loops and conditional statements. It supports all
DML commands, DDL commands and SQL*PLUS built-in functions as well.
Exception section starts with EXCEPTION keyword.This section is optional which contains statements
that are executed when a run-time error occurs. Any exceptions can be handled in this section.
PL/SQL Identifiers
In PL/SQL, identifiers are names used to represent various program elements like variables, constants,
procedures, cursors, triggers etc. These identifiers allow you to store, manipulate, and access data throughout
your PL/SQL code.
1. Variables in PL/SQL
Like several other programming languages, variables in PL/SQL must be declared prior to its use. A variable is
like a container that holds data during program execution. Each variable must have a valid name and a specific
data type.
NOT NULL: This optional constraint means the variable cannot be left empty.
SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
/
Output:
SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.
var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many
other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in
SQL as well like NUMBER(prec, scale), varchar, varchar2 etc.
Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.
The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to
display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and
triggers. Let us see an example to see how to display a message using PL/SQL :
BEGIN
dbms_output.put_line(var);
END;
/
Output:
I love GeeksForGeeks
3. Comments in PL/SQL
Like in many other programming languages, in PL/SQL also, comments can be put within the code which has
no effect in the code. There are two syntaxes to create comments in PL/SQL :
Single Line Comment: To create a single line comment , the symbol - - is used.
Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used.
/*
This is a multi-line comment
that spans over multiple lines.
*/
4. Taking input from users
In PL/SQL we can take input from the user and store it in a variable using substitution variables. These
variables are preceded by an & symbol. Let us see an example to show how to take input from users in PL/SQL:
SQL> DECLARE
BEGIN
null;
END;
/
Output:
&a and &b are substitution variables where the user will be prompted to provide values.
The user is asked to enter values for a and b when the code runs.
--PL/SQL code to print sum of two numbers taken from the user.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
BEGIN
c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
END;
Execution:
Sum of 2 and 3 is = 5
PL/SQL is a powerful tool in Oracle for combining SQL with procedural programming capabilities. With
PL/SQL features like error handling, reusable program units, and support for loops and conditionals, PL/SQL
extends SQL’s data manipulation capabilities and enables developers to create sophisticated applications
within the database. By understanding SQL vs PL/SQL and the advantages of the PL/SQL execution
environment, developers can unlock the full potential of Oracle’s PL/SQL language for robust database
applications.
Type Characters
Letters A-Z, a-z
Digits 0-9
Symbols ~ ! @ # $ % & * ( ) _ - + = | [ ] { } : ; " ' < > , . ? / ^
Whitespace Tab, space, newline, carriage return
Every keyword in PL/SQL is made from various combinations of characters in this character set. Now you just
have to figure out how to put them all together!
By default, PL/SQL is a case-insensitive language. That is, uppercase letters are treated the same way as
lowercase letters except when characters are surrounded by single quotes, which makes them a literal string.
A number of these characters—both singly and in combination with other characters—have a special
significance in PL/SQL. Table 3-3 lists these special symbols.
Symbo
Description
l
; Semicolon: terminates declarations and statements
Percent sign: attribute indicator (cursor attributes like %ISOPEN and indirect declaration attributes
%
like %ROWTYPE); also used as multibyte wildcard symbol with the LIKE condition
_ Single underscore: single-character wildcard symbol in LIKE condition
@ At- sign: remote ...
PL\SQL STRUCTURE
PL/SQL, or Procedural Language/SQL, is a powerful extension of SQL developed by Oracle. It combines
SQL's data manipulation capabilities with procedural programming constructs, enabling developers to write
complex database applications with better control and error handling. The fundamental structure of a PL/SQL
block is: DECLARE (optional), BEGIN, EXCEPTION (optional), and END.
Structure of a PL/SQL Block:
1. 1. DECLARE (Optional):
o This section is used to declare variables, constants, cursors, user-defined functions, procedures,
and other code elements that will be used within the block.
o It's not mandatory; if no declarations are needed, this section can be omitted.
o Example: DECLARE v_count NUMBER := 0;
2. 2. BEGIN:
o This is the executable part of the block and contains the main logic and code that interacts with
the database.
o All executable statements, including SQL queries and PL/SQL control structures, reside within
this section.
o Example: BEGIN ... SQL statements ... PL/SQL control structures ... END;
3. 3. EXCEPTION (Optional):
o This section handles runtime errors (exceptions) that might occur during the execution of the
code within the BEGIN section.
o Exception handlers are defined to catch specific exceptions and take appropriate actions.
o Example: EXCEPTION WHEN OTHERS THEN ...
4. 4. END:
o This keyword marks the end of the PL/SQL block.
4.
o
Example:
Code
DECLARE
v_employee_id NUMBER := 100;
v_salary NUMBER;
BEGIN
-- Select the salary of the employee
SELECT salary INTO v_salary FROM employees WHERE employee_id = v_employee_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred.');
END;
/
In this example:
1. IF THEN
2. IF THEN ELSE
3. NESTED-IF-THEN
1. IF THEN
if then the statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.
Syntax:
if condition then
-- do something
end if;
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is
true then it will execute the block of statements below it otherwise not. if and endif consider as a block here.
Example:
declare
-- declare the values here
begin
if condition then
dbms_output.put_line('output');
end if;
dbms_output.put_line('output2');
end;
begin
end;
As the condition present in the if statement is false. So, the block below the if statement is not executed.
Output:
I am Not in if
2. IF THEN ELSE
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition
is false it won’t. But what if we want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a block of code when the condition is
false.
Syntax:-
if (condition) then
-- Executes this block if
-- condition is true
else
-- Executes this block if
-- condition is false
Example:-
begin
ELSE
dbms_output.put_line('i am in else Block');
end if;
3. NESTED-IF-THEN
A nested if-then is an if statement that is the target of another if statement. Nested if-then statements mean an if
statement inside another if statement. Yes, PL/SQL allows us to nest if statements within if-then statements. i.e,
we can place an if then statement inside another if then statement. Syntax:-
if (condition1) then
-- Executes when condition1 is true
if (condition2) then
-- Executes when condition2 is true
end if;
end if;
begin
if num1 < num2 then
dbms_output.put_line('num1 small num2');
end if;
dbms_output.put_line('after end if');
end;
Output:-
Here, a user can decide among multiple options. The if then statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:-
if (condition) then
--statement
elsif (condition) then
--statement
.
.
else
--statement
endif
Flow Chart:-
Example:-
begin
ELSE
dbms_output.put_line('num2 greater');
end if;
num1 small
after end if
PL/SQL conditional statements are essential for effective procedural programming in Oracle databases.
The IF THEN and IF THEN ELSE statements provide straightforward decision-making, while NESTED-IF-THEN
supports complex nested logic. The IF THEN ELSIF-THEN-ELSE ladder allows handling multiple conditions in
a structured manner.
LOOPING STATEMENTS
One of the key features in PL/SQL for controlling program flow is the LOOP statement. The LOOP statement
is a feature of PL/SQL that allows you to repeatedly execute a block of code until a specified condition is
satisfied.
Procedural Language/Structured Query Language (PL/SQL) provides a robust environment for database
programming, allowing developers to create powerful and efficient code for Oracle databases.
Syntax
LOOP
-- Code block to be executed repeatedly
END LOOP;
EXIT Statement
The EXIT statement is used to break the loop whether the loop condition has been satisfied or not. This
statement is particularly useful when you want to terminate the loop based on certain conditions within the loop
block.
Syntax
LOOP
-- Code block
IF condition THEN
EXIT;
END IF;
END LOOP;
Example of PL/SQL LOOP with Conditional EXIT
In this example, we showcase the application of a PL/SQL LOOP construct with a conditional EXIT statement.
The code demonstrates a scenario where a loop iterates a specific block of code, printing iteration numbers, and
breaks out of the loop when a predefined condition is met.
DECLARE
counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('This is iteration number ' || counter);
IF counter = 3 THEN
EXIT;
END IF;
counter := counter + 1;
END LOOP;
END;
/
Output:
Statement processed.
This is iteration number 1
This is iteration number 2
This is iteration number 3
Explanation:
The LOOP statement repeatedly executes the code block within it.
Inside the loop, DBMS_OUTPUT.PUT_LINE is used to print Iteration number (value of counter).
IF statement is executed when the value of counter will become 3 and The EXIT statement is executed
and loop stops.
Syntax
LOOP
-- Code block
EXIT WHEN condition;
END LOOP;
Example of PL/SQL LOOP with EXIT WHEN
The purpose of this example is to show how to print "GeeksForGeeks" repeatedly using a PL/SQL LOOP
construct. With the help of the EXIT WHEN statement, the loop can be controlled to end when a counter
variable reaches a predetermined threshold.
DECLARE
counter NUMBER := 1; -- Initialization of the counter variable
BEGIN
-- Loop that prints "GeeksForGeeks" five times
LOOP
DBMS_OUTPUT.PUT_LINE('GeeksForGeeks');
EXIT WHEN counter > 5; -- Exit the loop when counter exceeds 5
END LOOP;
END;
/
Output:
Statement processed.
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Explanation:
The LOOP statement repeatedly executes the code block within it.
The EXIT WHEN statement is executed when the loop when the counter exceeds 5.
Nested Loops
Nested Loop is a Loop inside Loop and PL/SQL supports nested loops that allows you to have multiple levels
of iteration within a program. This is achieved by placing one or more LOOP statements inside another. Each
nested loop has its own set of loop control statements.
Syntax
-- Outer Loop
LOOP
-- Code block
-- Inner Loop
LOOP
-- Inner loop code block
EXIT WHEN inner_condition;
END LOOP;
EXIT WHEN outer_condition;
END LOOP;
Example of PL/SQL Nested FOR Loop Simultaneous Iteration
In this example, we will create nested FOR loops that iterate over two ranges, demonstrating simultaneous
iteration.
DECLARE
outer_counter NUMBER := 1;
inner_counter NUMBER := 1;
BEGIN
FOR outer_counter IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE('Outer Loop - Iteration ' || outer_counter);
Statement processed.
Outer Loop - Iteration 1
Inner Loop - Iteration 1
Inner Loop - Iteration 2
Outer Loop - Iteration 2
Inner Loop - Iteration 1
Inner Loop - Iteration 2
Outer Loop - Iteration 3
Inner Loop - Iteration 1
Inner Loop - Iteration 2
Explanation:
The outer FOR loop (FOR outer_counter IN 1..3 LOOP) runs three times.
Inside the outer FOR loop, there is an inner FOR loop (FOR inner_counter IN 1..2 LOOP) that runs
two times for each iteration of the outer loop.
Pl/SQL is a Procedural Language that is used to write program blocks, procedures, functions, cursors, triggers
for databases. It Provides a LOOP statement facility that is used to repeatedly execute a block of code. and It's
other feature like EXIT and EXIT WHEN statement are used to stop loop based on specific conditions and It
also support Nested loop functionality.
A cursor in SQL is a database object used to retrieve, process, and manipulate rows one at a time from a
result set.
While SQL is a set-based language (it usually works with entire result sets at once), cursors allow row-by-row
processing, which is useful when more control is needed in business logic or procedural code.
v_name employee.name%TYPE;
v_salary employee.salary%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_name, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;
CLOSE emp_cursor;
END;
Advantages of Cursors
Useful for row-by-row processing when complex logic is needed
Ideal for operations not possible in set-based queries
Helps in audit, logging, calculations, and conditional updates
Disadvantages of Cursors
Slower than set-based operations (looping is expensive)
More memory-intensive
Can make code more complex
Alternatives to Cursors
Whenever possible, try using:
Types of Subprograms
Type Description
1. Procedure (PL/SQL)
A procedure is a subprogram that performs a task but does not return a
value directly (though it can return values through OUT parameters).
✅ Syntax:
sql
CopyEdit
CREATE OR REPLACE PROCEDURE procedure_name (
param1 IN datatype,
param2 OUT datatype
)
IS
BEGIN
-- Procedure logic
END;
Example:
sql
CopyEdit
CREATE OR REPLACE PROCEDURE greet_user(p_name IN VARCHAR2)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello, ' || p_name || '!');
END;
sql
CopyEdit
BEGIN
T-SQL (SQL
Element PL/SQL
Server)
greet_user('John');
END;
2. Function (PL/SQL)
A function is a subprogram that returns a value and can be used in SQL
statements.
Syntax:
sql
CopyEdit
CREATE OR REPLACE FUNCTION function_name (
param1 IN datatype
) RETURN datatype IS
BEGIN
-- Function logic
RETURN value;
END;
Example:
sql
CopyEdit
CREATE OR REPLACE FUNCTION get_bonus(salary NUMBER) RETURN
NUMBER IS
BEGIN
RETURN salary * 0.10;
END;
sql
CopyEdit
DECLARE
bonus NUMBER;
BEGIN
bonus := get_bonus(50000);
DBMS_OUTPUT.PUT_LINE('Bonus: ' || bonus);
END;
sql
CopyEdit
SELECT name, get_bonus(salary) FROM employee;
Use:
sql
T-SQL (SQL
Element PL/SQL
Server)
CopyEdit
SELECT name, dbo.get_bonus(salary) FROM employee;
No (use OUT
Returns Value Yes (must return one value)
parameters)
No (used in
Called with EXEC Yes
expressions/SELECT)
Benefits of Subprograms
Reusability – Code once, use many times
Modularity – Divide logic into smaller parts
Maintainability – Easy to debug and update
Security – Hide complex logic behind callable names
UNIT-5
It helps ensure data integrity, prevents system crashes, and improves error reporting and
debugging.
Stored Procedures
Functions
Triggers
PL/SQL or T-SQL blocks
Transactions
Type Example
Syntax Error Missing keywords or incorrect SQL format
Runtime Error Division by zero, constraint violations
Logical Error Wrong calculations or query logic
System Error Disk space full, network failure
sql
CopyEdit
BEGIN
-- SQL or PL/SQL statements
EXCEPTION
WHEN exception_name THEN
-- Exception handling code
WHEN OTHERS THEN
-- Handles any other exceptions
END;
Example:
sql
CopyEdit
DECLARE
v_num NUMBER := 10;
v_denom NUMBER := 0;
v_result NUMBER;
BEGIN
v_result := v_num / v_denom;
DBMS_OUTPUT.PUT_LINE('Result: ' || v_result);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Cannot divide by zero.');
END;
T-SQL (used in Microsoft SQL Server) uses TRY...CATCH for error handling:
sql
CopyEdit
BEGIN TRY
-- SQL statements
END TRY
BEGIN CATCH
-- Error handling code
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH
Example:
sql
CopyEdit
BEGIN TRY
DECLARE @result INT;
SET @result = 10 / 0;
PRINT 'Result is ' + CAST(@result AS VARCHAR);
END TRY
BEGIN CATCH
PRINT 'Error: ' + ERROR_MESSAGE();
END CATCH
Conclusion
Exception handling in RDBMS is crucial for writing robust and safe database
programs.
It allows you to catch and handle predictable or unexpected errors.
Both Oracle (PL/SQL) and SQL Server (T-SQL) provide structured ways to handle
exceptions.
PREDEFINED EXCEPTIONS
Predefined exceptions are system-defined error conditions that occur during the execution of
database programs such as PL/SQL (Oracle) or T-SQL (SQL Server). These exceptions
automatically get triggered when certain common runtime errors occur.
Error
Exception Name Description
Code
ORA-
NO_DATA_FOUND Raised when a SELECT INTO returns no rows
01403
ORA-
TOO_MANY_ROWS Raised when a SELECT INTO returns more than one row
01422
ORA-
ZERO_DIVIDE Raised when attempting to divide by zero
01476
ORA-
INVALID_CURSOR Raised when an illegal cursor operation is attempted
01001
DUP_VAL_ON_INDEX
ORA- Raised when duplicate values are inserted into a column with
00001 a unique index
ORA-
VALUE_ERROR Raised when a value is too large for the variable
06502
ORA-
INVALID_NUMBER Raised when conversion of a string to number fails
01722
ORA-
LOGIN_DENIED Raised when login credentials are invalid
01017
ORA-
STORAGE_ERROR Raised when memory allocation fails
06500
Example: Using Predefined Exceptions in Oracle
sql
CopyEdit
DECLARE
v_result NUMBER;
BEGIN
v_result := 100 / 0; -- This will raise ZERO_DIVIDE
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Division by zero not allowed.');
END;
Predefined exceptions in Oracle PL/SQL have names and are automatically raised
for common errors.
SQL Server (T-SQL) handles errors using error numbers and TRY...CATCH blocks.
Handling predefined exceptions is essential for robust database programs.
User-Defined Exceptions
They are useful when built-in exceptions are not sufficient to describe business rules or
custom validations.
Syntax
sql
CopyEdit
DECLARE
custom_exception EXCEPTION;
BEGIN
-- Your logic
IF <condition> THEN
RAISE custom_exception;
END IF;
EXCEPTION
WHEN custom_exception THEN
DBMS_OUTPUT.PUT_LINE('Custom error occurred.');
END;
EXCEPTION
WHEN insufficient_balance THEN
DBMS_OUTPUT.PUT_LINE('Error: Insufficient balance for withdrawal.');
END;
IF @stock < 10
BEGIN
THROW 50001, 'Stock is below the minimum required level.', 1;
END
END TRY
BEGIN CATCH
PRINT 'Custom Error: ' + ERROR_MESSAGE();
END CATCH
Key Points
Feature Oracle (PL/SQL) SQL Server (T-SQL)
Yes (e.g., my_exception No (uses error
Exception Name
EXCEPTION) numbers/messages)
Raise Statement RAISE THROW or RAISERROR
Custom Messages Yes Yes
Error Handling EXCEPTION ... WHEN TRY...CATCH
Block
User-defined exceptions are vital for enforcing business logic and ensuring data
integrity.
Use them when predefined exceptions don’t match the logic you're trying to handle.
PL/SQL supports named user-defined exceptions, while T-SQL uses custom error
messages with error numbers.
Triggers help enforce business rules, auditing, and data validation without modifying
application code.
Types of Triggers
These are automatically fired by the database when certain DML operations occur.
They respond to INSERT, UPDATE, or DELETE operations.
You do not call them manually — they are implicit.
Example in Oracle:
sql
CopyEdit
CREATE OR REPLACE TRIGGER before_insert_employee
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
:NEW.hire_date := SYSDATE;
END;
sql
CopyEdit
CREATE TRIGGER trg_after_insert
ON employee
AFTER INSERT
AS
BEGIN
PRINT 'Employee record inserted.'
END
In some systems or programming contexts, explicit triggers refer to logic that mimics
trigger-like behavior, manually invoked by code.
Note: In standard RDBMS (Oracle, SQL Server), triggers are always implicitly
fired. There is no "explicit trigger" mechanism like in some programming
languages.
Trigger Execution Timing
Type Description
Triggers:
2. Cursors in RDBMS
A cursor is a pointer to a result set of a query. It allows row-by-row processing of data
from a table or query result, especially useful when the logic can't be handled in a single SQL
statement.
Types of Cursors
Type Description
Implicit Cursor Automatically created by the database for single-row queries like SELECT INTO
Explicit Cursor Defined by the programmer to process multiple rows, manually controlled
Created by default for DML operations (INSERT, UPDATE, DELETE, SELECT INTO)
Accessed using system attributes like:
o %FOUND
o %NOTFOUND
o %ROWCOUNT
o %ISOPEN
Example (PL/SQL):
sql
CopyEdit
DECLARE
v_name employee.name%TYPE;
BEGIN
SELECT name INTO v_name FROM employee WHERE id = 101;
DBMS_OUTPUT.PUT_LINE('Employee name: ' || v_name);
END;
2. Explicit Cursor (User-Defined)
You define it for multi-row queries
Requires 4 steps:
1. DECLARE the cursor
2. OPEN the cursor
3. FETCH rows one by one
4. CLOSE the cursor
Example (PL/SQL):
sql
CopyEdit
DECLARE
CURSOR emp_cursor IS
SELECT name FROM employee;
v_name employee.name%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_name;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_name);
END LOOP;
CLOSE emp_cursor;
END;
sql
CopyEdit
DECLARE @name VARCHAR(50)
DECLARE emp_cursor CURSOR FOR
SELECT name FROM employee
OPEN emp_cursor
FETCH NEXT FROM emp_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name
FETCH NEXT FROM emp_cursor INTO @name
END
CLOSE emp_cursor
DEALLOCATE emp_cursor
Cursors:
When working with explicit cursors in PL/SQL, loops are commonly used to fetch and
process each row from the result set.
v_name employee.name%TYPE;
v_salary employee.salary%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_name, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;
CLOSE emp_cursor;
END;
CLOSE emp_cursor;
END;
sql
CopyEdit
DECLARE
CURSOR emp_cursor IS
SELECT name, salary FROM employee;
BEGIN
FOR emp_record IN emp_cursor LOOP
DBMS_OUTPUT.PUT_LINE('Name: ' || emp_record.name || ', Salary: ' ||
emp_record.salary);
END LOOP;
END;