Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views23 pages

Unit 4 Rdbms

The document provides an overview of Relational Database Management Systems, focusing on database objects such as views, procedures, functions, and triggers. It explains how to create, update, and delete views and procedures in SQL, along with examples and syntax for each operation. Additionally, it discusses the purpose and benefits of triggers in database management.

Uploaded by

funhindi4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views23 pages

Unit 4 Rdbms

The document provides an overview of Relational Database Management Systems, focusing on database objects such as views, procedures, functions, and triggers. It explains how to create, update, and delete views and procedures in SQL, along with examples and syntax for each operation. Additionally, it discusses the purpose and benefits of triggers in database management.

Uploaded by

funhindi4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Relational Database Management System

Database Objects
A database object is any defined object in a database that is used to store or reference
data.Anything which we make from create command is known as Database Object.It
can be used to hold and manipulate the data.Some of the examples of database objects
are : View, Procedure, Function, Trigger, Sequence etc.

Views
Views in SQL are a kind of virtual table. A view also has rows and columns like tables,
but a view doesn’t store data on the disk like a table. View defines a customized query
that retrieves data from one or more tables, and represents the data as if it was coming
from a single source.

We can create a view by selecting fields from one or more tables present in the
database. A View can either have all the rows of a table or specific rows based on
certain conditions.
We will learn about creating, updating, and deleting views in SQL.

Demo SQL Database


We will be using these two SQL tables for examples.
StudentDetails

StudentMarks

You can create these tables on your system by writing the following SQL query:

Miss. Hemangi Panchal Page 1


Relational Database Management System

-- Create StudentDetails table


CREATE TABLE StudentDetails (
S_ID INT PRIMARY KEY,
NAME VARCHAR(255),
ADDRESS VARCHAR(255)
);

INSERT INTO StudentDetails (S_ID, NAME, ADDRESS)


VALUES
(1, 'Harsh', 'Kolkata'),
(2, 'Ashish', 'Durgapur'),
(3, 'Pratik', 'Delhi'),
(4, 'Dhanraj', 'Bihar'),
(5, 'Ram', 'Rajasthan');

-- Create StudentMarks table


CREATE TABLE StudentMarks (
ID INT PRIMARY KEY,
NAME VARCHAR(255),
Marks INT,
Age INT
);

INSERT INTO StudentMarks (ID, NAME, Marks, Age)


VALUES
(1, 'Harsh', 90, 19),
(2, 'Suresh', 50, 20),
(3, 'Pratik', 80, 19),
(4, 'Dhanraj', 95, 21),
(5, 'Ram', 85, 18);

CREATE VIEWS in SQL


We can create a view using CREATE VIEW statement. A View can be created from a
single table or multiple tables.

Syntax

CREATE VIEW view_name AS

Miss. Hemangi Panchal Page 2


Relational Database Management System

SELECT column1, column2.....


FROM table_name
WHERE condition;
Parameters:

● view_name: Name for the View


● table_name: Name of the table
● condition: Condition to select rows

SQL CREATE VIEW Statement Examples


Let’s look at some examples of CREATE VIEW Statement in SQL to get a better
understanding of how to create views in SQL.
Example 1: Creating View from a single table

In this example, we will create a View named DetailsView from the table StudentDetails.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;

To see the data in the View, we can query the view in the same manner as we query a
table.
SELECT * FROM DetailsView;
Output:

Miss. Hemangi Panchal Page 3


Relational Database Management System

Example 2: Create View From Table

In this example, we will create a view named StudentNames from the table
StudentDetails. Query:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

Example 3: Creating View from multiple tables

In this example we will create a View named MarksView from two tables StudentDetails
and StudentMarks. To create a View from multiple tables we can simply include multiple
tables in the SELECT statement. Query:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:

Miss. Hemangi Panchal Page 4


Relational Database Management System

DELETE VIEWS in SQL


SQL allows us to delete an existing View. We can delete or drop View using the DROP
statement.

Syntax

DROP VIEW view_name;

Example

In this example, we are deleting the View MarksView.


DROP VIEW MarksView;

UPDATE VIEW in SQL


If you want to update the existing data within the view, use the UPDATE statement.

Syntax

UPDATE view_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Note: Not all views can be updated using the UPDATE statement.

If you want to update the view definition without affecting the data, use the CREATE OR
REPLACE VIEW statement. you can use this syntax

CREATE OR REPLACE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name

Miss. Hemangi Panchal Page 5


Relational Database Management System

WHERE condition;

Rules to Update Views in SQL:

Certain conditions need to be satisfied to update a view. If any of these conditions are
not met, the view can not be updated.

1. The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using
multiple tables then we will not be allowed to update the view.

Examples

Let’s look at different use cases for updating a view in SQL. We will cover these use
cases with examples to get a better understanding.

Example 1: Update View to Add or Replace a View Field

We can use the CREATE OR REPLACE VIEW statement to add or replace fields from
a view.

If we want to update the view MarksView and add the field AGE to this View from
StudentMarks Table, we can do this by:
CREATE OR REPLACE VIEW MarksView AS

SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,


StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

Miss. Hemangi Panchal Page 6


Relational Database Management System

Example 2: Update View to Insert a row in a view

We can insert a row in a View in the same way as we do in a table. We can use the
INSERT INTO statement of SQL to insert a row in a View.

In the below example, we will insert a new row in the View DetailsView which we have
created above in the example of “creating views from a single table”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

Example 3: Deleting a row from a View

Deleting rows from a view is also as simple as deleting rows from a table. We can use
the DELETE statement of SQL to delete rows from a view. Also deleting a row from a
view first deletes the row from the actual table and the change is then reflected in the
view.
In this example, we will delete the last row from the view DetailsView which we just
added in the above example of inserting rows.

Miss. Hemangi Panchal Page 7


Relational Database Management System

DELETE FROM DetailsView


WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

Procedure

A Procedure is a logically grouped set of SQL and PL/SQL statements that perform a
specific task. A stored procedure is a named PL/SQL code block that has been
compiled and stored in one of the Oracle engine’s system tables.

To make a Procedure dynamic either of them can be passed parameters before


execution. A Procedure can then change the way it works depending upon the
parameters passed prior to its execution.

S.No Parts & Description

Declarative Part
It is an optional part. However, the declarative part for a subprogram does not
start with the DECLARE keyword. It contains declarations of types, cursors,
1
constants, variables, exceptions, and nested subprograms. These items are
local to the subprogram and cease to exist when the subprogram completes
execution.

Miss. Hemangi Panchal Page 8


Relational Database Management System

Executable Part
2 This is a mandatory part and contains statements that perform the
designated action.

Exception-handling
3 This is again an optional part. It contains the code that handles run-time
errors.

Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The

simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows


CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

Where,

● procedure-name specifies the name of the procedure.


● [OR REPLACE] option allows the modification of an existing procedure.
● The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the
parameter that will be used to return a value outside of the procedure.
● procedure-body contains the executable part.
● The AS keyword is used instead of the IS keyword for creating a standalone
procedure.

Example

The following example creates a simple procedure that displays the string 'Hello World!'
on the screen when executed.

SQL> SET SERVEROUTPUT ON;


SQL>

Miss. Hemangi Panchal Page 9


Relational Database Management System

CREATE OR REPLACE PROCEDURE greetings


AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/

When the above code is executed using the SQL prompt, it will produce the following

result −

Procedure created.

Executing a Procedure

A standalone procedure can be called in two ways −

● Using the EXECUTE keyword


● Calling the name of the procedure from a PL/SQL block

The above procedure named 'greetings' can be called with the EXECUTE keyword as

EXECUTE greetings;

The above call will display −

Hello World
PL/SQL procedure successfully completed.

The procedure can also be called from another PL/SQL block −

BEGIN
greetings;
END;
/

Miss. Hemangi Panchal Page 10


Relational Database Management System

The above call will display −

Hello World
PL/SQL procedure successfully completed.

Deleting a Standalone Procedure

A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for

deleting a procedure is −

DROP PROCEDURE procedure-name;

You can drop the greetings procedure by using the following statement −

DROP PROCEDURE greetings;

Parameter Modes in PL/SQL Subprograms

The following table lists out the parameter modes in PL/SQL subprograms −

S.N Parameter Mode & Description


o

IN
1 Indicates that the parameter will accept a value from the user.

OUT
2 Indicates that the parameter will return a value to the user.

Miss. Hemangi Panchal Page 11


Relational Database Management System

IN OUT

3 Indicates that the parameter will either accept a value from the user or return a
value to the user.

Example
/* Creating and Declaring Procedure */
Declare
Num1 number(2);
Num2 number(2);
Mul number(4);

Procedure Multiplication (Num1 IN number, Num2 IN number, Mul OUT number) IS


Begin
Mul := Num1 * Num2;
End multiplication;

/* Calling Procedure */
Begin
Num1 := &num1;
Num2 := &num2;
Multiplication(Num1,Num2,Mul);
DBMS_OUTPUT.PUT_LINE(Mul);
END;
/

Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference
between procedure and a function is, a function must always return a value, and on the

Miss. Hemangi Panchal Page 12


Relational Database Management System

other hand a procedure may or may not return a value. Except this, all the other things
of PL/SQL procedure are true for PL/SQL function too.

Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The

simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Where,

● function-name specifies the name of the function.


● [OR REPLACE] option allows the modification of an existing function.
● The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the
parameter that will be used to return a value outside of the procedure.
● The function must contain a return statement.
● The RETURN clause specifies the data type you are going to return from the
function.
● function-body contains the executable part.
● The AS keyword is used instead of the IS keyword for creating a standalone
function.

Miss. Hemangi Panchal Page 13


Relational Database Management System

Example

The following example illustrates how to create and call a standalone function. This
function returns the total number of CUSTOMERS in the customers table.

We will use the CUSTOMERS table, which we had created in the PL/SQL Variables

chapter −

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 |
+----+----------+-----+-----------+----------+

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/

Miss. Hemangi Panchal Page 14


Relational Database Management System

When the above code is executed using the SQL prompt, it will produce the following

result −

Function created.

Calling a Function
While creating a function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task. When a program
calls a function, the program control is transferred to the called function.

A called function performs the defined task and when its return statement is executed or
when the last end statement is reached, it returns the program control back to the main
program.

To call a function, you simply need to pass the required parameters along with the

function name and if the function returns a value, then you can store the returned value.

Following program calls the function totalCustomers from an anonymous block −

DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/

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

Total no. of Customers: 6

Miss. Hemangi Panchal Page 15


Relational Database Management System

PL/SQL procedure successfully completed.

Trigger

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

Creating Triggers

Miss. Hemangi Panchal Page 16


Relational Database Management System

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.

Miss. Hemangi Panchal Page 17


Relational Database Management System

● [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 |

Miss. Hemangi Panchal Page 18


Relational Database Management System

+----+----------+-----+-----------+----------+

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.

Miss. Hemangi Panchal Page 19


Relational Database Management System

● 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

Miss. Hemangi Panchal Page 20


Relational Database Management System

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

Sequence
SQL sequences specify the properties of a sequence object while creating it. An object
bound to a user-defined schema called a sequence produces a series of numerical
values in accordance with the specification used to create it. The series of numerical
values can be configured to restart (cycle) when it runs out and is generated in either
ascending or descending order at a predetermined interval. Contrary to identity
columns, sequences are not linked to particular tables. Applications use a sequence
object to access the next value in the sequence. The application has control over how
sequences and tables interact. A sequence object can be referred to by user
applications, and the values can be coordinated across various rows and tables.

Let’s suppose that sequence is a set of integers 1, 2, 3, … that are generated and
supported by some database systems to produce unique values on demands.

● A sequence is a user-defined schema-bound object that generates a series of


numeric values.

● Sequences are frequently used in many databases because many


applications require each row in a table to contain a unique value and
sequences provide an easy way to generate them.

● The sequence of numeric values is generated in an ascending or descending


order at defined intervals and can be configured to restart when it exceeds
max_value.

Miss. Hemangi Panchal Page 21


Relational Database Management System

Syntax:

CREATE SEQUENCE sequence_name

START WITH initial_value

INCREMENT BY increment_value

MINVALUE minimum value

MAXVALUE maximum value;

Following is the sequence query creating a sequence in ascending order.

Example 1:

SQL> CREATE TABLE STUDENTS (STD_ID NUMBER PRIMARY KEY, STD_NAME


VARCHAR2(20));

Table created.

SQL> CREATE SEQUENCE STD_SEQ

INCREMENT BY 1

START WITH 100

MAXVALUE 999

MINVALUE 1

Miss. Hemangi Panchal Page 22


Relational Database Management System

Sequence created.

SQL> INSERT INTO STUDENTS VALUES(STD_SEQ.NEXTVAL,('DHARMIK'));

1 row created.

SQL> SELECT *FROM STUDENTS;

STD_ID STD_NAME

---------- --------------------

100 DHARMIK

SQL> INSERT INTO STUDENTS VALUES(STD_SEQ.NEXTVAL,('JAYMIN'));

1 row created.

SQL> SELECT *FROM STUDENTS;

STD_ID STD_NAME

---------- --------------------

100 DHARMIK

101 JAYMIN

Miss. Hemangi Panchal Page 23

You might also like