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

Institute of Engineering and Management

Department of
Computer Science and Engineering

Database Management Laboratory (CS 691)

Lab Manual
Syllabus

Contact: 3P
Credits: 2
1. Structured Query Language
➢ Creating Database
➢ Creating a Database
➢ Creating a Table
➢ Specifying Relational Data Types
➢ Specifying Constraints
➢ Creating Indexes
2. Table and Record Handling
➢ INSERT statement
➢ Using SELECT and INSERT together
➢ DELETE, UPDATE, TRUNCATE statements
➢ DROP, ALTER statements
3. Retrieving Data from a Database
➢ The SELECT statement
➢ Using the WHERE clause
➢ Using Logical Operators in the WHERE clause
➢ Using IN, BETWEEN, LIKE , ORDER BY, GROUP BY and
HAVING
➢ Clause
➢ Using Aggregate Functions
➢ Combining Tables Using JOINS
➢ Subqueries
4. Database Management
➢ Creating Views
➢ Creating Column Aliases
➢ Creating Database Users
➢ Using GRANT and REVOKE
Cursors in Oracle PL / SQL
Writing Oracle PL / SQL Stored Procedures

2
CSE DBMS Lab Manual

Oracle Class I

IMPLEMENTATION OF DDL COMMANDS

AIM:

To create a DDL to perform creation of table, alter, modify and drop column.

DDL COMMANDS

1.The Create Table Command: - it defines each column of the table uniquely.
Each column has minimum of three attributes, a name , data type and size.
Syntax:

Create table <table name> (<col1> <datatype>(<size>),<col2>


<datatype><size>)); Ex:create table emp(empno number(4) primary
key, ename char(10));

2.Modifying the structure of tables.

a) Add new

columns Syntax:

Alter table <tablename> add(<new col><datatype(size),<new


col>datatype(size)); Ex:alter table emp add(sal number(7,2));

3.Dropping a column from a table.

Syntax:

Alter table <tablename> drop column <col>; Ex:alter table emp drop
column sal;

4.Modifying existing columns.

Syntax:

Alter table <tablename> modify(<col><newdatatype>(<newsize>)); Ex:alter


table emp modify(ename varchar2(15));

3
CSE DBMS Lab Manual

5.Renaming the tables

Syntax: Rename <oldtable> to <new table>; Ex:rename emp to emp1;

6.truncating the tables.

Syntax: Truncate table <tablename>; Ex:trunc table emp1;

7.Destroying tables.

Syntax: Drop table <tablename>; Ex:drop table emp;

CREATION OF TABLE:

SYNTAX: create table<tablename>(column1 datatype,column2 datatype...);

EXAMPLE:

SQL>create table std(sno number(5),sname varchar(20),age


number(5),sdob date,sm1 number(4,2),sm2 number(4,2),sm3
number(4,4)); Table created.

SQL>insert into std values(101,’AAA’,16,’03-jul-88’,80,90,98); 1 row created.


SQL>insert into std values(102,’BBB’,18,’04-aug-89’,88,98,90); 1 row created.
OUTPUT:

Select * from std;

SNO SNAME AGE SDOB SM1 SM2 SM3


101 AAA 16 03-jul-8880 90 98
102 BBB 18 04-aug-89 88 98 90

ALTER TABLE WITH ADD:

SQL>create table student(id number(5),name varchar(10),game varchar(20));


Table created.
SQL>insert into student values(1,’mercy’,’cricket’); 1 row created.

4
CSE DBMS Lab Manual

SYNTAX:
alter table <tablename> add (col1 datatype, col2 datatype..);

EXAMPLE: SQL>alter table student add(age number(4)); SQL>insert


into student values(2,’sharmi’,’tennis’,19);

OUTPUT:

ALTER: select * from student; ID NAME GAME


1 Mercy Cricket

ADD: select * from student; ID NAME GAME AGE


1 Mercy cricket

2 Sharmi Tennis 19
ALTER TABLE WITH MODIFY:

SYNTAX:

Alter table <tablename> modify (col1 datatype, col2 datatype..);

EXAMPLE:
SQL> alter table student modify (id number(6), game varchar(25));
OUTPUT:
MODIFY desc student;

DROP:
SYNTAX: drop table<tablename>;

EXAMPLE:
SQL>drop table student; SQL>Table dropped

5
CSE DBMS Lab Manual

TRUNCATE TABLE

SYNTAX: TRUNCATE TABLE <TABLE NAME>;

Example: Truncate table stud;


DESC

Example: desc emp;


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

EmpNo NOT NULL number(5) EName VarChar(15)


Job NOT NULL Char(10)

DeptNo NOT NULL number(3) PHONE_NO number (10)

CONSTRAINTS:

Create table tablename (column_name1 data_ type constraints,


column_name2 data_ type constraints …)
Example:

Create table Emp ( EmpNo number(5), EName VarChar(15), Job


Char(10) constraint un unique, DeptNo number(3) CONSTRAINT
FKey2 REFERENCES DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null,dob
date not null);

DOMAIN INTEGRITY

Example: Create table cust(custid number(6) not null, name char(10)); Alter
table cust modify (name not null);

CHECK CONSTRAINT

Example: Create table student (regno number (6), mark number (3)
constraint b check (mark
>=0 and mark <=100)); Alter table student add constraint
b2 check (length(regno<=4));

6
CSE DBMS Lab Manual

ENTITY INTEGRITY

a)Unique key constraint


Example: Create table cust(custid number(6) constraint unique, name
char(10)); Alter table cust add(constraint c unique(custid)); b)Primary
Key Constraint
Example: Create table stud(regno number(6) constraint primary key, name
char(20));

Assignment -I

1. Create a table called EMP with the following


structure. Name Type
---------- ----------------------
EMPNO NUMBER(6) ENAME VARCHAR2(20) JOB
VARCHAR2(10) DEPTNO NUMBER(3) SAL
NUMBER(7,2)
Allow NULL for all columns except ename and job.
2. Add a column experience to the emp table. experience numeric null
allowed.

3. Modify the column width of the job field of emp table.

4. create the emp1 table with ename and empno, add constraints to
check the empno value while entering (i.e) empno > 100.
Output-

7
CSE DBMS Lab Manual
Oracle Class II

Overview of select , insert , update , delete statements

SELECT
• Selecting some of the columns -> Projection
• Alias names if contains space or special symbol , then it needs to be put
in
double quotes
• Distinct and unique can be used to remove duplicates comparison
operators =; !=
or <>; <; >;<=, => are allowed in the conditions of a where clause.
• One useful query to get the number of queries is count(*)
• Order by , by default gives result in ascending order
• For string type of data like can be used.
• | | is used as a concatenation operator for strings and string literal is to be
enclosed within single quotes.
• Multiple conditions can be concatenated using and or etc
• for range queries we can use between and .
• Example : Select emailto, email from email where size between 10 and
20;
• IN for multiple values
• Select city, population from citydetails where city in
(‘kol’,’mum’,’del’,’chn’);
Similarly not in can be used
• Like to be used for pattern matching ‘a%’,‘%a%’ and ‘%a’
• An input value can be taken form the user , using and &
• select * from dept where deptno=&no;

• Syntax -
[DISTINCT | UNIQUE] (*, columnname [ AS alias], …) FROM
tablename [WHERE
condition] [GROUP BY
group_by_expression]
[HAVING group_condition]
[ORDER BY columnname];
Case sensitivity,whitespace, terminators
• SQL commands have the same meaning whether used with uppercase or
lowercase characters
• various SQL elements, or "words", must be separated by
whitespace (usually a "space" character), the use of extra spaces,
tabs, and end-of-line character has
little effect on the syntactical correctness of the statement.

8
CSE DBMS Lab Manual

• In Oracle SQL, two statement terminators can be used; the


semicolon (;) and the forward slash (/). The two are similar in their
use, the main difference being that
the forward slash can only be used on a separate line.
Aliasing:
select dname as "Departmentname" , loc as "Location" from dept;

Dual, dummy column

• How do we display a string literal for each row of the table


o select 'abc' as ABC from dept;

o select 'greetings from flipkart'as msg from dual;

DUAL is essentially a pseudo-table—it has no real data and is generally


used for string manipulation and mathematical computation.

The only column in dual is DUMMY, and the only row value
is X. Select sysdate from dual;

Assignment -II
1. Write query to select all the columns of emp table.
2. Write query to select only Empname, Ename andJob.
3. Write query to select unique Jobs.
4. write query to select only those employees who are salesman
5. select employee name , grade and salary , in the order of their salary
6. Mgmt is considering a pay raise , however they want to find out , if they
give a flat 200$ increment to all , then what % each person is getting . So
in your result display , ename , salary and pctincr
7. Express work experience of each of the employees by using sysdate and
hiredate in terms of no of years.

Hints : you would need to use cast ; use emp table and use different columns
and string concatenation to display a message like below for each of the
employees

9
CSE DBMS Lab Manual

Output Example :

JAMES is a CLERK and is working in the company for last 32Years

• use emp table to display only those employees who have joined
in the year 80 and 81.

Comment on if between clause is inclusive or exclusive

Output:

10
CSE DBMS Lab Manual

Oracle Class III

[Group by , Havin, Insert/Update/Delete, System Functions, Set Operators,

Group By]

• Group by The result will return # rows based in the group columns, basically based

on distinct combination of group by columns

• Some aggregate functions needs to be used on the columns. Example : Sum, Avg, Min, Max

, count(*) etc

• ‘Having’ is used to restrict some of the groups appearing in the result

Syntax-

Select <column(s)>

from <table(s)>

[where <condition>]

group by <group column(s)>

[having <group condition(s)>];

Insert/Update/Delete

Insert into <table> [(<column i, : : : , column j>)]

values (<value i, : : : , value j>);

• For each of the listed columns, a corresponding (matching) value must be specified.

• Insertion does not necessarily have to follow the order of the attributes as
specified in the create table statement

• If a column is omitted, the value null is inserted instead

update <table> set

<column i> = <expression i>, : : : , <column j> = <expression j>

11
CSE DBMS Lab Manual

[where <condition>];

delete from <table> [where <condition>];

Case conversion ,String

• Following are few String Functions

• Upper • Lower

• Initcap • Length

• Lpad • Rpad

• Rtrim • • Ltrim

Concat • substr • instr

Syntax-

SUBSTR(column_expression, start position, end position)

INSTR(column_expression, search_character, starting_position, occurrence_number)

Lpad/Rpad (Column, length,padding column)

Case sensitivity, whitespace, terminators

• SQL commands have the same meaning whether used with uppercase or lowercase
characters

• various SQL elements, or "words", must be separated by whitespace (usually


a "space" character), the use of extra spaces, tabs, and end-of-line character

has little effect on the syntactical correctness of the statement.

• In Oracle SQL, two statement terminators can be used; the semicolon (;) and the
forward slash (/). The two are similar in their use, the main difference being that the
forward slash can only be used on a separate line.

• Aliasing:

select dname as "Departmentname" , loc as "Location" from dept;

12
CSE DBMS Lab Manual

Set operators

• Set operators can be used to combine records from multiple tables

• Different operators are union, union all, intersect , minus respectively

• Union removes the duplicates , where as union all does not

• Both the sets need to have the same no of columns and compatible datatypes

Assignment -III

1. List down no of employees, minimum salary , maximum salary


for each department

2. Update Email_id , if department id is

a. < 1000 update the EMAIL field by appending @oracle.com b.


< 5000 update the EMAIL field by appending @oracle.co.uk

c. Else update it as oracle.co.in

d. Apart from ‘Delete’ a‘Truncate’ statement can also be used for deleting
the rows. Comment on their difference.

e. Display a department id wise count of employees

• Getting salary more than 5000


• Apart from the above condition, select only those
departments which has an average salary in excess of 6500

f. Explain how two levels of filtering is happening based on firstly where


clause secondly having clause based on this particular scenario

g. You want to add a new row in the employees table with employee id
10000, First Name = ‘Scott’ , Last Name = ‘Tiger’ , Email = Stiger, Hire
Date , 01/02/2014, Job id PR_Prsdnt ( Title ‘Company President’ )
Department_id 280 ( Department_Name ‘Database’ ) Salary 50000

h. Issue necessary insert statements.

i. After the update is over in the email column , use instr and substr to
display email id and domain information separately.

j. Display day , month and year of the hire date of the employees.

13
CSE DBMS Lab Manual

Output

14
CSE DBMS Lab Manual

Oracle Class IV

Joins Subquery

Join

A join query extracts information from two or more tables or views.A

join query differs from a regular query in at least the following two ways:

• The FROM clause of a join query refers to two or more tables or


views.

• A condition is specified in the join query (known as join condition)

that relates the rows of one table to the rows of another table.

Syntax

SELECT departments.location_id, departments.department_name,

locations.state_province FROM

departments JOIN locations

ON departments.location_id = locations.location_id;

Type of Joins

• Inner Join : Inner joins are the regular joins.An inner join returns the

rows that

satisfy the join condition.

• Outer Join : Outer joins are an extension to inner joins.An outer join

returns the rows that satisfy the join condition and also the rows from

one table for which no corresponding rows(i.e., that satisfy the join

15
CSE DBMS Lab Manual

condition) exist in the other table.

• FROM table1 { LEFT | RIGHT | FULL } [OUTER] JOIN table2


o Left Outer join :

o Right Outer Join

o Full outer Join

• Cartesian join or cross join

when you don't specify a join condition when joining two tables

• Self joins

A self join is a join of a table to itself.

• Equi- and non-equi-joins

An equi-join is a join where the join condition uses the equal to

(=) operator to relate the rows of two tables.

Other points of join

• Oracle proprietary syntax is different , inner join is written in


table 1, table 2 where table 1.columnname= table2.columnname
• A + sign is used to indicate an outer join

SELECT FIRSTNAME, LASTNAME,


PROJECTNAME FROM EMPLOYEE E, PROJECT P
WHERE E.PROJECT_ID(+)=P.PROJECT_ID

Subquery

• A subquery is simply a query that is nested inside another query or a


nested query
• The nested query, sometimes referred to as an inner query, is
evaluated first, and its resulting data set is passed back to the outer
query and evaluated to completion.

16
CSE DBMS Lab Manual

• Subqueries can be effectively used in situations where the combined


data has no direct relationship as compared to joins
• scalar or single-row subqueries: The subquery returns a single value to
the outer query
• Scaler subqueries can be used for both where and having clause.
• Subqueries are most often found in the WHERE clause of a SELECT,
UPDATE, or DELETE statement
Ex : Select name of the employees other than Kevin Feeney who
gets the same salary as Kevin

Non- correlated subquery

• Noncorrelated subqueries allow each row from the containing


SQL statement to be compared to a set of values.
• The nested query, sometimes referred to as an inner query, is
evaluated first, and its resulting data set is passed back to the outer
query and evaluated to completion.
• Subqueries can be effectively used in situations where the
combined data has no direct relationship as compared to joins

• scalar or single-row subqueries : The subquery returns a single value to


the outer query

• Scaler subqueries can be used for both where and having clause.

Correlated subquery

• A correlated subquery is a subquery that uses values from the outer


query, requiring the inner query to execute once for each outer query

• With a correlated subquery, the database must run the subquery for
each evaluation because it is based on the outer query’s data.
Syntax-
select book_key, store_key, quantityfrom sales s
Where quantity <
(select max(quantity) from sales where book_key = s.book_key);

Non correlated and correlated subquery –

• Noncorrelated subqueries allow each row from the containing SQL


statement to be compared to a set of values.
◦ Single-row, single-column subqueries
◦ Multiple-row, single-column subqueries
◦ Multiple-column subqueries
17
CSE DBMS Lab Manual

Syntax-

SELECT lname FROM employee WHERE salary >(SELECT AVG(salary) FROM


employee);

SELECT fname, lname FROM employee WHERE dept_id = 30 AND salary >= ALL
(SELECT salary FROM employee WHERE dept_id = 30);

SELECT fname, lname FROM employee WHERE dept_id = 30 AND NOT salary <
ANY (SELECT salary FROM employee WHERE dept_id = 30);

Assignment –IV
a. Display name of employees , department name and job name for each employee
b. Display the department name along with no of employees and average salary
of that department
c. For each department, find out no. of jobs the employees are assigned to.
d. Check for correctness of the above queries in terms of count, if you want
to bring in all entries, how would you achieve the same?
e. Group by the employees based on the first character of employee first
name. Display the results in alphabetic order (descending) of first
character.

Output-

18
CSE DBMS Lab Manual

Oracle Class V
PL/SQL basics

Architecture -

Single Unit-

What Is PL/SQL?
PL/SQL is a procedural programming language from Oracle that combines the following
elements:

19
CSE DBMS Lab Manual

• Logical constructs such as IF-THEN-ELSE and WHILE


• SQL DML statements, built-in functions, and operators
• Transaction control statements such as COMMIT and ROLLBACK
• Cursor control statements
• Object and collection manipulation statements

A simple PL/SQL block

• The Declaration section (optional)


The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any placeholders like variables, constants,
records and cursors

• The Execution section (mandatory).


The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and
ends with END. This is a mandatory section and is the section where the program logic is
written to perform any task. The programmatic constructs like loops, conditional
statement and SQL statements form the part of execution section.

• The Exception (or Error) Handling section (optional)


The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION.
This section is optional. Any errors in the program can be handled in this section, so that the
PL/SQL Blocks terminates gracefully.

Example – procedure
DECLARE
v_sal numeric(7,2); v_ename varchar(10); BEGIN
SELECT max(sal) INTO v_sal FROM emp;

SELECT ENAME INTO V_ENAME from emp WHERE SAL=V_SAL;

DBMS_OUTPUT.PUT_LINE (v_ename||' gets highest salary of ' ||v_sal ); END;


/
Example – function
CREATE OR REPLACE FUNCTION getmaxval (tname VARCHAR2 ,
cname VARCHAR2)
RETURN NUMBER IS
query_str VARCHAR2(1000); maxval
NUMBER; BEGIN
query_str := 'SELECT max(' || cname || ') FROM '
||tname; EXECUTE IMMEDIATE query_str INTO
maxval;
RETURN maxval;
END;
/

20
CSE DBMS Lab Manual

Assignment –V
1. Create a function which takes two parameters table name and column name
and returns second max value of the columns.
Output-

21
CSE DBMS Lab Manual

Oracle Class VI
Exception Block Cursors, For Loops

Pl/sql – some more basics


• Loop through records, manipulating them one at a time.
• Keep code secure by offering encryption, and storing code
permanently on the server rather than the client.
• Handle exceptions.
• Work with variables, parameters, collections, records, arrays, objects,
cursors, exceptions, BFILEs, etc.
• Pl/SQL is first compiled and stored and then interpreted Reminder :
use of ed
Exception blocks

CREATE OR REPLACE FUNCTION getname (vsal number)


RETURN varchar2 IS
query_str VARCHAR2(1000); vename varchar2(100);
BEGIN
query_str := 'SELECT ename FROM emp' ||' where sal= ' ||
vsal; EXECUTE IMMEDIATE query_str INTO vename;

query_str := vename || ' gets ' || vsal;


RETURN query_str;
EXCEPTION

WHEN NO_DATA_FOUND THEN


RETURN 'NOT FOUND';
END;
/

Some exceptions

ORA-1403 NO_DATA_FOUND No data found.

ORA-1422 TOO_MANY_ROWS A SELECT.INTO


statement matches more than one row.

ORA-1476 ZERO_DIVIDE Division by zero.

ORA-1722 INVALID_NUMBER Conversion to a


number failed; for example,‘1A’ is not valid.

22
CSE DBMS Lab Manual

ORA-6502 VALUE_ERROR Truncation,


arithmetic, or conversion error.

User defined exceptions

DECLARE
• Exception to indicate an error condition
• e_DuplicateAuthors EXCEPTION; RAISE e_DuplicateAuthors;
EXCEPTION
WHEN e_DuplicateAuthors THEN WHEN OTHERS THEN

Packages

Stored functions and procedures may be compiled individually, or they may


be grouped together into packages.

• Packages are loaded into memory as a whole, increasing the likelihood


that a
procedure or function will be resident in memory when called.
• Packages can include private elements, allowing logic to be hidden
from view.
• Placing functions and procedures inside packages eliminates the need to
recompile all functions and procedures that reference a newly
recompiled function/procedure.
• Function and procedure names may be overloaded within packages,
whereas
standalone functions and procedures cannot be overloaded.

Loops

DECLARE
v_count PLS_INTEGER := 0; BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Ah -- Much better'); v_count := v_count + 1;
EXIT WHEN v_count = 20;
END LOOP;
END;
/

FOR counter IN low_number .. high_number


LOOP
action;
23
CSE DBMS Lab Manual

END LOOP;

WHILE condition
LOOP
action;
END LOOP;

Cursor-

A cursor provides a subset of data, defined by a query, retrieved into


memory when opened, and stored in memory until the cursor is closed.

If data is added, deleted, or modified after the cursor is opened, the new
or changed data is not reflected in the cursor result set.

Declaration of a cursor:
CURSOR author_cur1
IS
SELECT rowid FROM authors WHERE id > 50;

Opening a cursor
OPEN author_cur1;

%FOUND
The %FOUND attribute tests whether a FETCH returned a
record.The return value is of Boolean type. If TRUE, a row was
returned by the FETCH. If FALSE, a row was not returned.

%ISOPEN
This attribute tests to see if a cursor is already open.If TRUE, the cursor is open.
If FALSE, it is not open.

%NOTFOUND
%NOTFOUND is the opposite of %FOUND. It returns TRUE if a row was
not returned by the FETCH and FALSE if one was returned.

%ROWCOUNT
This tests for the number of rows fetched from the cursor at any given time
and returns a number.

Use a cursor in a loop Opening a loop:


LOOP

24
CSE DBMS Lab Manual

Fetch:
FETCH auth_cur INTO v_first_name, v_last_name, v_book_count; Exit:
EXIT WHEN auth_cur%NOTFOUND;
End Loop
END LOOP;
Close Cursor
CLOSE auth_cur;

Example of a simple cursor

CREATE OR REPLACE PROCEDURE compile_warning AS


v_title VARCHAR2(100); CURSOR dbms_warning_cur IS
SELECT title FROM books; BEGIN OPEN
dbms_warning_cur;
LOOP
FETCH dbms_warning_cur INTO v_title;
EXIT WHEN dbms_warning_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Titles Available: '||v_title); END LOOP;
CLOSE dbms_warning_cur;
END;

Assignment –VI
1. Write a simple procedure , which executed now will return the time that of
two hours earlier
2. For emp table in scott, write a stored procedure that creates a table for each
unique department_id and stores the employee records that belong to that
particular department.
3. Create a stored procedure which given a table name will display the name of
the constraints available for the table. Handle all possible type of exception
4. Write a simple procedure, similar to previous assignments , given an email id , this
displays username and domain respectively , have correct messages displayed.
Output-

25
CSE DBMS Lab Manual

Oracle Class VII


More on Exception Sequence; RowID & Rownum Views
Sequence
An Oracle sequence is an Oracle database object that can be used to generate
unique numbers. You can use sequences to automatically generate primary key
values.

After a sequence has been created, you can access its values in SQL
statements with these
pseudocolumns:
• CURRVAL returns the current value of the sequence.
NEXTVAL increments the sequence and returns the new value
• We can use a maxvalue or minvalue to indicate the maximum value a
sequence can have
• CYCLE is used to indicate , if maxvalue is reached , then the values will
be cycled (NOCYCLE by default)

Example of sequence:

CREATE SEQUENCE trig_seq START WITH 1;


CREATE SEQUENCE trig_seq1 START WITH 1 INCREMENT BY 1;
CREATE SEQUENCE trig_seq2 START WITH 1 INCREMENT BY 1
maxvalue 255;

RowId & Rownum

For each row in the database, the ROWID pseudocolumn returns the
address of the row.

Use of Rowid:
• They are the fastest way to access a single row.
• They can show you how the rows in a table are stored.
• They are unique identifiers for rows in a table.

For each row returned by a query, the ROWNUM pseudocolumn returns a


number indicating the order in which Oracle selects the row from a table or
set of joined rows.The first row selected has a ROWNUM of 1, the second
has 2, and so on.

26
CSE DBMS Lab Manual

Views

Use the CREATE VIEW statement to define a view, which is a logical table
based on one or more tables or views. A view contains no data itself.The
tables upon which a view is based are called base tables.

Views have two purposes:


• Simplify issuing complex SQL queries
• Restrict users’ access to sensitive data

Types of View :
-Simple View
-Complex View
-Inline View
-Materialized View

Example :
Create view emp10 As select * from emp where deptno=10;

View can be created using join on multiple table

create view empbonus


(ename,sal,job,comm,deptno)
as select a.ename,a.sal,a.job,b.comm, a.deptno
from emp a inner join bonus b on
a.ename=b.ename /

Exception
Differentiate error and exception

More example :
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE ('A number cannot be divided by zero.');
VALUE_ERROR : When there is conversion or type mismatch error.
TOO_MANY_ROWS : This exception is raised when a SELECT INTO
statement returns more than one row.

You can declare your own exception

DECLARE e_exception1 EXCEPTION;


BEGIN

27
CSE DBMS Lab Manual

RAISE e_exception1

Assignment – VII(View)
1. Modify the procedure that takes salary and returns the name ,handle the handle
the exception so that if user gives a nonnumeric value this exits gracefully.
2. Create a table books, which has columns as bookid and bookname . Insert two rows
with booknames ‘database fundamentals’ and ‘database technologies’. Use a
sequence to populate the bookid for both therows.
3. Create a view , which hides the salary column from the user.
4. Cerate a view which has ename and dname respectively , check if you can update/insert
into the views , justify your results
Output-

28
CSE DBMS Lab Manual

Oracle Class VIII

Triggers

A database trigger is a named PL/SQL block stored in a database and executed


implicitly when a triggering event occurs.The act of executing a trigger is called
firing the trigger.

Four types of triggering events :-

• A DML statement (such as INSERT, UPDATE, or DELETE) executed


against a database table. Such a trigger can fire before or after a
triggering event.

• A DDL statement (such as CREATE or ALTER) executed either by a


particular user against a schema or by any user.

• A system event such as startup or shutdown of the database.

• A user event such as logon and logoff

Syntax-
CREATE [OR REPLACE] TRIGGER Ttrigger_name
{BEFORE|AFTER} Triggering_event ON table_name
[FOR EACH ROW]
[FOLLOWS another_trigger]

Example-
CREATE OR REPLACE TRIGGER student_bi
BEFORE INSERT ON students FOR EACH ROW
DECLARE
sid int;
BEGIN
select max(stid)+1 into sid from students;
dbms_output.put_line('hello'); :new.stid:=sid;
END; /

FOR EACH ROW


WHEN (NVL(NEW.ZIP, ' ') <> OLD.ZIP)

29
CSE DBMS Lab Manual

Assignment – VIII(Trigger)
1. There is a circular from federal govt. no employees can get salary less than 1000$ .
So in case some employees are being inserted in the table with salary less than 1000
automatically this should be updated to 1000, Write a trigger for the same. Do it first
by a just changing the below in insert before , and also by an update command after
insert is done.
2. Create a trigger on emp table such that when a new employee is inserted with a
deptno that is new , first insert that record in department and then insert the same in
emp to avoid foreign key error.

Output-

30

You might also like