You are on page 1of 54

Kalinga University

Department of Computer Science


Course-MCA Sem-II
Subject-Database Management System
Subject Code-MCA204

UNIT-II

Relational Model

Relational Model (RM) represents the database as a collection of relations. A relation is nothing
but a table of values. Every row in the table represents a collection of related data values. These
rows in the table denote a real-world entity or relationship.

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.

Relational Model Concepts

1. Attribute: Each column in a Table. Attributes are the properties which define a relation.
e.g., Student_Rollno, NAME,etc.
2. Tables – In the Relational model the, relations are saved in the table format. It is stored
along with its entities. A table has two properties rows and columns. Rows represent
records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single record.
4. Relation Schema: A relation schema represents the name of the relation with its
attributes.
5. Degree: The total number of attributes which in the relation is called the degree of the
relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called relation
key.
10. Attribute domain – Every attribute has some pre-defined value and scope which is
known as attribute domain

1
Relational Integrity Constraints

Relational Integrity constraints in DBMS are referred to conditions which must be present for a
valid relation. These Relational constraints in DBMS are derived from the rules in the mini-
world that the database represents.

There are many types of Integrity Constraints in DBMS. Constraints on the Relational database
management system is mostly divided into three main categories are:

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:

Create DOMAIN CustomerName


CHECK (value not NULL)

The example shown demonstrates creating a domain constraint such that CustomerName is not
NULL

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:

In the given table, CustomerID is a key attribute of Customer Table. It is most likely to have a
single key for one customer, CustomerID =1 is only for the CustomerName =" Google".

CustomerID CustomerName Status

1 Google Active

2
2 Amazon Active

3 Apple Inactive

Referential Integrity Constraints

Referential Integrity constraints in DBMS are based on the concept of Foreign Keys. A foreign
key is an important attribute of a relation which should be referred to in other relationships.
Referential integrity constraint state happens where relation refers to a key attribute of a different
or same relation. However, that key element must exist in the table.

Example:

In the above example, we have 2 relations, Customer and Billing.

Tuple for CustomerID =1 is referenced twice in the relation Billing. So we know


CustomerName=Google has billing amount $300

Relational Algebra

RELATIONAL ALGEBRA is a widely used procedural query language. 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.

Relational Algebra devided in various groups

Unary Relational Operations

 SELECT (symbol: σ)
 PROJECT (symbol: π)
 RENAME (symbol: ρ)

Relational Algebra Operations From Set Theory

 UNION (υ)
 INTERSECTION ( ),
 DIFFERENCE (-)
 CARTESIAN PRODUCT ( x )

3
Binary Relational Operations

 JOIN
 DIVISION

SELECT (σ)

The SELECT operation is used for selecting a subset of the tuples according to a given selection
condition. Sigma(σ)Symbol denotes it. It is used as an expression to choose tuples which meet
the selection condition. Select operator selects tuples that satisfy a given predicate.

σp(r)

σ is the predicate

r stands for relation which is the name of the table

p is prepositional logic

Example 1

σ topic = "Database" (Tutorials)

Output - Selects tuples from Tutorials where topic = 'Database'.

Example 2

σ topic = "Database" and author = "guru99"( Tutorials)

Output - Selects tuples from Tutorials where the topic is 'Database' and 'author' is guru99.

Example 3

σ sales > 50000 (Customers)

Output - Selects tuples from Customers where sales is greater than 50000

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.

This helps to extract the values of specified attributes to eliminates duplicate values. (pi) symbol
is used to choose attributes from a relation. This operator helps you to keep specific columns
from a relation and discards the other columns.

4
Example of Projection:

Consider the following table

CustomerID CustomerName Status


1 Google Active
2 Amazon Active
3 Apple Inactive
4 Alibaba Active

Here, the projection of CustomerName and status will give

Π CustomerName, Status (Customers)

CustomerName Status
Google Active
Amazon Active
Apple Inactive
Alibaba Active

Rename (ρ)

Rename is a unary operation used for renaming attributes of a relation.

ρ (a/b)R will rename the attribute 'b' of relation by 'a'.

Union operation (υ)

UNION is symbolized by ∪ symbol. It includes all tuples that are in tables A or in B. It also
eliminates duplicate tuples. So, set A UNION set B would be expressed as:

The result <- A ∪ B

For a union operation to be valid, the following conditions must hold -

 R and S must be the same number of attributes.


 Attribute domains need to be compatible.
 Duplicate tuples should be automatically removed.

Example

Consider the following tables.

Table A Table B
column column column column
1 2 1 2

5
1 1 1 1
1 2 1 3

A ∪ B gives

Table A ∪ B
column 1 column 2
1 1
1 2
1 3

Set Difference (-)

- Symbol denotes it. The result of A - B, is a relation which includes all tuples that are in A but
not in B.

 The attribute name of A has to match with the attribute name in B.


 The two-operand relations A and B should be either compatible or Union compatible.
 It should be defined relation consisting of the tuples that are in relation A, but not in B.

Example

A-B
Table A - B
column 1 column 2
1 2

Intersection

An intersection is defined by the symbol ∩

A∩B

Defines a relation consisting of a set of all tuple that are in both A and B. However, A and B
must be union-compatible.

Visual Definition of Intersection

Example:

A∩B

Table A ∩ B

6
column 1 column 2
1 1

Join Operations

Join operation is essentially a cartesian product followed by a selection criterion.

Join operation denoted by ⋈.

JOIN operation also allows joining variously related tuples from different relations.

Types of JOIN:

Various forms of join operation are:

Inner Joins:

 Theta join
 EQUI join
 Natural join

Outer join:

 Left Outer Join


 Right Outer Join
 Full Outer Join

Inner Join:

In an inner join, only those tuples that satisfy the matching criteria are included, while the rest
are excluded. Let's study various types of Inner Joins:

Theta Join:

The general case of JOIN operation is called a Theta join. It is denoted by symbol θ

Example

A ⋈θ B
7
Theta join can use any conditions in the selection criteria.

For example:

A ⋈ A.column 2 > B.column 2 (B)

A ⋈ A.column 2 > B.column 2 (B)


column 1 column 2
1 2

EQUI join:

When a theta join uses only equivalence condition, it becomes a equi join.

For example:

A ⋈ A.column 2 = B.column 2 (B)

A ⋈ A.column 2 = B.column 2 (B)


column 1 column 2
1 1

EQUI join is the most difficult operations to implement efficiently using SQL in an RDBMS and
one reason why RDBMS have essential performance problems.

NATURAL JOIN (⋈)

Natural join can only be performed if there is a common attribute (column) between the
relations. The name and type of the attribute must be same.

Example

Consider the following two tables

C D
Num Square Num Cube
2 4 2 8
3 9 3 27

C⋈D
C⋈D
Num Square Cube
2 4 4
3 9 27

8
OUTER JOIN

In an outer join, along with tuples that satisfy the matching criteria, we also include some or all
tuples that do not match the criteria.

Left Outer Join(A B)

In the left outer join, operation allows keeping all tuple in the left relation. However, if there is
no matching tuple is found in right relation, then the attributes of right relation in the join result
are filled with null values.

Consider the following 2 Tables

A B
Num Square Num Cube
2 4 2 8
3 9 3 18
4 16 5 75

A B

A⋈B
Num Square Cube
2 4 4
3 9 9
4 16 -

Right Outer Join: ( A B)

In the right outer join, operation allows keeping all tuple in the right relation. However, if there is
no matching tuple is found in the left relation, then the attributes of the left relation in the join
result are filled with null values.

A B

A⋈B
Num Cube Square
2 8 4

9
3 18 9
5 75 -

Full Outer Join: (A B)

In a full outer join, all tuples from both relations are included in the result, irrespective of the
matching condition.

A B

A⋈B
Num Cube Square
2 4 8
3 9 18
4 16 -
5 - 75

Relational calculus

Relational calculus is a non-procedural query language, and instead of algebra, it uses


mathematical predicate calculus. The relational calculus is not the same as that of differential and
integral calculus in mathematics but takes its name from a branch of symbolic logic termed as
predicate calculus. When applied to databases, it is found in two forms. These are

 Tuple relational calculus which was originally proposed by Codd in the year 1972 and
 Domain relational calculus which was proposed by Lacroix and Pirotte in the year 1977

In first-order logic or predicate calculus, a predicate is a truth-valued function with arguments.


When we replace with values for the arguments, the function yields an expression, called a
proposition, which will be either true or false.

For example, steps involved in listing all the employees who attend the 'Networking' Course
would be:

SELECT the tuples from COURSE relation with COURSENAME = 'NETWORKING'

PROJECT the COURSE_ID from above result

SELECT the tuples from EMP relation with COURSE_ID resulted above.

Tuple Relational Calculus

10
In the tuple relational calculus, you will have to find tuples for which a predicate is true. The
calculus is dependent on the use of tuple variables. A tuple variable is a variable that 'ranges
over' a named relation: i.e., a variable whose only permitted values are tuples of the relation.

For example, to specify the range of a tuple variable S as the Staff relation, we write:

Staff(S)

To express the query 'Find the set of all tuples S such that F(S) is true,' we can write:

{S | F(S)}

Here, F is called a formula (well-formed formula, or wff in mathematical logic). For example, to
express the query 'Find the staffNo, fName, lName, position, sex, DOB, salary, and branchNo of
all staff earning more than £10,000', we can write:

{S | Staff(S) ∧ S.salary > 10000}


{t | TEACHER (t) and t.SALARY>20000}

- It implies that it selects the tuples from the TEACHER in such a way that the resulting teacher
tuples will have a salary higher than 20000. This is an example of selecting a range of values.

{t | TEACHER (t) AND t.DEPT_ID = 6}

- T select all the tuples of teachers' names who work under Department 8. Any tuple variable
with 'For All' (?) or 'there exists' (?) condition is termed as a bound variable. In the last example,
for any range of values of SALARY greater than 20000, the meaning of the condition does not
alter. Bound variables are those ranges of tuple variables whose meaning will not alter if another
tuple variable replaces the tuple variable.

In the second example, you have used DEPT_ID= 8, which means only for DEPT_ID = 8
display the teacher details. Such a variable is called a free variable. Any tuple variable without
any 'For All' or 'there exists' condition is called Free Variable.

In the tuple relational calculus, you have use variables that have a series of tuples in a relation. In
the domain relational calculus, you will also use variables, but in this case, the variables take
their values from domains of attributes rather than tuples of relations. A domain relational
calculus expression has the following general format:

{d1, d2, . . . , dn | F(d1, d2, . . . , dm)} m ≥ n

where d1, d2, . . . , dn, . . . , dm stand for domain variables and F(d1, d2, . . . , dm) stands for a
formula composed of atoms.

11
select TCHR_ID and TCHR_NAME of teachers who work for department 8, (where suppose -
dept. 8 is Computer Application Department)

{<tchr_id, tchr_name=""> | <tchr_id, tchr_name=""> ? TEACHER Λ DEPT_ID = 10}

Get the name of the department name where Karlos works:

{DEPT_NAME |< DEPT_NAME > ? DEPT Λ ? DEPT_ID ( ? TEACHER Λ


TCHR_NAME = Karlos)}

It is to be noted that these queries are safe. The use domain relational calculus is restricted to safe
expressions; moreover, it is equivalent to the tuple relational calculus, which in turn is similar to
the relational algebra.

Structured Query Language(SQL)

Structured Query Language(SQL) as we all know is the database language by the use of which
we can perform certain operations on the existing database and also we can use this language to
create a database. SQL uses certain commands like Create, Drop, Insert etc. to carry out the
required tasks.

These SQL commands are mainly categorized into four categories as:

1. DDL – Data Definition Language


2. DQl – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language

Though many resources claim there to be another category of SQL clauses TCL – Transaction
Control Language. So we will see in detail about TCL as well.

DDL(Data Definition Language) : DDL or Data Definition Language actually consists of


the SQL commands that can be used to define the database schema. It simply deals with
descriptions of the database schema and is used to create and modify the structure of database
objects in the database.

Examples of DDL commands:

 CREATE – is used to create the database or its objects (like table, index, function,
views, store procedure and triggers).
 DROP – is used to delete objects from the database.
 ALTER-is used to alter the structure of the database.
 TRUNCATE–is used to remove all records from a table, including all spaces allocated
for the records are removed.

12
 COMMENT –is used to add comments to the data dictionary.
 RENAME –is used to rename an object existing in the database.

DQL (Data Query Language) :

DML statements are used for performing queries on the data within schema objects. The purpose
of DQL Command is to get some schema relation based on the query passed to it.

Example of DQL:

 SELECT – is used to retrieve data from the a database.

DML(Data Manipulation Language) : The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data Manipulation Language and
this includes most of the SQL statements.

Examples of DML:

 INSERT – is used to insert data into a table.


 UPDATE – is used to update existing data within a table.
 DELETE – is used to delete records from a database table.

DCL(Data Control Language) : DCL includes commands such as GRANT and REVOKE
which mainly deals with the rights, permissions and other controls of the database system.

Examples of DCL commands:

 GRANT-gives user’s access privileges to database.


 REVOKE-withdraw user’s access privileges given by using the GRANT command.

TCL(transaction Control Language) : TCL commands deals with the transaction within the
database.

Examples of TCL commands:

 COMMIT– commits a Transaction.


 ROLLBACK– rollbacks a transaction in case of any error occurs.
 SAVEPOINT–sets a savepoint within a transaction.

Tables-
The SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.

13
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

The column parameters specify the names of the columns of the table.

The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date,
etc.).

Tip: For an overview of the available data types, go to our complete Data Types Reference.

SQL CREATE TABLE Example

The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:

Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

The PersonID column is of type int and will hold an integer.

The LastName, FirstName, Address, and City columns are of type varchar and will hold
characters, and the maximum length for these fields is 255 characters.

The empty "Persons" table will now look like this:

PersonID LastName FirstName Address City

14
Create Table Using Another Table

A copy of an existing table can also be created using CREATE TABLE.

The new table gets the same column definitions. All columns or specific columns can be
selected.

If you create a new table using an existing table, the new table will be filled with the existing
values from the old table.

Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;

The following SQL creates a new table called "TestTables" (which is a copy of the "Customers"
table):

Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;Top of Form
Test Yourself W Exercises

Write the correct SQL statement to create a new table called Persons.

(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

15
SQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples

The following SQL creates a view that shows all customers from Brazil:

Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

We can query the view above as follows:

Example
SELECT * FROM [Brazil Customers];

The following SQL creates a view that selects every product in the "Products" table with a price
higher than the average price:

Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price

16
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

We can query the view above as follows:

Example
SELECT * FROM [Products Above Average Price];

Creating Indexes

Now that you are familiar with the different index architectures, we will discuss creating and
dropping indexes and obtaining information on existing indexes.

You create indexes by using the CREATE INDEX statement and can remove them by using the
DROP INDEX statement.

Using the CREATE INDEX Statement

Use the CREATE INDEX statement to create indexes. You also can use the Create Index Wizard
in SQL Server Enterprise Manager. When you create an index on one or more columns in a
table, consider the following facts and guidelines:

 SQL Server automatically creates indexes when a PRIMARY KEY or UNIQUE


constraint is created on a table. Defining a PRIMARY KEY or UNIQUE constraint is
preferred over creating standard indexes.
 You must be the table owner to execute the CREATE INDEX statement.
 Indexes can be created on views.
 SQL Server stores index information in the sys indexes system table.
 Before you create an index on a column, determine whether indexes already exist on that
column.
 Keep your indexes small by defining them on columns that are small in size. Typically,
smaller indexes are more efficient than indexes with larger key values.
 Select columns on the basis of uniqueness so that each key value identifies a small
number of rows.
When you create a clustered index, all existing nonclustered indexes are rebuilt.

CREATE INDEX idx_lastname ON Persons (LastName);

Use the DROP INDEX statement to remove an index on a table.

DROP INDEX table_name.index_name;

This example drops the cl_lastname index from the Member table.
17
USE Northwind

DROP INDEX employees.CL_lastname

Query and Subqeries


A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
 An ORDER BY command cannot be used in a subquery, although the main query can
use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
 Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
 The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.

Subqueries with the SELECT Statement

Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows

SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

18
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Subqueries with the INSERT Statement

Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
The basic syntax is as follows.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

19
Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

Subqueries with the UPDATE Statement

The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS
table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for
all the customers whose AGE is greater than or equal to 27.
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

20
Subqueries with the DELETE Statement

The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the CUSTOMERS table
for all the customers whose AGE is greater than or equal to 27.
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following
records.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

21
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

1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

22
Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

23
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>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

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST

24
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

Com1 150
Com2 170

Example: SUM() with HAVING

1. SELECT COMPANY, SUM(COST)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=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

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

25
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

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Example:

1. SELECT MAX(RATE)
2. 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

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10

26
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

The Second table,

ID Name

2 adam

3 Chester

Union SQL query will be,

SELECT * FROM First

UNION

SELECT * FROM Second;

The resultset table will look like,

27
ID NAME

1 abhi

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.
Example of Intersect
The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

28
2 adam

3 Chester

Intersect query will be,

SELECT * FROM First

INTERSECT

SELECT * FROM Second;

The resultset table will look like

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

29
2 adam

The Second table,

ID NAME

2 adam

3 Chester

Minus query will be,

SELECT * FROM First

MINUS

SELECT * FROM Second;

The resultset table will look like,

ID NAME

1 abhi

SQL JOIN
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. It is used for combining column from two or more tables by using values common to both
tables.

30
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
Following are the types of JOIN that we can use in SQL:

 Inner

 Outer

 Left

 Right

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

31
1 abhi

2 adam

4 alex

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Cross JOIN query will be,

SELECT * FROM

class CROSS JOIN class_info;

The resultset table will look like,

ID NAME ID Address

32
1 abhi 1 DELHI

2 adam 1 DELHI

4 alex 1 DELHI

1 abhi 2 MUMBAI

2 adam 2 MUMBAI

4 alex 2 MUMBAI

1 abhi 3 CHENNAI

2 adam 3 CHENNAI

4 alex 3 CHENNAI

As you can see, this join returns the cross product of all the records present in both the tables.

INNER Join or EQUI Join


This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the SQL query.

33
Inner Join Syntax is,

SELECT column-name-list FROM

table-name1 INNER JOIN table-name2

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

Example of INNER JOIN


Consider a class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

and the class_info table,

ID Address

1 DELHI

34
2 MUMBAI

3 CHENNAI

Inner JOIN query will be,

SELECT * from class INNER JOIN class_info where class.id = class_info.id;

The resultset table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 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;

35
Example of Natural JOIN
Here is the class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Natural join query will be,

SELECT * from class NATURAL JOIN class_info;

36
The resultset table will look like,

ID NAME Address

1 abhi DELHI

2 adam MUMBAI

3 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,

1. Left Outer Join

2. Right Outer Join

3. Full Outer Join

LEFT Outer Join


The left outer join returns a resultset table with the matched data from the two tables and then
the remaining rows of the left table and null from the right table's columns.
Syntax for Left Outer Join is,

SELECT column-name-list FROM

table-name1 LEFT OUTER JOIN table-name2

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

To specify a condition, we use the ON keyword with Outer Join.


Left outer Join Syntax for Oracle is,

SELECT column-name-list FROM

table-name1, table-name2 on table-name1.column-name = table-name2.column-name(+);

Example of Left Outer Join


Here is the class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

and the class_info table,

ID Address

38
1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Left Outer Join query will be,

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

The resultset table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

39
4 anu null null

5 ashish null null

RIGHT Outer Join


The right outer join returns a resultset table with the matched data from the two tables being
joined, then the remaining rows of the right table and null for the remaining left table's columns.
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;

Right outer Join Syntax for Oracle is,

SELECT column-name-list FROM

table-name1, 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

40
2 adam

3 alex

4 anu

5 ashish

and the class_info table,

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);


41
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


The full outer join returns a resultset table with the matched data of two table then remaining
rows of both left table and then the right table.
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,

42
ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

43
7 NOIDA

8 PANIPAT

Full Outer Join query will be like,

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

The resultset table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

null null 7 NOIDA

44
null null 8 PANIPAT

Triggers

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 −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

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

45
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

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)

46
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 −

47
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

Cursors

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor
holds is referred to as the active set.

You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −

 Implicit cursors
 Explicit cursors

Implicit Cursors

Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,
designed for use with the FORALL statement. The following table provides the description of
the most used attributes −

S.No Attribute & Description

48
1 %FOUND

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.
3 %ISOPEN

Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
4 %ROWCOUNT

Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or


returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.

Example

We will be using the CUSTOMERS table we had created and used in the previous chapters.

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+

The following program will update the table and increase the salary of each customer by 500 and
use the SQL%ROWCOUNT attribute to determine the number of rows affected −

DECLARE
total_rows number(2);
BEGIN
UPDATE customers

49
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

If you check the records in customers table, you will find that the rows have been updated −

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

Explicit Cursors

Explicit cursors are programmer-defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.

The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory

50
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor

Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example −

CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor

Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows
returned by the SQL statement into it. For example, we will open the above defined cursor as
follows −

OPEN c_customers;

Fetching the Cursor

Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from
the above-opened cursor as follows −

FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor

Closing the cursor means releasing the allocated memory. For example, we will close the above-
opened cursor as follows −

CLOSE c_customers;

Example

Following is a complete example to illustrate the concepts of explicit cursors &minua;

DECLARE
c_id customers.id%type;
c_name customer.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP

51
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL Procedure

The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks. It is just like procedures in other programming languages.

The procedure contains a header and a body.

o Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
o Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.

How to pass parameters in procedure:

When you want to create a procedure or function, you have to define parameters .There is three
ways to pass parameters in procedure:

1. IN parameters: The IN parameter can be referenced by the procedure or function. The


value of the parameter cannot be overwritten by the procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure or
function, but the value of the parameter can be overwritten by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure or
function and the value of the parameter can be overwritten by the procedure or function.

52
A procedure may or may not return any value.

PL/SQL Create Procedure

Syntax for creating procedure:

1. CREATE [OR REPLACE] PROCEDURE procedure_name


2. [ (parameter [,parameter]) ]
3. IS
4. [declaration_section]
5. BEGIN
6. executable_section
7. [EXCEPTION
8. exception_section]
9. END [procedure_name];

Create procedure example

In this example, we are going to insert record in user table. So you need to create user table first.

Table creation:

1. create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user values(id,name);
7. end;
8. /

Output:

Procedure created.

53
PL/SQL program to call procedure

Let's see the code to call above created procedure.

1. BEGIN
2. insertuser(101,'Rahul');
3. dbms_output.put_line('record inserted successfully');
4. END;
5. /

Now, see the "USER" table, you will see one record is inserted.

ID Name

101 Rahul

PL/SQL Drop Procedure

Syntax for drop procedure

1. DROP PROCEDURE procedure_name;

Example of drop procedure

1. DROP PROCEDURE pro1;

54

You might also like