Вы находитесь на странице: 1из 111

Relational Database Management System

M.S.P.V.L.POLYTECHNIC COLLEGE, PAVOORCHATRAM


Department of Computer Engineering / I nformation Technology
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.

Page1

Relational Database Management System

S.NO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 SQL Editor Command Column Commands Use Index on a Table SQL Function

PROGRAM

PAGE NO
5 11 17 19 26 35 39 44 48 52 56 60 64 68 71 76 81 84 88 95

Data Control Language Select Command in SQL *Plus Integrity Constraints Sub Queries Joins in Sql * Plus Logical Operator in SQL * PLUS Different Select Statements in SQL* Employee Details Using PL/SQL To Calculate EB Bill Using If Statement Built in Function using PL/SQL User Define Exception using PL/SQL Procedure & Function using PL/SQL Students Admission Using Trigger Employee Salary Detail Using Cursor DML Using ADO Creation Navigation object using ADO creation

EXTRA PROGRAMS
1 2 3 4 Transaction Control Language Sequence Creation View Synonyms 102 104 106 108

Page2

Relational Database Management System


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 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 sentences and pass them to the DBA for execution. These sentences allow the user to create, access and maintain data structures

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

Page3

Relational Database Management System


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.
Page4

Relational Database Management System


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:
Page5

Relational Database Management System

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.

Page6

Relational Database Management System

1. SQL Editor Command


Aim:
To Execute and test all the SQL Editor Commands.

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

Page7

Relational Database Management System Predefined commands:


Select user from dual; USER MAGESHWARI

describe tabs; Name TABLE_NAME TABLESPACE_NAME CLUSTER_NAME IOT_NAME PCT_FREE PCT_USED INI_TRANS MAX_TRANS INITIAL_EXTENT NEXT_EXTENT MIN_EXTENTS MAX_EXTENTS PCT_INCREASE FREELISTS FREELIST_GROUPS LOGGING BACKED_UP NUM_ROWS select table_name from tabs order by table_name; TABLE_NAME EMP STUDENT Null? NOT NULL Type VARCHAR2(30) VARCHAR2(30) VARCHAR2(30) VARCHAR2(30) NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER VARCHAR2(3) VARCHAR2(1) NUMBER

Page8

Relational Database Management System

You can use the describe command on the following views to obtain information on your account. View Name DICT DICT_COLUMN CAT OBJ TABS COLS USER_VIEWS SYN SEQ USER_CONSTRAINTS IND USER_IND_COLUMNS Description table names and table description column names of table names and column description names of all user's tables, views, synonyms, and sequences information on all objects in your account table information on all user's tables column information on all user's columns view information on all user's views synonyms information on all user's synonyms sequence information on all user's sequences constraint information on user's constraints index information on all user's indices column information on user's indices

USER_CONS_COLUMNS column information on user's constraints

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 REGNO NAME AGE DOB SEX ADDRESS Null? NUMBER(5) VARCHAR2(6) NUMBER(3) DATE VARCHAR2(5) VARCHAR2(9) Type

Page9

Relational Database Management System Add New Columns:


Alter table student add (phoneno number (8)); Table altered. desc student Name REGNO NAME AGE DOB SEX ADDRESS PHONENO Null? Type NUMBER(5) VARCHAR2(6) NUMBER(3) DATE VARCHAR2(5) VARCHAR2(9) 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.

Page10

Relational Database Management System View the Table:


select * from student; REGNO 101 102 103 104 105 NAME Mala Jeya viji mitha Mathu AGE 18 17 18 19 21 DOB 12-SEP-89 10-NOV-90 31-MAR-89 15-SEP-88 19-SEP-86 SEX F F F F M ADDRESS Tenkasi Madurai Tirunel chennai tenkasi PHONENO 257567 234557 565776 234567 234789

Modify the Table Value:


update student set phoneno=240902 where regno=101; 1 row updated. select * from student; REGNO 101 102 103 104 105 NAME Mala Jeya viji mitha Mathu AGE 18 17 18 19 21 DOB 12-SEP-89 10-NOV-90 31-MAR-89 15-SEP-88 19-SEP-86 SEX F F F F M ADDRESS Tenkasi Madurai Tirunel chennai tenkasi PHONENO 240902 234557 565776 234567 234789

Delete the Rows


delete from student where regno='102'; 1 row deleted. select * from student; REGNO 101 103 104 105 NAME Mala viji mitha Mathu AGE 18 18 19 21 DOB 12-SEP-89 31-MAR-89 15-SEP-88 19-SEP-86 SEX F F F M ADDRESS Tenkasi Tirunel chennai tenkasi PHONENO 240902 565776 234567 234789

Result:The query was executed successfully and output was verified.


Page11

Relational Database Management System


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.

Page12

Relational Database Management System

2. Column Commands
Aim:
To work the following conditions: a) Column formatting b) Alias and Column ordering

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

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 EMP_NO EMP_NAME DESIG DOJ SALARY HRA

Null? NUMBER VARCHAR2(8)

Type

VARCHAR2(12) DATE NUMBER(8) NUMBER(7)

Page13

Relational Datab Mana o base agement Sy ystem


Insert t the values s: insert in emp values('111 nto 11','Jeyant thi','Manag ger','12-sep p-08',2000 00,600); insert in emp values('111 nto 12','Seetha a','designin ngeng','25-mar-05',4 47000,1200); insert in emp values('111 nto 13','Glory','Lecturer', ,'17-Feb-08',17000,1 1000); insert in emp values('111 nto 13','Ratha','Teacher', ,'29-Jan-0 07',12000,7 700); insert in emp values('111 nto 14','Uma','s softwareen ng','26-Aug g-05',4700 00,1200) 1 row created. c 1 row created. c 1 row created. c 1 row created. c 1 row created. c

View t table the e:


select * from emp p EMP_N NO 1111 1 1112 2 1113 3 1113 3 1114 4 EMP P_NAME Je eyanthi Seetha S Glory G Ratha R Uma DESIG G Manage er Designing geng Lecture er Teache er Softwareeng DOJ D 12-SEP-08 25-M MAR-05 17-FEB-08 29-JAN-07 26-A AUG-05 SALARY 20000 47000 17000 12000 47000 HRA 600 1200 1000 700 1200

Colum Forma mn ating


a) To d display th salary f he field with dollar sig we can use the following gn, n g com mmand: column sal lary forma $9,99,99 at 99; m select * from emp

Relational Database Management System


EMP_NO EMP_NAME DESIG Manager designingeng Lecturer Teacher softwareeng DOJ 12-SEP-08 25-MAR-05 17-FEB-08 29-JAN-07 26-AUG-05 SALARY $20,000 $47,000 $17,000 $12,000 $47,000 HRA 600 1200 1000 700 1200 1111 Jeyanthi 1112 Seetha 1113 Glory 1113 Ratha 1114 Uma

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 Mana ger desi gnin geng Lect urer Teac her soft ware eng DOJ 12-SEP-08 25-MAR-05 17-FEB-08 29-JAN-07 26-AUG-05 SALARY $20,000 $47,000 $17,000 $12,000 $47,000 HRA 600 1200 1000 700 1200

1111 Jeyanthi 1112 Seetha 1113 Glory 1113 Ratha 1114 Uma

c) To display the number in scientific notation, use EEEE format column hra format 9.9999EEEE; select * from emp EMP_NO EMP_ DESI Mana ger desi gnin geng Lect urer Teac her soft ware eng DOJ 12-SEP-08 25-MAR-05 17-FEB-08 29-JAN-07 26-AUG-05 SALARY $20,000 $47,000 $17,000 $12,000 $47,000 HRA 6.0000E+02 1.2000E+03 1.0000E+03 7.0000E+02 1.2000E+03

1111 Jeya nthi 1112 Seet ha 1113 Glor y 1113 Rath a 1114 Uma

Page15

Relational Database Management System


d) Create column headings column emp_name heading EmployeeName column emp_no heading EmployeeNumber column desig heading Designation select * from emp; EmployeeNumber EmployeeName Designation 1111 1112 1113 1113 1114 Jeyanthi Seetha Glory Ratha Uma Manager DOJ 12-SEP-08 SALARY HRA 20000 47000 17000 12000 47000 600 1200 1000 700 1200

designingeng 25-MAR-05 Lecturer Teacher softwareeng 17-FEB-08 29-JAN-07 26-AUG-05

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 1111 1112 1113 1113 1114 EMP_NAME Jeyanthi Seetha Glory Ratha Uma Designation Manager DOJ 12-SEP-08 SALARY HRA 20000 47000 17000 12000 47000 600 1200 1000 700 1200

designingeng 25-MAR-05 Lecturer Teacher softwareeng 17-FEB-08 29-JAN-07 26-AUG-05

Page16

Relational Database Management System 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 1113 1111 1113 1112 1114 EMP_NAME Glory Jeyanthi Ratha Seetha Uma

Result:The query was executed successfully and output was verified.

Page17

Relational Database Management System


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

Alter

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.

Page18

Relational Database Management System

3. Use Index on a Table


Aim:
Use indexing on a table simple and composite indexes.

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

Simple Index:
create index empno_index on emp(emp_no) Index created. select index_name,table_name from user_indexes; INDEX_NAME EMPNO_INDEX TABLE_NAME 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 EMP_INDEX EMPNO_INDEX

INDEX_TYPE NORMAL NORMAL


Page19

TABLE_NAME EMP EMP

Relatio Datab Mana onal base agement Sy ystem


Droppi Index: ing :
drop index empno_index; select in ndex_nam me,index_ty ype,table_n name from user_ind m dexes; Index d dropped. IND DEX_NAM ME EMP_INDEX X INDEX_ _TYPE NORM MAL TAB BLE_NAME E EMP

Resul lt:The query w execu T was uted successfully and output w verifie d was ed.

Viva Que estions:


1. What is simple an compos 1 s nd site index? ? An index is an ordered list of a column o group o column in a table An i a d or of e. index created on a single column of a tab is called simple index. W c n e ble e When multiple table col lumns are included in the ind it is ca e dex alled compo osite index x.

2. How to drop an in 2 ndex? When you no longer nee an inde you ca drop it using the DROP IN n ed ex, an e NDEX comma and. When the index is dropp n x ped, oracle removes any refere e ence to it from the data dictionary and frees any dis space used by the index. a sk u e

Relational Database Management System

4. SQL Function
Aim:
To Work with the different categories of functions such as Math, Date, Aggregate and Conversion functions.

Syntax:
Math Numeric Function:
ABS(n); CEIL(n): COS(n); COSH(n); EXP(n);

Date Function
ADD_MONTH(date,month); LASY_DAY(date); MONTHS_BETWEEN(date1,date2); NEXT_DAY(date,day_name); ROUND(date,[format]);

Aggregate Function:
AVG(n); COUNT(n); MAX(n); MIN(n); STDDEV(n); VARIANCE(n);

Conversion functions:
TO_CHAR(date[,format]); TO_DATE(date[,format]); TO_NUMBER(date[,format]);

Math Function:
SELECT ABS(10), ABS(-10) FROM dual; ABS(10) 10 ABS(-10) 10

Page21

Relational Database Management System


SELECT CEIL(5.8), CEIL(-5.2) FROM dual; CEIL(5.8) 6 CEIL(-5.2) -5

select cos(45) from dual; COS(45) .525321989

select cosh(0) from dual; COSH(0) 1

select exp(5) from dual; EXP(5) 148.413159

Date Function:
ADD_MONTH: select * from student; REGNO 101 103 104 105 NAME Mala viji mitha Mathu AGE 18 18 19 21 DOB 12-SEP-89 31-MAR-89 15-SEP-88 19-SEP-86 SEX F F F M ADDRESS Tenkasi Tirunel chennai tenkasi PHONENO 240902 565776 234567 234789

select dob,add_months(dob,60) from student; DOB 12-SEP-89 31-MAR-89 15-SEP-88 19-SEP-86 ADD_MONTHS(DOB,60) 12-SEP-94 31-MAR-94 15-SEP-93 19-SEP-91

Page22

Relational Database Management System


LAST DAY: select name,dob,last_day(dob) from student; NAME Mala viji mitha Mathu Months_BETWEEN: create table staff(name varchar2(10),dob date,doj date); Table created. select * from staff; NAME Malar Mageshwari Gowsic Santhiya DOB 10-MAY-85 15-SEP-84 07-JUN-08 09-OCT-07 DOJ 26-MAY-08 06-JUL-06 07-JUN-09 09-AUG-09 DOB 12-SEP-89 31-MAR-89 15-SEP-88 19-SEP-86 LAST_DAY(DOB) 30-SEP-89 31-MAR-89 30-SEP-88 30-SEP-86

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

Page23

Relational Database Management System


Round select name,round(dob,'year')from student where regno=105 NAME Mathu ROUND(DOB,'YEAR') 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

Page24

Relational Database Management System


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 Mala viji mitha Mathu TO_CHAR(DOB,'DAY-MONTH-YEAR') tuesday -september-nineteen eighty-nine friday -march -nineteen eighty-nine thursday -september-nineteen eighty-eight 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 computer printer UPS AC computer STOCK 100 50 75 10 10 COST 25000 1500 2000 30000 25000

Page25

Relational Database Management System


select item_name,to_char(stock*cost,'9,99,999.99') from stoc; ITEM_NAME computer printer UPS AC computer TO_CHAR(STOCK*COST,'9,99,999.99') ############ 75,000.00 1,50,000.00 3,00,000.00 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-MONYYYY'),200); 1 row created. insert into purchase_master values(1,'JTrade', to_date('01-January-2000','DDMON-YYYY'),200); 1 row created. NUM 1 1 To_number: select * from stoc; ITEM_NAME computer printer UPS AC computer

TRADE_NAME JKTrade JTrade

DATE_OF_PURCHASE 01-JAN-00 01-JAN-00

NO_OF_ITEM 200 200

STOCK 100 50 75 10 10

COST 25000 1500 2000 30000 25000

Page26

Relational Database Management System


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.

Page27 5. Data Control Language

Relational Database Management System

Aim:
a) b) c) d) Create a table to show the salary details of the employees. Grant select and update privileges on above table to other users Grant all the privileges to some other users. Revoke all the above granted permissions.

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;

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;

Page28

Relational Database Management System


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-jun06',20000) 1 row created. insert into employee values('PRABHU',1112,'COLLECTO','12-FEB-78','12-DEC08',50000) 1 row created.

View the table:


select * from employee; NAME RAJA RAMA PRABHU ID_NO JOB DOB 12-JUN-86 12-MAY-80 12-FEB-78 DOJ 12-JUN-08 12-JUN-06 12-DEC-08 SALARY 20000 20000 50000

1110 lecturer 1111 LAWYER 1112 COLLECTO

Page29

Relational Database Management System


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:


Page30

Relational Datab Mana o base agement Sy ystem


select * from emp p_sal NAME E Raja a Rama a Prabh hu TA A 500 0 750 0 100 00 HRA 750 0 100 00 120 00 DA A 366 6 500 0 150 00 BF F 780 0 120 00 170 00 N NETSALAR RY 8000 10000 20000

Grant select an updat privili nd te iges:


grant se elect,upda on emp ate p_sal to ma athu; Grant s succeeded.

Check the sele permi k ect ission:


connect mathu/m t mitha Connec cted. select * from sant thya.emp_ _sal; NAM ME Raja Ram ma Prabhu TA T 500 750 10 000 HR RA 75 50 10 000 12 200 D DA 36 66 50 00 15 500 BF B 78 80 1200 1700 NETSALA ARY 8000 10000 20000

Check the upd k date perm mission:


update santhya.e emp_sal se netsalar et ry=12000 where nam w me='Raja' 1 row updated. u select * from sant thya.emp_ _sal; NAM ME Raja Ram ma Prabhu TA T 500 5 750 7 10 000 HRA 750 10 000 12 200 D DA 36 66 50 00 15 500 BF B 78 80 12 200 17 700 NETSALA ARY 12000 0 10000 0 20000 0

k ommand d: Check other co

Relational Datab Mana o base agement Sy ystem


delete f from santh hya.emp_sal * ERROR at line 1: R ORA-01 1031: insu ufficient pr rivileges

c. Gran all the p nt privileges to some other use s ers: connect mathu/m t mitha Connec cted select * from emp ployee NA AME RAJA RAMA PRABHU ID_NO I JOB DOB D DOJ SA ALARY 20000 20000 50000

1110 lec cturer 1111 LA AWYER

12-JUN-86 12-JU UN-08 12-MAY-80 12-JU UN-06 12-DE EC-08

1112 CO OLLECTO 12-FEB-78

oyee to san nthya grant all on emplo Grant su ucceeded. connect santhya/silviya t Connect ted. select * from math hu.employ yee

NAME E RAMA A RAJA A PRABH HU

ID_NO O 1111 1110 1112

JOB LAWYE ER lecture er

DO OB

DOJ

SALARY 20000 20000 50000

12-M MAY-80 12 2-JUN-06 12-JU UN-86 12 2-JUN-08

COLLEC CTO 12-FE EB-78 12 2-DEC-08

Insert in mathu nto u.employee values('S e Selva','1114','doctor','19-jun-81','20-mayy 06',400 000)

Relational Datab Mana o base agement Sy ystem


1 row created. c NAME E RAMA A RAJA A PRABH HU Selva a ID_NO 1111 1 1110 0 1112 2 1114 4 JO OB LAW WYER lectu urer COLL LECTO doc ctor DOB 12-MAY-80 1 0 1 12-JUN-86 6 1 12-FEB-78 8 1 19-JUN-81 1 DO OJ 12-JU UN-06 12-JU UN-08 12-DE EC-08 20-MA AY-06 SA ALARY 20000 2 20000 2 50000 5 40000 4

Delete f from math hu.employe where i ee id_no=1110 1 row deleted. d NAME E RAMA A PRABH HU Selva a ID_NO O 1111 1 1112 2 1114 4 JO OB LAW WYER COLLECTO doc ctor DOB 12-MAY-80 1 0 12-FEB-78 1 8 1 19-JUN-81 1 DO OJ 12-JU UN-06 12-DE EC-08 20-MA AY-06 SA ALARY 20000 2 50000 5 40000 4

update mathu.em mployee se dob='14et -feb-84' wh here id_no o=1114 1 row updated. u NAME E RAMA PRABHU Selva ID_N NO JO OB DOB 12 2-MAY-80 12 2-FEB-78 14 4-FEB-84 DO OJ 12-JUN N-06 12-DEC C-08 20-MAY Y-06 SA ALARY 20000 50000 40000

1111 LAWYE ER 1112 COLLE ECTO 1114 doctor

d. Revo oke all the above granted pe e ermissions s: Revoke select,upd date on em mp_sal from mathu m Revoke succeeded d. connect mathu/m t mitha Connec cted.

select * from sant thya.emp_ _sal *

Relatio Datab Mana onal base agement Sy ystem


ERROR at line 1: R ORA-00 0942: table or view d e does not ex xist update santhya.e emp_sal se netsalar et ry=1000 w where name='Raja' * ERROR at line 1: R ORA-00 0942: table or view d e does not ex xist Revoke all on employee from santhya m a Revoke succeeded d. connect santhya/ t /silviya Connec cted. select * from mat thu.employ yee * ERROR at line 1: R ORA-00 0942: table or view d e does not ex xist.

Resul lt:The query w execu T was uted successfully and output w verifie d was ed.

Viva Que estions:


1. How to u data c use control lan nguage statements? Data base access is controlle by the d D e s ed data contr langua rol age. Once a login account is created for a us that u d ser user can be given pr b rivileges o the dat on tabase. Privilege are give using the GRAN stateme es en NT ent and a taken away usin the are ng REVOKE statemen E nt. 2. What is User? User is any perso or grou of peop with so on up ple ome rights to acces the dat ss tabase. The Ora acle system comes w m with two u users alrea ady create SYSTEM and SY The ed, M YS. passwor for the SYS user is alway change rd r ys e_on_insta all and th passwo he ord for SYSTEM user is m M manager. . 3. How to c 3 create a USER comm mand?

Relational Database Management System

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 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: ii. Object privileges

Privilege

Description
Enables a user to connect to the database instance. After creating a user, you need to grant the CREATE SESSION

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 CREATE VIEW CREATE SYNONYM

Enables a user to create a table in his or her schema. Enables a user to create a view in his or her schema. Enables a user to create a private synonym in his or her schema. Enables a user to create another user in the database and specify the password and other settings at creation time.

CREATE USER

6. What is object privilege?


Page35

Relational Database Management System


perform an action on an object, such as execute a stored procedure. Unlike system privileges, the owner of the object must grant object privileges.

Object privileges enable a user to manipulate data in the database or

Privilege
SELECT INSER UPDATE DELETE ALTER INDEX REFERENCES EXECUTE

Granted On
Table, View, Sequence Table, View Table, View Table, View Table, Sequence Table Table Procedure, function, package

6. Select Command in SQL *Plus Page36

Relational Database Management System

Aim:
a) Create a table student_master with the following fields name, Regno, dept and year with suitable data types. Use select command to do the following. b) Select the students name column. c) Display the unique rows. d) Sort the table in alphabetical order. e) Select all the students of a particular department.

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

a) Create a table student_master with the following fields 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.


Page37

Relational Database Management System


insert into student_master values(125,'Kala','Computer',2003); 1 row created. select * from student_master; REGNO 123 124 125 NAME Dhivya Muthu Kala DEPT Physics Maths Computer YEAR 1998 2000 2003

b) Select the students 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 123 124 125 124 NAME Dhivya Muthu Kala fdgdf DEPT Physics Maths Computer sgf YEAR 1998 2000 2003 1998

select distinct regno from student_master;

Page38

Relational Database Management System


REGNO 123 124 125

d) Sort the table in alphabetical order. select * from student_master order by name; REGNO 123 125 124 124 NAME Dhivya Kala Muthu fdgdf DEPT Physics Computer Maths sgf YEAR 1998 2003 2000 1998

e) Select all the students of a particular department. select * from student_master where dept='Computer'; REGNO 123 125 124 124 NAME Dhivya Kala Muthu fdgdf DEPT Physics Computer Maths sgf YEAR 1998 2003 2000 1998

Result:The query was executed successfully and output was verified.

Viva Questions:
Page39

Relational Database Management System


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 L ALL * Table View WHERE It means that only rows that are unique will be returned; any duplicates will be weeded out first. 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. It means that all columns from this table will be displayed. Select all the columns of the specified view. Filters the rows that will be displayed by the query. Without this clause, all the rows are displayed.

7. Integrity Constraints
Page40

Relational Database Management System 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

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

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

Page41

Relational Database Management System


Name S_ORDER_NO PRODUCT_NO CLIENT_NO DELY_ADDR DELY_DATE ORDER_STATUS Null? NOT NULL NOT NULL Type VARCHAR2(6) VARCHAR2(6) VARCHAR2(6) VARCHAR2(25) DATE 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 S_ORDER_NO PRODUCT_NO CLIENT_NO DELY_ADDR DELY_DATE ORDER_STATUS SALES_MAN_NO Null? NOT NULL NOT NULL Type VARCHAR2(6) VARCHAR2(6) VARCHAR2(6) VARCHAR2(25) DATE VARCHAR2(10) NUMBER(5)

c) set the s_order_no as foreign key as column constraint select * from sales_order_det; S_ORDER_ NO 11 12 13 14 15 PNO 343 345 346 347 348 DESCRI QTY_ PTION ORD Arial shear Oil colgate Pears 10 34 56 45 35 QTY_DISP P_RATE 4 4 12 56 65 45 56 45 67 32 PROFIT_ SELL_ PER PRICE 67 76 20 15 13 12 50 18 24 14

alter table sales_orders add constraint sal_f_key foreign key(s_ord_no)references sales_order_det;


Page42

Relational Datab Mana o base agement Sy ystem


insert in sales_ nto _orders val lues('11','2 23','0001','Tenkasi','1 12-may09','Ful lfilled','111 11'); 1 row created. c insert in sales_ nto _orders val lues('101','23','0001' ','Tenkasi', ,'12-may09','Ful lfilled','111 11') * ERROR at line 1: R ORA-02 2291: integ grity const traint (MA AGESH.SAL_F_KEY) violated - parent ke not ey found insert in sales_ nto _orders val lues('11','2 23','0001','Tenkasi','1 12-may09','Ful lfilled','111 11'); D) Set the s_order_no fore t eign key a table constraint as t First dr rop the tab sales_o ble orders usin drop ta ng able statem ment.

Table creation n:
create t table sal_d d(s_order_n numbe no er(4) prima key,pro ary oduct varc char2(5),st tock number r(5)); Table cr reated. select * from sal_ _d; S_ORDE ER_NO 102 2 104 4 101 1 103 3 105 5 PRODU UCT UPS CPU COMP PU PRIN N KEYB B STOC CK 15 5 123 10 0 134 109

Table creation n:
create t table sales s_order1(s_ _order_no number(4 4),product_ _no varcha ar(5),clien nt_no number r(5),del_ad varcha ddr ar(8),dely_d date date,o ord_status varchar(8 s 8),primary y key(s_order_no,pr roduct_no o),foreign k key(s_order_no) refer rences sal_ _d); Table cr reated.

insert in sales_ nto _order1 val lues('101','34','1110','Chennai i','19-jan-0 09','Fulfiled d')

Relational Database Management System


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?

Page44

Relational Database Management System


identified by a unique value. 4. What is referential integrity?

The primary key value rule specifies that each row of a table must be

The referential integrity rule determines that the value or group of fields corresponds to the key fields of other tables

Reference
Restrict Set to NULL Set to default Cascade

Description
Disables the updating are deletion of the specified data. when specified data is updated or deleted, all the associated data is adjusted to NULL when specified data is updated or deleted, all the dependent data is adjusted to the default value 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 Page45

Relational Database Management System

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 students 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.

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

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


Page46

Relational Database Management System


1 row created. insert into student values(127,'Raju',23,'BCA','VB'); 1 row created. select * from student; ROLLNO 123 124 125 126 127 NAME Mitha Malar Santhiya Ram Raju AGE 25 24 21 20 23 DEGREE MSC MCA ME BE BCA SUBJECT Java .Net CG VC++ 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',&times_handled);

select * from staff;


Page47

Relational Database Management System


STAFF_ID 346 347 345 STAFF_NAME jeyam Prabha Jeya SUBJECT_NAME VC++ CG Java TIMES_HANDLED 4 2 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||'TIME S.' Jeyam Prabha Jeya handled handled handled VC++ CG Java 4 2 3 times. times. times.

d) Use sub queries to display the information about students 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 Ram Santhiya Mitha STAFF_NAME jeyam Prabha 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 346 347 345 348 STAFF_NAME jeyam Prabha Jeya Ravi SUBJECT_NAME VC++ CG java java TIMES_HANDLED 4 2 3 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;


Page48

Relational Database Management System


SUBJECT_NAME java java STAFF_NAME Jeya 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. ii. iii. iv. v. To insert records in the target table To create tables and insert records in this table To update records in the target table To create views 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.

Page49 9. Joins in Sql * Plus

Relational Database Management System


:

Aim:
a) b) c) d) Create a sales_order table and client_master table with suitable fields. Find the total number of quantity ordered for a particular product. Display the rows of the table in the sales order date wise. 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.

Syntax:
Join:
SELECT column1,column2,..FROM <table1>,<table2> where <logical expression>;

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


Page50

Relational Database Management System


1 row created. select * from sales_order; S_ORD_NO PROD_NO PROD_NAME QTY CLI_NO S_MAN_NO 122 232 343 434 90 Rin 78 Colgate 23 Oil 90 Flour 34 35 34 45 1222 343 232 454

S_DATE

123 11-APR-04 343 22-MAR-98 4354 10-MAY-03 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 23 45 67 Raj Gowsic C_NAME Mitha CLI_ORDER_NO 122 1343 769 ADDR Nellai Ten 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.
Page51

Relational Datab Mana o base agement Sy ystem


select * from sale es_order or rder by s_d date; S_ORD_NO PROD_NO PRO OD_NAME QTY CL E LI_NO S_M MAN_NO 232 434 343 122 78 Col lgate 90 Flou ur 23 Oil 90 Rin n 35 45 34 34 343 454 232 1222 S_DAT TE

343 22-MAR-98 8 23 09-JAN-01 4354 10-MAY-03 3 123 11-APR-04

d) Join the two ta t ables and display the produc number,product name wh ct t here the or rderno in the sales s_order table and orderno in client_m master are equal. select p prod_no,pr rod_name,cli_order_ _no,s_ord_n from sa no ales_order ss, r client_m master_det cc where ss.s_ord_ t e _no=cc.cli_ _order_no; PROD D_NO PROD_NA AME CLI_ORD DER_NO 122 S_OR RD_NO 122

90 Ri in

e) Join the sales_ t _order tab to itself and dis ble splay the o order num mber,clien nt numb and sa ber alesman n number wh here clien has bee services by more than nt en e one sa alesman. select d distinct a.s s_ord_no,a a.s_man_n from sal no les_order a a,sales_ord b where der a.cli_no o=b.cli_no and a.s_m man_no<>b b.s_man_n no; no rows selected s insert in sales_ nto _order valu ues(456,08 89,'Pons',4 45,1222,67 78,'11-feb-04');
1 row cre eated.

S_ORD_ _NO PROD D_NO PRO OD_NAME QTY CLI_ _NO S_MA AN_NO 122 232 343 434 456 90 Rin 78 Colga ate 23 Oil 90 Flour r 89 Pons 34 35 34 45 45 1222 1 343 232 454 1222 1

S_ _DATE

123 11-A APR-04 343 22-M MAR-98 4354 10-M MAY-03 23 09-J JAN-01 678 11-F FEB-04

distinct a.s s_ord_no,a a.s_man_n from sal no les_order a a,sales_ord b where der select d a.cli_no o=b.cli_no and a.s_m man_no<>b b.s_man_n no;

Relational Database Management System


S_ORD_NO 122 456 S_MAN_NO 123 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. ii. Equi- join 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


Page53

Relational Database Management System

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.

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

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


Page54

Relational Database Management System


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 11 12 13 PNO 343 345 346 DESCRI QTY_ QTY_ PTIO Arial Rin Oil ORD 10 34 56 DISP 4 4 12 P_RATE 45 56 45 PROFIT_ SELL_ PER 67 76 20 PRICE 12 50 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 6 25 9 SELL_PRICE*1.5 18 75 27

select * from sales_order_det; S_ORDER _NO 11 12 13 14 15 PNO DESCRIPTIO QTY_ QTY_ ORD 10 34 56 45 35 DISP 4 4 12 56 65 P_RATE 45 56 45 67 32 PROFIT SELL_PRIC _PER 67 76 20 15 13 E 12 50 18 24 14

343 Arial 345 Rin 346 Oil 347 colgate 348 Pears

b) Select product_no,profit_percent, sell_price where profit_per is not between 10 and 20 both includive.
Page55

Relational Database Management System

select pno,profit_per,sell_price from sales_order_det where profit_per <=10 or profit_per>=20; PNO 343 345 346 PROFIT_PER 67 76 20 SELL_PRICE 12 50 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 343 345 347 348 PROFIT_PER 67 76 15 13 DESCRIPTIO Arial Rin colgate Pears SELL_PRICE 12 50 24 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 Arial shear PNO 343 345

Result: Page56

Relational Database Management System


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*


Page57

Relational Database Management System 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.

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

a) Create a table client_master with the following fields client_no, name, address1, address2, city, state, pincode, remarks, bal_due with suitable
Page58

Relational Database Management System

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 101 102 CITY STATE REMARKS BAL_DUE TN TN Good Bad 1900 1000

Mathu 2nd st 2nd st Tenkasi Madan 3rd st 3rd st Tenkasi

c) Insert data into supplier_master from client_master.


Page59

Relational Database Management System

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 101 102 Mathu Madan CITY STATE REMARKS TN TN Good Bad

2nd st 2nd st Tenkasi 3rd st 3rd st Tenkasi

d) Delete the selected row in the client_master. Before Deletion: select * from client_master; CLIENT_NO NAME ADDR1 ADDR2 101 102 Madan 3rd st CITY STATE REMARKS TN TN Good Bad BAL_DUE 1900 1000

Mathu 2nd st 2nd st Tenkasi 3rd st Tenkasi

After Deletion: delete from client_master where name='Madan'; 1 row deleted. select * from client_master; CLIENT_NO NAME ADDR1 ADDR2 101 CITY STATE REMARKS TN Good BAL_DUE 1900

Mathu 2nd st 2nd st Tenkasi

Result:The query was executed successfully and output was verified.

Viva Questions:
Page60

Relational Database Management System


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


Page61

Relational Database Management System

Aim:
Create a PL/SQL code to display the employee details for an employee.

Syntax:
PL/SQL Block Structure:
[DECLARE Variable declarations] BEGIN Executable statements [EXCEPTION Exception handlers] END;

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 Ravi sankar Hari

EMP_ID 101 102 103

BP 3000 10000 5000

HRA 100 200 150

DA 75 400 200

PF 500 1000 500

Page62

Relational Database Management System


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 || ' Gross Pay :' || gp || ' Net Pay:' ||np ); end loop; end; Emp_id : ' || x || '

Page63

Relational Database Management System


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_Name: sankar Emp_Name: Hari Emp_id : 101 Emp_id : 102 Emp_id : 103 Gross Pay :3175 Gross Pay :10600 Gross Pay :5350

Net Pay:2675 Net Pay:9600 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?


Page64

Relational Database Management System


blocks such as: a) Declare b) Begin c) Exception 4. What is a comment statement?

The PL/SQL is a program which can be written in a file. It contains three

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 Page65

Relational Database Management System

Aim:
To write a PL/SQL code to calculate EB bill for the given units using if statement.

Syntax:
If Statement:
IF condition THEN S1 S2 . . . . END IF; S1,S2 Statements Condition Boolean Expression

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.

Page66

Relational Database Management System

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 Sudan Jana Kishore Arun Kumaran E_ID 1001 1002 1003 1004 1005 PRE_READING 103 500 430 340 750 CURR_READING 250 750 690 400 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;

Page67

Relational Database Management System


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 || ' || units || ' Amount : ' || amount); end loop; end; ID : ' || x || '

Units : '

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 Name Name Name Name : : : : : Sudan Jana Kishore Arun Kumaran ID ID ID ID ID : : : : : 1001 1002 1003 1004 1005 Units Units Units Units Units : : : : : 147 250 260 60 300 Amount Amount Amount Amount Amount : : : : : 441 1000 1040 1040 1200

PL/SQL procedure successfully completed.

Result:The query was executed successfully and output was verified.

Page68

Relational Database Management System


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

Page69

Relational Database Management System

14. Built in Function using PL/SQL


AIM:
To write a PL/SQL block to handle built-in exception like NO_DATA_FOUND, TOO_MANY_ROWS.

Syntax:
Exception Handlers:
WHEN <exception name> [OR <exception name>] then <Sequence of statements>

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', '&degree', '&batch'); select * from alumni; NAME Babu Christy Malar Mitha Jency ADDRESS PCM Surandai Ppy Pv govai DEGREE BE MCA MCA Mphil BE BATCH 2002 2000 2005 2003 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);
Page70

Relational Database Management System


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.


Page71

Relational Database Management System


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
No_data_found Too_many_rows Zero_divide Program error

Raised if
Select statement returns no rows (records). Select into statement returns more than one row. Try to divide a number by zero. PL/SQL has an internal problem. Conversion of a character string to a

Invalid_number

number fails. (e.g. to_number(234A4);234A4 does not represent a valid number)

Page72

Relational Database Management System

15. User Define Exception using PL/SQL


Aim:
To write a PL/SQL code to handle user defined exception.

Syntax:
User-define Exception:
RAISE exception name;

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

Relational Database Management System


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

Relational Database Management System


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. 2. 3. 4. Addition Subtraction Multiplication 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.

Page75

Relational Database Management System


2. 1. 2. 3. 4. Addition Subtraction Multiplication 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. 2. 3. 4.

Addition Subtraction Multiplication 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.

Page76

Relational Database Management System


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.

Page77

Relational Database Management System

16. Procedure & Function using PL/SQL


Aim:
To write a PL/SQL block to use procedure and function and get the result.

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

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
Page78

Relational Database Management System


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

Page79

Relational Datab Mana o base agement Sy ystem


b) To us Functio and get the resu se on t ult create t table phon ne(ph_no n number(7), ,username varchar(10),doorno e o number r(5),place v varchar(10 0),pincode number(6 e 6)); Table cr reated. insert in phone values(23 nto e 32324,'Ram man',234,'Nellai',654553); 1 row created. c insert in phone values(56 nto e 65656,'Gan nesh',34,'T Tenkasi',6 627811); 1 row created. c insert in phone values(43 nto e 35434,'Mu urugan',67 76,'Madura ai',343434 4); 1 row created. c select * from phon ne; PH_N NO 23232 24 56565 56 43543 34 US SERNAME E Raman Ganesh Murugan M DOORNO 2 234 34 6 676 PLACE Nellai Tenkasi i Madurai i PINC CODE 654 4553 627 7811 343 3434

create o replace function f or findaddres ss(phno in number) return var n rchar2 as addr varchar r2(50); begin select u username||','||door rno||','||p place||','||pincode into addr from phon ne where ph_no=p phno; return a addr; exceptio on when no_data_found then retu ' Addre Not Fo w d urn ess ound'; end; Functio created. on

Relational Database Management System


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.

Page81

Relational Database Management System


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

Page82

Relational Database Management System

17. Students Admission Using Trigger


Aim:
Create a PL/SQL trigger to update the records while deleting the one record in another table.

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

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 Raju Viji APP_NO JOIN_YEAR DOB 02-MAR-87 12-APR-88 QUALIFICATION +2 10

501 26-MAY-06 502 26-MAY-06

create table student_detail(name varchar2(10),app_no number(10), join_year date,primary key(app_no)); Table created. desc student_detail; Name NAME APP_NO JOIN_YEAR
Page83

Null? NOT NULL

Type VARCHAR2(10) NUMBER(10) DATE

Relational Database Management System


select * from student_detail; NAME Kavi Vijay Reegan Raju viji APP_NO JOIN_YEAR 555 02-JUN-08 556 01-JUN-09 557 05-JUN-98 501 02-MAR-87 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 Kavi Vijay Reegan Anu viji select * from student; NAME Viji APP_NO JOIN_YEAR DOB 12-APR-88 QUALIFICATION 10 APP_NO JOIN_YEAR 555 02-JUN-08 556 01-JUN-09 557 05-JUN-98 501 02-MAR-87 502 26-MAY-06

502 26-MAY-06

Page84

Relational Database Management System

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.
Page85

Relational Database Management System

18. Employee Salary Detail Using Cursor


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.

Syntax:
Open:
OPEN <cursor_name>;

Fetch:
FETCH cursor_name INTO column_name;

Close:
CLOSE cursor_name;

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.

Page86

Relational Database Management System


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 ---------122 34 111

NAME -------Sam Aravind Ravi

NET SALARY --------------6220 220100 19950

PL/SQL procedure successfully completed.

declare no number(5):=34; basic number(5); da cur_sal.da%type; med cur_sal.ma%type;


Page87

Relational Database Management System


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 122 34 111 NAME Sam Ravi DESIG Lecturer DEPART CE BP 5000 8000 DA MA ALLOW DED 20 120 20 222 400 600 300 300 250 500

Aravind Engineer EEE Designer IT

10000 100 150

Result:The query was executed successfully and output was verified.

Page88

Relational Database Management System


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.

Page89

Relational Database Management System

19. DML Using ADO Creation


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 number(3),total varchar2(8),subject1 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

number(1),subject2

number(3),subject3

number(4),avg number(4));

-------- -------1002 1001 Hari Mathu

-----------EEE Mech

-----------40 100

------------ -----------45 99 50 99

-------- ----135 298 45 99

SQL> commit; Commit complete.

Page90

Relational Database Management System 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

Page91

Relational Database Management System


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()
Page92

Relational Database Management System


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
Page93

Relational Database Management System


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

Page94

Relational Database Management System

output:

Database output:
SQL> select * from stud;
REGNO NAME DEPARTME SUBJECT1 SUBJECT2 SUBJECT3 TOTAL AVG

-------1002 1003 1001

------Hari Silviya Mathu

-----------EEE IT Mech

------------ -----------40 89 100 45 90 99

-----------50 99 99

------135 278 298

---45 93 99

Result:The above program was successfully and the output was verified.

Page95

Relational Database Management System


Viva Questions:
1. DATA NAMESPACE: SYSTEMDATA:

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. Dataobject: Allow to store a local disconnected copy of data, they dont store a connection to a data store. Dataset: Dataset class and disconnect information drawn by direct connection and allows you to manipulate the datas. The data is a class no direct connection to a data source. Datatable: Add information in to a dataset in one table at a time data table object represent one of this table. Datarow: It represents a single row of information into the table. Datacolumn: Data column object not contain any actual data.

20. NavigationPage96 using ADO creation object

Relational Database Management System

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','chr@gmail.com','9894677898'); 1 row created. SQL> insert into biodata values('Jency','FEMALE','unMarried','BE','94','Lecturer','2years','TIRUNELV ELI','jeya@gmail.com','9987543784'); 1 row created.

Page97

Relational Database Management System


SQL> insert into biodata ','malar@gmail.com','9876540902'); 1 row created. SQL> insert into biodata values('kanaga','FEMALE','Married','MCA','87','Lecturer','3years','CHENNAI' ,'kan@gmail.com','9890456778'); 1 row created. SQL> select * from biodata;
NAME SEX STATUS QUALIFICA PERCENTAGE DESIGNATION EXPRIE ADDRESS EMAIL_ID

values('Malar','FEMALE','unMarried','MCA','99','Lecturer','1years','CHENNAI

PHONENO

---Magesh Christy Jency Malar kanaga

--FEMALE FEMALE FEMALE FEMALE FEMALE

-----Married Married

-------- ----------- ------------ -----Msc.MPhil MCA 89 92 94 99 87 Lecturer Lecturer Lecturer Lecturer Lecturer 3years 3years 2years 1years 3years

-------Tenkasi SURANDAI TIRUNELVELI CHENNAI CHENNAI

------www.gmail.com chr@gmail.com jeya@gmail.com

-------9790894132 9894677898 9987543784

unMarried BE unMarried MCA Married MCA

malar@gmail.com 9876540902 kan@gmail.com 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

Page98

Relational Database Management System


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
Page99

Relational Database Management System


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

Page100

Relational Database Management System


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.

Page101

Relational Database Management System


Viva Questions:
OracleConnection:

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 ExecuteNonQuery: It allows you to execute the command without retrieving any information. This is ideal for add , update, delete operation using SQL statement. ExecuteReader: Create or Reader connection which provides a fast forward connection only that allows you to retrieved rows from the data source. ExecuteScalerL: 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.

Page102

Relational Database Management System

Extra Programs

Page103 1. Transaction Control Language

Relational Database Management System

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 1001 1002 EMPNAME mathu raja DESIG designeng manager DOJ 12-SEP-07 14-SEP-07 SALARY 30000 35000

A.COMMIT:
Commit Commit complete. insert into emp values('1003','Vishal','operator','12-feb-03','4000') 1 row created.

Page104

Relational Database Management System


select * from emp; EMPNUM 1001 1002 1003 Rollback Rollback complete. select * from emp; EMPNUM 1001 1002 EMPNAME mathu raja DESIG designeng manager DOJ 12-SEP-07 14-SEP-07 SALARY 30000 35000 EMPNAME mathu raj Vishal DESIG designeng manager operator DOJ 12-SEP-07 14-SEP-07 12-FEB-03 SALARY 30000 35000 4000

B.COMMIT(savepoint)
commit; Commit complete. insert into emp values('1003','barath','operator','12-may-03','4000') 1 row created. select * from emp EMPNUM 1003 1001 EMPNAME barath mathu DESIG operator designeng manager DOJ 12-MAY-03 12-SEP-07 14-SEP-07 SALARY 4000 30000 35000

1002 raja savepoint id; Savepoint created. rollback to savepoint id Rollback complete. select * from emp; EMPNUM 1003 1001 1002 EMPNAME barath mathu raja

DESIG operator designeng manager

DOJ 12-MAY-03 12-SEP-07 14-SEP-07

SALARY 4000 30000 35000

Page105

Relational Datab Mana o base agement Sy ystem

2 2. Seq quence C Creation n


Aim:
To T perform the auto increment using Da object. m t ata

Create sequen e nce:


create s sequence o order_seq increment by 1 star with 1 m t rt maxvalue 9 9999 cycle e; Sequen created nce d.

Reffer rence seq quence:


select o order_seq.n nextval fro dual; om N NEXTVAL 1 select o order_seq.c currval fro dual; om C CURRVAL 6 insert in emp values(orde nto er_seq.nex xtval,'hari', ,'accounta ant',sysdat te,'4000') 1 row created. c

EMPN NUM 100 01 100 02 8

EMPNAME E E mat thu raja a har ri

DE ESIG designe eng manage er accoun ntant

DOJ 12-SEP-07 14-SEP-07 02-MAY-09

SA ALARY 30 0000 35 5000 4000 4

Relational Database Management System 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

Page107

3. View

Relational Database Management System Aim:


To view the record using the Data object.

create view emp_view as select * from emp View created. select * from emp_view; EMPNUM 1001 1002 8 EMPNAME mathu raja hari DESIG designeng manager accountant DOJ 12-SEP-07 14-SEP-07 02-MAY-09 SALARY 30000 35000 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 1001 1002 8 designeng manager accountant DESIG SALARY 30000 35000 4000

A view based on two tables(join view)


select * from emp; EMPNUM 1001 1002 8 EMPNAME mathu raja hari DESIG designeng manager accountant DOJ 12-SEP-07 14-SEP-07 02-MAY-09 SALARY 30000 35000 4000

select * from empl;


Page108

Relational Database Management System


EMPNUM 1001 1002 raja NAME mathu tenkasi madurai ADDR

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 1001 1002 raja NAME mathu tenkasi madurai ADDR

Information about view:


select view_name,text from user_views; VIEW_NAME EMP_VIEW TEXT 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
Page109

Relational Database Management System

Aim:
To Modify the Table name using data object.

Create synonym command:


create synonym e for emp; Synonym created. select * from emp; EMPNUM 1001 1002 EMPNAME mathu raja DESIG desigeng manager DOJ 12-SEP-09 03-FEB-06 SALARY 34000 45000

select * from e; EMPNUM 1001 1002 EMPNAME mathu raja DESIG desigeng manager DOJ 12-SEP-09 03-FEB-06 SALARY 34000 45000

Create synonyms for table of other users:


connect student/comp Connected. create synonym t for system.emp; Synonym created. select * from t; EMPNUM 1001 1002 EMPNAME mathu raja DESIG desigeng manager DOJ 12-SEP-09 03-FEB-06 SALARY 34000 45000

Rename Synonyms:
Page110

Relational Database Management System


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 1001 1002 EMPNAME mathu raja DESIG desigeng manager DOJ 12-SEP-09 03-FEB-06 SALARY 34000 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

Page111