Unit 2
Unit 2
Relational data model is the primary data model, which is used widely around
the world for data storage and processing. This model is simple and it has all
the properties and capabilities required to process data with storage efficiency.
The table name and column names are helpful to interpret the meaning of
values in each row. The data are represented as a set of relations. In the
relational model, data are stored as tables. However, the physical storage of
the data is independent of the way the data are logically organized.
Summary
The Relational database model represents the database as a collection
of relations (tables)
Attribute, Tables, Tuple, Relation Schema, Degree, Cardinality, Column,
Relation instance, are some important components of Relational Model
Relational Integrity constraints are referred to conditions which must be
present for a valid relation
Domain constraints can be violated if an attribute value is not appearing
in the corresponding domain or it is not of the appropriate data type
Insert, Select, Modify and Delete are operations performed in Relational
Model
The relational database is only concerned with data and not with a
structure which can improve the performance of the model
Advantages of relational model is simplicity, structural independence,
ease of use, query capability, data independence, scalability.
Few relational databases have limits on field lengths which can't be
exceeded.
UNIT-2
Codd’s Rules
Dr Edgar F. Codd, after his extensive research on the Relational Model of database
systems, came up with twelve rules of his own, which according to him, a database must
obey in order to be regarded as a true relational database.
These rules can be applied on any database system that manages stored data using
only its relational capabilities. This is a foundation rule, which acts as a base for all the
other rules.
1) DBMS applications store data as file. RDBMS applications store data in a tabular form.
2) In DBMS, data is generally stored in either In RDBMS, the tables have an identifier called primary
a hierarchical form or a navigational form.
key and the data values are stored in the form of tables.
4) DBMS does not apply any security with RDBMS defines the integrity constraint for the purpose
regards to data manipulation.
of ACID (Atomocity, Consistency, Isolation and Durability)
property.
5) DBMS uses file system to store data, so in RDBMS, data values are stored in the form of tables, so
there will be no relation between the a relationship between these data values will be stored
tables.
in the form of a table as well.
6) DBMS has to provide some uniform RDBMS system supports a tabular structure of the data
methods to access the stored information.
and a relationship between them to access the stored
information.
9) Examples of DBMS are file Example of RDBMS are mysql, postgre, sql server,
systems, xml etc.
oracle etc.
The main differences between DBMS and RDBMS are given below:
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.
UNIT-2
Relational Integrity constraints
Relational Integrity constraints is referred to conditions which must be present
for a valid relation. These integrity constraints are derived from the rules in the
mini-world that the database represents.
1. Domain constraints
2. Key constraints
3. Referential integrity constraints
Domain Constraints
Domain constraints can be violated if an attribute value is not appearing in the
corresponding domain or it is not of the appropriate data type.
Domain constraints specify that within each tuple, and the value of each
attribute must be unique. This is specified as data types which include
standard data types integers, real numbers, characters, Booleans, variable
length strings, etc.
Example:
Key constraints
An attribute that can uniquely identify a tuple in a relation is called the key of
the table. The value of the attribute for different tuples in the relation has to be
unique.
Example:
1 Google Active
2 Amazon Active
3 Apple Inactive
SELECT (symbol: σ)
PROJECT (symbol: π)
RENAME (symbol: ρ)
UNION (U)
INTERSECTION (∩),
DIFFERENCE (-)
CARTESIAN PRODUCT ( x )
SELECT (σ)
σp(r)
σ is the predicate
p is prepositional logic
Select Operator (σ) Example
Table: CUSTOMER
---------------
Query:
σ Customer_City="Mumbai" (CUSTOMER)
Output:
Projection(π)
The projection eliminates all attributes of the input relation but those
mentioned in the projection list. The projection method defines a
relation that contains a vertical subset of Relation.
Query:
Output:
Customer_Name Customer_City
------------- -------------
Shivendra Mumbai
Mohit Mumbai
Karan Noida
Aman Delhi
Virat Delhi
Rename (ρ)
Rename (ρ) operation can be used to rename a relation or an attribute
of a relation.
Table: CUSTOMER
ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Output:
CUST_NAMES
----------
Shivendra
Mohit
Karan
Aman
Virat
Lets discuss union operator a bit more. Lets say we have two relations
R1 and R2 both have same columns and we want to select all the
tuples(rows) from these relations then we can apply the union operator
on these relations.
Note: The rows (tuples) that are present in both the tables will only
appear once in the union set. In short you can say that there are no
duplicates present after the union operation.
table_name1 ∪ table_name2
Union Operator (∪) Example
Table 1: COURSE
Table 2: STUDENT
Output:
Student_Name
------------
Aditya
Virat
Prateek
Ruchika
Richa
Shivendra
Note: As you can see there are no duplicate names present in the output
even though we had few common names in both the tables, also in the
COURSE table we had the duplicate name itself.
Lets say we have two relations R1 and R2 both have same columns and
we want to select all those tuples(rows) that are present in both the
relations, then in that case we can apply intersection operation on these
two relations R1 ∩ R2.
Note: Only those rows that are present in both the tables will appear in
the result set.
Syntax of Intersection Operator (∩)
table_name1 ∩ table_name2
Table 1: COURSE
Table 2: STUDENT
Student_Name
------------
Aditya
Shivendra
Prateek
Ruchika
table_name1 - table_name2
Query:
Lets write a query to select those student names that are present in
STUDENT table but not present in COURSE table.
Student_Name
------------
Virat
Richa
Relational Algebra:
Relational database systems are expected to be equipped with a query language that can assist
its users to query the database instances. There are two kinds of query languages − relational
algebra and relational calculus.
Relational algebra is a procedural query language, which takes instances of relations as input
and yields instances of relations as output. It uses operators to perform queries. An operator can
be either unary or binary. They accept relations as their input and yield relations as their
output. Relational algebra is performed recursively on a relation and intermediate results are
also considered relations. It collects instances of relations as input and gives occurrences of
relations as output. It uses various operations to perform this action. SQL Relational algebra
query operations are performed recursively on a relation. The output of these operations is a
new relation, which might be formed from one or more input relations.
SELECT (symbol: σ)
PROJECT (symbol: π)
RENAME (symbol: ρ)
UNION (υ)
INTERSECTION (Ո)
DIFFERENCE (-)
CARTESIAN PRODUCT ( x )
JOIN
DIVISION
Example
Table A Table B
1 2 1 3
The result of set difference operation is tuples, which are present in one relation but are not in
the second relation.
Notation: r − s
Finds all the tuples that are present in r but not in s.
- Symbol denotes it. The result of A - B, is a relation which includes all tuples that are in A but
not in B.
Table A – B
column 1 column 2
1 2
Cartesian Product (Χ):
This type of operation is helpful to merge columns from two relations. Generally, a Cartesian
product is never a meaningful operation when it performs alone. However, it becomes
meaningful when it is followed by other operations.
σ column 2 = '1' (A X B)
Output – The above example shows all rows from relation A and B whose column 2 has value 1
σ column 2 = '1' (A X B)
column 1 column 2
1 1
1 1
• The relation returned by division operator will have attributes = (All attributes of A – All
Attributes of B)
• The relation returned by division operator will return those tuples from relation A which
are associated to every B’s tuple.
STUDENT_SPORTS
ROLL_NO SPORTS
1 Badminton
2 Cricket
2 Badminton
4 Badminton
ALL_SPORTS
SPORTS
Badminton
Cricket
• The tuples in resulting relation will have those ROLL_NO which are associated with all
B’s tuple {Badminton, Cricket}. ROLL_NO 1 and 4 are associated to Badminton only.
ROLL_NO 2 is associated to all tuples of B. So the resulting relation will be:
STUDENT_SPORTS÷ ALL_SPORTS
ROLL_NO
2
Join Operations:
A Join operation combines related tuples from different relations, if and only if a given join
condition is satisfied. It is denoted by ⋈.
Example:
EMPLOYEE
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
SALARY
EMP_CODE SALARY
101 50000
102 30000
103 25000
Result:
1. Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are equal on
their common attribute names.
o It is denoted by ⋈.
Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
Output:
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with missing
information.
Example:
EMPLOYEE
FACT_WORKERS
Input:
(EMPLOYEE ⋈ FACT_WORKERS)
Output:
Input:
EMPLOYEE ⟕ FACT_WORKERS
Input:
EMPLOYEE ⟖ FACT_WORKERS
Output:
Input:
EMPLOYEE ⟗ FACT_WORKERS
Output:
3. Equi 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(=).
Example:
CUSTOMER RELATION
CLASS_ID NAME
1 John
2 Harry
3 Jackson
PRODUCT
PRODUCT_ID CITY
1 Delhi
2 Mumbai
3 Noida
Input:
CUSTOMER ⋈ PRODUCT
Output:
1 John 1 Delhi
2 Harry 2 Mumbai
3 Harry 3 Noida
Scanned by CamScanner
Scanned by CamScanner
RELATIONAL CALCULUS
In this section, we introduce another formal query language for the relational model
called relational calculus. In relational calculus, we write one declarative
expression to specify a retrieval request, and hence there is no description of how to
evaluate a query. A calculus expression specifies what is to be retrieved rather than
how to retrieve it. Therefore, the relational calculus is considered to be a
nonprocedural language. This differs from relational algebra, where we must write
a sequence of operations to specify a retrieval request; hence, it can be considered
as a procedural way of stating a query. It is possible to nest algebra operations to
form a single expression; however, a certain order among the operations is always
explicitly specified in a relational algebra expression. This order also influences the
strategy for evaluating the query. A calculus expression may be written in different
ways, but the way it is written has no bearing on how a query should be evaluated.
Relational Algebra:
Relational Algebra is a Procedural language. In Relational Algebra, The order is
specified in which the operations have to be performed. In Relation Algebra frameworks
are created to implement the queries. The basic operation included in relational algebra
are:
1. Select (σ)
2. Project (Π)
3. Union (U)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)
Relational Calculus:
Relational Calculus is the formal query language. It also known as Declarative
language. In Relational Calculus, The order is not specified in which the operation
have to be performed. Relational Calculus means what result we have to obtain.
Relational Calculus has two variations:
When queries are optimized, the system will choose a particular sequence of
operations that corresponds to an execution strategy that can be executed efficiently.
It has been shown that any retrieval that can be specified in the basic relational
algebra can also be specified in relational calculus, and vice versa; in other words,
the expressive power of the two languages is identical. This led to the definition of
the concept of a relationally complete language. A relational query language L is
considered relationally complete if we can express in L any query that can be
expressed in relational calculus. Relational completeness has become an important
basis for comparing the expressive power of high-level query languages.
Most relational query languages are relationally complete but have more expressive
power than relational algebra or relational calculus because of additional operations
such as aggregate functions, grouping, and ordering.
The tuple relational calculus is based on specifying a number of tuple variables. Each
tuple variable usually ranges over a particular database relation, meaning that the
variable may take as its value any individual tuple from that relation. A simple tuple
relational calculus query is of the form
{ t | COND(t)}
The condition EMPLOYEE(t) specifies that the range relation of tuple variable t is
EMPLOYEE. Each EMPLOYEE tuple t that satisfies the condition
t.SALARy>50000 will be retrieved.
Notice that t.SALARY references attribute SALARY of tuple variable t; this
notation resembles how attribute names are qualified with relation names or aliases
in SQL.
The above query retrieves all attribute values for each selected EMPLOYEE tuple r.
To retrieve only some of the attributes-say, the first and last names-we write
{t.FNAME, t.LANME I EMPLOYEE(t) AND t.SALARy>50000}
QUERY 0
Retrieve the birth date and address of the employee (or employees) whose name is
'John B. Smith'.
ln tuple relational calculus, we first specify the requested attributes t.BDATE and
t.ADDRESS for each selected tuple r. Then we specify the condition for selecting a
tuple following the bar ( | )-namely, that t be a tuple of the EMPLOYEE relation
whose FNAME, MINIT, and LNAME attribute values are 'John', 'B', and 'Smith',
respectively.
3. An atom of the form ti.A op core op tj.B, where op is one of the comparison
operators in the set {=, <, ≤, >, ≥, ≠}, tj and tj are tuple variables, A is an attribute of
the relation on which tj ranges, B is an attribute of the relation on which tj ranges,
and c is a constant value.
Each of the preceding atoms evaluates to either TRUE or FALSE for a specific
combination of tuples; this is called the truth value of an atom. In general, a tuple
variable t ranges over all possible tuples "in the universe." For atoms of the form
R(t), if t is assigned to a tuple that is a member of the specified relation R, the atom
is TRUE; otherwise, it is FALSE. In atoms of types 2 and 3, if the tuple variables
are assigned to tuples such that the values of the specified attributes of the tuples
satisfy the condition, then the atom is TRUE.
A formula (condition) is made up of one or more atoms connected via the logical
operators AND, OR, and NOT and is defined recursively as follows:
1. Every atom is a formula.
2. If F1 and F2 are formulas, then so are (F1 AND F2), (F1 OR F2), NOT (F1),
and NOT (F2). The truth values of these formulas are derived from their
component formulas F1 and F2 as follows:
a. (F1 AND F2) is TRUE if both F1 and F1 are TRUE; otherwise, it is FALSE.
b. (F1 OR F2) is FALSE if both F1 and F2 are FALSE; otherwise, it is TRUE.
c. NOT (F1) is TRUE if F1 is FALSE; it is FALSE if F1 is TRUE.
d. NOT (F2) is TRUE if F2 is FALSE; it is FALSE if F2 is TRUE.
The tuple variable d is free in both F1 and F2, whereas it is bound to the (∀) quantifier
in F3. Variable t is bound to the (∃) quantifier in F2.
We can now give rules 3 and 4 for the definition of a formula we started earlier:
3. If F is a formula, then so is (∃ t)(F), where t is a tuple variable. The formula
(∃t)(F) is TRUE if the formula F evaluates to TRUE for some (at least one) tuple
assigned to free occurrences of tin F; otherwise, (3 t)(F) is FALSE.
4. If F is a formula, then so is (∀ t)(F), where t is a tuple variable. The formula
(∀t)(F) is TRUE if the formula F evaluates to TRUE for every tuple (in the universe)
assigned to free occurrences of tin F; otherwise, (∀ t)(F) is FALSE.
The (∃) quantifier is called an existential quantifier because a formula (∃ t)(F) is
TRUE if "there exists" some tuple that makes F TRUE. For the universal quantifier,
(∀t)(F) is TRUE if every possible tuple that can be assigned to free occurrences of t
in F is substituted for t, and F is TRUE for every such substitution.
It is called the universal or "for all" quantifier because every tuple in "the universe
of" tuples must make F TRUE to make the quantified formula TRUE.
QUERY 1
Retrieve the name and address of all employees who work for the 'Research'
department.
The only free tuple variables in a relational calculus expression should be those that
appear to the left of the bar ( | ). In Ql, t is the only free variable; it is then bound
successively to each tuple. If a tuple satisfies the conditions specified in Ql, the
attributes FNAME, LNAME, and ADDRESS are retrieved for each such tuple. The
conditions EMPLOYEE (t) and DEPARTMENT (d) specify the range relations for
t and d. The condition d.DNAME = 'Research' is a selection condition and
corresponds to a SELECT operation in the relational algebra, where as the condition
d.DNUMBER = t.DNO is a join condition and serves a similar purpose to the JOIN
operation.
QUERY 2
For every project located in 'Stafford', list the project number, the controlling
department number, and the department manager's last name, birth date, and address.
In Q2 there are two free tuple variables, p and m. Tuple variable d is bound to the
existential quantifier. The query condition is evaluated for every combination of
tuples assigned to p and m; and out of all possible combinations of tuples to which
p and m are bound, only the combinations that satisfy the condition are selected.
Several tuple variables in a query can range over the same relation. For example, to
specify the query Q8-for each employee, retrieve the employee's first and last name
and
the first and last name of his or her immediate supervisor-we specify two tuple
variables
e and s that both range over the EMPLOYEE relation:
QUERY 3’
Find the name of each employee who works on some project controlled by
department number 5. This is a variation of query 3 in which "all" is changed to
"some." In this case we need two join conditions and two existential quantifiers.
QUERY 4
Make a list of project numbers for projects that involve an employee whose last name
is 'Smith', either as a worker or as manager of the controlling department for the
project.
Compare this with the relational algebra version of this query in Section 6.5. The
UNION operation in relational algebra can usually be substituted with an OR
connective in relational calculus. In the next section we discuss the relationship
between the universal and existential quantifiers and show how one can be
transformed into the other.
Transforming the Universal and Existential Quantifiers
We now introduce some well-known transformations from mathematical logic that
relate the universal and existential quantifiers. It is possible to transform a universal
quantifier into an existential quantifier, and vice versa, to get an equivalent
expression. One general transformation can be described informally as follows:
Transform one type of quantifier into the other with negation (preceded by NOT);
AND and OR replace one another; a negated formula becomes un negated; and an
unnegated formula becomes negated. Some special cases of this transformation can
be stated as follows, where the == symbol stands for
equivalent to:
QUERY 3
Find the names of employees who work on all the projects controlled by department
number 5. One way of specifying this query is by using the universal quantifier as
shown.
We want to make sure that a selected employee e works on all the projects controlled
by department 5, but the definition of universal quantifier says that to make the
quantified formula TRUE, the inner formula must be TRUE for all tuples in the
universe.
The trick is to exclude from the universal quantification all tuples that we are not
interested in by making the condition TRUE for all such tuples. This is necessary
because a universally quantified tuple variable, such as x in Q3, must evaluate to
TRUE for every possible tuple assigned to it to make the quantified formula TRUE.
The first tuples to exclude (by making them evaluate automatically to TRUE) are
those that are not in the relation R of interest. In Q3, using the expression NOT
(PROJECT(x)) inside the universally quantified formula evaluates to TRUE all
tuples x that are not in the PROJECT relation. Then we exclude the tuples we are
not interested in from R itself. In Q3, using the expression NOT (x.DNUM=5)
evaluates to TRUE all tuples x that are in the PROJECT relation but are not
controlled by department 5. Finally, we specify a condition F2 that must hold on all
the remaining tuples in R. Hence, we can explain Q3 as follows:
1. For the formula F' = (∀ x)(F) to be TRUE, we must have the formula F be TRUE
for all tuples in the universe that can be assigned to x. However, in Q3 we are only
interested in F being TRUE for all tuples of the PROJECT relation that are controlled
by department 5. Hence, the formula F is of the form (NOT (PROJECT(X)) OR F1).
The 'NOT(PROJECT(X)) OR ...' condition is TRUE for all tuples not in the
PROJECT relation and has the effect of eliminating these tuples from consideration
in the truth value of Fl' For every tuple in the PROJECT relation, FI must be TRUE
if F' is to be TRUE.
2. Using the same line of reasoning, we do not want to consider tuples in the
PROJECT relation that are not controlled by department number 5, since we are only
interested in PROJECT tuples whose DNUM = 5. We can therefore write:
IF (x.DNUM=5) THEN F2
which is equivalent to
(NOT (x.DNUM=5) OR F2)
3. Formula F1, hence, is of the form NOT (x.DNuM=5) OR F2. In the context of
Q3, this means that, for a tuple x in the PROJECT relation, either its DNUM, t5 or
it must satisfy F2.
4. Finally, F2 gives the condition that we want to hold for a selected EMPLOYEE
tuple: that the employee works on every PROJECT tuple that has not been excluded
yet. Such employee tuples are selected by the query.
In English, Q3 gives the following condition for selecting an EMPLOYEE tuple e:
For every tuple x in the PROJECT relation with X.DNUM = 5, there must exist a
tuple w in WORKS_ON such that W.ESSN = e.SSN and W.PNO = X.PNUMBER.
This is equivalent to saying that EMPLOYEE e works on every PROJECT x in
DEPARTMENT number 5.
QUERY 6
Find the names of employees who have no dependents.
QUERY 7
List the names of managers who have at least one dependent.
This query is handled by interpreting "managers who have at least one dependent"
as "managers for whom there exists some dependent."
Safe Expressions
Whenever we use universal quantifiers, existential quantifiers, or negation of
predicates in a calculus expression, we must make sure that the resulting expression
makes sense. A safe expression in relational calculus is one that is guaranteed to
yield a finite number of tuples as its result; otherwise, the expression is called unsafe.
For example, the expression
[t | NOT (EMPLOYEE(t))}
is unsafe because it yields all tuples in the universe that are not EMPLOYEE tuples,
which are infinitely numerous. If we follow the rules for Q3 discussed earlier, we
will get a safe expression when using universal quantifiers. We can define safe
expressions more precisely by introducing the concept of the domain of a tuple
relational calculus expression: This is the set of all values that either appear as
constant values in the expression or exist in any tuple in the relations referenced in
the expression.
The domain of [t | NOT(EMPLOYEE(t))} is the set of all attribute values appearing
in some tuple of the EMPLOYEE relation (for any attribute).
The domain of the expression Q3A would include all values appearing in
EMPLOYEE, PROJECT, and WORKS_ON (unioned with the value 5 appearing in
the query itself).
An expression is said to be safe if all values in its result are from the domain of the
expression. Notice that the result of [t I NOT(EMPLOYEE(t))} is unsafe, since it
will, in general, include tuples (and hence values) from outside the EMPLOYEE
relation; such values are not in the domain of the expression. All of our other
examples are safe expressions.
where Xl' X2' ... , x", Xn+l' x,,+2' ... , x,,+m are domain variables that range over
domains (of attributes), and COND is a condition or formula of the domain relational
calculus.
A formula is made up of atoms. The atoms of a formula are slightly different from
those for the tuple calculus and can be one of the following:
1. An atom of the form R(x1, x2, ... , xj ) , where R is the name of a relation of degree
j and each Xi ,1≤ i ≤ j is a domain variable. This atom states that a list of values of
(x1, x2, ... , xj )must be a tuple in the relation whose name is R, where Xi is the value
of the ith attribute value of the tuple. To make a domain calculus expression more
concise, we can drop the commas in a list of variables; thus, we can write
As in tuple calculus, atoms evaluate to either TRUE or FALSE for a specific set of
values, called the truth values of the atoms. In case 1, if the domain variables are
assigned values corresponding to a tuple of the specified relation R, then the atom is
TRUE. In cases 2 and 3, if the domain variables are assigned values that satisfy the
condition, then the atom is TRUE.
In a similar way to the tuple relational calculus, formulas are made up of atoms,
variables, and quantifiers, so we will not repeat the specifications for formulas here.
Some examples of queries specified in the domain calculus follow. We will use
lowercase letters l, m, n, ... , x, y, z for domain variables.
QUERY 0
Retrieve the birthdate and address of the employee whose name is 'John B. Smith'.
We need ten variables for the EMPLOYEE relation, one to range over the domain
of each attribute in order. Of the ten variables q, r, s, ... , z, only u and v are free. We
first specify the requested attributes, BDATE and ADDRESS, by the free domain
variables u for BDATE and v for ADDRESS. Then we specify the condition for
selecting a tuple following the bar (|) namely, that the sequence of values assigned
to the variables qrstuvwxyz be a tuple of the EMPLOYEE relation and that the values
for q (FNAME), r (MINH), and s (LNAME) be 'John', 'B', and 'Smith', respectively.
For convenience, we will quantify only those variables actually appearing in a
condition (these would be q, r, and s in Q0 in the rest of our examples.
An alternative shorthand notation, used in QBE, for writing this query is to assign
the constants 'John', 'B', and 'Smith' directly as shown in Q0A. Here, all variables
not appearing to the left of the bar are implicitly existentially quantified.!"
QUERY 1
Retrieve the name and address of all employees who work for the 'Research'
department.
A condition relating two domain variables that range over attributes from two
relations, such as m = Z in Q1, is a join condition; whereas a condition that relates a
domain variable to a constant, such as l == 'Research', is a selection condition.
QUERY 6
Find the names of employees who have no dependents.
QUERY 7
List the names of managers who have at least one dependent.
SQL Operators
SQL statements generally contain some reserved words or characters that are used to
perform operations such as comparison and arithmetical operations etc. These reserved
words or characters are known as operators.
Example:
- It subtracts right hand operand from left hand operand a-b will give -
50
/ It divides left hand operand by right hand operand b/a will give 2
% It divides left hand operand by right hand operand and b%a will give 0
returns reminder
SQL Comparison Operators:
Let's take two variables "a" and "b" that are valued 50 and 100.
= Examine both operands value that are equal or not,if yes (a=b) is not
condition become true. true
!= This is used to check the value of both operands equal or not,if (a!=b) is
not condition become true. true
<> Examines the operand's value equal or not, if values are not (a<>b) is
equal condition is true true
> Examine the left operand value is greater than right Operand, if (a>b) is not
yes condition becomes true true
< Examines the left operand value is less than right Operand, if (a<=""
yes condition becomes true td="">
>= Examines that the value of left operand is greater than or equal (a>=b) is
to the value of right operand or not,if yes condition become true not true
<= Examines that the value of left operand is less than or equal to (a<=b) is
the value of right operand or not, if yes condition becomes true true
!< Examines that the left operand value is not less than the right (a!<=""
operand value td="">
!> Examines that the value of left operand is not greater than the (a!>b) is
value of right operand true
SQL Logical Operators:
This is the list of logical operators used in SQL.
Operator Description
ALL this is used to compare a value to all values in another value set.
AND this operator allows the existence of multiple conditions in an SQL statement.
ANY this operator is used to compare the value in list according to the condition.
BETWEEN this operator is used to search for values, that are within a set of values
NOT the NOT operator reverse the meaning of any logical operator
EXISTS the EXISTS operator is used to search for the presence of a row in a specified
table
LIKE this operator is used to compare a value to similar values using wildcard
operator
If you want to add tables in that database, you can use CREATE TABLE statement.
If you want to delete or drop an existing database in a SQL schema, you can use SQL
DROP DATABASE
If you are using SQL server 2000, you can also use this command to rename the
database. But, Microsoft phased out it.
SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term,
table is known as relation and row as tuple.
Note: A table has a specified number of columns, but can have any number of
rows.
Table is the simple form of data storage. A table is also considered as a convenient
representation of relations.
Employee
In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and
"SALARY" are the column names. The combination of data of multiple columns forms a
row e.g. "Ankit", "Lucknow" and 15000 are the data of one row.
It is a variable where we temporary store records and results. This is same like temp
table but in the case of temp table we need to explicitly drop it.
Table variables are used to store a set of records. So declaration syntax generally looks
like CREATE TABLE syntax.
When a transaction rolled back the data associated with table variable is not rolled back.
If you want to create a table, you should name the table and define its column and each
column's data type.
The data type of the columns may vary from one database to another. For example,
NUMBER is supported in Oracle database for integer value whereas INT is supported in MySQL.
Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL
are the constraint showing that these fields cannot be NULL while creating records in the
table.
You can verify it, if you have created the table successfully by looking at the message displayed
by the SQL Server, else you can use DESC command as follows:
ID Int(11) NO PRI
NAME Varchar(20) NO
AGE Int(11) NO
Now you have the STUDENTS table available in your database and you can use to store required
the same column signature as the old table. We can select all columns or some specific columns.
If we create a new table using an old table, the new table will be filled with the existing value from
The basic syntax for creating a table with the other table is:
CREATE TABLE table_name AS
SELECT column1, column2,...
FROM old_table_name WHERE ..... ;
The following SQL creates a copy of the employee table.
CREATE TABLE EmployeeCopy AS
SELECT EmployeeID, FirstName, Email
FROM Employee;
The following query creates a PRIMARY KEY on the "D" column when the "Employee" table is created.
MySQL
CREATE TABLE Employee(
EmployeeID NOT NULL,
FirstName varchar(255) NOT NULL,
LastName varchar(255),
City varchar(255),
PRIMARY KEY (EmployeeID)
);
SQL Server / Oracle / MS Access
CREATE TABLE Employee(
EmployeeID NOT NULL PRIMARY KEY,
FirstName varchar(255) NOT NULL,
LastName varchar(255),
City varchar(255)
);
Use the following query to define a PRIMARY KEY constraints on multiple columns, and to
This is very important to know that once a table is deleted all the information available in
the table is lost forever, so we have to be very careful when using this command.
Let's see the syntax to drop the table from the database.
First we verify STUDENTS table and then we would delete it from the database.
ID Int(11) NO PRI
NAME Varchar(20) NO
AGE Int(11) NO
This shows that STUDENTS table is available in the database, so we can drop it as
follows:
Now, use the following command to check whether table exists or not.
But if you do not specify the WHERE condition it will remove all the rows from the table.
There are some more terms similar to DELETE statement like as DROP statement and
TRUNCATE statement but they are not exactly same there are some differences between
them.
The TRUNCATE statement: it is used to delete all the rows from the table and free
the containing space.
On the other hand when we TRUNCATE a table, the table structure remains the same,
so you will not face any of the above problems.
Let us take an example of a table named "STUDENTS", now due to some reason we want
to change it into table name "ARTISTS".
Table1: students
You should use any one of the following syntax to RENAME the table name:
Truncate table is faster and uses lesser resources than DELETE TABLE command.
Drop table command can also be used to delete complete table but it deletes table
structure too. TRUNCATE TABLE doesn't delete the structure of the table.
Let's see the syntax to truncate the table from the database.
For example, you can write following command to truncate the data of employee table
You can also use SQL ALTER TABLE command to add and drop various constraints on an
existing table.
If you want to add multiple columns in table, the SQL table will be
If you want to modify multiple columns in table, the SQL table will be
SQL SELECT
The most commonly used SQL command is SELECT statement. It is used to query the
database and retrieve selected data that follow the conditions we want.
In simple words, we can say that the select statement used to query or retrieve data
from a table in the database.
SELECT expressions
FROM tables
WHERE conditions;
[GROUP BY Clause] : Groups rows that share a property so that the aggregate
function can be applied to each group.
[HAVING Clause] : It selects among the groups defined by the GROUP BY clause.
From the above example, select the first name of all the students. To do so, query
should be like this:
Note: the SQL commands are not case sensitive. We can also write the above SELECT
statement as:
Amar
Akbar
Anthony
We can also retrieve data from more than one column. For example, to select first name
and last name of all the students, you need to write
Amar Sharma
Akbar Khan
Anthony Milton
We can also use clauses like WHERE, GROUP BY, HAVING, ORDER BY with SELECT
statement.
Here a point is notable that only SELECT and FROM statements are necessary in SQL
SELECT statements. Other clauses like WHERE, GROUP BY, ORDER BY, HAVING may be
optional.
SELECT UNIQUE is an old syntax which was used in oracle description but later ANSI
standard defines DISTINCT as the official keyword.
After that oracle also added DISTINCT but did not withdraw the service of UNIQUE
keyword for the sake of backward compatibility.
In simple words, we can say that SELECT UNIQUE statement is used to retrieve a unique
or distinct element from the table.
In a table, there may be a chance to exist a duplicate value and sometimes we want to
retrieve only unique values. In such scenarios, SQL SELECT DISTINCT statement is used.
Note: SQL SELECT UNIQUE and SQL SELECT DISTINCT statements are same.
Here is a table of students from where we want to retrieve distinct information For
example: distinct home-town.
HOME_TOWN
Lucknow
Varanasi
The COUNT() function is used with SQL SELECT statement and it is very useful to count
the number of rows in a table having enormous data.
For example: If you have a record of the voters in selected area and want to count the
number of voters then it is very difficult to do it manually but you can do it easily by
using the SQL SELECT COUNT query.
The "select count(*) from table" is used to return the number of records in table.
Let's see an example. If a table has a large number of data, select top statement
determines that how many rows will be retrieved from the given table.
SQL WHERE
A WHERE clause in SQL is a data manipulation language statement.
WHERE clauses are not mandatory clauses of SQL DML statements. But it can be used to
limit the number of rows affected by a SQL DML statement or returned by a query.
Actually. it filters the records. It returns only those queries which fulfill the specific
conditions.
= equal
This syntax is for SQL WITH clause using a single sub-query alias.
When you use multiple sub-query aliases, the syntax will be as follows.
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression [ASC | DESC];
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
UNION Operation
UNION is used to combine the results of two or more SELECT statements. However it
will eliminate duplicate rows from its resultset. In case of union, number of columns
and datatype must be same in both the tables, on which UNION operation is being
applied.
Example of UNION
The First table,
ID Name
1 abhi
2 adam
ID Name
2 adam
3 Chester
UNION
ID NAME
1 abhi
2 adam
3 Chester
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
UNION ALL
1 abhi
2 adam
2 adam
3 Chester
INTERSECT
Intersect operation is used to combine two SELECT statements, but it only retuns the
records which are common from both SELECT statements. In case of Intersect the
number of columns and datatype must be same.
NOTE: MySQL does not support INTERSECT operator.
Example of Intersect
The First table,
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
INTERSECT
ID NAME
2 adam
MINUS
The Minus operation combines results of two SELECT statements and return only
those in the final result, which belongs to the first set of the result.
Example of Minus
The First table,
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
MINUS
1 abhi
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Syntax
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
SELECT COUNT(*)
FROM PRODUCT_MAST;
Output:
10
SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
Com3 2
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
SELECT SUM(COST)
FROM PRODUCT_MAST;
Output:
670
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;
Output:
320
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values.
Syntax
AVG()
or
AVG( [ALL|DISTINCT] expression )
Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax
MAX()
or
MAX( [ALL|DISTINCT] expression )
Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
MIN()
or
MIN( [ALL|DISTINCT] expression )
Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
SQL Subquery
Summary: in this tutorial, you will learn about the SQL subquery and how
to use the subqueries to form flexible SQL statements.
Suppose you have to find all employees who locate in the location with the
id 1700. You might come up with the following solution.
SELECT
*
FROM
departments
WHERE
location_id = 1700;
Second, find all employees that belong to the location 1700 by using the
department id list of the previous query:
SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (1 , 3, 8, 10, 11)
ORDER BY first_name , last_name;
This solution has two problems. To start with, you have looked at
the departments table to check which department belongs to the location
1700. However, the original question was not referring to any specific
departments; it referred to the location 1700.
Because of the small data volume, you can get a list of department easily.
However, in the real system with high volume data, it might be problematic.
Another problem was that you have to revise the queries whenever you
want to find employees who locate in a different location.
SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (SELECT
department_id
FROM
departments
WHERE
location_id = 1700)
ORDER BY first_name , last_name;
The query placed within the parentheses is called a subquery. It is also
known as an inner query or inner select. The query that contains the
subquery is called an outer query or an outer select.
To execute the query, first, the database system has to execute the
subquery and substitute the subquery between the parentheses with its
result – a number of department id located at the location 1700 – and then
executes the outer query.
comparison_operator (subquery)
where the comparison operator is one of these operators:
Equal (=)
Greater than (>)
Less than (<)
Greater than or equal ( >=)
Less than or equal (<=)
Not equal ( !=) or (<>)
The following example finds the employees who have the highest salary:
SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary = (SELECT
MAX(salary)
FROM
employees)
ORDER BY first_name , last_name;
In this example, the subquery returns the highest salary of all employees
and the outer query finds the employees whose salary is equal to the
highest one.
The following statement finds all employees who salaries are greater than
the average salary of all employees:
SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary > (SELECT
AVG(salary)
FROM
employees);
In this example, first, the subquery returns the average salary of all
employees. Then, the outer query uses the greater than operator to find all
employees whose salaries are greater than the average.
SELECT
department_name
FROM
departments d
WHERE
EXISTS( SELECT
1
FROM
employees e
WHERE
salary > 10000
AND e.department_id = d.department_id)
ORDER BY department_name;
Similarly, the following statement finds all departments that do not have
any employee with the salary greater than 10,000:
SELECT
department_name
FROM
departments d
WHERE
NOT EXISTS( SELECT
1
FROM
employees e
WHERE
salary > 10000
AND e.department_id = d.department_id)
ORDER BY department_name;
SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary >= ALL (SELECT
MIN(salary)
FROM
employees
GROUP BY department_id)
ORDER BY first_name , last_name;
SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary >= SOME (SELECT
MAX(salary)
FROM
employees
GROUP BY department_id);
In this example, the subquery finds the highest salary of employees in each
department. The outer query looks at these values and determines which
employee’s salaries are greater than or equal to any highest salary by
department.
SELECT
AVG(salary) average_salary
FROM
employees
GROUP BY department_id;
You can use this query as a subquery in the FROM clause to calculate the
average of average salary of departments as follows:
SELECT
ROUND(AVG(average_salary), 0)
FROM
(SELECT
AVG(salary) average_salary
FROM
employees
GROUP BY department_id) department_salary;
A view is nothing more than a SQL statement that is stored in the database with an
associated name. A view is actually a composition of a table in the form of a
predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be
created from one or many tables which depends on the written SQL query to create
a view.
Views, which are a type of virtual tables allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes)
modify exactly what they need and no more.
Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the
specific implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you
use them in a normal SQL SELECT query.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example to create a view from the CUSTOMERS table. This view
would be used to have customer name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual
table. Following is an example for the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
SQL - Indexes
Indexes are special lookup tables that the database search engine can use to
speed up data retrieval. Simply put, an index is a pointer to data in a table. An index
in a database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain
topic, you first refer to the index, which lists all the topics alphabetically and are then
referred to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down
data input, with the UPDATE and the INSERT statements. Indexes can be created
or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name
the index, to specify the table and which column or columns to index, and to indicate
whether the index is in an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there is an index.
In this chapter, we will discuss the cursors in PL/SQL. Oracle creates a memory area,
known as the context area, for processing an SQL statement, which contains all the
information needed for processing the statement; for example, the number of rows
processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through
a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The
set of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and
process the rows returned by the SQL statement, one at a time. There are two types
of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit
cursor is associated with this statement. For INSERT operations, the cursor holds the
data that needs to be inserted. For UPDATE and DELETE operations, the cursor
identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use
with the FORALL statement. The following table provides the description of the most
used attributes −
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.
2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned no
rows. Otherwise, it returns FALSE.
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer
by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows
affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected
');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result
−
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement which returns more than one
row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
In this chapter, we will discuss Triggers in PL/SQL. Triggers are stored programs,
which are automatically executed or fired when some events occur. Triggers are, in
fact, written to be executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event
is associated.
Benefits of Triggers
Triggers can be written for the following purposes −
Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the
trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just
once when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in
the previous chapters −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS
table. This trigger will display the salary difference between the old values and new
values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at the SQL prompt, it produces the following result
−
Trigger created.
The following points need to be considered here −
OLD and NEW references are not available for table-level triggers, rather you
can use them for record-level triggers.
If you want to query the table in the same trigger, then you should use the
AFTER keyword, because triggers can query the table or change it again only
after the initial changes are applied and the table is back in a consistent state.
The above trigger has been written in such a way that it will fire before any
DELETE or INSERT or UPDATE operation on the table, but you can write your
trigger on a single or multiple operations, for example BEFORE DELETE,
which will fire whenever a record will be deleted using the DELETE operation
on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one
INSERT statement, which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes
as null. Let us now perform one more DML operation on the CUSTOMERS table. The
UPDATE statement will update an existing record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500