Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

DBMS UNIT-II

UNIT-II Relational Algebra, Calculus & Basic SQL

Relational Algebra, Relational Operations, Relational Calculus, Tuple And Domain Relational
Calculus.
PL/ SQL : Database Languages, Data Types, Integrity Constraints, Simple And Nested Queries,
Implementation Of Different Types Of Joins, Stored Procedures

Relational Algebra and Calculus

Introduction of Relational Algebra in DBMS

Relational Algebra is procedural query language. which takes One or two Relation as input and
generate new relation as output. It gives a step by step process to obtain the result of the query. It
uses operators to perform queries. Relational algebra mainly provides theoretical foundation for
relational databases and SQL.The fundamental operations of relational algebra are as follows
1.Unary Relational Operations

 Select (symbol: σ)
 Project (symbol: π)
 Rename (symbol: ρ)

2. Relational Algebra Operations From Set Theory

 Union (υ)
 Intersection (∩),
 Difference (-)
 Cartesian Product ( x )

3.Binary Relational Operations

 Join
 Division

I. Unary Relational Operations

1. Select Operation (σ):Relational algebra includes operators to select rows from a relation (σ).The
select operation selects tuples that satisfy a given predicate. It is denoted by lower greek letter 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 =, ≠, ≥, <, >, ≤.
example: σrating>8(S2)
2. Project Operation :(π) : The projection operator π allows us to extract columns from a relation.
Projection is used to project required column data from a relation. It is denoted by π. Notation: ∏ A1,
A2, An (r) Where A1, A2, A3 is used as an attribute name of relation r. This operation shows the list
of those attributes that we wish to appear in the result. projection method defines a relation that contains
a vertical subset of Relation Rest of the attributes are eliminated from the table.
Note: By Default projection removes duplicate data.
DBMS UNIT-II
for example find out all sailor names and ratings by using π. The expression π sname ,rating(S2)

Suppose that we wanted to find out only the ages of sailors. The expression πage(S2)

3. Rename Operation: (ρ):

The rename operation is used to rename the output relation. It is denoted by rho (ρ).'rename'
operation is denoted with small Greek letter rho ρ. Notation − ρ x (E).Where the result of expression
E is saved with name of x. Rename is a unary operation used for renaming attributes of a relation

Example: We can use the rename operator to rename STUDENT relation to STUDENT1.

ρ(STUDENT1, STUDENT)

II. Set Operations

The following standard operations on sets are also available in relational algebra:

 Union(𝖴),
 Intersection (∩),
 Set-Difference (−), and
 Cross-Product (×).
Union: Notation: R 𝖴 S

Union operation in relational algebra is same as union operation in set theory, only constraint is for
union of two relation both relation must have same set of Attributes. R𝖴S returns a relation instance
containing all tuples that occur in either relation instance R or relation instance S (or both). It eliminates
the duplicate tuples. It is denoted by.Two relation instances are said to be union- compatible if the
following conditions hold: they have the same number of the fields, and corresponding fields, taken in
order from left to right, have the same domains.R and S must have the attribute of the same number.
Intersection: Notation: R ∩ S

R∩S returns a relation instance containing all tuples that occur in both R and S.The relations R and S
must be union-compatible, and the schema of the result is defined to be identical to the schema of R.
Set-difference: Notation: R - S 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 (-).R−S returns a
relation instance containing all tuples that occur in R but not in S. The relations R and S must be
union-compatible, and the schema of the result is defined to be identical to the schema of R.
Cross-product: Notation: E X D

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.R ×S returns a relation instance whose schema
contains all the fields of R (in the same order as they appear in R) followed by all the fields of S (in
the same order as they appear in S). The result of R × S contains one tuple <r, s> (the concatenation of
tuples r and s) for each pair of tuples r ∈ R, s ∈ S.The cross-product opertion is sometimes called
Cartesian product.
DBMS UNIT-II
3. Binary Relational Operations

 Join
 Division

JOINS:

A Join operation combines related tuples from different relations, if and only if a given join condition
is satisfied. It is denoted by ⋈.Join is used to fetch data from two or more tables. Join statement is used
to combine data or rows from two or more tables based on a common field between them . Although a
join can be defined as a cross-product followed by selections and projections,joins arise much more
frequently in practice than plain cross-products.by applying the selections and projections ‘on-the-
fly’

Different types of Joins are:

1. Natural Join
2. Outer join
3. Equi join
4. Conditional join

1. Natural Join:

 A natural join is the set of tuples of all combinations in R and S that are equal on their
common attribute names.
 It is denoted by ⋈.
 Natural join does not use any comparison operator.
 It does not concatenate the way a Cartesian product does. We can perform a Natural Join
only if there is at least one common attribute that exists between two relations.
 In addition, the attributes must have the same name and domain.
Natural join acts on those matching attributes where the values of attributes in both the relations
are same.Example: EMPLOYEE

EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
DBMS UNIT-II
SALARY

EMP_CODE SALARY
101 50000
102 30000
103 25000

Operation: (EMPLOYEE ⋈ SALARY)


Result:

EMP_CODE EMP_NAME SALARY


101 Stephan 50000
102 Jack 30000
103 Harry 25000
101 Stephan 50000
102 Jack 30000
103 Harry 25000

Example: EMPLOYEE table and SALARY table:

Input: ∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
Stephan 50000
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with missing
information. outer joins to include all the tuples from the participating relations in the resulting relation.
here are three kinds of outer joins − left outer join, right outer join, and full outer join.
Example: EMPLOYEE
EMP_NAM STREET CITY
E
Ram Civil line Mumbai
Shyam Park street Kolkata
Ravi M.G. Street Delhi
Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY


Ram Infosys 10000
Shyam Wipro 20000
Kuber HCL 30000
Hari TCS 50000

Input: (EMPLOYEE ⋈ FACT_WORKERS)


DBMS UNIT-II
Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000


Shyam Park street Kolkata Wipro 20000
Hari Nehru nagar Hyderabad TCS 50000

An outer join is basically of three types:

a. Left outer join


b. Right outer join
c. Full outer join or

a. Left outer join: (R S)


 Left outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
 In the left outer join, tuples in R have no matching tuples in S.
 It is denoted by ⟕.
 All the tuples from the Left relation, R, are included in the resulting relation.
 If there are tuples in R without any matching tuple in the Right relation S, then the S-
attributes of the resulting relation are made NULL.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:EMPLOYEE ⟕ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000


Shyam Park street Kolkata Wipro 20000
Hari Nehru street Hyderabad TCS 50000
Ravi M.G. Street Delhi NULL NULL

b. Right outer join: ( R S)


 Right outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
 In right outer join, tuples in S have no matching tuples in R.
 It is denoted by ⟖.
 All the tuples from the Right relation, S, are included in the resulting relation.
DBMS UNIT-II
 If there are tuples in S without any matching tuple in R, then the R-attributes of resulting
relation are made NULL.

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai


Shyam Wipro 20000 Park street Kolkata
Hari TCS 50000 Nehru street Hyderabad
Kuber HCL 30000 NULL NULL

c. Full outer join: ( R S)


 Full outer join is like a left or right join except that it contains all rows from both tables.
 In full outer join, tuples in R that have no matching tuples in S and tuples in S that have
no matching tuples in R in their common attribute name.
 It is denoted by ⟗.
 All the tuples from both participating relations are included in the resulting relation.
 If there are no matching tuples for both relations, their respective unmatched attributes are
made NULL.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:EMPLOYEE ⟗ FACT_WORKERS

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000


Shyam Park street Kolkata Wipro 20000
Hari Nehru street Hyderabad TCS 50000
Ravi M.G. Street Delhi NULL NULL
Kuber NULL NULL HCL 30000
3. Equi join: or inner join
It is also known as an inner join. It is the most common join. It is based on matched data as per the
equality condition. The equi join uses the comparison operator(=).join uses only equality comparison
operator, it is said to be equijoin

Example:
DBMS UNIT-II
CUSTOMER RELATION

CLASS_ID NAME

1 John
2 Harry
3 Jackson

PRODUCT

PRODUCT_ID CITY

1 Delhi
2 Mumbai
3 Noida

Input:CUSTOMER ⋈ PRODUCT

CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi
2 Harry 2 Mumbai
3 Harry 3 Noida

Condition Joins:
The most general version of the join operation accepts a join condition c and a pair of relation
instances as arguments, and returns a relation instance. The join condition is identical to a selection
condition in form. The operation is defined as follows: R ./c S = σc(R × S)
DIVISION:
Consider two relation instances A and B in which A has (exactly) two fields x and y and B has just one
field y, with the same domain as in A. We define the division operation A/B as the set of all x values (in
the form of unary tuples) such that for every y value in (a tuple of) B, there is a tuple hx,yi in A.

For each x value in (the first column of) A, consider the set of y values that appear in (the second field of)
tuples of A with that x value. If this set contains (all y values in) B, the x value is in the result of A/B.
For relation instances A and B, A/B is the largest relation instance Q such that Q × B ⊆ A.
DBMS UNIT-II
It helps to think of A as a relation listing the parts supplied by suppliers, and of the B relations as listing
parts. A/Bi computes suppliers who supply all parts listed in relation instance Bi
The basic idea is to compute all x values in A that are not disqualified. An x value is disqualified if by
attaching a y value from B, we obtain a tuple hx,yi that is not in A. We can compute disqualified tuples
using the algebra expression πx((πx(A)× B)−A) Thus we can define A/B as πx(A)−πx((πx(A)×B)−A).
Relational Calculus

Relational calculus is an alternative to relational algebra. Relational calculus is a non-procedural query


language. or declarative In the non-procedural query language, the user is concerned with the details
of how to obtain the end results. The relational calculus tells what to do but never explains how to do
Thus, it explains what to do but not how to do. Relational calculus has had a big influence on the design
of commercial query languages such as SQL and, especially, Query-by-Example (QBE).
Types of Relational calculus:
1. Tuple Relational Calculus (TRC)
2. Domain Relational Calculus (DRC)
Variables in TRC take on tuples as values. the domain relational calculus (DRC), the variables range
over field values.TRC has had more of an influence on SQL, while DRC has strongly influenced QBE
1. Tuple Relational Calculus (TRC)
Tuple Relational Calculus is a non-procedural query language. Tuple Calculus provides only the
description of the query but it does not provide the methods to solve it. every value assigned to a given
tuple variable has the same number and type of fields. In Tuple Calculus, a query is expressed as {t|
P(t)} where t = resulting tuples,
P(t) = known as Predicate and these are the conditions that are used to fetch t
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t. P(t) may have various
conditions logically combined with OR (∨), AND (𝖠), NOT(¬). It also uses quantifiers:
∃ t ∈ r (Q(t)) = "there exists" a tuple in t in relation r such that predicate Q(t) is true.
∀ t ∈ r (Q(t)) = Q(t) is true "for all" tuples in relation r.
Syntax of TRC Queries
Let Rel be a relation name, R and S be tuple variables, a an attribute of R, and b an attribute of S.Let
op denote an operator in the set {<, >, =, ≤, ≥, 6=}.
An atomic formula is one of the following:
 R ∈ Rel
 R.a op S.b
 R.a op constant, or constant op R.a
A formula is recursively defined to be one of the following, where p and q are themselves formulas,
and p(R) denotes a formula in which the variable R appears:
 any atomic formula
DBMS UNIT-II
 ¬p, p 𝖠 q, p ∨ q, or p ⇒ q
 ∃R(p(R)), where R is a tuple variable
 ∀R(p(R)), where R is a tuple variable
Examples of TRC Queries :
Find all sailors with a rating above 7 ?
{S | S ∈ Sailors 𝖠 S.rating > 7}
When this query is evaluated on an instance of the Sailors relation, the tuple variable S is instantiated
successively with each tuple, and the test S.rating>7 is applied. The answer contains those instances
of S that pass this test. On instance S3 of Sailors, the answer contains Sailors tuples with sid 31, 32,
58, 71, and 74.

1. Find all sailors with a rating above 7.


{S | S ∈ Sailors 𝖠 S.rating > 7}
On instance S3 of Sailors, the answer contains Sailors tuples with sid 31, 32, 58, 71, and 74.
2. Find the names and ages of sailors with a rating above 7.
{P | ∃S ∈ Sailors(S.rating > 7 𝖠 P.name = S.sname 𝖠 P.age = S.age)}
P is considered to be a tuple variable with exactly two fields, which are called name and age.
The result of this query is a relation with two fields, name and age.
The atomic formulas P.name = S.sname and P.age = S.age give values to the fields of an answer tuple P
On instances B1, R2, and S3, the answer is the set of tuples Lubber, 55.5, Andy, 25.5, Rusty, 35.0, Zorba,
16.0, and Horatio, 35.0
3. Find the sailor name, boat id, and reservation date for each reservation.
{P | ∃R ∈ Reserves ∃S ∈ Sailors (R.sid = S.sid 𝖠 P.bid = R.bid 𝖠 P.day = R.day 𝖠 P.sname = S.sname)}
Domain Relational Calculus:
Domain Relational Calculus is a non-procedural query language equivalent in power to Tuple Relational
Calculus. The second form of relation is known as Domain relational calculus. In domain relational
calculus, filtering variable uses the domain of attributes. Domain Relational Calculus provides only the
description of the query but it does not provide the methods to solve it.
A DRC query has the form: In Domain Relational Calculus, a query is expressed as,
{ < x1, x2, x3, ..., xn > | P (x1, x2, x3, ..., xn ) }
where, < x1, x2, x3, …, xn > represents resulting domains variables and P (x1, x2, x3, …, xn ) represents
the condition or formula equivalent to the Predicate calculus.
DBMS UNIT-II
Predicate Calculus Formula:
 Set of all comparison operators {<, >, =, ≤, ≥, }
 Set of connectives like and, or, not or Domain relational calculus uses the same operators as tuple
calculus.
 It uses logical connectives 𝖠 (and), ∨ (or) and ┓ (not).
 Set of quantifiers or It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.
Example:

(Q11) Find all sailors with a rating above 7.

T Sailors {〈I, N, T, A〉 | 〈I, N, T, A〉 > 7}

This differs from the TRC version in giving each attribute a (variable) name. The Sailors ensures that the
domain variables I, N , T , andcondition 〈 I, N, T, A 〉 A are restricted to be fields of the same tuple. In
comparison with the TRC query, we can say T > 7 instead of S.rating > 7, but we must specify the tuple 〈
I, N, T, A 〉 in the result, rather than just S.

(Q1) Find the names of sailors who have reserved boat 103.

{〈N 〉 | I, T, A(〈I, N, T, A〉 Sailors Ir, Br, D(〈Ir, Br, D〉 Reserves  Ir = I  Br = 103))}

(Q2) Find the names of sailors who have reserved a red boat.

{〈N 〉 | I, T, A(〈I, N, T, A〉 Sailors I, Br, D〉Reserves  〈Br, BN,′red′〉 Boats)}

(Q7) Find the names of sailors who have reserved at least two boats.

{〈N 〉 | I, T, A(〈I, N, T, A〉 Sailors  Br1, Br2, D1, D2(〈I, Br1, D1〉Reserves 〈I, Br2,D2 〉 Reserves  Br1 = Br2)

Notice how the repeated use of variable I ensure that the same sailor has reserved both the boats in question.

(Q9) Find the names of sailors who have reserved all boats.

{〈N〉 |I, T, A(〈I, N, T, A〉Sailors

B, BN, C(¬(〈B, BN, C〉Boats) 

(〈Ir, Br, D〉Reserves(I = Ir Br = B))))}

This query can be read as follows: “Find all values of N such that there is some tuple 〈 I, N,T,A 〉 in Sailors

satisfying the following condition: for every 〈 B, BN,C 〉 , either this is not a tuple in Boats or there is some

tuple 〈 Ir, Br, D 〉 in Reserves that proves that Sailor I has reserved boat B.” The ∀ quantifier allows the

domain variables B,BN, and C to range over all values in their respective attribute domains, and
DBMS UNIT-II

the pattern ‘¬( 〈 B, BN, C 〉Boats)∨ ’ is necessary to restrict attention to those values that appear in tuples

of Boats.

**************************************************************************************

PL/ SQL : Database Languages, Data Types, Integrity Constraints, Simple And Nested Queries,
Implementation Of Different Types Of Joins, Stored Procedures
Database Languages
A database system provides a data-definition language to specify the database schema and a data-
manipulation language to express database queries and updates. In practice, the data definition and data-
manipulation languages are not two separate languages; instead they simply form parts of a single database
language, such as the widely used SQL language.
Data-Manipulation Language
A data-manipulation language (DML) is a language that enables users to access or manipulate data as
organized by the appropriate data model. The types of access are:
• Retrieval of information stored in the database
• Insertion of new information into the database
• Deletion of information from the database
• Modification of information stored in the database
There are basically two types:
• Procedural DMLs require a user to specify what data are needed and how to get those data.
• Declarative DMLs (also referred to as nonprocedural DMLs) require a user to specify what data are needed
without specifying how to get those data.Declarative DMLs are usually easier to learn and use than are
procedural DMLs. However, since a user does not have to specify how to get the data, the database system
has to figure out an efficient means of accessing data. A query is a statement requesting the retrieval of
information. The portion of a DML that involves information retrieval is called a query language. Although
technically incorrect, it is common practice to use the terms query language and data- manipulation language
synonymously.
Data-Definition Language (DDL)
We specify a database schema by a set of definitions expressed by a special language called a data- definition
language (DDL). The DDL is also used to specify additional properties of the data. We specify the storage
structure and access methods used by the database system by a set of statements in a special type of DDL
called a data storage and definition language. These statements define the implementation details of the
database schemas, which are usually hidden from the users. The data values stored in the database must
satisfy certain consistency constraints. For example, suppose the university requires that the account balance
of a department must never be negative. The DDL provides facilities to specify such constraints. The database
system checks these constraints every time the database is updated. In general, a constraint can be an
arbitrary predicate pertaining to the database. However, arbitrary predicates may be
DBMS UNIT-II
costly to test. Thus, database systems implement integrity constraints that can be tested with minimal
overhead.
The Data Definition Language (DDL):
This feature supports the creation, deletion, and modification of definitions for tables and views. Integrity
constraints can be defined on tables, either when the table is created or later. The DDL also provides
commands for specifying access rights or privileges to tables and views. Although the standard does not
discuss indexes, commercial implementations also provide commands for creating and deleting indexes.
The Data Manipulation Language (DML):
This feature supports the insertion, deletion, updation and retrieval of the data from the database.
The Data Control Language (DCL):
This subset of SQL Restricts the Access among the Database. The Database Administrator can give access
over the Database to the users. The commands are Grant and Revoke .
DDL -- CREATE, ALTER, DROP, TRUNCATE, RENAME
CREATE TABLE Statement
The Oracle CREATE TABLE statement allows you to create and define a table.
Syntax:The syntax for the CREATE TABLE statement in Oracle/PLSQL is:
SQL create table with constraint syntax
CREATE TABLE table_name ( column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name, column_name3 data_type(size)
constraint_name, ...);
Parameters or Arguments:
<Table_name>: The name of the table that you wish to create.
<column1, column2, ... column_n>: The columns that you wish to create in the table.
Each column must have a datatype.
The column should either be defined as "null" or "not null" and
if this value is left blank, the database assumes "null" as the
default.
ALTER TABLE Statement :The Oracle ALTER TABLE statement is used to add, modify, or
drop/delete columns in a table. The Oracle ALTER TABLE statement is also used to rename a table.
Add column in table
Syntax :To add a single column in a table, the oracle alter table Syntax is:
ALTER TABLE table_name ADD column_name column-definition;
Syntax :Add multiple columns in table
To ADD MULTIPLE COLUMNS to an existing table, the Oracle ALTER TABLE syntax is:
ALTER TABLE table_name ADD ( column_1 column-definition,
column_2 column-definition, ... column_n column_definition);
Modify column in table :Syntax
ALTER TABLE table_name MODIFY column_name column_type;
DBMS UNIT-II
Modify Multiple columns in table : Syntax
syntax is:
ALTER TABLE table_name MODIFY( column_1 column_type, column_2 column_type, ...
column_n column_type);
Drop column in table
Syntax :Alter table table_Name Drop Column Column_name;
TRUNCATE TABLE Statement:
The TRUNCATE TABLE statement is used to remove all records from a table in Oracle. It performs
the same function as a DELETE statement without a WHERE clause.
Warning: If you truncate a table, the TRUNCATE TABLE statement cannot be rolled back.
Syntax
TRUNCATE TABLE [schema_name.] table_name
[ PRESERVE MATERIALIZED VIEW LOG | PURGE MATERIALIZED VIEW LOG ]
[ DROP STORAGE | REUSE STORAGE ] ;
Parameters or Arguments
schema_name :Optional. If specified, it is the name of the schema that the table belongs to.
table_name :The table that you wish to truncate.
Rename column in table:
Syntax :To rename a column in an existing table, the oracle alter table syntax is:
ALTER TABLE table_name RENAME COLUMN old_name to new_name;
Rename table
Syntax: alter table table_name rename to new_table_name;
DML : INSERT, UPDATE, DELETE
INSERT Statement: INSERT INTO/VALUES
The Oracle INSERT statement is used to insert a single record or multiple records into a table in Oracle.
Use to Add Rows to existing table. INSERT This will be used to insert the records into table. There
are two Insert methods.
 By value method
 By address method
Using Value Method
Syntax: INSERT INTO <table_name> VALUES (value1, value2, value3 …. Value n);
Note: To insert a new record again you have to type entire insert command, if there are lot of records
this will be difficult. This will be avoided by using address method.
Using Address Method
The syntax for the Oracle INSERT statement when inserting a single record using the VALUES
keyword is:
Syntax: INSERT INTO <table_name> VALUES (&col1, &col2, &col3 …. &coln);
This will prompt you for the values but for every insert you have to use forward slash.
DBMS UNIT-II
Inserting Data into Specified Columns Using Value Method
Syntax:
insert into <table_name)(col1, col2, col3 … Coln) values (value1, value2, value3 …. Valuen);
Inserting Data into Specified Columns Using Address Method
Syntax: insert into <table_name)(col1, col2, col3 … coln) values (&col1, &col2 ….&coln); This will
prompt you for the values but for every insert you have to use forward slash.
UPDATE Statement: UPDATE/SET/WHERE
The Oracle UPDATE statement is used to update existing records in a table in an Oracle database.
There are 2 syntaxes for an update query in Oracle depending on whether you are performing a
traditional update or updating one table with data from another table.Use to Edit Existing Rows in
tables.
Syntax:UPDATE table SET column1 = expression1,column2 = expression2, ... column_n =
expression_n WHERE conditions;
DELETE Statement: DELETE FROM/WHERE
The Oracle DELETE statement is used to delete a single record or multiple records from a table in
Oracle. Use the DELETE statement to delete the rows from existing tables which are in your schema
or if you have DELETE privilege on them.This can be used to delete the table data temporarily.
Syntax: DELETE FROM table WHERE conditions;
Parameters or Arguments
Table:The table that you wish to delete records from.
Conditions: The conditions that must be me t for the records to be deleted.
Note: You do not need to list fields in the Oracle DELETE statement since you are deleting the entire
row from the table.
DQL : Data Query Language: SELECT Clause
SELECT/FROM/WHERE
SELECT Statement :The Oracle SELECT statement is used to retrieve records from one or more
tables in an Oracle database.
SELECT: retrieve records from one or more table
SELECT [ DISTINCT ] select-list
FROM from-list
[WHERE qualification]
[ORDER BY column1, column2; ]
[GROUP BY column1, column2]
[HAVING group-qualification]

Syntax : SELECT[ DISTINCT ] select-list FROM from-list WHERE qualification or


SELECT expressions FROM tables WHERE conditions;
Parameters or Arguments
DBMS UNIT-II
Expressions: The columns or calculations that you wish to retrieve.
Tables: The tables that you wish to retrieve records from. There must be at least one table listed in the
FROM clause.
Conditions: The conditions that must be met for the records to be selected.
SELECT − This is one of the fundamental query command of SQL. It selects the attributes based on
the condition described by WHERE clause.
FROM − This clause takes a relation name as an argument from which attributes are to be
selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian
product.
WHERE − This clause defines predicate or conditions, which must match in order to qualify the
attributes to be projected.
ORDER BY order-item-list: The ORDER BY statement in SQL is used to sort the fetched data in
either ascending or descending according to one or more columns. By default ORDER BY sorts the
data in ascending order. use the keyword DESC to sort the data in descending order and the keyword
ASC to sort in ascending order.
GROUP BY grouping-list:
In SQL, The Group By statement is used for organizing similar data into groups. The data is further
organized with the help of equivalent function. It means, if different rows in a precise column have the
same values, it will arrange those rows in a group.
The SELECT statement is used with the GROUP BY clause in the SQL query.
WHERE clause is placed before the GROUP BY clause in SQL.
ORDER BY clause is placed after the GROUP BY clause in SQL. HAVING group-qualification :
HAVING Clause: WHERE clause is used for deciding purpose. It is used to place conditions on the
columns to determine the part of the last result-set of the group. Here, we are not required to use the
combined functions like COUNT (), SUM (), etc. with the WHERE clause. After that, we need to use
a HAVING clause.

Comparison Basis WHERE Clause HAVING Clause

Definition It is used to perform filtration on individual rows. It is used to perform filtration on groups.

Basic It is implemented in row operations. It is implemented in column operations.

Data fetching The WHERE clause fetches the specific data from The HAVING clause first fetches the complete
particular rows based on the specified condition data. It then separates them according to the
given condition.
Aggregate The WHERE clause does not allow to work with The HAVING clause can work with aggregate
Functions aggregate functions. functions.
Act as The WHERE clause acts as a pre-filter. The HAVING clause acts as a post-filter.

Used with We can use the WHERE clause with the SELECT, The HAVING clause can only use with the
UPDATE, and DELETE statements. SELECT statement.
GROUP BY The GROUP BY clause comes after the WHERE The GROUP BY clause comes before the
clause. HAVING clause.
SQL Data Types
DBMS UNIT-II
Data types are used to represent the nature of the data that can be stored in the database table. Data types
mainly classified into three categories for every database.

 String Data types


 Numeric Data types
 Date and time Data types
Oracle String data types

CHAR(size) :It is used to store character data within the predefined length.It can be stored up to 2000
bytes. Example: sname char(10),

NCHAR(size): It is used to store national character data within the predefined length. It can be stored up to
2000 bytes. it used to store the fixed length unicode characters.

VARCHAR2(size) :It is used to store variable string data within the predefined length.It can be stored up to
4000 byte.example: F_name Varchar2(15).

VARCHAR(SIZE):It is the same as VARCHAR2(size). You can also use VARCHAR(size), but it is
suggested to use VARCHAR2(size). Example: L_name Varchar(15).

NVARCHAR2(size): It is used to store Unicode string data within the predefined length. We have to must
specify the size of NVARCHAR2 data type. It can be stored up to 4000 bytes.it is used to store the variable
length unicode characters. example :Name Nvchar2(20)

Oracle Numeric Data Types

NUMBER(p, s): It contains precision p and scale s. The precision p can range from 1 to 38, and the scale s
can range from -84 to 127.

FLOAT(p) : It is a subtype of the NUMBER data type.The precision p can range from 1 to 126.

BINARY_FLOAT : It is used for binary precision( 32-bit).It requires 5 bytes, including length byte.

BINARY_DOUBLE : It is used for double binary precision (64-bit).It requires 9 bytes, including length
byte.

Oracle Date and Time Data Types

DATE:It is used to store a valid date-time format with a fixed length.Its range varies from January 1, 4712
BC to December 31, 9999 AD.

TIMESTAMP:It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.

Oracle Large Object Data Types (LOB Types)

BLOB :It is used to specify unstructured binary data.Its range goes up to 232-1 bytes or 4 GB.

BFILE: It is used to store binary data in an external file.Its range goes up to 232-1 bytes or 4 GB.

CLOB:It is used for single-byte character data. Its range goes up to 232-1 bytes or 4 GB.

NCLOB:It is used to specify single byte or fixed length multibyte national character set (NCHAR) data.Its
range is up to 232-1 bytes or 4 GB.

RAW(size):It is used to specify variable length raw binary data. Its range is up to 2000 bytes per row.Its
maximum size must be specified.
DBMS UNIT-II
LONG RAW:It is used to specify variable length raw binary data. Its range up to 231-1 bytes or 2 GB, per
row.

Integrity Constraints (ICs)


An integrity constraint is a condition that is specified on a database schema, and restricts the data that can be
stored in an instance of the database. Integrity constraint can be specified by the DBA at the time creation of
tables and imposed or enforced by the SQL at the time of insertion or updation or deletion of the data.
Legal Instance: If a database instance satisfies all the integrity constraints specified on the database schema,
it is a legal instance. A DBMS enforces integrity constraints, in that it permits only legal instances to be stored
in the database.

 Domain Integrity Constraints


 Entity Integrity Constraints
 Referential Integrity Constraints
 Key Constraints
1. Domain Integrity Constraints:
 Default Values
 Check constraints
Default Values : Domain constraint defines the domain or set of values for an attribute.It specifies that the
value taken by the attribute must be the atomic value from its domain.the data type can allow only specific
range of values. Example-Consider the following Student table

STU_ID Name Age

502 Akshay 20

502 Abhishek 21

503 Shashank 20

504 Rahul A

Here, value ‘A’ is not allowed since only integer values can be taken by the age attribute.

The CHECK constraint: The CHECK constraint is used to limit the value range that can be placed in a
column. Check constraint on a column it will allow only certain values for this column. If the value being
added to an attribute of a tuple violates the check constraint, the check constraint evaluates to false and the
corresponding update is aborted.
Example: GENDER VARCHAR (9),check(GENDER in ('Male', 'Female', 'Unknown')
DBMS UNIT-II
Age INT NOT NULL, check (Age >= 17)
With alter: Check constraint can also be added to an already created relation using the syntax:
alter table TABLE_NAME modify COLUMN_NAME check(Predicate).
2. Entity Integrity Constraints
 Not Null
 Unique
 Primary key
Not Null :The NOT NULL constraint enforces a column to NOT accept NULL values.This enforces a field
to always contain a value, which means that you cannot insert a new record, or update a record without
adding a value to this field.
Example: ID int NOT NULL, First Name varchar (255) NOT NULL
Not Null On Alter Table: ALTER TABLE <table name> MODIFY <column name data type> NOT
NULL.
Unique Constraint: The UNIQUE constraint ensures that all values in a column are different. Tuple
Uniqueness constraint specifies that all the tuples must be necessarily unique in any relation. Table have
many UNIQUE constraints.
Example: sid int unique
Example-01: Consider the following Student table-
STU_ID Name Age
S001 Akshay 20
S002 Abhishek 21
S003 Shashank 20
S004 Rahul 20
This relation satisfies the tuple uniqueness constraint since here all the tuples are unique.
PRIMARY KEY Constraint:
A Primary Key is the minimal set of attributes of a table that has the task to uniquely identify the rows or the
tuples of the given particular table. the PRIMARY KEY constraint uniquely identifies each record in a table.
A relation may have several candidate keys. Out of all the available candidate keys, a database designer can
identify a primary key.Primary keys must contain UNIQUE values, and cannot contain NULL values. A table
can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns
(fields).
For example, we can refer to a Students tuple by storing its sid value. As a consequence of referring to student
tuples in this manner, tuples are frequently accessed by specifying their sid value
Properties of a Primary Key:
 A relation can contain only one primary key.
 A primary key may be composed of a single attribute known as single primary key or more than
one attribute known as composite key.
 The data values for the primary key attribute should not be null.
 Attributes which are part of a primary key are known as Prime attributes.
DBMS UNIT-II
 Primary key is always chosen from the possible candidate keys.
 Primary key cannot contain duplicate values.
 Columns that are defined as LONG or LONG RAW cannot be part of a primary key.
Example:CREATE TABLE student ( sid int PRIMARY KEY, Name varchar(255) NOT NULL);
3. FOREIGN KEY Constraint:
It is a link between two tables. Sometimes the information stored in a one relation is linked to the information
stored in another relation. If one of the relations is modified, the other must be checked, and perhaps modified,
to keep the data consistent. An Integrity Constraint involving both relations must be specified if a DBMS is
to make such checks. The most common Integrity Constraint involving two relations is a foreign key
constraint. A Foreign Key is a field (or collection of fields) in one table that refers to the Primary Key in
another table.The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
Suppose that one relation is Students (sid int primary key,name varchar2(10),age int,not null,gpa
number(5,8)) and second relation is Enrolled (cid: string, grade: string,sid: int).

To ensure that only bonafide students can enroll in courses, any value that appears in the sid field of an
instance of the Enrolled relation should also appear in the sid field of some tuple in the Students relation. The
sid field of Enrolled is called a foreign key and refers to Students. The foreign key in the referencing relation
must match the primary key of the referenced relation (Students), i.e., it must have the same number of
columns and compatible data types, although the column names can be different. This constraint is illustrated
in above table. As the table shows, there may well be some students who are not referenced from Enrolled
(e.g., the student with sid=50000).However, every sid value that appears in the instance of the Enrolled table
appears in the primary key column of a row in the Students table.
Specifying Foreign Key Constraints in SQL:
CREATE TABLE Students (sid int primary key,name char(30)not null,login char(20) not null, age int ,gpa
number(5,8)).
CREATE TABLE Enrolled (cid varchar2(10) Primary Key,grade CHAR(10),sid int references student(sid));
4. Key Constraints:
Key Constraint: A key constraint is a statement that a certain minimal subset of the fields of a relation is a
unique identifier for a tuple.
DBMS UNIT-II
Super Key : A sub set of Attributes that uniquely identifies a tuple(row) in a relation(table).A superkey
SK specifies a uniqueness constraint that no two distincttuples in any state r of R can have the same
value for SK
*Minimal Super Key (Key) :
Definition: A Minimal Super Key (Key) K is a super key with the additional property that removal of
any attribute from K will cause K not to be a super key any more.A key K of a relation schema R is a
super key of R with the additional property that removing any attribute A from K leaves a set of
attributes K that is not a super key of R any more. Hence, a key satisfies two properties:
1. Two distinct tuples in any state of the relation cannot have identical values for (all) the attributes
in the key. This first property also applies to a super key.
2. It is a minimal super key—that is, a super key from which we cannot remove any attributes and still
have the uniqueness constraint in condition 1 hold. This property is not required by a super key.
*Candidate Key :
Definition : If a relation schema has more than one key (Minimal Super Key) then each of them is
called as candidate key.
 One of the candidate keys is arbitrarily designated to be the primary key, and the others are
called secondary keys(or Alternative key).
 A key formed by combining at least two or more columns is called composite key
*Primary Key : Definition : Set of attributes of a relation which uniquely identifies a tuple in a relation.
Note : A Relation(table) can have many Superkeys, and also many Minimal Superkeys.If a
Relation(table) has more than on Minimal Superkeys each can be called as Candidate Keys. One of the
candidate keys is arbitrarily designated to be the primary key, and the others are called secondary
keys(or Alternative key).
Key Hierarchy

 Primary key doesn’t allows duplicates and Null Values.


 In Oracle a table will have maximum one Primary Key.
 A Prime attribute must be a member of some candidate key
 A Nonprime attribute is not a prime attribute that is, it is not a member of any candidate key.
Simple and Nested Queries:
A relational database query is a question about the data, and the answer consists of a new relation
containing the result. A query language is a specialized language for writing queries. SQL is the most
popular commercial query language for a relational DBMS.A query is a statement requesting the
retrieval of information.
DBMS UNIT-II
Simple queries: A simple query is a query that searches using just one parameter. A simple query
might use all of the fields in a table and search using just one parameter .
Example: select * from emp;
Nested Queries or Sub Query:
A sub query is a query within another query. The outer query is known as the main query, and the inner
query is known as a sub query. A Sub query is a query within another SQL query and embedded within
the WHERE clause. a query is written inside a query. Sub queries provide an easy and efficient way to
handle the queries that depend on the results from another query. A sub query, also known as a nested
query ..Sub queries are on the right side of the comparison operator.
Important Rule:
A sub query can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING
clause. You can use Sub query with SELECT, UPDATE, INSERT, DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
A subquery is enclosed in parentheses. In the Subquery, ORDER BY command cannot be used. But
GROUP BY command can be used to perform the same function as ORDER BY command.
1. Subqueries with the Select Statement SQL subqueries are most frequently used with the Select
statement.
Syntax :the form of a basic SQL query

SELECT [ DISTINCT ] select-list


FROM from-list
[WHERE qualification]
[ORDER BY column1, column2; ]
[GROUP BY column1, column2]
[HAVING group-qualification]Example:
Such a query intuitively corresponds to a relational algebra expression involving selections,
projections, and cross-products. Every query must have a SELECT clause, which specifies columns to
be retained in the result, and a FROM clause, which specifies a crossproduct of tables. The optional
WHERE clause specifies selection conditions on the tables mentioned in the FROM clause. Let us
consider a simple query
Examples of Basic SQL Queries

1. Query to find the highest salary employee details

select * from empc where sal = (select max(sal) from empc);

2. Query to find the second highest salary employee details

select * from empc where sal in(select max(sal) from empc where sal not in(select max(sal)from
empc));

General Query to find nth highest salary /nth highest rank student.
DBMS UNIT-II
select * from emp e where (2)=(select count(distinct (e1.salary)) from emp e1 where
e1.salary>e.salary);

Different Types of SQL JOINs :Implementation Of Different Types Of Joins,

A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.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:

 Cross JOIN or Cartesian Product


 Natural JOIN
 Inner Join or Equi Join
 Outer Join

1. Cross JOIN or Cartesian product: 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.

Cross JOIN Syntax is: SELECT column-name-list FROM table-name1 CROSS JOIN table-name2;

Example of Cross JOIN Following is the class table:

ID NAME
501 abhi
502 adam
504 alex
and the classinf table,

ID Address
501 DELHI
502 MUMBAI
503 CHENNAI

Cross JOIN query will be: SELECT * FROM class CROSS JOIN classinf; The resultset table will
look like,

ID NAME ID Address
501 abhi 501 DELHI
502 adam 501 DELHI
504 alex 501 DELHI
501 abhi 501 DELHI
501 abhi 502 MUMBAI
502 adam 502 MUMBAI
DBMS UNIT-II
504 alex 502 MUMBAI
501 abhi 503 CHENNAI
502 adam 503 CHENNAI
504 alex 503 CHENNAI
As you can see, this join returns the cross product of all the records present in both the tables.

INNER Join or EQUI Join

(INNER) JOIN: Returns records that have matching values in both tables.This is a simple JOIN in
which the result is based on matched data as per the equality condition specified in the SQL query.In
SQL, INNER JOIN selects records that have matching values in both tables as long as the condition
is satisfied. It returns the combination of all rows from both the tables where the condition satisfies.

Inner Join Syntax is:

SELECT column-name-list FROM table-name1 INNER JOIN table-name2 on

table-name1.column-name = table-name2.column-name;

Example of INNER JOIN Consider a class table:

ID NAME
501 abhi
502 adam
503 alex
504 anu
and the classinf table:

ID Address
501 DELHI
502 MUMBAI
503 CHENNAI
Inner JOIN query will be:

SQL> select * from class inner join classinf on class.id=classinf.id;

ID NAME ID Address
501 abhi 501 DELHI
502 adam 502 MUMBAI
503 alex 503 CHENNAI

Natural JOIN

Natural Join is a type of Inner join which is based on column having same name and same datatype
present in both the tables to be joined.The syntax for Natural Join is,

SELECT * FROM table-name1 NATURAL JOIN table-name2;


DBMS UNIT-II
Example of Natural JOIN Here is the class table,

and the classinfo table,

ID NAME ID Address
501 abhi 501 DELHI
502 adam 502 MUMBAI
503 alex 503 CHENNAI
504 anu

Natural join query will be,

SQL> select * from class natural join classinf ;The resultset table will look like,

ID NAME Address
501 abhi DELHI
502 adam MUMBAI
503 alex CHENNAI

In the above example, both the tables being joined have ID column(same name and same datatype),
hence the records for which value of ID matches in both the tables will be the result of Natural Join
of these two tables.

OUTER JOIN:Outer Join is based on both matched and unmatched data. Outer Joins subdivide
further into

 Left Outer Join


 Right Outer Join
 Full Outer Join

LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right
table.The left outer join returns a result set 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. The SQL left join returns
all the values from left table and the matching values from the right table. If there is no matching join
value, it will return NULL.

Syntax for Left Outer Join is:

SELECT column-name-list FROM table-name1 LEFT OUTER JOIN table-name2 ON

table-name1.column-name = table-name2.column-name;

Example of Left Outer Join Here is the class table,

ID NAME
501 abhi
502 adam
DBMS UNIT-II
503 alex
504 anu
505 ashish
and the classinf table,

ID Address
501 DELHI
502 MUMBAI
503 CHENNAI
507 NOIDA
508 PANIPAT
Left Outer Join query will be,
SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id = class_info.id);
SQL> select * from class left outer join classinf on class.id=classinf.id;
ID NAME ID Address
501 abhi 501 DELHI
502 adam 502 MUMBAI
503 alex 503 CHENNAI
504 anu null null
505 ashish null null
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the
left table. The right outer join returns a result set 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. In
SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched
values from the left table. If there is no matching in both tables, it will return NULL.

Syntax for Right Outer Join is,

SELECT column-name-list FROM table-name1 RIGHT OUTER JOIN table-name2

ON table-name1.column-name = table-name2.column-name;

Example of Right Outer Join Once again the class table,

ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
1 abhi
and the classinf table,

Prepared by D Madhu BaBu


DBMS UNIT-II
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
Right Outer Join query will be,

SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id = class_info.id);

SQL> select * from class right outer join classinf on class.id=classinf.id;

The resultant table will look like,

ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
null null 7 NOIDA
null null 8 PANIPAT
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table. The full
outer join returns a result set table with the matched data of two table then remaining rows of both left
table and then the right table. In SQL, FULL JOIN is the result of a combination of both left and right
outer join. Join tables have all the records from both tables. It puts NULL on the place of matches not
found.

Syntax of Full Outer Join is,

SELECT column-name-list FROM table-name1 FULL OUTER JOIN table-name2 ON

table-name1.column-name = table-name2.column-name;

Example of Full outer join is,The class table,

ID NAME
501 abhi
502 adam
503 alex
504 anu
505 ashish

and the classinf table,

ID Address
501 DELHI
Prepared by D Madhu BaBu
DBMS UNIT-II
502 MUMBAI
503 CHENNAI
507 NOIDA
508 PANIPAT

Full Outer Join query will be like,

SQL> select * from class full join classinf on class.id=classinf.id;

The resultset table will look like,

ID NAME ID Address
501 abhi 501 DELHI
502 adam 502 MUMBAI
503 alex 503 CHENNAI
504 anu null null
505 ashish null null
null null 507 NOIDA
null null 508 PANIPAT

SQL> select * from class cross join classinf;

SQL> select * from class inner join classinf on class.id=classinf.id;

SQL> select * from class natural join classinf ;

SQL> select * from class left outer join classinf on class.id=classinf.id;

SQL> select * from class right outer join classinf on class.id=classinf.id;

SQL> select * from class full join classinf on class.id=classinf.id;

Stored Procedures:

A stored procedure is a PL/SQL block that is stored in the database with a name. It is invoked using the name.
Each procedure is meant for a specific purpose. A stored procedure is stored in the database as an object. It
is also called as database procedure as it is stored in the database. A procedure may take one or more
parameters. If a procedure takes parameters then these parameters are to be supplied at the time of calling
the procedure. these subprograms do not return a value directly, mainly used to perform an action.
Creating a Procedure

A procedure is created with the CREATE OR REPLACE PROCEDURE statement.The simplified syntax
for the CREATE OR REPLACE PROCEDURE statement is as follows:

CREATE [OR REPLACE] PROCEDURE procedure_name

Prepared by D Madhu BaBu


DBMS UNIT-II
[(parameter_name [IN | OUT | IN OUT] type [, ...])]

{IS | AS}

BEGIN

< procedure_body >

END procedure_name;

Where,procedure-name specifies the name of the procedure.

[OR REPLACE] option allows modifying an existing procedure.

The optional parameter list contains name, mode and types of the parameters.

There are three types of parameters that can be declared:

IN represents that value will be passed from outside and

IN - The parameter can be referenced by the procedure or function. The value of the parameter can not be
overwritten by the procedure or function.

OUT represents that this parameter will be used to return a value outside of the procedure.

OUT - The parameter can not be referenced by the procedure or function, but the value of the parameter
can be overwritten by the procedure or function.

IN OUT - The parameter can be referenced by the procedure or function and the value of the parameter can
be overwritten by the procedure or function.

procedure-body contains the executable part.

The AS keyword is used instead of the IS keyword for creating a standalone procedure.

Example to create PROCEDURE

create or replace procedure pro1(sd number) as sn varchar2(20);

begin

select ename into sn from empl where eid=sd;

dbms_output.put_line('The employee is:'||sn);

end;

******EXECUTING PROCEDURE USING EXEC***********

exec pro1(101);

*****CALLING PROCEDURE IN PL/SQL******************

declare

s number;

begin
Prepared by D Madhu BaBu
DBMS UNIT-II
s:=&s;

pro1(s);

end;

********************************

create or replace procedure pro2(eno in number,enm out varchar2) as

en empl.ename%type;

begin

select ename into en from empl where eid=eno;

enm:=en;

exception

when no_data_found then

raise_application_error(-20001,'Employee Data Not Found');

end;

declare

eno number;

enm varchar2(20);

sal number;

begin

eno:=&eno;

pro2(eno,enm);

select salary into sal from empl where ename=enm;

dbms_output.put_line('The employee name is '||enm||'And employee salary is '||sal);

end;

*********************************************************************************

Prepared by D Madhu BaBu

You might also like