Relational Database Management System Page 1 M.S.P.V.L.POLYTECHNIC COLLEGE, PAVOORCHATRAM Department of Computer Engineering / I nformation Technology
Oct 24, 2014
Relational Database Management System
Page 1
Subject : Relational Database Management System
Semester :Vth Semester
AUTHOR:
M.Mageshwari M.Sc., MPhil.,
Lecturer,
Department of CE,
M.S.P.V.L.Polytechnic College,
Pavoorchatram.
M.S.P.V.L.POLYTECHNIC COLLEGE,
PAVOORCHATRAM
Department of Computer Engineering / I nformation Technology
Relational Database Management System
Page 2
S.NO PROGRAM PAGE NO
1 SQL Editor Command 5
2 Column Commands 11
3 Use Index on a Table 17
4 SQL Function 19
5 Data Control Language 26
6 Select Command in SQL *Plus 35
7 Integrity Constraints 39
8 Sub Queries 44
9 Joins in Sql * Plus 48
10 Logical Operator in SQL * PLUS 52
11 Different Select Statements in SQL* 56
12 Employee Details Using PL/SQL 60
13 To Calculate EB Bill Using If Statement 64
14 Built in Function using PL/SQL 68
15 User Define Exception using PL/SQL 71
16 Procedure & Function using PL/SQL 76
17 Students Admission Using Trigger 81
18 Employee Salary Detail Using Cursor 84
19 DML Using ADO Creation 88
20 Navigation object using ADO creation 95
EXTRA PROGRAMS
1 Transaction Control Language 102
2 Sequence Creation 104
3 View 106
4 Synonyms 108
Relational Database Management System
Page 3
Oracle server: In the Oracle language RDBMS system is used to manipulate the
database. This system is used to manipulate the database. This system accepts
all user requests for insertion, updating and deletion of data. RDBMS engine is
loaded and a remains running in the memory till the database operation is not
complete. In the multiuser system RDBMS engine respond to multiuser request
which is handled by RDBMS server known as Oracle server.
Invoking SQL* Plus
To work in oracle, the user should be able to effectively communicate with
the oracle DBA. The user can communicate with the oracle DBA by using ANSI
SQL, the natural language of DBA.
Oracle provide an interactive SQL tool i.e. SQL * Plus, which allow users
to enter the ANSI SQL sentences and pass them to the DBA for execution.
These sentences allow the user to create, access and maintain data structures
like table, Index etc.
This is the first tool to be used by most programmers when they begin
their study in oracle
The steps in invoking SQL * Plus are as follows
Step1: Start windows in the normal way
Step2: Click on the start button and click on Internet Explorer. It displays the
Microsoft Internet Explorer home page.
Step3: Login Screen
You connect to the Login screen from your web browser with a URL like:
http://machine_name.domain:port/isqlplus
Relational Database Management System
Page 4
The Login screen is displayed:
Username: Enter a valid username to connect to Oracle Database (mandatory).
Password: Enter a valid password for the username (mandatory).
Connection Identifier: Leave this field blank to use the default Oracle database, otherwise enter a
connection identifier for the database you want to connect to.
ISQL*Plus can be configured to restrict connections to specific databases. If
restricted database access has been enabled, a dropdown list of available
databases is displayed in place of the Connection Identifier text field. This
enables greater security for iSQL*Plus Servers in hosted environments. This is
configured using the iSQLPlusConnectIdList parameter in the configuration file.
Relational Database Management System
Page 5
Login Click the Login button to log in to iSQL*Plus. If you enter an invalid
username or password, the Login screen is re-displayed with an error message.
Step4:
Workspace The Workspace consists of the Workspace, History and Load Script screens.
After successfully logging in, the Workspace is displayed.
From the Workspace you can:
• Access Preferences screens
• Enter, Execute and Cancel scripts
• Load and Save scripts
• View, Save and Print output
• Log out
• Get help
The Workspace and History screens display the user's connection information
in the top right. The connection information is displayed in the form:
Relational Database Management System
Page 6
Connected as [username]@[connection_identifier] [AS SYSDBA| AS SYSOPER]
or
Not connected
Clear
Clears all statements in the Input area, and all displayed output. Cancels any
script that may be running.
Execute
Executes the contents of the Input area. Depending on your preference settings,
the results are displayed in the Output area, in a new web browser window, or
saved to a file.
Load Script
Displays the Load Script screen where you enter a path and file name, or a URL
for the script you want to load into the Input area for editing or execution.
Save Script
Displays the File > Save As dialog where you enter a file name for the script
you want to save from the Input area as a plain text file. It may be useful to
identify scripts with an extension of .SQL.
Cancel
Cancels any script that is currently running, but does not clear the Output
area. A message saying that the script was cancelled is displayed.
Next Page
Displays the next page of report output. The Next Page button is displayed when
there are more results to display than can fit on the current output page or the
script contains a PAUSE command.
You can configure whether pages are displayed on a single page or multiple
pages using Preferences > Interface Configuration > Output Page Setup, or
by executing the SET PAUSE ON or SET PAUSE OFF command.
Relational Database Management System
Page 7
Aim:
To Execute and test all the SQL Editor Commands.
1. SQL Editor Command
Syntax:
The Describe Command:
DESC table_name;
Create Command:
CREATE TABLE <table name> (column1 datatype1,….. column datatype n);
Alter Command:
ALTER TABLE <table name> MODIFY (column datatype,……….);
ALTER TABLE <table name> ADD (column datatype,……….);
Insert Command:
INSERT INTO <table name> VALUES (value1, value2,……….);
Select Command:
SELECT * FROM <table name>; (or)
SELECT column1, column2…. FROM <table name>;
Update Command:
UPDATE <table name> SET column1=expression, column2=expression…..WHERE <search_condituin>;
Delete Command:
DELETE FROM <table name> [WHERE <search_condition>];
Relational Database Management System
Page 8
Predefined commands:
Select user from dual;
USER MAGESHWARI
describe tabs;
Name Null? Type TABLE_NAME NOT NULL VARCHAR2(30)
TABLESPACE_NAME
VARCHAR2(30)
CLUSTER_NAME
VARCHAR2(30)
IOT_NAME
VARCHAR2(30)
PCT_FREE
NUMBER
PCT_USED
NUMBER
INI_TRANS
NUMBER
MAX_TRANS
NUMBER
INITIAL_EXTENT
NUMBER
NEXT_EXTENT
NUMBER
MIN_EXTENTS
NUMBER
MAX_EXTENTS
NUMBER
PCT_INCREASE
NUMBER
FREELISTS
NUMBER
FREELIST_GROUPS
NUMBER
LOGGING
VARCHAR2(3)
BACKED_UP
VARCHAR2(1)
NUM_ROWS
NUMBER
select table_name from tabs order by table_name;
TABLE_NAME EMP
STUDENT
Relational Database Management System
Page 9
You can use the describe command on the following views to obtain information on your account.
View Name Description
DICT table names and table description
DICT_COLUMN column names of table names and column description
CAT names of all user's tables, views, synonyms, and sequences
OBJ information on all objects in your account
TABS table information on all user's tables
COLS column information on all user's columns
USER_VIEWS view information on all user's views
SYN synonyms information on all user's synonyms
SEQ sequence information on all user's sequences
USER_CONSTRAINTS constraint information on user's constraints
USER_CONS_COLUMNS column information on user's constraints
IND index information on all user's indices
USER_IND_COLUMNS column information on user's indices
User defined commands:
Table Creation
create table student(Regno Number(5),Name varchar2(6),age number(3),dob date, sex varchar2(5),address varchar2(9));
Table created.
desc student;
Name Null? Type REGNO
NUMBER(5)
NAME
VARCHAR2(6)
AGE
NUMBER(3)
DOB
DATE
SEX
VARCHAR2(5)
ADDRESS
VARCHAR2(9)
Relational Database Management System
Page 10
Add New Columns:
Alter table student add (phoneno number (8));
Table altered.
desc student
Name Null? Type REGNO
NUMBER(5)
NAME
VARCHAR2(6)
AGE
NUMBER(3)
DOB
DATE
SEX
VARCHAR2(5)
ADDRESS
VARCHAR2(9)
PHONENO
NUMBER(8)
Insert the Number of Rows:
insert into student values(101,'Mala',18,'12-sep-89','F','Tenkasi','257567');
1 row created.
insert into student values(102,'Jeya',17,'10-nov-90','F','Madurai','234557');
1 row created.
insert into student values(103,'viji',18,'31-mar-89','F','Tirunel',565776);
1 row created.
insert into student values(104,'mitha',19,'15-sep-88','F','chennai',234567);
1 row created.
insert into student values(105,'Mathu',21,'19-sep-86','M','tenkasi',234789);
1 row created.
Relational Database Management System
Page 11
View the Table:
select * from student;
REGNO NAME AGE DOB SEX ADDRESS PHONENO 101 Mala 18 12-SEP-89 F Tenkasi 257567
102 Jeya 17 10-NOV-90 F Madurai 234557
103 viji 18 31-MAR-89 F Tirunel 565776
104 mitha 19 15-SEP-88 F chennai 234567
105 Mathu 21 19-SEP-86 M tenkasi 234789
Modify the Table Value:
update student set phoneno=240902 where regno=101;
1 row updated.
select * from student;
REGNO NAME AGE DOB SEX ADDRESS PHONENO 101 Mala 18 12-SEP-89 F Tenkasi 240902
102 Jeya 17 10-NOV-90 F Madurai 234557
103 viji 18 31-MAR-89 F Tirunel 565776
104 mitha 19 15-SEP-88 F chennai 234567
105 Mathu 21 19-SEP-86 M tenkasi 234789
Delete the Rows
delete from student where regno='102';
1 row deleted.
select * from student;
REGNO NAME AGE DOB SEX ADDRESS PHONENO 101 Mala 18 12-SEP-89 F Tenkasi 240902
103 viji 18 31-MAR-89 F Tirunel 565776
104 mitha 19 15-SEP-88 F chennai 234567
105 Mathu 21 19-SEP-86 M tenkasi 234789
Result:-
The query was executed successfully and output was verified.
Relational Database Management System
Page 12
Viva Questions:
1. What is SQL*plus? SQL * Plus is made up two distinct parts;
These are,
Interactive SQL
PL/SQL
2. What is interactive sql?
Interactive SQL is designed to create, access and maintain all data
structures like tables, indexes etc. It can also be used for interactive, data maintain.
3. How to create a table?
The first letter should be an alphabet. Oracle reserve words cannot be used as table name The length of a table name should not exceed 30 characters Different tables should have different names. Underscore, numerals and letters are allowed. Blank space and single
quote are not allowed. Double quotes can be used for naming a table. In this case the tables
“student”, “Student” and “STUDENT” are all different tables.
4. How to change the structure of a table?
The structure of a table can be changed using this command. Using this command we can do the following.
Add a new column Change the width of a data type Change the data type of a column Include an integrity constraint Drop an integrity constraint.
Relational Database Management System
Page 13
Aim:
To work the following conditions:
a) Column formatting
b) Alias and Column ordering
Query:
Table creation:
create table emp(emp_no number,emp_name varchar2(8),desig varchar2(12),doj date,salary number(8),hra number(7));
Table created.
desc emp
Name Null? Type EMP_NO NUMBER EMP_NAME VARCHAR2(8) DESIG VARCHAR2(12) DOJ DATE SALARY NUMBER(8) HRA NUMBER(7)
2. Column Commands
Syntax:
Column Formatting
COLUMN name_of_column FORMAT style Column Alias SELECT column name "alias name" FROM table Order By SELECT column FROM table ORDER BY column name
Relatioonal DatabInsert t
insert in
insert in
insert in
insert in
insert in
1 row c
1 row c 1 row c 1 row c 1 row c
View t
select *
EMP_N
1111
1112
1113
1113
1114
Colum
a) To d
com
c
s
base Manathe values
nto emp v
nto emp v
nto emp v
nto emp v
nto emp v
created.
created.
created.
created.
created.
the table
from emp
NO EMP
1 Je
2 S
3 G
3 R
4
mn Forma
display th
mmand:
olumn sal
elect * from
agement Sys:
alues('111
alues('111
alues('111
alues('111
alues('111
e:
p
P_NAME
eyanthi
Seetha
Glory
Ratha
Uma
ating
he salary f
lary forma
m emp
ystem
11','Jeyant
12','Seetha
13','Glory',
13','Ratha'
14','Uma','s
DESIG
Manage
Designing
Lecture
Teache
Software
field with
at $9,99,99
thi','Manag
a','designin
'Lecturer',
,'Teacher',
softwareen
G D
er 12-
geng 25-M
er 17-
er 29-
eng 26-A
dollar sig
99;
ger','12-sep
ngeng','25-
,'17-Feb-0
,'29-Jan-0
ng','26-Aug
DOJ
-SEP-08
MAR-05
-FEB-08
-JAN-07
AUG-05
gn, we can
p-08',2000
-mar-05',4
8',17000,1
07',12000,7
g-05',4700
SALARY
20000
47000
17000
12000
47000
n use the
00,600);
47000,120
1000);
700);
00,1200)
HRA
600
1200
1000
700
1200
following
0);
g
Relational Database Management System
Page 15
EMP_NO EMP_NAME DESIG DOJ SALARY HRA
1111 Jeyanthi Manager 12-SEP-08 $20,000 600
1112 Seetha designingeng 25-MAR-05 $47,000 1200
1113 Glory Lecturer 17-FEB-08 $17,000 1000
1113 Ratha Teacher 29-JAN-07 $12,000 700
1114 Uma softwareeng 26-AUG-05 $47,000 1200
b) To change the width of the column, use the element ‘A’ followed by the number of characters that the column must contain
column desig format a4;
select * from emp
EMP_NO EMP_ DESI DOJ SALARY HRA
1111 Jeyanthi Mana ger 12-SEP-08 $20,000 600
1112 Seetha desi gnin geng 25-MAR-05 $47,000 1200
1113 Glory Lect urer 17-FEB-08 $17,000 1000
1113 Ratha Teac her 29-JAN-07 $12,000 700
1114 Uma soft ware eng 26-AUG-05 $47,000 1200
c) To display the number in scientific notation, use EEEE format
column hra format 9.9999EEEE;
select * from emp
EMP_NO EMP_ DESI DOJ SALARY HRA
1111 Jeya nthi Mana ger 12-SEP-08 $20,000 6.0000E+02
1112 Seet ha desi gnin geng 25-MAR-05 $47,000 1.2000E+03
1113 Glor y Lect urer 17-FEB-08 $17,000 1.0000E+03
1113 Rath a Teac her 29-JAN-07 $12,000 7.0000E+02
1114 Uma soft ware eng 26-AUG-05 $47,000 1.2000E+03
Relational Database Management System
Page 16
d) Create column headings
column emp_name heading EmployeeName
column emp_no heading EmployeeNumber
column desig heading Designation
select * from emp;
EmployeeNumber EmployeeName Designation DOJ SALARY HRA
1111 Jeyanthi Manager 12-SEP-08 20000 600
1112 Seetha designingeng 25-MAR-05 47000 1200
1113 Glory Lecturer 17-FEB-08 17000 1000
1113 Ratha Teacher 29-JAN-07 12000 700
1114 Uma softwareeng 26-AUG-05 47000 1200
e) Display the current settings
column emp_no
output: COLUMN emp_no ON
HEADING 'EmployeeNumber'
f) Clear Settings
column emp_name clear
select * from emp;
EmployeeNumber EMP_NAME Designation DOJ SALARY HRA
1111 Jeyanthi Manager 12-SEP-08 20000 600
1112 Seetha designingeng 25-MAR-05 47000 1200
1113 Glory Lecturer 17-FEB-08 17000 1000
1113 Ratha Teacher 29-JAN-07 12000 700
1114 Uma softwareeng 26-AUG-05 47000 1200
Relational Database Management System
Page 17
Alias and Column ordering:
select emp_name "EMPLOYEE NAME" from emp;
EMPLOYEE NAME
Jeyanthi
Seetha
Glory
Ratha
Uma
SELECT EMP_NO,EMP_NAME from emp order by emp_name ASC;
EMP_NO EMP_NAME
1113 Glory
1111 Jeyanthi
1113 Ratha
1112 Seetha
1114 Uma
Result:-
The query was executed successfully and output was verified.
Relational Database Management System
Page 18
Viva Questions:
1. What is the use of column command? The COLUMN controls column and column heading formatting. The
options are all cumulative and may be entered either simultaneously on a single line.
2. How to change the column header?
Column titles that are displayed by SQL* plus reflect the name given to the column in the table. We can define a title for a column that is more easily understood by using the HEADING parameter.
3. Data Definition Language Statements: When creating and managing any object in an oracle database, you use the
Data Definition Language (DDL) elements of the SQL language.
Create This statement add a new object to the database. You use it to create new tables, views, stored procedure and other objects.
Alter This statement is used to change the characteristics of tables, indexes and other objects in the database. The ALTER statement does not apply to all objects in the database.
4. How to use of ORDER by expr? Organizes the rows returned by SELECT command. Expr is expression,
generally a field by which the rows will be stored. ASC/DESC The default is ASC; it sorts in ascending order. DESC sorts in descending order.
Relational Database Management System
Page 19
Aim:
Use indexing on a table – simple and composite indexes.
Simple Index:
create index empno_index on emp(emp_no)
Index created.
select index_name,table_name from user_indexes;
INDEX_NAME TABLE_NAME
EMPNO_INDEX EMP
Composite Index:
create index emp_index on emp(emp_name,desig,salary)
Index created. select index_name,index_type,table_name from user_indexes;
INDEX_NAME INDEX_TYPE TABLE_NAME
EMP_INDEX NORMAL EMP
EMPNO_INDEX NORMAL EMP
3. Use Index on a Table
Syntax:
Simple Index
CREATE INDEX <Index_name> ON <table_name>(column_name);
Composite Index
CREATE INDEX <Index_name> ON <table_name>(column_name1,……);
Dropping Index DROP INDEX <Index_name>;
Relatio
1
2
onal Datab
Droppi
drop in
select in
Index d
IND
E
Resul
T
Viva Que
1. What is An iindex cmultipl
2. How to
Whencommathe data
base Mana
ing Index:
dex empn
ndex_nam
dropped.
DEX_NAM
MP_INDEX
lt:-
The query w
estions:
s simple anindex is acreated one table col
drop an inn you no
and. Whena dictiona
agement Sy
:
o_index;
me,index_ty
ME
X
was execu
nd composan orderedn a singlelumns are
ndex? longer nee
n the indexry and fre
ystem
ype,table_n
INDEX_
NORM
uted succe
site index?d list of a e column e included
ed an index is droppes any dis
name from
_TYPE
MAL
ssfully and
? column o of a tab in the ind
ex, you caped, oraclesk space u
m user_ind
TAB
d output w
or group oble is calldex it is ca
an drop it e removes used by the
dexes;
BLE_NAME
EMP
was verifie
of column ed simple
alled compo
using the any referee index.
E
ed.
in a tablee index. Wosite index
e DROP INence to it
e. An When x.
NDEX from
Relational Database Management System
Page 21
Aim:
To Work with the different categories of functions such as Math, Date, Aggregate and Conversion functions.
Math Function:
SELECT ABS(10), ABS(-10) FROM dual;
ABS(10) ABS(-10)
10 10
4. SQL Function
Syntax:
Math Numeric Function: Date Function
ABS(n); ADD_MONTH(date,month);
CEIL(n): LASY_DAY(date);
COS(n); MONTHS_BETWEEN(date1,date2);
COSH(n); NEXT_DAY(date,day_name);
EXP(n); ROUND(date,[format]);
Aggregate Function: Conversion functions:
AVG(n); TO_CHAR(date[,format]);
COUNT(n); TO_DATE(date[,format]);
MAX(n); TO_NUMBER(date[,format]);
MIN(n);
STDDEV(n);
VARIANCE(n);
Relational Database Management System
Page 22
SELECT CEIL(5.8), CEIL(-5.2) FROM dual;
CEIL(5.8) CEIL(-5.2)
6 -5
select cos(45) from dual;
COS(45)
.525321989
select cosh(0) from dual; select exp(5) from dual;
COSH(0)
1
EXP(5)
148.413159
Date Function:
ADD_MONTH:
select * from student;
REGNO NAME AGE DOB SEX ADDRESS PHONENO
101 Mala 18 12-SEP-89 F Tenkasi 240902
103 viji 18 31-MAR-89 F Tirunel 565776
104 mitha 19 15-SEP-88 F chennai 234567
105 Mathu 21 19-SEP-86 M tenkasi 234789
select dob,add_months(dob,60) from student;
DOB ADD_MONTHS(DOB,60)
12-SEP-89 12-SEP-94
31-MAR-89 31-MAR-94
15-SEP-88 15-SEP-93
19-SEP-86 19-SEP-91
Relational Database Management System
Page 23
LAST DAY:
select name,dob,last_day(dob) from student;
NAME DOB LAST_DAY(DOB)
Mala 12-SEP-89 30-SEP-89
viji 31-MAR-89 31-MAR-89
mitha 15-SEP-88 30-SEP-88
Mathu 19-SEP-86 30-SEP-86
Months_BETWEEN:
create table staff(name varchar2(10),dob date,doj date);
Table created.
select * from staff;
NAME DOB DOJ Malar 10-MAY-85 26-MAY-08
Mageshwari 15-SEP-84 06-JUL-06
Gowsic 07-JUN-08 07-JUN-09
Santhiya 09-OCT-07 09-AUG-09
select months_between(doj,dob) from staff;
MONTHS_BETWEEN(DOJ,DOB) 276.516129
261.709677
12
22
Next_Day:
select next_day('6-apr-09','Monday') from dual;
NEXT_DAY('6-APR-09 13-APR-09
Relational Database Management System
Page 24
Round
select name,round(dob,'year')from student where regno=105
NAME ROUND(DOB,'YEAR')
Mathu 01-JAN-87
Aggregate Function:
Avg:
select avg(age) from student;
AVG(AGE)
19
Count:
select count(age) from student;
COUNT(AGE)
4
Max:
select max(age) from student;
MAX(AGE)
21
Min:
select min(age) from student;
MIN(AGE) 18
Stddev:
select stddev(age) from student;
STDDEV(AGE) 1.41421356
Relational Database Management System
Page 25
Variance:
select variance(age) from student;
VARIANCE(AGE) 2
Conversion functions:
Conversion function converts a value from one data type to another. The conversion function are classified into three characters
TO_CHAR (date conversion):
Select name,to_char(dob,'day-month-year') from student;
NAME TO_CHAR(DOB,'DAY-MONTH-YEAR') Mala tuesday -september-nineteen eighty-nine
viji friday -march -nineteen eighty-nine
mitha thursday -september-nineteen eighty-eight
Mathu friday -september-nineteen eighty-six
TO_CHAR (Number conversion):
create table stoc(item_name varchar2(10),stock number(10),cost number(10));
Table created.
select * from stoc;
ITEM_NAME STOCK COST
computer 100 25000
printer 50 1500
UPS 75 2000
AC 10 30000
computer 10 25000
Relational Database Management System
Page 26
select item_name,to_char(stock*cost,'9,99,999.99') from stoc;
ITEM_NAME TO_CHAR(STOCK*COST,'9,99,999.99')
computer ############
printer 75,000.00
UPS 1,50,000.00
AC 3,00,000.00
computer 2,50,000.00
TO_DATE:
create table purchase_master(num number(5),trade_name varchar2(10), date_of_purchase date,no_of_item number(5));Table created.
insert into purchase_master values(1,'JKTrade', to_date('01-Jan-2000','DD-MON-YYYY'),200);
1 row created.
insert into purchase_master values(1,'JTrade', to_date('01-January-2000','DD-MON-YYYY'),200);
1 row created.
NUM TRADE_NAME DATE_OF_PURCHASE NO_OF_ITEM
1 JKTrade 01-JAN-00 200
1 JTrade 01-JAN-00 200
To_number:
select * from stoc;
ITEM_NAME STOCK COST computer 100 25000
printer 50 1500
UPS 75 2000
AC 10 30000
computer 10 25000
Relational Database Management System
Page 27
select to_number(cost) from stoc;
TO_NUMBER(COST) 25000
1500
2000
30000
25000
Result:-
The query was executed successfully and output was verified.
Viva Questions:
1. What is function? An SQL function is a built-in-function that manipulates data items and returns a result. SQL functions may accept zero, one or more arguments.
2. How to use Date function?
Date functions accept DATE input and may return value of data type or a number.
3. How to use aggregate function or group function?
A group function returns one result row based on a group of rows.
5. Data Control Language
Relational Database Management System
Page 28
Aim:
a) Create a table to show the salary details of the employees. b) Grant select and update privileges on above table to other users c) Grant all the privileges to some other users. d) Revoke all the above granted permissions.
a. Create a table to show the salary details of the employees:
User creation:
Connect system/manager;
Connected.
create user mathu identified by mitha;
User created.
grant create session to mathu;
Grant succeeded.
grant create table to mathu;
Syntax:
Grant System Privilege:
GRANT system PRIVILEGE TO user
Grant Object Privilege:
GRANT object PRIVILEGE [, object privilege] ON object TO user [WITH GRANTOPTION]
Revoking the Permissions:
REVOKE object privilege [object privilege]……….ON object name FROM USER name;
Relational Database Management System
Page 29
Grant succeeded.
grant resource to mathu;
Grant succeeded.
Connect to user:
connect mathu/mitha;
Connected.
Create a table:
create table employee(name varchar2(8),id_no number(5),job varchar2(8),dob date,doj date,salary number(7));Table created.
Insert a table:
insert into employee values('RAJA',1110,'lecturer','12-jun-86','12-jun-08',20000)
1 row created.
insert into employee values('RAMA',1111,'LAWYER','12-MAY-80','12-jun-06',20000)
1 row created.
insert into employee values('PRABHU',1112,'COLLECTO','12-FEB-78','12-DEC-08',50000)
1 row created.
View the table:
select * from employee;
NAME ID_NO JOB DOB DOJ SALARY RAJA 1110 lecturer 12-JUN-86 12-JUN-08 20000
RAMA 1111 LAWYER 12-MAY-80 12-JUN-06 20000
PRABHU 1112 COLLECTO 12-FEB-78 12-DEC-08 50000
Relational Database Management System
Page 30
b. Grant select and update privileges on above table to other user:
Create another user:
connect system/manager;
Connected.
create user santhya identified by silviya;
User created.
grant create session to santhya;
Grant succeeded.
grant create table to santhya; Grant succeeded.
grant resource to santhya; Grant succeeded. Create a table:
connect santhya/silviya Connected. create table emp_sal(name varchar2(10),ta number(6),hra number(6),da number(6),bf number(5),netsalary number(6)); Table created.
Insert a table:
insert into emp_sal values('Raja',500,750,366,780,8000); 1 row created. insert into emp_sal values('Rama',750,1000,500,1200,10000); 1 row created. insert into emp_sal values('Prabhu',1000,1200,1500,1700,20000); 1 row created. View the table:
Relatioonal Datab
select *
NAME
Raja
Rama
Prabh
Grant
grant seGrant s Check
connectConnec select *
NAM
Raj
Ram
Prab
Check
update 1 row u select *
NAM
Raj
Ram
Prab
Check
base Mana
from emp
E TA
a 500
a 750
hu 100
select an
elect,updasucceeded
k the selet mathu/mcted.
from sant
ME T
a 5
ma 7
hu 10
k the upd
santhya.eupdated.
from sant
ME T
a 5
ma 7
hu 10
k other co
agement Sy
p_sal
A HR
0 750
0 100
00 120
nd updat
ate on emp.
ect permimitha
thya.emp_
TA HR
00 75
50 10
000 12
date perm
emp_sal se
thya.emp_
TA H
500 7
750 10
000 12
ommand
ystem
A DA
0 366
00 500
00 150
te privili
p_sal to ma
ission:
_sal;
RA D
50 36
000 50
200 15
mission:
et netsalar
_sal;
RA D
50 36
000 50
200 15
d:
A BF
6 780
0 120
00 170
iges:
athu;
DA B
66 78
00 12
500 17
ry=12000 w
DA B
66 78
00 12
500 17
F N
0
00
00
BF
80
00
00
where nam
BF
80
200
700
NETSALAR
8000
10000
20000
NETSALA
8000
10000
20000
me='Raja'
NETSALA
12000
10000
20000
RY
ARY
ARY
0
0
0
Relatioonal Databdelete f ERRORORA-01
c. Gran
connectConnec
select *
NA
RAJA
RAMA
PRABH
grant al
Grant su
connect
Connect
select *
NAME
RAMA
RAJA
PRABH
Insert in06',400
base Manafrom santh *
R at line 1:1031: insu
nt all the p
t mathu/mcted
from emp
AME I
U
l on emplo
ucceeded.
t santhya/
ted.
from math
E ID_NO
A 1111
A 1110
HU 1112
nto mathu000)
agement Syhya.emp_s
ufficient pr
privileges
mitha
ployee
ID_NO
1110 lec
1111 LA
1112 CO
oyee to san
silviya
hu.employ
O JOB
LAWYE
lecture
COLLEC
u.employee
ystem al
rivileges
s to some
JOB
cturer
AWYER
OLLECTO
nthya
yee
DO
ER 12-M
er 12-JU
CTO 12-FE
e values('S
other use
DOB
12-JUN-
12-MAY-
12-FEB-
OB
MAY-80 12
UN-86 12
EB-78 12
Selva','111
ers:
D
86 12-JU
-80 12-JU
78 12-DE
DOJ
2-JUN-06
2-JUN-08
2-DEC-08
4','doctor'
DOJ SA
UN-08
UN-06
EC-08
SALARY
20000
20000
50000
,'19-jun-8
ALARY
20000
20000
50000
1','20-mayy-
Relatioonal Datab1 row c
NAME
RAMA
RAJA
PRABH
Selva
Delete f1 row d
NAME
RAMA
PRABH
Selva
update 1 row u
NAMERAMA
PRABH
Selva
d. Revo Revoke Revoke connectConnec select *
base Manacreated.
E ID_N
A 1111
A 1110
HU 1112
a 1114
from mathdeleted.
E ID_NO
A 1111
HU 1112
a 1114
mathu.emupdated.
E ID_N11
U 11
11
oke all the
select,upd succeeded
t mathu/mcted.
from sant *
agement Sy
O JO
1 LAW
0 lectu
2 COLL
4 doc
hu.employe
O JO
1 LAW
2 COLL
4 doc
mployee se
NO JO11 LAWYE
12 COLLE
14 doctor
e above g
date on emd.
mitha
thya.emp_
ystem
OB
WYER 1
urer 1
LECTO 1
ctor 1
ee where i
OB
WYER 1
ECTO 1
ctor 1
et dob='14-
OB ER 12
ECTO 12
14
ranted pe
mp_sal from
_sal
DOB
12-MAY-80
12-JUN-86
12-FEB-78
19-JUN-81
id_no=111
DOB
12-MAY-80
12-FEB-78
19-JUN-81
-feb-84' wh
DOB 2-MAY-80
2-FEB-78
4-FEB-84
ermissions
m mathu
DO
0 12-JU
6 12-JU
8 12-DE
1 20-MA
0
DO
0 12-JU
8 12-DE
1 20-MA
here id_no
DO 12-JUN
12-DEC
20-MAY
s:
OJ SA
UN-06 2
UN-08 2
EC-08 5
AY-06 4
OJ SA
UN-06 2
EC-08 5
AY-06 4
o=1114
OJ SAN-06
C-08
Y-06
ALARY
20000
20000
50000
40000
ALARY
20000
50000
40000
ALARY 20000
50000
40000
Relatio
1
2
3
onal DatabERRORORA-00 update ERRORORA-00 Revoke Revoke connectConnec select * ERRORORA-00
Resul
T
Viva Que
. How to u D
account
Privilege
REVOKE
. What is
User is
The Ora
passwor
SYSTEM
3. How to c
base ManaR at line 1:0942: table
santhya.e *
R at line 1:0942: table
all on em succeeded
t santhya/cted.
from mat *
R at line 1:0942: table
lt:-
The query w
estions:
use data cData base
is created
es are give
E statemen
User?
any perso
acle system
rd for the
M user is “m
create a U
agement Sy e or view d
emp_sal se
e or view d
ployee fromd.
/silviya
thu.employ
e or view d
was execu
control lane access is
d for a us
en using
nt.
on or grou
m comes w
SYS user
manager”.
SER comm
ystem
does not ex
et netsalar
does not ex
m santhya
yee
does not ex
uted succe
nguage stas controlle
ser that u
the GRAN
up of peop
with two u
r is alway
.
mand?
xist
ry=1000 w
xist
a
xist.
ssfully and
tements? ed by the d
user can b
NT stateme
ple with so
users alrea
ys “change
where nam
d output w
data contr
be given pr
ent and a
ome right
ady create
e_on_insta
e='Raja'
was verifie
rol langua
rivileges o
are taken
s to acces
ed, SYSTEM
all” and th
ed.
age. Once a
on the dat
away usin
ss the dat
M and SY
he passwo
a login
tabase.
ng the
tabase.
YS. The
ord for
Relational Database Management System
Page 35
The CREATE USER command is responsible for the creation of new users.
It creates a user or an account through which you can connect to the database,
and establish the means by which oracle will allow the user access.
4. What are privileges?
A privilege is an authorization given to the user to access and manipulate
a database object in a certain way.
There are two types of privileges:
i. System privileges ii. Object privileges
5. What are system privileges?
Oracle includes over 100 privileges that can be granted to users. They include
the capability to create various database objects and modify the configuration of
the database. The granting of these privileges is restricted to the DBA by default.
Some of the most commonly granted system privileges are listed in the following
table:
Privilege
Description
CREATE SESSION
Enables a user to connect to the database instance. After
creating a user, you need to grant the CREATE SESSION
privilege; otherwise, the user cannot connect. Granting the
CREATE SESSION privilege is not done automatically by
oracle and must be granted explicitly.
CREATE TABLE
Enables a user to create a table in his or her schema.
CREATE VIEW
Enables a user to create a view in his or her schema.
CREATE SYNONYM
Enables a user to create a private synonym in his or her
schema.
CREATE USER Enables a user to create another user in the database and
specify the password and other settings at creation time.
6. What is object privilege?
Relational Database Management System
Page 36
Object privileges enable a user to manipulate data in the database or
perform an action on an object, such as execute a stored procedure. Unlike
system privileges, the owner of the object must grant object privileges.
Privilege
Granted On
SELECT
Table, View, Sequence
INSER
Table, View
UPDATE
Table, View
DELETE
Table, View
ALTER
Table, Sequence
INDEX
Table
REFERENCES
Table
EXECUTE
Procedure, function, package
6. Select Command in SQL *Plus
Relational Database Management System
Page 37
Aim:
a) Create a table student_master with the following field’s name, Regno, dept and year with suitable data types. Use select command to do the following.
b) Select the student’s name column. c) Display the unique rows. d) Sort the table in alphabetical order. e) Select all the students of a particular department.
a) Create a table student_master with the following field’s name, Regno, dept
and year with suitable data types. Use select command to do the following.
create table student_master(regno number(8),name varchar(10),dept varchar(10),year number(4)); Table created.
insert into student_master values(123,'Dhivya','Physics',1998); 1 row created.
insert into student_master values(124,'Muthu','Maths',2000); 1 row created.
Syntax:
Select Command:
SELECT * FROM <table_name>; (or)
SELECT column1, column2,…… FROM <table_name>;
Selecting distinct rows:
SELECT DISTINCT field_name FROM table_name;
Selecting specific rows:
SELECT column1,……..FROM <table_name> WHERE <condition> [ORDER BY column[desc]]
Relational Database Management System
Page 38
insert into student_master values(125,'Kala','Computer',2003); 1 row created.
select * from student_master;
REGNO NAME DEPT YEAR
123 Dhivya Physics 1998
124 Muthu Maths 2000
125 Kala Computer 2003
b) Select the student’s name column.
select name from student_master;
NAME
Dhivya
Muthu
Kala
c) Display the unique rows.
insert into student_master values(124,'fdgdf','sgf',1998); 1 row created. select * from student_master;
REGNO NAME DEPT YEAR
123 Dhivya Physics 1998
124 Muthu Maths 2000
125 Kala Computer 2003
124 fdgdf sgf 1998
select distinct regno from student_master;
Relational Database Management System
Page 39
REGNO
123
124
125
d) Sort the table in alphabetical order.
select * from student_master order by name;
REGNO NAME DEPT YEAR
123 Dhivya Physics 1998
125 Kala Computer 2003
124 Muthu Maths 2000
124 fdgdf sgf 1998
e) Select all the students of a particular department.
select * from student_master where dept='Computer';
REGNO NAME DEPT YEAR
123 Dhivya Physics 1998
125 Kala Computer 2003
124 Muthu Maths 2000
124 fdgdf sgf 1998
Result:-
The query was executed successfully and output was verified.
Viva Questions:
Relational Database Management System
Page 40
1. What is the purpose of select command & distinct clause?
The select command is used to retrieve the stored data from a table. To
avoid the selection of duplicate rows, the distinct clause is used in the select
statement.
2. What is sorting?
To arrange the given numbers in ascending or desc order.
3. How to use select command?
All SQL queries begin with the SELECT statement. This statement enables
you to retrieve all data or only certain columns and rows in a table. It can also
return data from more than one table. It enables you not only to retrieve data but
also perform calculations on existing data and return the results of these
calculations.
Arguments:
DISTINCT It means that only rows that are unique will be returned; any
duplicates will be weeded out first.
L ALL It means that all rows satisfying the conditions will be returned
(this is the default).
* Selects all the columns of tables or views specified in FROM
clause.
Table It means that all columns from this table will be displayed.
View Select all the columns of the specified view.
WHERE Filters the rows that will be displayed by the query. Without
this clause, all the rows are displayed.
7. Integrity Constraints
Relational Database Management System
Page 41
Aim:
a) Create a sales_order with s_order_no and product_no as primary key. Set other field store client number, delivery address, delivery date, order status.
b) Add a new column for storing salesman number using ALTER command c) Set the s_order_no as foreign key as column constraint d) Set the s_order_no foreign key as table constraint
a) Create a sales_order with s_order_no and product_no as primary key. Set
other field store client number, delivery address, delivery date, order
status.
create table sales_orders(s_order_no varchar2(6),product_no varchar2(6),
client_no varchar2(6), dely_addr varchar2(25), dely_date date, order_status
varchar2(10),PRIMARY KEY(s_order_no, product_no));
desc sales_order
Syntax:
The Constraint Keyword:
CREATE TABLE <TABLE_NAME> (column 1 datatype CONSTRAINT <constraint_name> constraint definition, column2 datatype………);
Adding a foreign Key:
CREATE TABLE <table name> (column1 data type, column2 data type CONSTRAINT constraint_name REFERENCES parent_table (column_name);
(or)
ALTER TABLE <table name> add constraint (constraint_name) foreign key (<column name>) references <table_name>;
Relational Database Management System
Page 42
Name Null? Type S_ORDER_NO NOT NULL VARCHAR2(6)
PRODUCT_NO NOT NULL VARCHAR2(6)
CLIENT_NO
VARCHAR2(6)
DELY_ADDR
VARCHAR2(25)
DELY_DATE
DATE
ORDER_STATUS
VARCHAR2(10)
b) Add a new column for storing salesman number using ALTER command
Alter table sales_orders add (sales_man_no number(5))
Table altered.
desc sales_orders
Name Null? Type S_ORDER_NO NOT NULL VARCHAR2(6)
PRODUCT_NO NOT NULL VARCHAR2(6)
CLIENT_NO
VARCHAR2(6)
DELY_ADDR
VARCHAR2(25)
DELY_DATE
DATE
ORDER_STATUS
VARCHAR2(10)
SALES_MAN_NO
NUMBER(5)
c) set the s_order_no as foreign key as column constraint
select * from sales_order_det;
alter table sales_orders add constraint sal_f_key foreign key(s_ord_no)references sales_order_det;
S_ORDER_NO PNO DESCRI
PTION QTY_ORD QTY_DISP P_RATE PROFIT_
PER SELL_PRICE
11 343 Arial 10 4 45 67 12
12 345 shear 34 4 56 76 50
13 346 Oil 56 12 45 20 18
14 347 colgate 45 56 67 15 24
15 348 Pears 35 65 32 13 14
Relatioonal Databinsert in09','Ful1 row c
insert in09','Ful* ERRORORA-02found insert in09','Ful
D) Set t
First dr
Table
create tnumber
Table cr
select *
Table
create tnumberkey(s_o
Table cr
insert in
base Mananto sales_lfilled','111created.
nto sales_lfilled','111
R at line 1:2291: integ
nto sales_lfilled','111
the s_ord
rop the tab
creation
table sal_dr(5));
reated.
from sal_
S_ORDE102
104
101
103
105
creation
table salesr(5),del_adrder_no,pr
reated.
nto sales_
agement Sy_orders val11');
_orders val11')
grity const
_orders val11');
er_no fore
ble sales_o
n:
d(s_order_n
_d;
ER_NO 2
4
1
3
5
n:
s_order1(s_ddr varcharoduct_no
_order1 val
ystem lues('11','2
lues('101',
traint (MA
lues('11','2
eign key a
orders usin
no numbe
_order_no ar(8),dely_do),foreign k
lues('101',
23','0001','
'23','0001'
AGESH.SA
23','0001','
as table c
ng drop ta
er(4) prima
PRODUUPS
CPU
COMP
PRIN
KEYB
number(4date date,okey(s_orde
'34','1110
Tenkasi','1
','Tenkasi',
L_F_KEY)
Tenkasi','1
onstraint
able statem
ary key,pro
UCT
PU
N
B
4),product_ord_statusr_no) refer
','Chennai
12-may-
,'12-may-
violated -
12-may-
t
ment.
oduct varc
STOC15
12
10
13
10
_no varchas varchar(8rences sal_
i','19-jan-0
parent ke
char2(5),st
CK 5
3
0
4
9
ar(5),clien8),primary_d);
09','Fulfiled
ey not
tock
nt_no y
d')
Relational Database Management System
Page 44
1 row created.
insert into sales_order1 values('1011','34','1110','Chennai','19-jan-09','Fulfiled') * ERROR at line 1: ORA-02291: integrity constraint (MAGESH.SYS_C005312) violated - parent key not found
Result:-
The query was executed successfully and output was verified.
Viva Questions:
1. What is meant by data integrity?
The integrity of data can be verified and checked by data integrity systems.
These systems are required at the time of supply of data that the user can be
prevented from supplying data of specific nature.
2. What are the different types of data integrity?
There are two types of data integrity
a. Entity
b. Referential
The entity data integrity are
a) Default – Indicates the default value
b) Not NULL – The value is not NULL
c) Unique – The value needs to be unique
d) Check – The value should be within limits
The referential integrity are
a) Primary key
b) Foreign key
3. What is meant by Primary key?
Relational Database Management System
Page 45
The primary key value rule specifies that each row of a table must be
identified by a unique value.
4. What is referential integrity?
The referential integrity rule determines that the value or group of fields
corresponds to the key fields of other tables
Reference Description Restrict Disables the updating are deletion of the specified data.
Set to NULL when specified data is updated or deleted, all the associated
data is adjusted to NULL
Set to default when specified data is updated or deleted, all the
dependent data is adjusted to the default value
Cascade When specified data is updated or deleted, all the dependent
data is updated too. If a row that is referenced is deleted, all
the dependent rows will also be deleted
No Action Disables the updation and deletion of specified data. This id
default operation in Oracle
5. Explain the column level constraints?
If the constraints are defined along with the column definition, it is called
column level constraint. Column level constraint can be applied to any one
column at a time i.e. they are local to a specific column. If the constraint spans
across multiple columns, the user will have to use table level constraints.
6. Explain the Table level constraints?
If the data constraint attached to specific cell in a table references the
contents of another cell in the table then the user will have to use table level
constraints. Table level constraints are stored as a part of the global table
definition.
8. Sub Queries
Relational Database Management System
Page 46
Aim: a) Create a table student with their elective paper as one field b) Create another table staff with the subject names they have handled
and number of times handled. c) Construct an English sentence to display the rows in the staff table. d) Use sub-query to display the information about student’s name and
staff names where both have same subject names e) Display the subject name, staff name where same subject is handled by
more than one staff f) Display the student, subject name where the subject is not at all
handled any staff in the staff table.
a) Create a table student with their elective paper as one field: create table student (rollno number(5), name varchar2(10), age number(4), degree varchar2(4), subject varchar2(8)); Table created.
insert into student values(123,'Mitha',25,'MSC','Java'); 1 row created. insert into student values(124,'Malar',24,'MCA','.Net'); 1 row created. insert into student values(125,'Santhiya',21,'ME','CG'); 1 row created. insert into student values(126,'Ram',20,'BE','VC++');
Syntax:
SubQuery:
SELECT * FROM <table_name> where [condition]SELECT * FROM <tablename> where [search condition]
Multiple Queries:
SELECT DISTINCT (column name) FROM <table_name> where (column name)IN (SELECT * FROM <table_name> where[search condition] IN (SELECT * FROM <table_name> where [search condition];
Relational Database Management System
Page 47
1 row created. insert into student values(127,'Raju',23,'BCA','VB'); 1 row created. select * from student;
ROLLNO NAME AGE DEGREE SUBJECT
123 Mitha 25 MSC Java
124 Malar 24 MCA .Net
125 Santhiya 21 ME CG
126 Ram 20 BE VC++
127 Raju 23 BCA VB
b) Create another table staff with the subject names they have handled and
number of times handled.
create table staff(staff_id number(3), staff_name varchar2(8), subject_name varchar2(6), times_handled number(3));
Table created. insert into staff values (&staff_id,'&staff_name','&subject_name',×_handled);
select * from staff;
Relational Database Management System
Page 48
STAFF_ID STAFF_NAME SUBJECT_NAME TIMES_HANDLED
346 jeyam VC++ 4
347 Prabha CG 2
345 Jeya Java 3
c) construct a English sentence to display the rows in the staff table:
select staff_name || ' handled' || subject_name || ' ' || times_handled || 'times.' from staff;
STAFF_NAME||'HANDLED'||SUBJECT_NAME||''||TIMES_HANDLED||'TIMES.'
Jeyam handled VC++ 4 times.
Prabha handled CG 2 times.
Jeya handled Java 3 times.
d) Use sub queries to display the information about student’s name and staff
names where both have same subject names:
select name, staff_name from student a, staff b where upper(subject)in(select upper(subject_name) from staff)and upper(a.subject)=upper(b.subject_name);
NAME STAFF_NAME Ram jeyam
Santhiya Prabha
Mitha Jeya
e) Display the subject name, staff names where same subject is handled by
more than one staff: insert into staff values(348,'Ravi','java',2); 1 row created.
select * from staff;
STAFF_ID STAFF_NAME SUBJECT_NAME TIMES_HANDLED 346 jeyam VC++ 4
347 Prabha CG 2
345 Jeya java 3
348 Ravi java 2
select a.subject_name,b.staff_name from staff a, staff b where a.staff_id<>b.staff_id and a.subject_name=b.subject_name;
Relational Database Management System
Page 49
SUBJECT_NAME STAFF_NAME java Jeya java Ravi
f) Display the student, subject name where subject is not at all handle any
staff in the staff table:
select distinct subject from student where upper(subject) not in(select distinct upper(subject_name) from staff);
SUBJECT .Net
VB
Result:-
The query was executed successfully and output was verified.
Viva Questions:
1. What do you mean by subqueries?
The subqueries are the form of SQL statement which appears inside other
SQL statements. Then the statement containing subqueries is called parent
statement. This is just like SQL executing another SQL statement.
2. Explain important uses of subqueries?
i. To insert records in the target table
ii. To create tables and insert records in this table
iii. To update records in the target table
iv. To create views
v. To provide values for conditions in WHERE, HAVING clauses of
SELECT, UPDATE and DELETE statements
3. What is the use of upper function?
It changes all the characters in char into capitals.
9. Joins in Sql * Plus
Relational Database Management System
Page 50
:
Aim:
a) Create a sales_order table and client_master table with suitable fields. b) Find the total number of quantity ordered for a particular product. c) Display the rows of the table in the sales order date wise. d) Join the two tables and display the product number,product name where the
orderno in the sales_order table and orderno in client_master are equal. e) Join the sales_order table to itself and display the order number,client number
and salesman number where client has been services by more than one salesman.
a) Create a sales_order table and client_master table with suitable fields.
Create sales_order Detail Table: create table sales_order(s_ord_no number(5),prod_no number(5), prod_name char(7),qty number(5),cli_no number(5),s_man_no number(6),s_date date); Table created. insert into sales_order values(122,090,'Rin',34,1222,123,'11-apr-04');
1 row created. insert into sales_order values(232,78,'Colgate',35,343,343,'22-mar-98');
1 row created.
insert into sales_order values(343,23,'Oil',34,232,4354,'10-may-03');
1 row created.
insert into sales_order values(434,90,'Flour',45,454,23,'9-jan-01');
Syntax:
Join:
SELECT column1,column2,…..FROM <table1>,<table2> where <logical expression>;
Relational Database Management System
Page 51
1 row created.
select * from sales_order;
S_ORD_NO PROD_NO PROD_NAME QTY CLI_NO S_MAN_NO S_DATE 122 90 Rin 34 1222 123 11-APR-04
232 78 Colgate 35 343 343 22-MAR-98
343 23 Oil 34 232 4354 10-MAY-03
434 90 Flour 45 454 23 09-JAN-01
Create client_master Detail Table: create table client_master_det(cli_no number(5),c_name char(7),cli_order_no number(5),addr char(6)); Table created.
insert into client_master_det values(23,'Mitha',122,'Nellai'); 1 row created.
insert into client_master_det values(45,'Raj',1343,'Ten');
1 row created.
insert into client_master_det values(67,'Gowsic',769,'UK');
1 row created.
select * from client_master_det;
CLI_NO C_NAME CLI_ORDER_NO ADDR 23 Mitha 122 Nellai
45 Raj 1343 Ten
67 Gowsic 769 UK
b) Find the total number of quantity ordered for a particular product.
select sum(qty) from sales_order where prod_no=90;
SUM(QTY) 79
c) Display the rows of the table in the sales order date wise.
Relatioonal Datab
select *
S_ORD
d) Join t
the orequal
select pclient_m
PROD
e) Join t
numbone sa
select da.cli_no
no rows insert in1 row cre
S_ORD_
select da.cli_no
base Mana
from sale
_NO PRO232
434
343
122
the two tarderno in .
prod_no,prmaster_det
D_NO 90 Ri
the sales_ber and saalesman.
distinct a.so=b.cli_no
s selected
nto sales_eated.
_NO PROD122 232 343 434 456
distinct a.so=b.cli_no
agement Sy
es_order or
D_NO PRO78 Col
90 Flou
23 Oil
90 Rin
ables and the sales
rod_name,t cc where
PROD_NAin
_order tabalesman n
s_ord_no,a and a.s_m
_order valu
D_NO PRO90 Rin 78 Colga23 Oil 90 Flour89 Pons
s_ord_no,a and a.s_m
ystem
rder by s_d
OD_NAMElgate
ur
n
display ts_order ta
cli_order_e ss.s_ord_
AME
ble to itsenumber wh
a.s_man_nman_no<>b
ues(456,08
OD_NAME
ate
r
a.s_man_nman_no<>b
date;
E QTY CL35
45
34
34
he producble and o
_no,s_ord_n_no=cc.cli_
CLI_ORD
lf and dishere clien
no from salb.s_man_n
89,'Pons',4
QTY CLI_34 135 34 45 45 1
no from salb.s_man_n
LI_NO S_M343
454
232
1222
ct numberderno in
no from sa_order_no;
DER_NO 12
splay the ont has bee
les_order ano;
45,1222,67
_NO S_MA1222
343 232 454
1222
les_order ano;
MAN_NO 343 2
23 0
4354 1
123 1
r,product client_m
ales_order
S_OR2 1
order numen service
a,sales_ord
78,'11-feb-
AN_NO S_123 11-A343 22-M
4354 10-M23 09-J
678 11-F
a,sales_ord
S_DAT2-MAR-98
9-JAN-01
0-MAY-03
1-APR-04
t name whmaster are
r ss,
RD_NO 22
mber,cliens by more
der b whe
-04');
_DATE APR-04 MAR-98 MAY-03 JAN-01 FEB-04
der b whe
TE 8
3
here
nt e than
re
re
Relational Database Management System
Page 53
S_ORD_NO S_MAN_NO 122 123 456 678
Result:-
The query was executed successfully and output was verified.
Viva Questions:
1. What is join?
A join combines the data spread across tables. A join is performed by
the ‘WHERE’ clause which combines the specified rows of tables.
2. What is simple join?
The simple join retrieves rows from two tables having a common
column. It is further classified into
i. Equi- join
ii. Non equi – join
3. Explain self join?
Joining a table to itself called a self join. The join condition compares
the each row of the table to itself and also other rows of the same table.
10. Logical Operator in SQL * PLUS
Relational Database Management System
Page 54
Aim: a) Create table sales_order_details with the s_order_no as primary key and with
the following fields:
product_no, description, qty_ordered, qty_dispatched, product_rate,
profit_percent, sell_price, supplier-name:
b) Select each row and compute sell_price*.50 and sell_price*1.50 for each row
selected.
c) Select product_no,profit_percent, sell_price where profit_per is not between 10
and 20 both includive.
d) select product_no, description, Profit_percent, sell_price where profit_percent
is not between 20 and 30.
e) select the suppier_name and product_no where supplier_name has ‘r’ or ‘h’
as second charcter.
Table Creation:
create table sales_order_det(s_order_no number(5) PRIMARY KEY,pno number(5),descriptio varchar(10),qty_ord number(4),qty_disp number(4),p_rate number(4),profit_per number(3),sell_price number(4));
Table created.
insert into sales_order_det values(11,343,'Arial',10,4,45,67,12); [[[[ 1 row created.
insert into sales_order_det values(12,345,'Rin',34,4,56,76,50);
Syntax:
Logical Operators:
Logical operators are used to combine two or more conditions.The value of a condition is either TRUE or FALSE.
List of logical operators
AND, OR, NOT
Relational Database Management System
Page 55
1 row created.
insert into sales_order_det values(13,346,'Oil',56,12,45,20,18); 1 row created.
select * from sales_order_det;
S_ORDER
_NO PNO
DESCRI
PTIO
QTY_
ORD
QTY_
DISP P_RATE
PROFIT_
PER
SELL_
PRICE
11 343 Arial 10 4 45 67 12
12 345 Rin 34 4 56 76 50
13 346 Oil 56 12 45 20 18
a) Select each row and compute sell_price*.50 and sell_price*1.50 for each
row selected.
select sell_price*.50,sell_price*1.5 from sales_order_det;
SELL_PRICE*.50 SELL_PRICE*1.5
6 18
25 75
9 27
select * from sales_order_det;
b) Select product_no,profit_percent, sell_price where profit_per is not
between 10 and 20 both includive.
S_ORDER
_NO PNO DESCRIPTIO
QTY_
ORD
QTY_
DISP P_RATE
PROFIT
_PER
SELL_PRIC
E
11 343 Arial 10 4 45 67 12
12 345 Rin 34 4 56 76 50
13 346 Oil 56 12 45 20 18
14 347 colgate 45 56 67 15 24
15 348 Pears 35 65 32 13 14
Relational Database Management System
Page 56
select pno,profit_per,sell_price from sales_order_det where profit_per <=10 or profit_per>=20;
PNO PROFIT_PER SELL_PRICE
343 67 12
345 76 50
346 20 18
c) select product_no, description, Profit_percent, sell_price where
profit_percent is not between 20 and 30.
select pno,profit_per,descriptio,sell_price from sales_order_det where profit_per not between 20 and 30;
PNO PROFIT_PER DESCRIPTIO SELL_PRICE
343 67 Arial 12
345 76 Rin 50
347 15 colgate 24
348 13 Pears 14
d) select the suppier_name and product_no where supplier_name has ‘r’ or
‘h’ as second charcter.
update sales_order_det set descriptio='shear' where pno=345
1 row updated.
select descriptio,pno from sales_order_det where descriptio like '_r%' or descriptio like '_h%';
DESCRIPTIO PNO
Arial 343
shear 345
Result:-
Relational Database Management System
Page 57
The query was executed successfully and output was verified.
Viva Questions:
1. Explain the use of Logical expression?
The logical expressions are created by joining field names or variables
with values by logical operators. The logical expression creates a condition
which may be true or false. These expressions are attached to SQL and if they
are true then SQL is executed.
2. Explain the variety of Logical operators used?
The varieties of logical operators used are
>
>=
<
<=
=
3. Explain how the conditional retrieval of data is carried out?
The data can be retrieved by writing SQL command using select *
and attaching a logical expression. For example
Select * from emp where condition
The condition can be a logical expression.
4. What is meant by pattern matching?
The use of the like predicate:
For character data types: % matches any string
_ (underscore) matches any single character
11. Different Select Statements in SQL*
Relational Database Management System
Page 58
Aim:
a) Create a table client_master with the following fields client_no, name,
address1, address2, city, state, pincode, remarks, bal_due with suitable
types.Create another table supplier_table from client_master. Select all the
fields and rename client_no with supplier_no and name with supplier_name.
b) Insert data into client_master.
c) Insert data into supplier_master from client_master.
d) Delete the selected row in the client_master.
a) Create a table client_master with the following fields client_no, name,
address1, address2, city, state, pincode, remarks, bal_due with suitable
Syntax:
Creating a table from an existing table:
CREATE TABLE<target_table>(column1,column2,…)] as SELECT
[*|column1,column2,….] FROM <source_table>;
Insert ion of selected data into a table from another table:
INSERT INTO <target_table> [(column1, column2,…)] SELECT
column_name,column_name,….. FROM <source_table> where
column_name=expression
Delete the selected Row:
DELETE FROM <table_name>[where<search condition>];
Relational Database Management System
Page 59
types.Create another table supplier_table from client_master. Select all the
fields and rename client_no with supplier_no and name with supplier_name
Create client_master Table:
create table client_master (client_no number(5), name varchar(10), addr1
varchar(8),addr2 varchar(8),city varchar(7),state varchar(7),remarks
varchar(7),bal_due number(5));
Table created.
Create supplier_master Table:
create table supplier_master(supplier_no, supplier_name,addr1,
addr2,city,state,remarks) as select client_no, name,addr1, addr2, city, state,
remarks from client_master;
Table created.
b) Insert data into client_master.
insert into client_master values(101,'Mathu','2nd st','2nd
st','Tenkasi','TN','Good',1900);
1 row created.
insert into client_master values(102,'Madan','3rd st','3rd
st','Tenkasi','TN','Bad',1000);
1 row created.
select * from client_master;
CLIENT_NO NAME ADDR1 ADDR2 CITY STATE REMARKS BAL_DUE
101 Mathu 2nd st 2nd st Tenkasi TN Good 1900
102 Madan 3rd st 3rd st Tenkasi TN Bad 1000
c) Insert data into supplier_master from client_master.
Relational Database Management System
Page 60
insert into supplier_master select client_no,name, addr1,addr2,city,state,remarks from client_master;
2 rows created.
select * from supplier_master;
SUPPLIER_NO SUPPLIER_NAME ADDR1 ADDR2 CITY STATE REMARKS
101 Mathu 2nd st 2nd st Tenkasi TN Good
102 Madan 3rd st 3rd st Tenkasi TN Bad
d) Delete the selected row in the client_master.
Before Deletion:
select * from client_master;
CLIENT_NO NAME ADDR1 ADDR2 CITY STATE REMARKS BAL_DUE 101 Mathu 2nd st 2nd st Tenkasi TN Good 1900
102 Madan 3rd st 3rd st Tenkasi TN Bad 1000
After Deletion:
delete from client_master where name='Madan';
1 row deleted.
select * from client_master;
CLIENT_NO NAME ADDR1 ADDR2 CITY STATE REMARKS BAL_DUE
101 Mathu 2nd st 2nd st Tenkasi TN Good 1900
Result:-
The query was executed successfully and output was verified.
Viva Questions:
Relational Database Management System
Page 61
1. What is structured query language?
It is a non- procedure language which allows for accessing the data and
manipulation of data. It allows for data query and security. These are four basic
operations in SQL:
i. Select the database
ii. Update the database
iii. Insert the database
iv. Delete the database
2. What is the benefit of random access file in a database system?
In this file the data is access directly by random access of any record.
Every record has fixed number of bytes of memory. Therefore access to any
record can be easily done.
3. What are the different types of file organizations?
The data in the file has to be properly organize to ensure that the records
are available for processing. There are four methods of organizing file.
i. Sequential file
ii. Direct file
iii. Index sequential file
iv. Random access file
4. What is the database administrator?
The database administrator (DBA)
12. Employee Details Using PL/SQL
Relational Database Management System
Page 62
Aim:
Create a PL/SQL code to display the employee details for an employee.
Create Table:
create table e_detail(emp_name varchar2(10), emp_id varchar2(10),BP number(5), HRA number(5), DA number(5),PF number(5));
insert into e_detail values('&emp_name', &emp_id,&BP, &HRA, &DA, &PF);
old 1: insert into e_detail values('&emp_name', &emp_id,&BP, &HRA, &DA, &PF) new 1: insert into e_detail values('Hari', 103,5000, 150, 200, 500) 1 row created.
select * from e_detail;
EMP_NAME EMP_ID BP HRA DA PF Ravi 101 3000 100 75 500 sankar 102 10000 200 400 1000 Hari 103 5000 150 200 500
Syntax:
PL/SQL Block Structure:
[DECLARE
Variable declarations]
BEGIN
Executable statements
[EXCEPTION
Exception handlers]
END;
Relational Database Management System
Page 63
set serveroutput on
declare
e_id1 number(5);
e_id2 number(5);
e_name varchar2(10);
e_bp number(5);
e_hra number(5);
e_da number(5);
e_pf number(5);
gp number(5);
np number(5);
begin
e_id1:=&start_emp_id;
e_id2:=&end_emp_id;
for x in e_id1..e_id2 loop
select emp_name,BP,HRA,DA,PF into e_name,e_bp,e_hra,e_da,e_pf from e_detail where emp_id=x;
gp:=e_bp+e_hra+e_da;
np:=gp-e_pf;
dbms_output.put_line(' Emp_Name: ' || e_name || ' Emp_id : ' || x || ' Gross Pay :' || gp || ' Net Pay:' ||np );
end loop;
end;
Relational Database Management System
Page 64
OUTPUT:
old 12: start_id:=&start_id; new 12: start_id:=101; old 13: end_id:=&end_id; new 13: end_id:=103;
Emp_Name: Ravi Emp_id : 101 Gross Pay :3175 Net Pay:2675 Emp_Name: sankar Emp_id : 102 Gross Pay :10600 Net Pay:9600 Emp_Name: Hari Emp_id : 103 Gross Pay :5350 Net Pay:4850
PL/SQL procedure successfully completed.
Result:-
The query was executed successfully and output was verified.
Viva Questions:
1. What do you mean by PL/SQL?
The PL/SQL is an extension of SQL and it contains number of SQL
statement which can be executed at a time. The PL/SQL allows to perform
updating and retrieval values in the database. It also allows for decision
making and conditional checking. It also allows for cyclic operation on
database.
2. What do you mean by literals or constants?
The literals are the value which remains constants. There are three types
of literals:
a) Numeric
b) String
c) Logical
3. Explain the system of PL/SQL?
Relational Database Management System
Page 65
The PL/SQL is a program which can be written in a file. It contains three
blocks such as:
a) Declare
b) Begin
c) Exception
4. What is a comment statement?
It is a non executable statement written in the program by use of – or /*
*/. This statement are inserted in the program for explaining the title and
variables of the program or description or logics of the program
5. Explain the use of variables in the programs?
The variables in the program are used for storing the values which are
unknown and which may vary during the execution of program.
6. What are different types of variables used in the program?
There are four types of variable
a) Numeric variable
b) Char variable
c) Date variable
d) Logical variable
13. To Calculate EB Bill Using If Statement
Relational Database Management System
Page 66
Aim:
To write a PL/SQL code to calculate EB bill for the given units using if statement.
Table Creation:
create table eb_bill(name varchar2(10), e_id number(5), pre_reading number(5), curr_reading number(5));
Table created.
insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading);
old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Sudan', 1001, 103, 250) 1 row created.
old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Jana', 1002, 500, 750) 1 row created.
Syntax:
If Statement:
IF condition THEN
S1
S2 . . . . END IF; S1,S2 Statements
Condition Boolean Expression
Relational Database Management System
Page 67
old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Kishore', 1003, 430, 690) 1 row created.
old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Arun', 1004, 340, 400) 1 row created.
old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Kumaran', 1005, 750, 1050) 1 row created.
select * from eb_bill;
NAME E_ID PRE_READING CURR_READING Sudan 1001 103 250
Jana 1002 500 750
Kishore 1003 430 690
Arun 1004 340 400
Kumaran 1005 750 1050
To calculate EB bill for the given units using if statement.
set serveroutput on
declare
e_name varchar2(10);
start_id number(5):=&start_id;
end_id number(5):=&end_id;
e_pre_reading number(5);
e_curr_reading number(5);
units number(5);
amount number(5);
x number;
begin
for x in start_id..end_id loop
select name,pre_reading,curr_reading into e_name,e_pre_reading,e_curr_reading from eb_bill where e_id=x;
Relational Database Management System
Page 68
units:=e_curr_reading-e_pre_reading;
if units>='100' then
amount:=units*1.75;
end if;
if (units>'100' and units<='200') then
amount:=units*3;
end if;
if(units>'200') then
amount:=units*4;
end if;
dbms_output.put_line('Name : ' || e_name || ' ID : ' || x || ' Units : ' || units || ' Amount : ' || amount);
end loop;
end;
OUTPUT:
old 3: start_id number(5):=&start_id; new 3: start_id number(5):=1001; old 4: end_id number(5):=&end_id; new 4: end_id number(5):=1005;
Name : Sudan ID : 1001 Units : 147 Amount : 441 Name : Jana ID : 1002 Units : 250 Amount : 1000 Name : Kishore ID : 1003 Units : 260 Amount : 1040 Name : Arun ID : 1004 Units : 60 Amount : 1040 Name : Kumaran ID : 1005 Units : 300 Amount : 1200
PL/SQL procedure successfully completed.
Result:-
The query was executed successfully and output was verified.
Relational Database Management System
Page 69
Viva Questions:
1. Explain the function used for display of value of variable?
The function used for display of value for variable is DBMS output
function which calls upon put line function to display a value of variable.
2. Explain the control statement used in oracle?
The control statements are used for decision making. The control
statement checks the condition and accordingly executes the decision.
3. What are the different types of control statement used?
If statement are used as control statements. These statements are
a) If – THEN statement
b) If – THEN ELSE statement
c) If – THEN ELSE if statement
d) Compound if statement
4. Explain the used of looping statements?
The looping statements have the capability to repeat sequence of
statement. It performs number of cycles of operation over the given statement
for modification of variables. The cycles are terminated when the condition is
false.
5. What are the different types looping statements used?
There are four types of looping statement used
a) Simple loop
b) While statement
c) For loop statement
d) Goto statement
Relational Database Management System
Page 70
AIM:
To write a PL/SQL block to handle built-in exception like NO_DATA_FOUND, TOO_MANY_ROWS.
Table Creation:
create table alumni(name varchar2(10), address varchar2(10), degree varchar2(10), batch number(10));
Table created.
insert into alumni values('&name', '&address', '°ree', '&batch');
select * from alumni;
NAME ADDRESS DEGREE BATCH Babu PCM BE 2002
Christy Surandai MCA 2000
Malar Ppy MCA 2005
Mitha Pv Mphil 2003
Jency govai BE 2002
To handle built-in exception like NO_DATA_FOUND, TOO_MANY_ROWS.
set serveroutput on
declare
a_batch number(10);
a_name varchar2(10);
14. Built in Function using PL/SQL
Syntax:
Exception Handlers:
WHEN <exception name> [OR <exception name>…] then <Sequence of statements>
Relational Database Management System
Page 71
ad varchar2(10);
a_degree varchar2(10);
begin
a_batch:=&batch;
select name, address, degree into a_name, ad, a_degree from alumni where batch= a_batch;
dbms_output.put_line('Alumni_Name: ' || a_name || ' Batch : ' || a_batch );
exception
when no_data_found then
dbms_output.put_line('The ' || a_batch || ' Record Not Found. Please Insert.');
when too_many_rows then
dbms_output.put_line('The ' || a_batch ||' Occurs Two Times. Please Select One Row Record.');
end;
old 7: a_batch:=&batch; new 7: a_batch:=2000;
Alumni_Name: Christy Batch : 2000
PL/SQL procedure successfully completed.
old 7: a_batch:=&batch; new 7: a_batch:=2002;
The 2002 Occurs Two Times. Please Select One Row Record.
PL/SQL procedure successfully completed.
old 7: a_batch:=&batch; new 7: a_batch:=1999;
The 1999 Record Not Found. Please Insert.
PL/SQL procedure successfully completed.
Result:-
The query was executed successfully and output was verified.
Relational Database Management System
Page 72
Viva Questions:
1. What do you mean by error handling?
The terminology for handling the errors in PL/SQL is ‘exception’. There
are two types of exception. They are
1. Predefined exceptions
2. User defined exceptions
An exception is raised when an error occurs.
2. What is a predefined exception?
Predefined exceptions are raised automatically by the system during
the run time when an error occurs.
3. List the predefined exception?
Predefined exception
Raised if
No_data_found Select statement returns no rows
(records).
Too_many_rows Select into statement returns more
than one row.
Zero_divide Try to divide a number by zero.
Program error PL/SQL has an internal problem.
Invalid_number
Conversion of a character string to a
number fails.
(e.g. to_number(‘234A4’);’234A4’
does not represent a valid number)
Relational Database Management System
Page 73
Aim:
To write a PL/SQL code to handle user defined exception.
To handle user defined exception:
set serveroutput on
prompt 1. Addition
prompt 2. Subtraction
prompt 3. Multiplication
prompt 4. Division
accept n number prompt 'Enter Your choice :'
declare
d number:=&n;
a number:=&a;
b number:=&b;
c number(5);
add_excep exception;
sub_excep exception;
mul_excep exception;
div_excep exception;
begin
if d=1 then
if (a>0 AND b> 0) then
c:=a+b;
15. User Define Exception using PL/SQL
Syntax:
User-define Exception:
RAISE exception name;
Relational Database Management System
Page 74
dbms_output.put_line('Addition :' ||c);
else
raise add_excep;
end if;
end if;
if d=2 then
if (a>0 and b>0 )then
c:=a-b;
dbms_output.put_line('Subtraction :'||c);
else
raise sub_excep;
end if;
end if;
if d=3 then
if (a>0 and b>0) then
c:=a*b;
dbms_output.put_line('Multiplication :'||c);
else
raise mul_excep;
end if;
end if;
if d=4 then
if(a>0 and b>=0) then
c:=a/b;
dbms_output.put_line('Divition :'||c);
else
raise div_excep;
end if;
end if;
Relational Database Management System
Page 75
exception
when add_excep then
dbms_output.put_line (' Arithmetic Exception ');
when sub_excep then
dbms_output.put_line ('Enter Passitive value' );
when mul_excep then
dbms_output.put_line ('Enter valid Input');
when div_excep then
dbms_output.put_line (' Divide by Zero Exception');
end;
Output:
1. 1. Addition 2. Subtraction 3. Multiplication 4. Division old 2: d number:=&n; new 2: d number:= 1; old 3: a number:=&a; new 3: a number:=10; old 4: b number:=&b; new 4: b number:=20; Addition :30 PL/SQL procedure successfully completed.
Relational Database Management System
Page 76
2. 1. Addition 2. Subtraction 3. Multiplication 4. Division old 2: d number:=&n; new 2: d number:= 3; old 3: a number:=&a; new 3: a number:=10; old 4: b number:=&b; new 4: b number:=23; Multiplication :230 PL/SQL procedure successfully completed.
3. 1. Addition 2. Subtraction 3. Multiplication 4. Division old 2: d number:=&n; new 2: d number:= 4; old 3: a number:=&a; new 3: a number:=12; old 4: b number:=&b; new 4: b number:=0; Divide by Zero Exception PL/SQL procedure successfully completed.
Result:-
The query was executed successfully and output was verified.
Relational Database Management System
Page 77
Viva Questions:
1. What is user – defined exceptions?
Unlike predefined exceptions, user_defined exceptions should be
declared in the declarative part and raised explicitly by a raise statement.
2. Explain the pragma?
A pragma is a compiler directive. This is processed at compile time and
not at run time.
3. What is mean by Raise_application_error?
This is more descriptive than named exception.
The general syntax is
Raise_application_error (error number, error message);
Where
Error_number is a number between -20,000 and -20,999
Error message is the text associated with this error. The error
message must be fewer than 512 characters.
4. What is mean by exception handling in oracle?
The exceptional errors occurring during the program can be handled by
exception handling block in oracle program. If the error condition occurs in the
program than the program can be terminated and the error is raised to the
user indicating the exception to an error.
Relational Database Management System
Page 78
Aim:
To write a PL/SQL block to use procedure and function and get the result.
a) To use procedure and get the result
create or replace procedure find_address(phno number) as addr varchar2(50);
begin
select username||','||doorno||','||place||','||pincode into addr from phone where ph_no=phno;
dbms_output.put_line(addr);
exception
16. Procedure & Function using PL/SQL
Syntax:
Procedure:
Create or Replace procedure procedure_name [parameter list] is
.
.
. Begin . . . Exception . . .
End;
Executing a Procedure:
Exec <Procedure_name> (parameter);
Declarative Part
Execution Part
Execution Handler
Relational Database Management System
Page 79
when no_data_found then
dbms_output.put_line(' Address Not Found');
end;
1) begin
find_address(565656);
end;
OUTPUT:
Ganesh,34,Tenkasi,627811 PL/SQL procedure successfully completed.
2) begin
find_address(257342);
end;
OUTPUT:
Address Not Found PL/SQL procedure successfully completed.
Syntax:
Function:
CREATE OR REPLACE
FUNCTION [schema.] function name (argument IN datatype,..)
RETURN datatype {IS, AS}
variable declaration;
constant declaration;
BEGIN
PL/SQL subprogram body;
EXCEPTION
Exception PL/SQL block;
END
Relatioonal Datab
b) To us
create tnumber
Table cr
insert in
1 row c
insert in
1 row c
insert in
1 row c
select *
PH_N23232
56565
43543
create ovarchar
begin
select uwhere
return a
exceptio
w
end;
Functio
base Mana
se Functio
table phonr(5),place v
reated.
nto phone
created.
nto phone
created.
nto phone
created.
from phon
NO US24
56
34 M
or replace r2(50);
username| ph_no=p
addr;
on
when no_d
on created
agement Sy
on and get
ne(ph_no nvarchar(10
e values(23
e values(56
e values(43
ne;
SERNAMERaman
Ganesh
Murugan
function f
|','||doorphno;
ata_found
.
ystem
t the resu
number(7),0),pincode
32324,'Ram
65656,'Gan
35434,'Mu
E DO2
6
findaddres
rno||','||p
d then retu
ult
,usernamee number(6
man',234,
nesh',34,'T
urugan',67
ORNO 234
34
676
ss(phno in
place||','|
urn ' Addre
e varchar(6));
'Nellai',65
Tenkasi',6
76,'Madura
PLACE Nellai
Tenkasi
Madurai
n number)
|pincode
ess Not Fo
10),doorno
4553);
627811);
ai',343434
PINC654
i 627
i 343
return var
into addr
ound';
o
4);
CODE 4553
7811
3434
rchar2 as
from phon
addr
ne
Relational Database Management System
Page 81
1) set serveroutput on
declare
addr varchar2(50);
begin
addr:=findaddress(232324);
dbms_output.put_line(addr);
end;
OUTPUT:
Raman,234, Nellai,654553 PL/SQL procedure successfully completed.
2) declare
addr varchar2(50);
begin
addr:=findaddress(243434);
dbms_output.put_line(addr);
end;
OUTPUT:
Address Not Found PL/SQL procedure successfully completed.
Result:-
The query was executed successfully and output was verified.
Relational Database Management System
Page 82
Viva Questions:
1. Explain what do you mean by procedure?
The procedure is a subprogram which can be called in the main program
by the user. These the user made functions and operations which can be
performed on the given database. The procedures are attached to the database
and can be called by PL/SQL program to perform the calculations.
2. Explain what do you mean by function?
The functions are similar to procedures and are subprograms called by
PL/SQL program. The function retrieves the input values and the output value is
returned to the PL/SQL program.
3. Explain modes of parameter?
The parameter defined in the parameter list may be in one of the following
three modes. They are
a. In
b. Out
c. Inout
Relational Database Management System
Page 83
Aim:
Create a PL/SQL trigger to update the records while deleting the one record in another table.
To update the records while deleting the one record in another table.
create table student(name varchar2(10),app_no number(10), join_year date,dob date,qualification varchar2(10));
Table created.
insert into student values('&name',&app_no,'&join_year','&dob','&qualification');
select * from student;
NAME APP_NO JOIN_YEAR DOB QUALIFICATION Raju 501 26-MAY-06 02-MAR-87 +2
Viji 502 26-MAY-06 12-APR-88 10
create table student_detail(name varchar2(10),app_no number(10), join_year date,primary key(app_no));
Table created.
desc student_detail;
Name Null? Type NAME VARCHAR2(10)
APP_NO NOT NULL NUMBER(10)
JOIN_YEAR DATE
17. Students Admission Using Trigger
Syntax:
Creation of Triggers:
Create or replace Trigger <trigger_name> {before/after} {insert/update/delete} on <table_name>
[for each statement/for each row] [when<condition];
Relational Database Management System
Page 84
select * from student_detail;
NAME APP_NO JOIN_YEAR Kavi 555 02-JUN-08 Vijay 556 01-JUN-09 Reegan 557 05-JUN-98 Raju 501 02-MAR-87 viji 502 26-MAY-06
Trigger Creation:
create or replace trigger trig after update on student_detail for each row
declare
s_app_no number(10);
s_joint_year date;
pass_out number(5);
begin
s_app_no:=:new.app_no;
delete from student where app_no=s_app_no;
end;
Update student_detail set name='Anu' where app_no=501;
1 row updated.
select * from student_detail;
NAME APP_NO JOIN_YEAR Kavi 555 02-JUN-08 Vijay 556 01-JUN-09 Reegan 557 05-JUN-98 Anu 501 02-MAR-87 viji 502 26-MAY-06
select * from student;
NAME APP_NO JOIN_YEAR DOB QUALIFICATION Viji 502 26-MAY-06 12-APR-88 10
Relational Database Management System
Page 85
Result:-
The query was executed successfully and output was verified.
Viva Questions:
1. What is trigger?
A database trigger is a PL/SQL block that can be associated to a specific
database table. The purpose of a database trigger is to perform a service when
a specified operation occurs on a table. We create a database trigger by
specifying a database table and by specifying that before or after a database
operation (INSERT, UPDATE, or DELETE) on that table a procedure should be
invoked.
2. Explain the trigger restrictions?
A trigger cannot execute the COMMIT, ROLLBACK, or SAVEPOINT
commands. It also cannot call procedures or functions that execute those
tasks. The SELECT command can be used only with the INTO clause.
3. List the component of a trigger?
A trigger has three parts:
i. SQL command that activates the trigger
The trigger can be activated by a SQL command or by user event. In a table,
it can be triggered by INSERT, UPDATE, or DELETE commands. In a
schema object, it can be triggered through the CREATE, ALTER or DROP
commands, when the database is loaded or shut down, or through an error
message.
ii. Trigger restriction
Represented by the WHEN clause, it specifies what condition must be true
for the trigger to be triggered
iii. Trigger action
The PL/SQL block, or Java or C routine executed by the trigger.
4. How to explain the modifying a trigger?
A trigger cannot be directly modified. To change it you must recreate it with
the CREATE command. If a trigger had its privileges granted to other users,
they remain valid as long as the trigger exists.
Relational Database Management System
Page 86
Aim: -
Create a table to store the salary details of the employees in a company. Declare the cursor id to contain employee number, employee name and net salary. Use cursor to update the employee salaries.
create table cur_sal(emp_no number(6) primary key,name varchar(7),
desig varchar(9),depart varchar(10),bp number(6),da number(4),ma number(4),allow number(4),ded number(6,2));
Table created.
insert into cur_sal values(122,'Sam','Lecturer','CE', 5000, 20, 120, 400, 300);
1 row created.
insert into cur_sal values(34,'Aravind','Engineer','EEE', 20000, 1000,200, 700, 800);
1 row created.
insert into cur_sal values(111,'Ravi','Designer','IT', 10000, 100,150, 300, 500);
1 row created.
18. Employee Salary Detail Using Cursor
Syntax:
Open:
OPEN <cursor_name>;
Fetch:
FETCH cursor_name INTO column_name;
Close:
CLOSE cursor_name;
Relational Database Management System
Page 87
PL/SQL Procedure:
set serveroutput on
declare
e_no number(6);
e_name varchar2(7);
net_sal number(8,2);
cursor empsal is select emp_no,name,bp+da*bp/100+ma+allow-ded from
cur_sal;
begin
dbms_output.put_line('EMP_NO'||'NAME'||'NET SALARY');
dbms_output.put_line('------------------------------------------');
open empsal;
loop
fetch empsal into e_no,e_name,net_sal;
exit when empsal%notfound;
dbms_output.put_line(rpad(e_no,10,' ')||rpad(e_name,7,' ')||net_sal);
end loop;
close empsal;
end;
EMP_NO NAME NET SALARY ---------- -------- --------------- 122 Sam 6220 34 Aravind 220100 111 Ravi 19950
PL/SQL procedure successfully completed.
declare
no number(5):=34;
basic number(5);
da cur_sal.da%type;
med cur_sal.ma%type;
Relational Database Management System
Page 88
other cur_sal.allow%type;
ded cur_sal.ded%type;
cursor c_sal(emp_id number) is select emp_no,bp,da,ma,allow,ded from
cur_sal where emp_no=emp_id;
begin
open c_sal(no);
fetch c_sal into no,basic,da,med,other,ded;
if c_sal%notfound then
dbms_output.put_line('No such employee found');
else
update cur_sal set bp=8000,da=20,ma=222,allow=600,ded=250
where emp_no=no;
end if;
close c_sal;
end;
PL/SQL procedure successfully completed.
After Updating:
select * from cur_sal;
EMP_NO NAME DESIG DEPART BP DA MA ALLOW DED 122 Sam Lecturer CE 5000 20 120 400 300
34 Aravind Engineer EEE 8000 20 222 600 250
111 Ravi Designer IT 10000 100 150 300 500
Result:-
The query was executed successfully and output was verified.
Relational Database Management System
Page 89
Viva Questions:
1. What do you mean by cursor?
The cursors are the memory areas or work areas used for internal
processing of data. These are capable are storing the data on which SQL
operations can be performed.
2. What are the operations required for cursors?
The following operations are required for the cursor
a. Declare a cursor along with SQL statement
b. Open a cursor
c. Fetch data from cursor
d. Closed the cursor
3. What is the use of %notfound?
The %notfound evaluates to true if the data manipulation language
statement does not return any row. Otherwise it evaluates to false.
4. What is the use of fetch command?
The fetch command retrieves the current row and places the pointer to the
next row.
5. What is the use of close command?
After processing the last row in the active set, the cursor is closed using
close command.
Relational Database Management System
Page 90
Aim:
Develop visual basic form with suitable Labels & Textboxes for the columns
of a table. Add command buttons to perform the following: Insert Record, Delete
Record, Update Record, and Locate Record.
Table Creation :(Database connection)
SQL> create table stud(Regno number(8),name varchar2(8),Department
varchar2(8),subject1 number(1),subject2 number(3),subject3 number(3),total
number(4),avg number(4));
Table created.
SQL> insert into stud values('1001','mathu','Mech',90,90,90,270,90);
1 row created.
SQL> select * from stud;
REGNO NAME DEPARTME SUBJECT1 SUBJECT2 SUBJECT3 TOTAL AVG -------- -------- ------------ ------------ ------------ ------------ -------- -----
1002 Hari EEE 40 45 50 135 45
1001 Mathu Mech 100 99 99 298 99
SQL> commit;
Commit complete.
19. DML Using ADO Creation
Relational Database Management System
Page 91
Program:
Imports System.Windows.Forms.Form
Imports System.Data
Imports System.Data.OracleClient
Imports System.Data.OracleClient.OracleConnection
Public Class Form2
Dim dr As OracleDataReader
Dim x As Integer
Dim oda As New OracleDataAdapter
Dim cmd As New OracleCommand
Dim con As New OracleConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim cnstr As String
cnstr = "Data Source=orcl;User ID=scott;Password=tiger;"
con = New OracleConnection(cnstr)
End Sub
Private Sub cmdinsert_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Enter the Regno")
TextBox1.Focus()
ElseIf TextBox2.Text = "" Then
MsgBox("Enter the Name")
TextBox2.Focus()
ElseIf TextBox3.Text = "" Then
MsgBox("Enter the Department")
TextBox3.Focus()
ElseIf TextBox4.Text = "" Then
MsgBox("Enter the subject1")
TextBox4.Focus()
ElseIf TextBox5.Text = "" Then
Relational Database Management System
Page 92
MsgBox("Enter the subject2")
TextBox5.Focus()
ElseIf TextBox8.Text = "" Then
MsgBox("Enter the subject3")
TextBox8.Focus()
Else
Try
con.Open()
cmd = New OracleCommand("insert into stud values('" &
TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox8.Text & "','" &
TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "', '"
& TextBox6.Text & "', '" & TextBox7.Text & "')", con)
x = cmd.ExecuteNonQuery()
If (x = 1) Then
MsgBox("1row created")
Else
MsgBox("no rows created")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
Private Sub cmdclickme_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button5.Click
TextBox6.Text = Val(TextBox3.Text) + Val(TextBox4.Text) +
Val(TextBox5.Text)
TextBox7.Text = Val(TextBox6.Text) / 3
End Sub
Private Sub cmdupdate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
con.Open()
Relational Database Management System
Page 93
cmd = New OracleCommand("update stud set regno='" & TextBox1.Text &
"',name='" & TextBox2.Text & "',department='" & TextBox8.Text & "',subject1='" &
TextBox3.Text & "',subject2='" & TextBox4.Text & "', subject3='" & TextBox5.Text
& "',total='" & TextBox6.Text & "', avg='" & TextBox7.Text & "' Where regno ='" &
TextBox1.Text & "'", con)
x = cmd.ExecuteNonQuery()
If (x = 1) Then
MsgBox("1row updated")
Else
MsgBox("no rows updated")
End If
con.Close()
End Sub
Private Sub cmddelete_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
con.Open()
cmd = New OracleCommand("delete from stud where regno='" &
TextBox1.Text & "'", con)
x = cmd.ExecuteNonQuery()
If (x = 1) Then
MsgBox("1row deleted")
Else
MsgBox("no rows deleted")
End If
con.Close()
End Sub
Private Sub cmdview_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button6.Click
con.Open()
cmd = New OracleCommand("select * from stud where regno='" &
TextBox1.Text & "'", con)
dr = cmd.ExecuteReader
Relational Database Management System
Page 94
If dr.HasRows Then
While dr.Read
TextBox1.Text = (dr(0))
TextBox2.Text = (dr(1))
TextBox8.Text = (dr(2))
TextBox3.Text = (dr(3))
TextBox4.Text = (dr(4))
TextBox5.Text = (dr(5))
TextBox6.Text = (dr(6))
TextBox7.Text = (dr(7))
End While
Else
MsgBox("no rows")
End If
con.Close()
End Sub
Private Sub cmdclear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button4.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
End Sub
Private Sub cmdexit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button7.Click
End
End Sub
End Class
Relational Database Management System
Page 95
output:
Database output:
SQL> select * from stud;
REGNO NAME DEPARTME SUBJECT1 SUBJECT2 SUBJECT3 TOTAL AVG -------- ------- ------------ ------------ ------------ ------------ ------- ----
1002 Hari EEE 40 45 50 135 45
1003 Silviya IT 89 90 99 278 93
1001 Mathu Mech 100 99 99 298 99
Result:-
The above program was successfully and the output was verified.
Relational Database Management System
Page 96
Viva Questions:
1. DATA NAMESPACE:
SYSTEM DATA:
Contain fundamental classes with the core ADO.Net functionality. These
include dataset and data relation which allow you to manipulate structured
relation data.
System.Data.Oracleclient:
It contains classes to connect the Microsoft oracle server database. These
classes like oracle command and connection provide all the same properties and
method as the counter parts in system data.oracle namespace.
Data object:
Allow to store a local disconnected copy of data, they don’t store a
connection to a data store.
Dataset:
Dataset class and disconnect information drawn by direct connection and
allows you to manipulate the data’s. The data is a class no direct connection to a
data source.
Data table:
Add information in to a dataset in one table at a time data table object
represent one of this table.
Data row:
It represents a single row of information into the table.
Data column:
Data column object not contain any actual data.
20. Navigation object using ADO creation
Relational Database Management System
Page 97
Aim: To develop a visual basic application with suitable Lables&Textboxes for
the columns of a table. Add command buttons to perform the following:
display records,Previous,Next,First and Last. Use the ODBC driver to connect the
application with the oracle.
Table creation:
SQL> create table biodata(name varchar2(8),sex varchar2(6),status
varchar2(9),Qualification varchar2(9),percentage number(4),designation
varchar2(12),Exprience varchar2(6),address varchar2(14),email_id
varchar2(15),phoneno number(10));
Table created.
SQL> insert into biodata
values('Magesh','FEMALE','Married','Msc.MPhil','89','Lecturer','3years','Te
nkasi','www.gmail.com','9790894132');
1 row created.
SQL> insert into biodata
values('Christy','FEMALE','Married','MCA','92','Lecturer','3years','SURANDA
I','[email protected]','9894677898');
1 row created.
SQL> insert into biodata
values('Jency','FEMALE','unMarried','BE','94','Lecturer','2years','TIRUNELV
ELI','[email protected]','9987543784');
1 row created.
Relational Database Management System
Page 98
SQL> insert into biodata
values('Malar','FEMALE','unMarried','MCA','99','Lecturer','1years','CHENNAI
','[email protected]','9876540902');
1 row created.
SQL> insert into biodata
values('kanaga','FEMALE','Married','MCA','87','Lecturer','3years','CHENNAI'
,'[email protected]','9890456778');
1 row created.
SQL> select * from biodata;
NAME SEX STATUS QUALIFICA PERCENTAGE DESIGNATION EXPRIE ADDRESS EMAIL_ID PHONENO
---- --- ------ -------- ----------- ------------ ------ -------- ------- -------- Magesh FEMALE Married Msc.MPhil 89 Lecturer 3years Tenkasi www.gmail.com 9790894132
Christy FEMALE Married MCA 92 Lecturer 3years SURANDAI [email protected] 9894677898
Jency FEMALE unMarried BE 94 Lecturer 2years TIRUNELVELI [email protected] 9987543784
Malar FEMALE unMarried MCA 99 Lecturer 1years CHENNAI [email protected] 9876540902
kanaga FEMALE Married MCA 87 Lecturer 3years CHENNAI [email protected] 9890456778
SQL> commit;
Commit complete.
Program:
Imports System.Data
Imports System.Data.OracleClient
Imports System.Data.OracleClient.OracleConnection
Imports System.Data.OracleClient.OracleDataReader
Public Class Form3
Inherits System.Windows.Forms.Form
Private WithEvents mycurrencymanager As CurrencyManager
Dim con As New OracleConnection
Dim ds As New DataSet
Dim cmd As New OracleCommand
Dim dr As OracleDataReader
Relational Database Management System
Page 99
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim cnstr As String
cnstr = "Data Source=orcl;User ID=scott;Password=tiger;"
con = New OracleConnection(cnstr)
Dim oda As New OracleDataAdapter("select * from biodata", con)
oda.Fill(ds, "biodata")
con.Open()
TextBox1.DataBindings.Add("text", ds.Tables!biodata, "name")
TextBox2.DataBindings.Add("text", ds.Tables!biodata, "sex")
TextBox3.DataBindings.Add("text", ds.Tables!biodata, "status")
TextBox4.DataBindings.Add("text", ds.Tables!biodata, "qualification")
TextBox5.DataBindings.Add("text", ds.Tables!biodata, "percentage")
TextBox6.DataBindings.Add("text", ds.Tables!biodata, "Designation")
TextBox7.DataBindings.Add("text", ds.Tables!biodata, "Exprience")
TextBox8.DataBindings.Add("text", ds.Tables!biodata, "Address")
TextBox9.DataBindings.Add("text", ds.Tables!biodata, "EMail_id")
TextBox10.DataBindings.Add("text", ds.Tables!biodata, "Phoneno")
mycurrencymanager = CType(Me.BindingContext(ds.Tables!biodata),
CurrencyManager)
MsgBox("connection success")
con.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
mycurrencymanager.Position = 0
MsgBox("FIRST RECORED")
End Sub
Private Sub cmdfirst_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
mycurrencymanager.Position = 0
MsgBox("FIRST RECORED")
End Sub
Relational Database Management System
Page 100
Private Sub cmdprivous_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
If mycurrencymanager.Position > 0 Then
mycurrencymanager.Position -= 1
MsgBox("PRIVIOUS RECORED")
End If
End Sub
Private Sub cmdnext_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
If mycurrencymanager.Position < mycurrencymanager.Count Then
mycurrencymanager.Position += 1
MsgBox("NEXT RECORED")
End If
End Sub
Private Sub cmdlast_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button4.Click
mycurrencymanager.Position = mycurrencymanager.Count
MsgBox("LAST RECORED")
End Sub
Private Sub cmdclear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button5.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
TextBox9.Text = ""
TextBox10.Text = ""
End Sub
Relational Database Management System
Page 101
Private Sub cmdexit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button6.Click
End
End Sub
End Class
Output:
Result:-
The above program was successfully and the output was verified.
Relational Database Management System
Page 102
Viva Questions:
Oracle Connection:
These object represent and sql statement or stored procedure are back you can used in future for to read, update or modify the data.
To used your command you must be use a data adapter or use one of the following
Execute Non Query:
It allows you to execute the command without retrieving any information. This is ideal for add , update, delete operation using SQL statement.
Execute Reader:
Create or Reader connection which provides a fast forward connection only that allows you to retrieved rows from the data source.
Execute ScalerL:
These also create a reader but only return a single value. The first column from the first row of the resulting rows.
This method cannot be used if you are using an SQL statement or stored procedure that return a value instead of row set.
Relational Database Management System
Page 103
1. Transaction Control Language
Extra Programs
Relational Database Management System
Page 104
Aim:
To Execute all the TCL Commands.
Table Creation:
create table emp(empnum varchar2(8),empname varchar2(8),desig
varchar2(14),doj date,salary number(8));
Table created.
To Insert the Record:
insert into emp values('&empnum','&empname','&desig','&doj','&salary');
old 1: insert into emp values('&empnum','&empname','&desig','&doj','&salary')
new 1: insert into emp values('1001','mathu','designeng','12-sep-07','30000')
1 row created.
old 1: insert into emp values('&empnum','&empname','&desig','&doj','&salary')
new 1: insert
insert into emp values('1002','raj','manager','14-sep-07','35000')
1 row created.
To View the Record:
select * from emp;
EMPNUM EMPNAME DESIG DOJ SALARY 1001 mathu designeng 12-SEP-07 30000
1002 raja manager 14-SEP-07 35000
A.COMMIT:
Commit
Commit complete.
insert into emp values('1003','Vishal','operator','12-feb-03','4000')
1 row created.
Relational Database Management System
Page 105
select * from emp;
EMPNUM EMPNAME DESIG DOJ SALARY 1001 mathu designeng 12-SEP-07 30000
1002 raj manager 14-SEP-07 35000
1003 Vishal operator 12-FEB-03 4000
Rollback
Rollback complete.
select * from emp;
EMPNUM EMPNAME DESIG DOJ SALARY 1001 mathu designeng 12-SEP-07 30000 1002 raja manager 14-SEP-07 35000
B.COMMIT(savepoint)
commit;
Commit complete.
insert into emp values('1003','barath','operator','12-may-03','4000')
1 row created.
select * from emp
EMPNUM EMPNAME DESIG DOJ SALARY 1003 barath operator 12-MAY-03 4000 1001 mathu designeng 12-SEP-07 30000 1002 raja manager 14-SEP-07 35000
savepoint id;
Savepoint created.
rollback to savepoint id
Rollback complete.
select * from emp;
EMPNUM EMPNAME DESIG DOJ SALARY 1003 barath operator 12-MAY-03 4000 1001 mathu designeng 12-SEP-07 30000 1002 raja manager 14-SEP-07 35000
Relatioonal Datab
Aim:
T
Create
create s
Sequen
Reffer
select o
select o
insert in
1 row c
EMPN100100
8
base Mana
To perform
e sequen
sequence o
nce created
rence seq
order_seq.n
order_seq.c
nto emp v
created.
NUM E01 mat02 raja har
agement Sy
m the auto
nce:
order_seq
d.
quence:
nextval fro
currval fro
alues(orde
EMPNAMEthu a ri
2.
ystem
increment
increment
om dual;
N
om dual;
C
er_seq.nex
E DEdesignemanageaccoun
2 Seq
t using Da
t by 1 star
NEXTVAL 1
CURRVAL 6
xtval,'hari',
ESIG eng er
ntant
quence C
ata object.
rt with 1 m
,'accounta
DOJ 12-SEP-14-SEP-02-MAY-
Creation
maxvalue 9
ant',sysdat
SA07 3007 35-09 4
n
9999 cycle
te,'4000')
ALARY 0000 5000 4000
e;
Relational Database Management System
Page 107
Altering a sequence:
alter sequence order_seq increment by 2 cache 30;
Sequence altered.
select order_seq.currval from dual;
CURRVAL 12
select order_seq.nextval from dual;
NEXTVAL 14
select order_seq.nextval from dual;
NEXTVAL 16
Dropping a sequence:
drop sequence order_seq
Sequence dropped.
select order_seq.currval from dual;
select order_seq.currval from dual
*
ERROR at line 1:
ORA-02289: sequence does not exist
3. View
Relational Database Management System
Page 108
Aim:
To view the record using the Data object.
create view emp_view as select * from emp
View created.
select * from emp_view;
EMPNUM EMPNAME DESIG DOJ SALARY 1001 mathu designeng 12-SEP-07 30000
1002 raja manager 14-SEP-07 35000
8 hari accountant 02-MAY-09 4000
View can be created with specific columns from the table:
create view emp_view1 as select empnum,desig,salary from emp;
View created.
select * from emp_view1
EMPNUM DESIG SALARY 1001 designeng 30000
1002 manager 35000
8 accountant 4000
A view based on two tables(join view)
select * from emp;
EMPNUM EMPNAME DESIG DOJ SALARY
1001 mathu designeng 12-SEP-07 30000
1002 raja manager 14-SEP-07 35000
8 hari accountant 02-MAY-09 4000
select * from empl;
Relational Database Management System
Page 109
EMPNUM NAME ADDR 1001 mathu tenkasi
1002 raja madurai
create view sal_view as select e.empnum,e1.name,e1.addr from emp e,empl e1
where e.empnum=e1.empnum;
View created.
select * from sal_view
EMPNUM NAME ADDR 1001 mathu tenkasi
1002 raja madurai
Information about view:
select view_name,text from user_views;
VIEW_NAME TEXT
EMP_VIEW select "EMPNUM","EMPNAME","DESIG","DOJ","SALARY"
from emp
EMP_VIEW1 select empnum,desig,salary from emp
SAL_VIEW select e.empnum,e1.name,e1.addr from emp e,empl e1
where e.empnum=e1.empnum
Deleting a view:
drop view sal_view;
View dropped.
select * from sal_view;
select * from sal_view
*
ERROR at line 1:
ORA-00942: table or view does not exist
4. Synonyms
Relational Database Management System
Page 110
Aim:
To Modify the Table name using data object.
Create synonym command:
create synonym e for emp;
Synonym created.
select * from emp;
EMPNUM EMPNAME DESIG DOJ SALARY
1001 mathu desigeng 12-SEP-09 34000
1002 raja manager 03-FEB-06 45000
select * from e;
EMPNUM EMPNAME DESIG DOJ SALARY
1001 mathu desigeng 12-SEP-09 34000
1002 raja manager 03-FEB-06 45000
Create synonyms for table of other users:
connect student/comp
Connected.
create synonym t for system.emp;
Synonym created.
select * from t;
EMPNUM EMPNAME DESIG DOJ SALARY
1001 mathu desigeng 12-SEP-09 34000
1002 raja manager 03-FEB-06 45000
Rename Synonyms:
Relational Database Management System
Page 111
rename e to m;
Table renamed.
select * from e;
select * from e
*
ERROR at line 1:
ORA-00942: table or view does not exist
select * from m;
EMPNUM EMPNAME DESIG DOJ SALARY
1001 mathu desigeng 12-SEP-09 34000
1002 raja manager 03-FEB-06 45000
Removing synonyms:
drop synonym m;
Synonym dropped.
select * from m;
select * from m
*
ERROR at line 1:
ORA-00942: table or view does not exist