Database Management Systems
7th SEMESTER
OCSE-407T
UNIT II
Department of Electronics and Communication , BVCOE New Delhi
1
Unit 2
SYLLABUS
Enhanced ER concepts -
• Specialization/Generalization, Aggregation,
• Mapping of ER model to Relational Model
SQL –
• Functions ‐ aggregate functions
• Built‐in functions – numeric, date, string functions, set operations
• Sub queries, correlated sub‐queries
• Use of group by, having, order by,
• Join and its types, Exist, Any, All ,
• View and its types
• Transaction control commands Commit, Rollback, Save point
2 Department of Electronics and Communication Engineering , BVCOE New Delhi
Introduction to RDBMS
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.
3 Department of Electronics and Communication , BVCOE New Delhi
1) What is Relational Model?
2) Relational Model represents how data is stored in
Relational Databases. A relational database stores data
in the form of relations (tables).
3) Consider a relation STUDENT with attributes
ROLL_NO, NAME, ADDRESS, PHONE and AGE
shown in the diagram:
Department of Electronics and Communication , BVCOE New Delhi
4
5 Department of Electronics and Communication , BVCOE New Delhi
Explanation:
Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME
Relation Schema: A relation schema represents name of the
relation with its attributes. e.g.; STUDENT (ROLL_NO,
NAME, ADDRESS, PHONE and AGE) is relation schema for
STUDENT. If a schema has more than 1 relation, it is called
Relational Schema.
Tuple: Each row in the relation is known as tuple. The above
relation contains 4 tuples, one of which is shown as:
1 RAM DELHI 9455123451 18
6 Department of Electronics and Communication , BVCOE New Delhi
Relation Instance: The set of tuples of a relation at a particular instance
of time is called as relation instance. Table 1 shows the relation instance
of STUDENT at a particular time. It can change whenever there is
insertion, deletion or updation in the database.
Degree: The number of attributes in the relation is known as degree of
the relation. The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality.
The STUDENT relation defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute.
The column ROLL_NO is extracted from relation STUDENT.
NULL Values: The value which is not known or unavailable is called NULL
value. It is represented by blank space. e.g.; PHONE of STUDENT having
ROLL_NO 4 is NULL.
7 Department of Electronics and Communication , BVCOE New Delhi
Constraints in Relational Model
While designing Relational Model, we define some conditions which must hold for data
present in database are called Constraints. These constraints are checked before
performing any operation (insertion, deletion and updation) in database. If there is a
violation in any of constrains, operation will fail.
Domain Constraints: These are attribute level constraints. An attribute can only take
values which lie inside the domain range. e.g,; If a constrains AGE>0 is applied on
STUDENT relation, inserting negative value of AGE will result in failure.
Key Integrity: Every relation in the database should have atleast one set of attributes
which defines a tuple uniquely. Those set of attributes is called key. e.g.; ROLL_NO in
STUDENT is a key. No two students can have same roll number. So a key has two
properties:
It should be unique for all tuples.
It can’t have NULL values.
8 Department of Electronics and Communication , BVCOE New Delhi
9 Department of Electronics and Communication , BVCOE New Delhi
BRANCH_CODE of STUDENT can only take the values
which are present in BRANCH_CODE of BRANCH which
is called referential integrity constraint.
The relation which is referencing to other relation is called
REFERENCING RELATION (STUDENT in this case) and
the relation to which other relations refer is called
REFERENCED RELATION (BRANCH in this case).
Department of Electronics and Communication , BVCOE
10 New Delhi
Department of Electronics and Communication , BVCOE
11 New Delhi
Department of Electronics and Communication , BVCOE
12 New Delhi
After observing the differences between DBMS and RDBMS,
you can say that RDBMS is an extension of DBMS.
There are many software products in the market today who
are compatible for both DBMS and RDBMS. Means today a
RDBMS application is DBMS application and vice-versa.
Department of Electronics and Communication , BVCOE
13 New Delhi
Relational Model Concept
Relational model can represent as a table with columns and rows.
Each row is known as a tuple. Each table of the column has a name
or attribute.
Domain: It contains a set of atomic values that an attribute can
take.
Attribute: It contains the name of a column in a particular table.
Each attribute Ai must have a domain, dom(Ai)
Relational instance: In the relational database system, the
relational instance is represented by a finite set of tuples. Relation
instances do not have duplicate tuples.
Department of Electronics and Communication , BVCOE
14 New Delhi
Relational schema: A relational schema contains the name of
the relation and name of all columns or attributes.
Relational key: In the relational key, each row has one or
more attributes. It can identify the row in the relation
uniquely.
Department of Electronics and Communication , BVCOE
15 New Delhi
Department of Electronics and Communication , BVCOE
16 New Delhi
In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS,
and AGE are the attributes.
The instance of schema STUDENT has 5 tuples.
t3 = <Laxman, 33289, 8583287182, Gurugram, 20>
Properties of Relations
Name of the relation is distinct from all other relations.
Each relation cell contains exactly one atomic (single) value
Each attribute contains a distinct name
Attribute domain has no significance
tuple has no duplicate value
Order of tuple can have a different sequence
Department of Electronics and Communication , BVCOE New Delhi
17
Relational Algebra
Relational algebra is a procedural query language. It gives a
step by step process to obtain the result of the query. It uses
operators to perform queries.
Department of Electronics and Communication , BVCOE New Delhi
18
1. Select Operation:
The select operation selects tuples that satisfy a given
predicate.
It is denoted by sigma (σ).
Notation: σ p(r)
Where:
σ is used for selection prediction
r is used for relation
p is used as a propositional logic formula which may use
connectors like: AND OR and NOT. These relational can use
as relational operators like =, ≠, ≥, <, >, ≤.
Department of Electronics and Communication , BVCOE
19 New Delhi
For example: LOAN Relation
Department of Electronics and Communication , BVCOE
20 New Delhi
Explanation:
Department of Electronics and Communication , BVCOE
21 New Delhi
2. Projection Operation:
• This operation shows the list of those attributes
that we wish to appear in the result. Rest of the
attributes are eliminated from the table.
• It is denoted by ∏.
1. Notation: ∏ A1, A2, An (r)
Where
A1, A2, A3 is used as an attribute name of
relation r.
Department of Electronics and Communication , BVCOE
22 New Delhi
Example: CUSTOMER RELATION
23 Department of Electronics and Communication , BVCOE New Delhi
Explanation:
Department of Electronics and Communication , BVCOE
24 New Delhi
3. Union Operation:
• Suppose there are two tuples R and S. The union
operation contains all the tuples that are either in
R or S or both in R & S.
• It eliminates the duplicate tuples. It is denoted by
∪.
1. Notation: R ∪ S
A union operation must hold the following
condition:
• R and S must have the attribute of the same
number.
• Duplicate tuples are eliminated automatically.
Department of Electronics and Communication , BVCOE
25 New Delhi
Example:
Department of Electronics and Communication , BVCOE
26 New Delhi
Example:
Department of Electronics and Communication , BVCOE
27 New Delhi
Department of Electronics and Communication , BVCOE
28 New Delhi
4. Set Intersection:
• Suppose there are two tuples R and S. The set
intersection operation contains all tuples that are
in both R & S.
• It is denoted by intersection ∩.
Notation: R ∩ S
Department of Electronics and Communication , BVCOE
29 New Delhi
Example
Using the previous DEPOSITOR table and
BORROW table
Department of Electronics and Communication , BVCOE
30 New Delhi
5. Set Difference:
• Suppose there are two tuples R and S. The set
intersection operation contains all tuples that are
in R but not in S.
• It is denoted by intersection minus (-).
Notation: R - S
Department of Electronics and Communication , BVCOE
31 New Delhi
Example
Using the previous DEPOSITOR table and
BORROW table
Department of Electronics and Communication , BVCOE
32 New Delhi
6. Cartesian Product:
•
The Cartesian product is used to combine each
row in one table with each row in the other table.
It is also known as a cross product.
• It is denoted by X.
1. Notation: E X D
Department of Electronics and Communication , BVCOE
33 New Delhi
Example:
Department of Electronics and Communication , BVCOE
34 New Delhi
7. Rename Operation:
The rename operation is used to rename the
output relation. It is denoted by rho (ρ).
Example: We can use the rename operator to
rename STUDENT relation to STUDENT1.
1. ρ(STUDENT1, STUDENT)
Note: Apart from these common operations
Relational algebra can be used in Join
operations.
Department of Electronics and Communication , BVCOE
35 New Delhi
36 Department of Electronics and Communication , BVCOE New Delhi
Types of Relational Model:
Depending on the data you're working with, you can set up
one of several relational database models.
In each of these models, however, you need to differentiate
between a child table (also called a dependent table or a
controlled table) and a parent table (also called a primary
table or a controlling table).
The child table is the one that is dependent on the parent
table to fill in the definition of its records.
The Contacts table, for example, is a child table because it is
dependent on the Companies table for the company
information associated with each person.
Department of Electronics and Communication , BVCOE
37 New Delhi
The One-To-Many Model
The most common relational model is one where a single record in the
parent table relates to multiple records in the child table.
This is called a one-to-many relationship. The sales leads example is a
one-to-many relationship because one record in the Companies table can
relate to many records in the Contacts table.
In these models, the "many" table is the one where you add the foreign
key.
Another example of a one-to-many relationship is an application that
tracks accounts- receivable invoices.
You need one table for the invoice data (Invoices) and another for the
customer data (Customers). In this case, one customer can place many
orders, so Customers is the parent table, Invoices is the child table, and
the common field is the Customer table's primary key.
Department of Electronics and Communication , BVCOE
38 New Delhi
I The One-to-One Model
If your data requires that one record in the parent table be related to only one
record in the child table, you have a one-to-one model.
The most common use of one-to-one relations is to create separate entity
classes to enhance security.
In a hospital, for example, each patient's data is a single entity class, but it makes
sense to create separate tables for the patient's basic information (such as the
name, address, and so on) and his or her medical history.
This enables you to add extra levels of security to the confidential medical data
(such as a password). The two tables then become related based on a common
"PatientID" key field.
Department of Electronics and Communication , BVCOE
39 New Delhi
Another example of a one-to-one model is employee
[Link] separate the less-sensitive information such as
job title and startup date into one table, and restricted
information such as salary and commissions into a
second table. If each employee has a unique identification
number, you use that number to set up a relationship
between the two tables.
Note that in a one-to-one model, the concepts of child
and parent tables are interchangeable. Each table relies
on the other to form the complete picture of each
patient or employee.
Department of Electronics and Communication , BVCOE
40 New Delhi
The Many-to-Many Model
In some cases, you might have data in which many records in
one table can relate to many records in another table. This is
called a many-to-many relationship. In this case, there is no
direct way to establish a common field between the two
tables. To see why, let's look at an example from a pared-
down accounts-receivable application.
Table 3.6 shows a simplified structure of an Invoices table. It
includes a primary key—InvoiceID—as well as a foreign
key—CustomerID—from a separate table of customer
information.
Department of Electronics and Communication , BVCOE
41 New Delhi
Department of Electronics and Communication , BVCOE
42 New Delhi
Explanation:
The idea here is that a given product can appear in many invoices,
and any given invoice can contain many products.
This is a many-to-many relationship, and it implies that both tables
are parents . But relational theory says that a child table is needed
to establish a common field.
In this case, the solution is to set up a third table—called a
relation table—that is the child of both the original tables. In the
ongoing example, the relation table contains the detail data for
each invoice.
Table 3.8 shows the structure of such a table. As you can see, the
table includes foreign keys from both Invoices (InvoiceID) and
Products (ProductID), as well as a Quantity field.
Department of Electronics and Communication , BVCOE
43 New Delhi
Tabular Representation:
Department of Electronics and Communication , BVCOE
44 New Delhi
Keys in Relational Model:
Keys are very important part of Relational database model.
They are used to establish and identify relationships between
tables and also to uniquely identify any record or row of data
inside a table.
A Key can be a single attribute or a group of attributes,
where the combination may act as a key.
Department of Electronics and Communication , BVCOE
45 New Delhi
Why we need a Key?
In real world applications, number of tables required for storing the data
is huge, and the different tables are related to each other as well.
Also, tables store a lot of data in them. Tables generally extends to
thousands of records stored in them, unsorted and unorganised.
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.
Department of Electronics and Communication , BVCOE
46 New Delhi
Example:
Let's take a simple Student table, with fields student_id, name, phone and age.
Department of Electronics and Communication , BVCOE
47 New Delhi
Super Key
Super Key is defined as a set of attributes within a table that can uniquely
identify each record within a table. Super Key is a superset of Candidate key.
In the table defined super key would include student_id, (student_id, name),
phone etc.
Confused? The first one is pretty simple as student_id is unique for every row of
data, hence it can be used to identity each row uniquely.
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.
Similarly, phone number for every student will be unique, hence again, phone
can also be a key.
So they all are super keys.
Department of Electronics and Communication , BVCOE
48 New Delhi
Candidate 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 candidate 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).
Department of Electronics and Communication , BVCOE
49 New Delhi
Primary Key
Primary key is a candidate key that is most appropriate to
become the main key for any table. It is a key that can
uniquely identify each record in a table.
For the table Student we can make the student_id column as the primary key.
Department of Electronics and Communication , BVCOE
50 New Delhi
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.
Department of Electronics and Communication , BVCOE
51 New Delhi
In the previous 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.
Department of Electronics and Communication , BVCOE
52 New Delhi
Secondary or Alternative key
The candidate key which are not selected as primary key are
known as secondary keys or alternative keys.
Non-key Attributes
Non-key attributes are the attributes or fields of a table,
other than candidate key attributes/fields in a table.
Non-prime Attributes
Non-prime Attributes are attributes other than Primary Key
attribute(s)..
Department of Electronics and Communication , BVCOE
53 New Delhi
Additional Operations in Relational
Algebra-
Additional operations in relational algebra are as below –
Set Intersection operation
Division operation
Assignment operation
Natural Join operation:
Left Outer Join Operation
Right Outer Join Operation
Full Outer Join Operation
Department of Electronics and Communication , BVCOE
54 New Delhi
Tables used for Examples
Note –We are going to use below relation tables to show
different dbms relational algebra examples. These tables will
be used for different examples shown in this post.
Department of Electronics and Communication , BVCOE
55 New Delhi
Explanation:
Department of Electronics and Communication , BVCOE
56 New Delhi
Types:
The first additional relational algebra operations in dbms is
Set intersection operation –
Let’s say you have two relation tables A and B. Now, what if
you are asked to find out the common tuples in tables A and
B. How can you achieve it?
To make this task easier, there is an operation defined in
relational algebra. This is called set intersection operation.
Department of Electronics and Communication , BVCOE
57 New Delhi
(1) Set Intersection Operation (∩)
Set Intersection operation selects common tuples from the
two relations. It is denoted by (∩)
Necessary condition to apply set intersection operation –
For set intersection operation, the two-argument relation
must be compatible relation.
So, if R and S are two relations, P = R ∩ S has tuples drawn
from R and S, such that each tuple in P is in R and S.
Department of Electronics and Communication , BVCOE
58 New Delhi
Notation of Set Intersection Operation
P=R∩S
Where, P = result of set intersection operation,
R and S are relations on which set intersection operation has
been applied.
Consider R and S relation shown at start of the post,
Result after applying set intersection operation in R and S
relations –
Department of Electronics and Communication , BVCOE
59 New Delhi
(2) Division Operation (÷)
Division operation is denoted by ÷ sign. It is useful in
queries, which involve the phrase “for all objects having all
the specified properties”.
Let R (R-Schema) and S(S-Schema) are relations and any
attribute of S – Schema is also in R – Schema. The relation
R / S is a relation on schema R-Schema – S-Schema i.e. on
the schema containing all the attributes of Schema R that are
not in Schema S.
Department of Electronics and Communication , BVCOE
60 New Delhi
Division operation R ÷ S can only be applied if and only if –
Attributes of S is proper subset of Attributes of R.
The relation returned by division operator will have
attributes = (All attributes of R – All Attributes of S)
The relation returned by division operator will return those
tuples from relation R which are associated to every S’s
tuple.
Department of Electronics and Communication , BVCOE
61 New Delhi
Notation of Division Operation
P=R÷S
Where,
P is result we get after applying division operator,
R and S stands for relation (name of the tables) on which
division operation is applied.
Department of Electronics and Communication , BVCOE
62 New Delhi
Assignment operation –
Suppose you wish to assign result of an expression into a relation R. How would
you denote it?
For such work, we use assignment operator (←).
Notation of Assignment Operator
Relational Variable ← Expression.
R ← E.
Where,
R is relation,
r stands for relation variable.
E is Expression whose result we wish to assign to relation variable
R.
The result of the expression to the right hand side of ← is assigned
to relation variable on the left side of ←.
Department of Electronics and Communication , BVCOE
63 New Delhi
4) Natural Join Operation (⋈)
It is denoted by the join symbol ⋈. The natural join operation
forms a Cartesian product of its two arguments,
performs selection forcing equality on those attributes that appear
in both relation schema, and finally removes
duplicate attributes. Natural join can be defined as:
Notation of Natural Join Operation
P=R⋈S
Where,
Pis resultant relation after applying natural join operation on R
and S,
R and S stands for relation (name of the table)
Department of Electronics and Communication , BVCOE
64 New Delhi
Employee relation
Department of Electronics and Communication , BVCOE
65 New Delhi
Tabular Representation:
Department of Electronics and Communication , BVCOE
66 New Delhi
(5) Outer Join Operation
The outer join operation is an extension of the join operation
to deal with missing information.
Suppose we have the relations with the following schemas
which contain data on permanent doctors.
Doctors (doc-id, name)
Permanent-doc (doc-id, address, birthdate, sal)
Department of Electronics and Communication , BVCOE
67 New Delhi
Doctor relation
Department of Electronics and Communication , BVCOE
68 New Delhi
Permanent Document
relation
It contains id, address, birth date and salary of doctors.
Suppose we wish to generate a single relation with all the information (Name, address, birthdate,
sal) about Permanent doctors.
One approach would be to use Natural-Join operation as follows:
= (Doctors ⋈ Permanent-Doc)
Department of Electronics and Communication , BVCOE
69 New Delhi
Department of Electronics and Communication , BVCOE
70 New Delhi
It is seen that, we have information about Doctor with docid=3 and his
address, birthdate, sal. Since the tuple describing docid=3, is absent in
Permanent-doc. Similarly we have lost the name of docid=5, since the
tuple describing docid=5, is absent from Doctors relation.
The outer join operation can be used to avoid this loss of information.
There are 3 forms of the operation.
Left outer join
Right outer join
Full outer join
All these 3 forms of join compute the join and add extra tuples to the
result of join
Department of Electronics and Communication , BVCOE
71 New Delhi
5.1 Left Outer Join Operation (⟕)
The left outer join takes all tuples in the left relation that did
not match with any tuple in the right relation pads the tuples
with NULL values for all other attributes from the right
relation, and adds them to the result of natural join.
Notation of Left Outer Join Operation
P=R⟕S
Where,
Pis resultant relation after applying natural join operation on
R and S,
R and S stands for relation (name of the table).
Department of Electronics and Communication , BVCOE
72 New Delhi
Department of Electronics and Communication , BVCOE
73 New Delhi
5.2 Right Outer Join Operation (⟖)
The right outer join is symmetric with the left outer join.
Tuples from the right relation that did not match any from
the left relation are padded with Nulls and added to the
result of Natural join.
Notation of Right Outer Join Operation
P=R⟖S
Where,
Pis resultant relation after applying natural join operation on
R and S,
R and S stands for relation (name of the table).
Department of Electronics and Communication , BVCOE
74 New Delhi
Tabular Representation
Department of Electronics and Communication , BVCOE
75 New Delhi
Introduction to SQL
SQL is a standard language for accessing and manipulating
databases.
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards
Institute (ANSI) in 1986, and of the International
Organization for Standardization (ISO) in 1987
Department of Electronics and Communication , BVCOE
76 New Delhi
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
77 Department of Electronics and Communication , BVCOE New Delhi
SQL Commands
• SQL commands are instructions. It is used to
communicate with the database. It is also used to
perform specific tasks, functions, and queries of
data.
• SQL can perform various tasks like create a table,
add data to tables, drop the table, modify the
table, set permission for users.
Department of Electronics and Communication , BVCOE
78 New Delhi
Types of SQL Commands
Department of Electronics and Communication , BVCOE
79 New Delhi
SQL is a Standard
Although SQL is an ANSI/ISO standard, there are different
versions of the SQL language.
However, to be compliant with the ANSI standard, they all
support at least the major commands (such as SELECT,
UPDATE, DELETE, INSERT, WHERE) in a similar manner.
Department of Electronics and Communication , BVCOE
80 New Delhi
Continuation:
SQL comes in many flavors. Oracle databases use its proprietary PL/SQL.
Microsoft SQL Server makes use of Transact-SQL. All of the variations are
based upon the industry standard ANSI SQL.
DDL and DML
SQL commands can be divided into two main sub-
languages.
The Data Definition Language contains the commands
used to create and destroy databases and database
objects.
After the database structure is defined with DDL,
database administrators and users can use the Data
Manipulation Language to insert, retrieve and modify
the data contained within it.
Department of Electronics and Communication , BVCOE
81 New Delhi
SQL supports a third type of syntax called Data Control
Language.
DCL governs security access to objects within the database.
For example, a DCL script grants or revokes specific user
accounts the right to read or write to tables within one or
more defined areas of the database.
In most managed multi-user environments, database
administrators usually execute DCL scripts.
Department of Electronics and Communication , BVCOE
82 New Delhi
Data Definition Language Commands
The Data Definition Language is used to create
and destroy databases and database objects.
These commands are primarily used by database
administrators during the setup and removal
phases of a database project. DDL revolves
around four primary commands—
create, use, alter, and drop.
Department of Electronics and Communication , BVCOE
83 New Delhi
Create command
The create command establishes databases, tables, or queries
on your platform. For example, the command:
CREATE DATABASE employees;
creates an empty database named employees on your DBMS.
After creating the database, the next step is to create tables
that contain data. Another variant of the create command
accomplishes this purpose. The command:
CREATE TABLE personal_info (first_name char(20) not
null, last_name char(20) not null, employee_id int not null);
Department of Electronics and Communication , BVCOE
84 New Delhi
establishes a table titled personal_info in the current
database. In the example, the table contains three attributes:
first_name, last_name, and employee_id along with some
additional information.
Department of Electronics and Communication , BVCOE
85 New Delhi
Use command
The use command specifies the active database. For example,
if you're currently working in the sales database and want to
issue some commands that will affect the employee database,
preface them with the following SQL command:
USE employees;
Double-check the database you're working in before issuing
SQL commands that manipulate data.
Department of Electronics and Communication , BVCOE
86 New Delhi
Alter
After you've created a table within a database, modify its definition
through the alter command, which changes to the structure of a
table without deleting and recreating it. Take a look at the
following command:
ALTER TABLE personal_info ADD salary money null;
This example adds a new attribute to the personal_info table—an
employee's salary. The money argument specifies that an
employee's salary stores using a dollars and cents format. Finally,
the null keyword tells the database that it's OK for this field to
contain no value for any given employee.
Department of Electronics and Communication , BVCOE
87 New Delhi
Drop
The final command of the Data Definition Language, drop, removes entire
database objects from our DBMS. For example, to permanently remove the
personal_info table that we created, use the following command:
DROP TABLE personal_info;
Similarly, the command below would be used to remove the entire employee
database:
DROP DATABASE employees;
Use this command with care. The drop command removes entire data
structures from your database. If you want to remove individual records, use
the delete command of the Data Manipulation Language.
Department of Electronics and Communication , BVCOE
88 New Delhi
Data Manipulation Language Commands
The Data Manipulation Language is used to retrieve, insert and modify database
information. These DML commands offer the typical framework for interacting wihtin
the database on a routine basis.
Insert
The insert command adds records to an existing table. Returning to the personal_info
example from the previous section, imagine that our HR department needs to add a new
employee to its database. Use a command similar to this one:
INSERT INTO personal_info
values('bart','simpson',12345,$45000);
Note that there are four values specified for the record. These correspond to the table
attributes in the order they were defined: first_name, last_name, employee_id and
salary.
Department of Electronics and Communication , BVCOE
89 New Delhi
Select
The select command is the most commonly used command in SQL. It retrieves
specific information from an operational database. Take a look at a few
examples, again using the personal_info table from the employee database.
The command shown below retrieves all the information contained within the
personal_info table. The asterisk is a wildcard character in SQL.
SELECT *
FROM personal_info;
Alternatively, limit the attributes that are retrieved from the database by
specifying what gets selected. For example, the Human Resources department
may require a list of the last names of all employees in the company. The
following SQL command would retrieve only that information:
Department of Electronics and Communication , BVCOE
90 New Delhi
SELECT last_name
FROM personal_info;
The where clause limits the records that are retrieved to those that
meet specified criteria. The CEO might be interested in reviewing
the personnel records of all highly paid employees. The following
command retrieves all of the data contained within personal_info
for records that have a salary value greater than $50,000:
SELECT *
FROM personal_info
WHERE salary > $50000;
Department of Electronics and Communication , BVCOE
91 New Delhi
Update
The update command modifies the information contained within a table, either in bulk
or individually. Assume the company gives all employees a 3 percent cost-of-living
increase in their salary annually. The following SQL command applies this bump to all
the employees stored in the database:
UPDATE personal_info
SET salary = salary * 1.03;
When the new employee Bart Simpson demonstrates performance above and beyond the
call of duty, management wishes to recognize his stellar accomplishments with a $5,000
raise. The WHERE clause singles out Bart for this raise:
UPDATE personal_info
SET salary = salary + 5000
WHERE employee_id = 12345;
Department of Electronics and Communication , BVCOE
92 New Delhi
Delete
Finally, let's take a look at the delete [Link]'ll find that the syntax of this
command is similar to that of the other DML commands. The DELETE
command, with a where clause, remove a record from a table:
DELETE FROM personal_info
WHERE employee_id = 12345;
DML supports aggregate fields, too. In a select statement, mathematical
operators like sum and count summarize data within a query. For example, the
query:
select count(*) from personal_info;
counts the number of records in the table.
Department of Electronics and Communication , BVCOE
93 New Delhi
3. Data Control Language
DCL commands are used to grant and take back authority
from any database user.
Here are some commands that come under DCL:
Grant
Revoke
Department of Electronics and Communication , BVCOE
94 New Delhi
a. Grant: It is used to give user access privileges to a
database.
Example
1. GRANT SELECT, UPDATE ON MY_TABLE TO SOM
E_USER, ANOTHER_USER;
2. b. Revoke: It is used to take back permissions
from the user.
3. Example
4. REVOKE SELECT, UPDATE ON MY_TABLE FROM
USER1, USER2;
Department of Electronics and Communication , BVCOE
95 New Delhi
4. Transaction Control Language
TCL commands can only use with DML commands like INSERT,
DELETE and UPDATE only.
These operations are automatically committed in the database
that's why they cannot be used while creating tables or dropping
them.
Here are some commands that come under TCL:
COMMIT
ROLLBACK
SAVEPOINT
Department of Electronics and Communication , BVCOE
96 New Delhi
A. Commit
a. Commit: Commit command is used to save all the transactions
to the database.
Syntax:
COMMIT;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
Department of Electronics and Communication , BVCOE
97 New Delhi
B. Rollback
b. Rollback: Rollback command is used to undo transactions that
have not already been saved to the database.
Syntax:
ROLLBACK;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
Department of Electronics and Communication , BVCOE
98 New Delhi
c. SAVEPOINT
c. SAVEPOINT: It is used to roll the transaction back to a
certain point without rolling back the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Department of Electronics and Communication , BVCOE
99 New Delhi
5. Data Query Language
DQL is used to fetch the data from the database.
It uses only one command:
SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It
is used to select the attribute based on the condition described by WHERE
clause.
Syntax:
SELECT expressions
FROM TABLES
WHERE conditions;
Department of Electronics and Communication , BVCOE
100 New Delhi
For example:
For example:
SELECT emp_name
FROM employee
WHERE age > 20;
Department of Electronics and Communication , BVCOE
101 New Delhi
INTRODUCTION TO PL/SQL Concept
PL/SQL is a combination of SQL along with the procedural
features of programming languages.
It was developed by Oracle Corporation in the early 90's to
enhance the capabilities of SQL.
PL/SQL is one of three key programming languages
embedded in the Oracle Database, along with SQL itself and
Java.
Department of Electronics and Communication , BVCOE
102 New Delhi
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.
Department of Electronics and Communication , BVCOE
103 New Delhi
Features of PL/SQL
PL/SQL is tightly integrated with SQL.
It offers extensive error checking.
It offers numerous data types.
It offers a variety of programming structures.
It supports structured programming through functions and
procedures.
It supports object-oriented programming.
It supports the development of web applications and server
pages.
Department of Electronics and Communication , BVCOE
104 New Delhi
Advantages of PL/SQL
SQL is the standard database language and PL/SQL is strongly integrated with SQL.
PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations
and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding
DDL statements in PL/SQL blocks.
PL/SQL allows sending an entire block of statements to the database at one time. This
reduces network traffic and provides high performance for the applications.
PL/SQL gives high productivity to programmers as it can query, transform, and update
data in a database.
PL/SQL saves time on design and debugging by strong features, such as exception
handling, encapsulation, data hiding, and object-oriented data types.
Applications written in PL/SQL are fully portable.
Department of Electronics and Communication , BVCOE
105 New Delhi
PL/SQL provides high security level.
PL/SQL provides access to predefined SQL packages.
PL/SQL provides support for Object-Oriented
Programming.
PL/SQL provides support for developing Web Applications
and Server Pages.
Department of Electronics and Communication , BVCOE
106 New Delhi
PL/SQL Syntax
Tthe 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
Department of Electronics and Communication , BVCOE
107 New Delhi
SYNTAX:
Department of Electronics and Communication , BVCOE
108 New Delhi
Explanation:
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;
Department of Electronics and Communication , BVCOE
109 New Delhi
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
PL/SQL procedure successfully completed.
Department of Electronics and Communication , BVCOE
110 New Delhi
PL/SQL Cursor
When an SQL statement is processed,
Oracle creates a memory area known as context area. A cursor is a
pointer to this context area. It contains all information needed for
processing the statement. In PL/SQL, the context area is controlled by
Cursor.
A cursor contains information on a select statement and the rows of data
accessed by it.
A cursor is used to referred to a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of
cursors:
Implicit Cursors
Explicit Cursors
Department of Electronics and Communication , BVCOE
111 New Delhi
1) PL/SQL Implicit Cursors
The implicit cursors are automatically generated by Oracle
while an SQL statement is executed, if you don't use an
explicit cursor for the statement.
These are created by default to process the statements when
DML statements like INSERT, UPDATE, DELETE etc. are
executed
Department of Electronics and Communication , BVCOE
112 New Delhi
Explaination:
Orcale provides some attributes known as Implicit cursor's
attributes to check the status of DML operations. Some of
them are: %FOUND, %NOTFOUND, %ROWCOUNT and
%ISOPEN.
For example: When you execute the SQL statements like
INSERT, UPDATE, DELETE then the cursor attributes tell
whether any rows are affected and how many have been
affected. If you run a SELECT INTO statement in PL/SQL
block, the implicit cursor attribute can be used to find out
whether any row has been returned by the SELECT
statement. It will return an error if there no data is selected.
Department of Electronics and Communication , BVCOE
113 New Delhi
The following table specifies the
status of the cursor with each of its
attribute.
Department of Electronics and Communication , BVCOE
114 New Delhi
PL/SQL Implicit Cursor Example
Create customers table and have records:
Department of Electronics and Communication , BVCOE
115 New Delhi
Let's execute the following program to update the table and
increase salary of each customer by 5000. Here,
SQL%ROWCOUNT attribute is used to determine the
number of rows affected:
Department of Electronics and Communication , BVCOE
116 New Delhi
Create procedure:
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Department of Electronics and Communication , BVCOE
117 New Delhi
Output:
6 customers updated
PL/SQL procedure successfully completed.
Now, if you check the records in customer table, you will
find that the rows are updated.
Department of Electronics and Communication , BVCOE
118 New Delhi
Representation:
Department of Electronics and Communication , BVCOE
119 New Delhi
2) PL/SQL Explicit Cursors
The Explicit cursors are defined by the programmers
to gain more control over the context area. These
cursors 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.
Following is the syntax to create an explicit cursor:
Syntax of explicit cursor
Following is the syntax to create an explicit cursor:
1. CURSOR cursor_name IS select_statement;;
Department of Electronics and Communication , BVCOE
120 New Delhi
Steps:
You must follow these steps while working with an explicit
cursor.
Declare the cursor to initialize in the memory.
Open the cursor to allocate memory.
Fetch the cursor to retrieve data.
Close the cursor to release allocated memory.
Department of Electronics and Communication , BVCOE
121 New Delhi
1) Declare the cursor:
It defines the cursor with a name and the associated SELECT
statement.
Syntax for explicit cursor decleration
CURSOR name IS
SELECT statement;
2) Open the cursor:
It is used to allocate memory for the cursor and make it easy to
fetch the rows returned by the SQL statements into it.
Syntax for cursor open:
OPEN cursor_name;
Department of Electronics and Communication , BVCOE
122 New Delhi
3) Fetch the cursor:
It is used to access one row at a time. You can fetch rows
from the above-opened cursor as follows:
Syntax for cursor fetch:
FETCH cursor_name INTO variable_list;
4) Close the cursor:
It is used to release the allocated memory. The following
syntax is used to close the above-opened cursors.
Syntax for cursor close:
Close cursor_name;
Department of Electronics and Communication , BVCOE
123 New Delhi
PL/SQL Explicit Cursor Example
Explicit cursors are defined by programmers to
gain more control over the context area. It is
defined in the declaration section of the PL/SQL
block. It is created on a SELECT statement which
returns more than one row.
Let's take an example to demonstrate the use of
explicit cursor. In this example, we are using the
already created CUSTOMERS table.
Department of Electronics and Communication , BVCOE
124 New Delhi
Department of Electronics and Communication , BVCOE
125 New Delhi
Create procedure:
Department of Electronics and Communication , BVCOE
126 New Delhi
OUTPUT:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.
127 Department of Electronics and Communication , BVCOE New Delhi