You are on page 1of 173

DATA DEFINITION LANGUAGE COMMANDS

EX NO: 01
DATE:

AIM
To study the various DDL commands and implement them on the database.

COMMANDS

SQL> create table stud (sname varchar2(30), sid varchar2(10), sage number(2), sarea
varchar2(20));

Table created.

SQL> desc stud;


Name Null? Type
----------------------------------------------------- -------- --------------------------------
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(2)
SAREA VARCHAR2(20)

SQL>alter table stud modify ( sage number(10));

Table altered.

SQL> alter table stud add ( sdept varchar2(20));

Table altered.

SQL> desc stud;


Name Null? Type
----------------------------------------------------- -------- --------------------------------
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)
SDEPT VARCHAR2(20)

SQL> alter table stud drop ( sdept varchar2(20));

Table altered.

1
SQL> desc studs;
Name Null? Type
----------------------------------------------------- -------- ------------------------------------
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)

SQL> truncate table studs;

Table truncated.

SQL> desc studs;


Name Null? Type
----------------------------------------------------- -------- ------------------------------------
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)
SDEPT VARCHAR2(20)

SQL> drop table studs;

Table dropped.

RESULT

Thus the DDL commands were implemented and the output was verified.

2
DATA MANIPULATION LANGUAGE COMMANDS-SET1
EX NO: 2a
DATE:

AIM
To study the various categories of DML commands such as logical operations, aggregate
functions, string functions , numeric functions, date functions and conversion functions.

THE ORACLE TABLE – DUAL


Dual is a small oracle table which consists of only one row and one column and contains
the value X in that column.
INSERT
This command is used to insert values into the table.
SELECT
This command is used to display the contents of the table or those of a particular column.
RENAME
This command renames the name of the table.
ARITHMETIC OPERATIONS
Various operations such as addition, multiplication, subtraction and division can be
performed using the numbers available in the table.
DISTINCT
This keyword is used along with select keyword to display unique values from the
specified column. It avoids duplicates during display.
CONCATENATION OPERATOR
This combines information from two or more columns in a sentence according to the
format specified.
LOGICAL OPERATORS
 AND : The oracle engine will process all rows in a table and displays the result only
when all of the conditions specified using the AND operator are specified.
 OR : The oracle engine will process all rows in a table and displays the result only when
any of the conditions specified using the OR operators are satisfied.
 NOT : The oracle engine will process all rows in a table and displays the result only
when none of the conditions specified using the NOT operator are specified.
 BETWEEN : In order to select data that is within a range of values, the between operator
is used. (AND should be included)
PATTERN MATCH
 LIKE PREDICATE : The use of like predicate is that it allows the comparison of one
string value with another string value, which is not identical. This is achieved by using
wildcard characters which are % and _. The purpose of % is that it matches any string
and _ matches any single character.
 IN AND NOT IN PREDICATE : The arithmetic operator = compares a single value to
another single value. In case a value needs to be compared to a list of values then the in
predicate is used.The not in predicate is the opposite of the in predicate. This will select
all the rows whose values do not match all of the values in the list.
NUMERIC FUNCTIONS
3
 ABS: It returns the absolute value of ‘n’.
 POWER: It returns m raised to nth power. n must be an integer else an error is returned.
 ROUND: It returns n rounded to m places right of the decimal point. If m is omitted, n is
rounded to zero places. m must be an integer.
 SQRT: It returns square root of n. n should be greater than zero.
STRING FUNCTIONS
 LOWER: It returns char with letters in lower case.
 INITCAP: It returns char with the first letter in upper case.
 UPPER: It returns char with all letters forced to upper case.
 SUBSTR: It returns a portion of char beginning at character m, exceeding up to n
characters. If n is omitted result is written up to the end character. The 1st position of char
is one.
 LENGTH: It returns the length of char
 LTRIM: It removes characters from the left of char with initial characters removed up to
the 1st character not in set.
 RTRIM: It returns char with final characters removed after the last character not in the
set. Set is optional. It defaults to spaces.
 LPAD: It returns char1, left padded to length n with the sequence of characters in char2.
char2 defaults to blanks.
 RPAD: It returns char1, right padded to length n with the characters in char2, replicated
as many times as necessary. If char2 is omitted, it is padded with blanks.
AGGREGATE FUNCTIONS
 AVG (N): It returns average value of n ignoring null values.
 MIN (EXPR): It returns minimum value of the expression.
 COUNT (EXPR): It returns the number of rows where expression is not null.
 COUNT (*): It returns the number of rows in the table including the duplicates and those
with null values.
 MAX (EXPR): It returns maximum value of the expression.
 SUM(N): It returns sum of values of n.
CONVERSION FUCTIONS
 TO_NUMBER(CHAR): It converts the char value containing a number to a value of
number data type.
 TO_CHAR(N,FMT): It converts a value of number data type to a value of char data type,
using the optional format string. It accepts a number n and a numeric format fmt in which
the number has to appear. If fmt is omitted, n is converted to a char value exactly long
enough to hold significant digits.
 TO_CHAR(DATE, FMT): It converts a value of data type to char value. It accepts a date
as well as the format in which the date has to appear. Fmt must be a date format. If fmt is
omitted, date is the default date format.
DATE FUNCTIONS

 SYSDATE : The sysdate is a pseudo column that contains the current date and time. It
requires no arguments when selected from the table dual and returns the current date.

4
 ADD_MONTHS(D,N): It returns date after adding the number of months specified with
the function.
 LAST_DAY(D): It returns the last date of the month specified with the function
 MONTHS_BETWEEN(D1,D2): It returns number of months between D1 and D2.
 NEXT_DAY(DATE, CHAR): It returns the date of the first week day named by char .
char must be a day of the week.

COMMANDS

CREATION OF TABLE

SQL>create table stud (sname varchar2(30), sid varchar2(10), sage number(10), sarea
varchar2(20), sdept varchar2(20));

Table created.

INSERTION OF VALUES INTO THE TABLE


SQL> insert into stud values ('ashwin',101,19,'anna nagar','aeronautical');

1 row created.

SQL> insert into stud values ('bhavesh',102,18,'nungambakkam','marine');

1 row created.

SQL> insert into stud values ('pruthvik',103,20,'anna nagar','aerospace');

1 row created.

SQL> insert into stud values ('charith',104,20,'kilpauk','mechanical');


1 row created.

SQL> select * from stud;


SNAME SID SAGE SAREA SDEPT
------------------------------ ---------- --------- -------------------- --------------------
ashwin 101 19 anna nagar aeronautical
bhavesh 102 18 nungambakkam marine
pruthvik 103 20 anna nagar aerospace
charith 104 20 kilpauk mechanical

RENAMING THE TABLE ‘STUD’


SQL> rename stud to studs;

Table renamed.

5
ARITHMETIC OPERATION

SQL> select sname, sid+100 "stid" from studs;

SNAME stid
------------------------------ ---------
ashwin 201
bhavesh 202
pruthvik 203
charith 204

CONCATENATION OPERATOR

SQL> select sname || ' is a ' || sdept || ' engineer. ' AS "PROFESSION" from studs;

PROFESSION
-------------------------------------------------------------------
ashwin is a aeronautical engineer.
bhavesh is a marine engineer.
pruthvik is a aerospace engineer.
charith is a mechanical engineer.

DISPLAY ONLY DISTINCT VALUES

SQL> select distinct sarea from studs;

SAREA
--------------------
anna nagar
kilpauk
nungambakkam

USING THE WHERE CLAUSE


SQL> select sname,sage from studs where sage<=19;

SNAME SAGE
------------------------------ ---------
ashwin 19
bhavesh 18
BETWEEN OPERATOR
SQL> select sname,sarea, sid from studs where sid between 102 and 104;

SNAME SAREA SID


------------------------------ -------------------- ----------
bhavesh nungambakkam 102
pruthvik anna nagar 103

6
charith kilpauk 104
IN PREDICATE
SQL> select sname,sarea , sid from studs where sid in(102,104);

SNAME SAREA SID


------------------------------ -------------------- ----------
bhavesh nungambakkam 102
charith kilpauk 104

PATTERN MATCHING
SQL> select sname, sarea from studs where sarea like '%g%';

SNAME SAREA
------------------------------ --------------------
ashwin anna nagar
bhavesh nungambakkam
pruthvik anna nagar

LOGICAL AND OPERATOR


SQL> select sname ,sid from studs where sid>102 and sarea='anna nagar';

SNAME SID
------------------------------ ----------
pruthvik 103

LOGICAL OR OPERATOR
SQL> select sname ,sid from studs where sid>102 or sarea='anna nagar';

SNAME SID
------------------------------ ----------
ashwin 101
pruthvik 103
charith 104
NOT IN PREDICATE
SQL> select sname, sid from studs where sid not in(102,104);

SNAME SID
------------------------------ ----------
ashwin 101
pruthvik 103

UPDATING THE TABLE


SQL> alter table studs add ( spocket varchar2(20) );

Table altered.

7
SQL> update studs set spocket=750 where sid=101;

1 row updated.

SQL> update studs set spocket=500 where sid=102;

1 row updated.

SQL> update studs set spocket=250 where sid=103;

1 row updated.

SQL> update studs set spocket=100 where sid=104;

1 row updated.

SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT


------------------------------ ---------- --------- -------------------- --------------------
SPOCKET
--------------------

ashwin 101 19 anna nagar aeronautical


750
bhavesh 102 18 nungambakkam marine
500
pruthvik 103 20 anna nagar aerospace
250
charith 104 20 kilpauk mechanical
100

AGGREGATE FUNCTIONS
SQL> select avg( spocket ) result from studs;

RESULT
---------
400

SQL> select min(spocket) result from studs;

RESULT
--------------------
100

8
SQL> select count(spocket) result from studs;

RESULT
---------
4

SQL> select count(*) result from studs;

RESULT
---------
4

SQL> select count(spocket) result from studs where sarea='anna nagar';

RESULT
---------
2
SQL> select max(spocket) result from studs;

RESULT
--------------------
750

SQL> select sum(spocket) result from studs;

RESULT
---------
1600

NUMERIC FUNCTIONS
SQL> select abs(-20) result from dual;

RESULT
---------
20

SQL> select power (2,10) result from dual;

RESULT
---------
1024

SQL> select round(15.359,2) result from dual;

RESULT
---------

9
15.36

SQL> select sqrt (36) result from dual;

RESULT
---------
6

STRING FUNCTIONS

SQL> select lower('ORACLE') result from dual;

RESULT
------
oracle

SQL> select upper('oracle') result from dual;

RESULT
------
ORACLE

SQL> select initcap('Oracle') result from dual;

RESULT
------
Oracle
SQL> select substr('oracle' ,2 ,5) result from dual;

RESULT
-----
racle

SQL> select lpad('oracle',10,'#') result from dual;

RESULT
----------
####oracle

SQL> select rpad ('oracle',10,'^') result from dual;

RESULT
----------
oracle^^^^

CONVERSION FUNCTIONS

10
SQL> update studs set sage=to_number(substr(118,2,3));

4 rows updated.

SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT


------------------------------ ---------- --------- -------------------- --------------------
SPOCKET
--------------------
ashwin 101 18 anna nagar aeronautical
750
bhavesh 102 18 nungambakkam marine
500
pruthvik 103 18 anna nagar aerospace
250
charith 104 18 kilpauk mechanical
100

SQL> select to_char( 17145, '099,999') result from dual;

RESULT
--------
017,145

SQL> select to_char(sysdate,'dd-mon-yyyy') result from dual;

RESULT
-----------
16-jul-2008

DATE FUNCTIONS
SQL> select sysdate from dual;

SYSDATE
---------
16-JUL-08

SQL> select sysdate,add_months(sysdate,4) result from dual;

SYSDATE RESULT
--------- ---------
16-JUL-08 16-NOV-08

SQL> select sysdate, last_day(sysdate) result from dual;

11
SYSDATE RESULT
--------- ---------
16-JUL-08 31-JUL-08

SQL> select sysdate, next_day(sysdate,'sunday') result from dual;

SYSDATE RESULT
--------- ---------
16-JUL-08 20-JUL-08

SQL> select months_between('09-aug-91','11-mar-90') result from dual;

RESULT
---------
16.935484

RESULT

Thus all the DML commands were executed and the output was verified.

12
DATA MANIPULATION LANGUAGE COMMANDS-SET2
EX NO: 2b
DATE:

AIM
To study the various categories of DML commands such as order by clause, group by
clause, set operations, join operations and nested queries.

DESCRIPTION

ORDER BY CLAUSE
The order by clause arranges the contents of the table in ascending order (by default) or
in descending order (if specified explicitly) according to the specified column.

GROUP BY CLAUSE
The group by clause is another section of the select statement. This optional class tells
oracle to group rows based on distinct values that exists for specified columns.
HAVING CLAUSE
The having clause can be used in conjunction with the group by clause. Having imposes a
condition on the group by clause, which further filters the groups created by the group by clause.
SET OPERATIONS
 UNION CLAUSE: Multiple queries can be put together and their output combined using
the union clause. The union clause merges the output of two or more queries into a single
set of rows and columns.
 INTERSECT CLAUSE: Multiple queries can be put together and their output can be
combined using the intersect clause. The intersect clause outputs only rows produced by
both the queries intersected. The output in an intersect clause will include only those
rows that are retrieved by both the queries.
JOIN OPERATIONS
 INNER JOIN/ NATURAL JOIN/ JOIN: It is a binary operation that allows us to combine
certain selections and a Cartesian product into one operation.
 OUTER JOIN: It is an extension of join operation to deal with missing information.
Left Outer Join: It takes tuples in the left relation that did not match with any tuple in the
right relation, pads the tuples with null values for all other attributes from the right relation and
adds them to the result of the natural join.
Right Outer Join: It takes tuples in the right relation that did not match with any tuple in
the left relation, pads the tuples with null values for all other attributes from the left relation and
adds them to the result of the natural join.
Full Outer Join: It combines tuples from both the left and the right relation and pads the
tuples with null values for the missing attributes and them to the result of the

13
natural join.

ORDER BY CLAUSE

SQL> select * from emppp56;

NAME ID
-------------------- ----------
x 1
a 2
g 3
d 4

SQL> select * from emppp56 order by na

NAME ID
-------------------- ----------
a 2
d 4
g 3
x 1

GROUP BY CLAUSE
SQL> select sarea, sum(spocket) result from studs group by sarea;

SAREA RESULT
-------------------- ------------
anna nagar 1000
nungambakkam 500
kilpauk 100

HAVING CLAUSE
SQL> select sarea, sum(spocket) result from studs group by sarea having spocket<600;

SAREA RESULT
-------------------- ------------
nungambakkam 500
kilpauk 100

DELETION
SQL> delete from studs where sid=101;

1 row deleted.

14
SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT


------------------------------ ---------- --------- -------------------- --------------------
SPOCKET
-------------------
bhavesh 102 18 nungambakkam marine
500
pruthvik 103 20 anna nagar aerospace
250
charith 104 20 kilpauk mechanical
100

CREATING TABLES FOR DOING SET OPERATIONS


TO CREATE PRODUCT TABLE
SQL> create table product(prodname varchar2(30), prodno varchar2(10));

Table created.

SQL> insert into product values('table',10001);

1 row created.

SQL> insert into product values('chair',10010);

1 row created.

SQL> insert into product values('desk',10110);

1 row created.

SQL> insert into product values('cot',11110);

1 row created.

SQL> insert into product values('sofa',10010);

1 row created.

SQL>

SQL> insert into product values('tvstand',11010);

1 row created.

15
SQL> select * from product;

PRODNAME PRODNO
------------------------------ ----------
table 10001
chair 10010
desk 10110
cot 11110
sofa 10010
tvstand 11010

TO CREATE SALE TABLE


SQL> create table sale(prodname varchar2(30),orderno number(10),prodno varchar2(10));

Table created.

SQL> insert into sale values('table',801,10001);

1 row created.

SQL> insert into sale values('chair',805,10010);

1 row created.

SQL> insert into sale values('desk',809,10110);

1 row created.

SQL> insert into sale values('cot',813,11110);

1 row created.

SQL> insert into sale values('sofa',817,10010);

1 row created.

SQL> select * from sale;

PRODNAME ORDERNO PRODNO


------------------------------ --------- ----------
table 801 10001
chair 805 10010
desk 809 10110
cot 813 11110
sofa 817 10010
SET OPERATIONS

16
SQL> select prodname from product where prodno=10010 union select prodname from sale
where prodno=10010;

PRODNAME
------------------------------
chair
sofa

SQL> select prodname from product where prodno=11110 intersect select prodname from sale
where prodno=11110;

PRODNAME
------------------------------
cot

CREATING TABLES FOR DOING JOIN AND NESTED QUERY OPERATIONS


TO CREATE SSTUD1 TABLE
SQL> create table sstud1 ( sname varchar2(20) , place varchar2(20));

Table created.

SQL> insert into sstud1 values ( 'prajan','chennai');

1 row created.

SQL> insert into sstud1 values ( 'anand','chennai');

1 row created.

SQL> insert into sstud1 values ( 'kumar','chennai');

1 row created.

SQL> insert into sstud1 values ( 'ravi','chennai');

1 row created.

SQL> select * from sstud1;

SNAME PLACE
-------------------- --------------------
prajan chennai
anand chennai
kumar chennai
ravi chennai

17
TO CREATE SSTUD2 TABLE
SQL> create table sstud2 ( sname varchar2(20), dept varchar2(10), marks number(10));

Table created.

SQL> insert into sstud2 values ('prajan','cse',700);

1 row created.

SQL> insert into sstud2 values ('anand','it',650);

1 row created.

SQL> insert into sstud2 values ('vasu','cse',680);

1 row created.

SQL> insert into sstud2 values ('ravi','it',600);

1 row created.

SQL> select * from sstud2;

SNAME DEPT MARKS


-------------------- ---------- ---------
prajan cse 700
anand it 650
vasu cse 680
ravi it 600

JOIN OPERATIONS
SQL> select sstud1.sname, dept from sstud1 inner join sstud2 on ( sstud1.sname= sstud2.sname);

SNAME DEPT
-------------------- ----------
anand it
prajan cse
ravi it

SQL> select sstud1.sname, dept from sstud1 join sstud2 on ( sstud1.sname= sstud2.sname);

SNAME DEPT
-------------------- ----------
anand it
prajan cse

18
ravi it

SQL> select sstud1.sname, dept from sstud1 left outer join sstud2 on ( sstud1.sname=
sstud2.sname);

SNAME DEPT
-------------------- ----------
prajan cse
anand it
ravi it
kumar

SQL> select sstud1.sname, dept from sstud1 right outer join sstud2 on ( sstud1.sname=
sstud2.sname)

SNAME DEPT
-------------------- ----------
prajan cse
anand it
ravi it
cse

SQL> select sstud1.sname, dept from sstud1 full outer join sstud2 on ( sstud1.sname=
sstud2.sname);

SNAME DEPT
-------------------- ----------
prajan cse
anand it
ravi it
kumar
cse

NESTED QUERIES

SQL> select sname from sstud1 where sstud1.sname in ( select sstud2.sname from
2 sstud2 );

SNAME
--------------------
anand
prajan
ravi

19
SQL> select sname from sstud1 where sstud1.sname not in ( select sstud2.sname from sstud2 );

SNAME
--------------------
kumar

SQL> select sname from sstud2 where marks > some(select marks from sstud2
2 where dept='cse');

SNAME
--------------------
prajan

SQL> select sname from sstud2 where marks >= some (select marks from sstud2
2 where dept='cse' );

SNAME
--------------------
prajan
vasu

SQL> select sname from sstud2 where marks > any ( select marks from sstud2 where
dept='cse' );

SNAME
--------------------
prajan

SQL> select sname from sstud2 where marks >= any ( select marks from sstud2
2 where dept='cse' );

SNAME
--------------------
prajan
vasu

SQL> select sname from sstud2 where marks > all ( select marks from sstud2 where dept='cse' );

no rows selected

SQL> select sname from sstud2 where marks < all ( select marks from sstud2 where dept='cse' );

SNAME
--------------------
anand
ravi

20
SQL> select sname from sstud1 where exists ( select sstud2.sname from sstud2
2 where sstud1.sname=sstud2.sname );

SNAME
--------------------
prajan
anand
ravi

SQL> select sname from sstud1 where not exists ( select sstud2.sname from
2 sstud2 where sstud1.sname=sstud2.sname );

SNAME
--------------------
Kumar

SQL> select ename from e234 where exists(select * from e234);

ENAME
--------------------
x
y
z
a
c

SQL> select ename from e234 where not exists(select * from e234);

no rows selected

TO RENAME A COLUMN

SQL> select * from emppp56;

NAME ID
-------------------- ----------
x 1
a 2
g 3
d 4

SQL> alter table emppp56 rename column name to emp_name;

Table altered.

21
SQL> desc emppp56;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMP_NAME VARCHAR2(20)
ID NUMBER

SQL> select * from emppp56;

EMP_NAME ID
-------------------- ----------
x 1
a 2
g 3
d 4

RESULT

Thus all the DML commands were executed and the output was verified.

22
INTEGRITY CONSTRAINTS
EX NO: 3
DATE:

AIM
To study the various Integrity constraints available in the SQL query language.

Integrity Constraints

1.Domain Constraint
a)NULL CONSTRAINT
B)NOT NULL CONSTRAINT
c)CHECK CONSTRAINT

2. Entity Constraint
a)UNIQUE
b)PRIMARY KEY

3. Referential Constraint
a)FOREIGN KEY

1.DOMAIN CONSTRAINT

NULL CONSTRAINT

SQL> create table customer(cname varchar2(20),accno number constraint consn null);

Table created.

SQL> desc customer;


Name Null? Type
----------------------------------------- -------- ----------------------------
CNAME VARCHAR2(20)
ACCNO NUMBER

SQL> insert into customer values('&cname',&accno);


Enter value for cname: x
Enter value for accno: 1
old 1: insert into customer values('&cname',&accno)
new 1: insert into customer values('x',1)

23
1 row created.

SQL> /
Enter value for cname: y
Enter value for accno: 2

old 1: insert into customer values('&cname',&accno)


new 1: insert into customer values('y',2)

1 row created.

SQL> insert into customer values('&cname',&accno);


Enter value for cname: z
Enter value for accno: null
old 1: insert into customer values('&cname',&accno)
new 1: insert into customer values('z',null)

1 row created.

SQL> select * from customer;

CNAME ACCNO
-------------------- ----------
x 1
y 2
z

SQL> update customer set accno=3 where cname='z';

1 row updated.

SQL> select * from customer;

CNAME ACCNO
-------------------- ----------
x 1
y 2
z 3

NOT NULL CONSTRAINT

24
SQL> create table borrower(cname varchar2(20),loan_no number constraint consl not null);

Table created.

SQL> insert into borrower values('&cname',&loan_no);


Enter value for cname: x
Enter value for loan_no: 1
old 1: insert into borrower values('&cname',&loan_no)
new 1: insert into borrower values('x',1)

1 row created.

SQL> /
Enter value for cname: y
Enter value for loan_no: 2
old 1: insert into borrower values('&cname',&loan_no)
new 1: insert into borrower values('y',2)

1 row created.

SQL> /
Enter value for cname: z
Enter value for loan_no: null
old 1: insert into borrower values('&cname',&loan_no)
new 1: insert into borrower values('z',null)
insert into borrower values('z',null)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."BORROWER"."LOAN_NO")

SQL> /
Enter value for cname: a
Enter value for loan_no:
old 1: insert into borrower values('&cname',&loan_no)
new 1: insert into borrower values('a',)
insert into borrower values('a',)
*
ERROR at line 1:
ORA-00936: missing expression

SQL> select * from borrower;

CNAME LOAN_NO

25
-------------------- ----------
x 1
y 2

CHECK CONSTRAINT

SQL> create table withdraw(cname varchar2(20),balance number constraint consc


check(balance>500));

Table created.

SQL> insert into withdraw values('&cname',&balance);


Enter value for cname: x
Enter value for balance: 10000
old 1: insert into withdraw values('&cname',&balance)
new 1: insert into withdraw values('x',10000)

1 row created.

SQL> /
Enter value for cname: y
Enter value for balance: 200
old 1: insert into withdraw values('&cname',&balance)
new 1: insert into withdraw values('y',200)
insert into withdraw values('y',200)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CONSC) violated

SQL> /
Enter value for cname: y
Enter value for balance: 20000
old 1: insert into withdraw values('&cname',&balance)
new 1: insert into withdraw values('y',20000)

1 row created.

SQL> select * from withdraw;

CNAME BALANCE
-------------------- ----------

26
x 10000
y 20000

SQL> update withdraw set balance=balance-9700 where cname='x';

update withdraw set balance=balance-9700 where cname='x'


*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CONSC) violated

SQL> create table company1(ename varchar2(20),cname varchar2(20),place varchar2(20)


constraint consp
check(place in ('chennai','madurai','trichy')));

Table created.

SQL> insert into company1 values('&emane','&cname','&place');


Enter value for emane: x
Enter value for cname: tcs
Enter value for place: chennai
old 1: insert into company1 values('&emane','&cname','&place')
new 1: insert into company1 values('x','tcs','chennai')

1 row created.

SQL> /
Enter value for emane: y
Enter value for cname: tcs
Enter value for place: maadurai
old 1: insert into company1 values('&emane','&cname','&place')
new 1: insert into company1 values('y','tcs','maadurai')
insert into company1 values('y','tcs','maadurai')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CONSP) violated

SQL> /
Enter value for emane: y
Enter value for cname: tcs
Enter value for place: madurai
old 1: insert into company1 values('&emane','&cname','&place')
new 1: insert into company1 values('y','tcs','madurai')

1 row created.

27
SQL> /
Enter value for emane: z
Enter value for cname: wipro
Enter value for place: adyar

old 1: insert into company1 values('&emane','&cname','&place')


new 1: insert into company1 values('z','wipro','adyar')
insert into company1 values('z','wipro','adyar')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CONSP) violated

SQL> select * from company1;

ENAME CNAME PLACE


-------------------- -------------------- --------------------
x tcs chennai
y tcs madurai

SQL> update company1 set place='vadapalani' where ename='x';


update company1 set place='vadapalani' where ename='x'
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CONSP) violated

2.ENTITY INTEGRITY CONSTRAINT

UNIQUE CONSTRAINT

SQL> create table company(comp_name varchar2(20) not null unique,location varchar2(20) not
null uniq
ue);

Table created.

SQL> desc company;


Name Null? Type
----------------------------------------- -------- ----------------------------
COMP_NAME NOT NULL VARCHAR2(20)
LOCATION NOT NULL VARCHAR2(20)

SQL> insert into company values('&comp_name','&location');


Enter value for comp_name: tcs
Enter value for location: vadapalani
old 1: insert into company values('&comp_name','&location')

28
new 1: insert into company values('tcs','vadapalani')

1 row created.

SQL> /
Enter value for comp_name: tcs
Enter value for location: adyar
old 1: insert into company values('&comp_name','&location')
new 1: insert into company values('tcs','adyar')
insert into company values('tcs','adyar')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C003014) violated

SQL> /
Enter value for comp_name: cts
Enter value for location: vadapalani
old 1: insert into company values('&comp_name','&location')
new 1: insert into company values('cts','vadapalani')
insert into company values('cts','vadapalani')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C003015) violated

SQL> /
Enter value for comp_name: null
Enter value for location: solinganalur
old 1: insert into company values('&comp_name','&location')
new 1: insert into company values('null','solinganalur')

1 row created.

SQL> /
Enter value for comp_name:
Enter value for location: padi
old 1: insert into company values('&comp_name','&location')
new 1: insert into company values('','padi')
insert into company values('','padi')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."COMPANY"."COMP_NAME")

29
SQL> /
Enter value for comp_name: wipro
Enter value for location:
old 1: insert into company values('&comp_name','&location')

new 1: insert into company values('wipro','')


insert into company values('wipro','')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."COMPANY"."LOCATION")

SQL> select * from company;

COMP_NAME LOCATION
-------------------- --------------------
tcs vadapalani
null solinganalur

SQL> create table account(accno number constraint consu unique);

Table created.

SQL> insert into account values(&accno);


Enter value for accno: 1
old 1: insert into account values(&accno)
new 1: insert into account values(1)

1 row created.

SQL> /
Enter value for accno: 2
old 1: insert into account values(&accno)
new 1: insert into account values(2)

1 row created.

SQL> /
Enter value for accno: 3
old 1: insert into account values(&accno)
new 1: insert into account values(3)

1 row created.

SQL> /
Enter value for accno: 2

30
old 1: insert into account values(&accno)
new 1: insert into account values(2)
insert into account values(2)
*

ERROR at line 1:
ORA-00001: unique constraint (SCOTT.CONSU) violated

SQL> alter table account add(cname varchar2(20));

Table altered.

SQL> desc account;


Name Null? Type
----------------------------------------- -------- ----------------------------
ACCNO NUMBER
CNAME VARCHAR2(20)

SQL> alter table account add constraint consuu unique(cname);

Table altered.

SQL> desc account;


Name Null? Type
----------------------------------------- -------- ----------------------------
ACCNO NUMBER
CNAME VARCHAR2(20)

SQL> select * from account;

ACCNO CNAME
---------- --------------------
1
2
3

SQL> update account set cname='y' where accno=1;

1 row updated.

SQL> update account set cname='z' where accno=2;

1 row updated.

31
SQL> update account set cname='a' where accno=3;

1 row updated.

SQL> select * from account;

ACCNO CNAME
---------- --------------------
1y
2z
3a

SQL> create table depositor(cname varchar2(20),accno number,constraint consuni


unique(cname,accno));

Table created.

SQL> insert into depositor values('&cname',&accno);


Enter value for cname: x
Enter value for accno: 1
old 1: insert into depositor values('&cname',&accno)
new 1: insert into depositor values('x',1)

1 row created.

SQL> /
Enter value for cname: x
Enter value for accno: 2
old 1: insert into depositor values('&cname',&accno)
new 1: insert into depositor values('x',2)

1 row created.

SQL> /
Enter value for cname: y
Enter value for accno: 2
old 1: insert into depositor values('&cname',&accno)
new 1: insert into depositor values('y',2)

1 row created.

SQL> /
Enter value for cname: y
Enter value for accno: 2

32
old 1: insert into depositor values('&cname',&accno)
new 1: insert into depositor values('y',2)
insert into depositor values('y',2)
*

ERROR at line 1:
ORA-00001: unique constraint (SCOTT.CONSUNI) violated

CNAME ACCNO
-------------------- ----------
x 1
x 2
y 2

PRIMARY KEY AND FOREIGN KEY CONSTRAINTS

SQL> create table empv(name varchar2(20),id number not null constraint cons_pri primary key);

Table created.

SQL> desc empv;


Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(20)
ID NOT NULL NUMBER

SQL> insert into empv values('&name',&id);


Enter value for name: john
Enter value for id: 11
old 1: insert into empv values('&name',&id)
new 1: insert into empv values('john',11)

1 row created.

SQL> /
Enter value for name: henry
Enter value for id: 11
old 1: insert into empv values('&name',&id)
new 1: insert into empv values('henry',11)
insert into empv values('henry',11)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.CONS_PRI) violated

SQL> /
Enter value for name: henry

33
Enter value for id: 12
old 1: insert into empv values('&name',&id)
new 1: insert into empv values('henry',12)

1 row created.

SQL> select * from empv;

NAME ID
-------------------- ----------
john 11
henry 12

SQL> create table project(pname varchar2(20),id number not null,constraint cons_fr foreign
key(id)
references empv(id));

Table created.

SQL> desc project;


Name Null? Type
----------------------------------------- -------- ----------------------------
PNAME VARCHAR2(20)
ID NOT NULL NUMBER

SQL> insert into project values('&pname',&id);


Enter value for pname: banking_system
Enter value for id: 11
old 1: insert into project values('&pname',&id)
new 1: insert into project values('banking_system',11)

1 row created.

SQL> /
Enter value for pname: banking_system
Enter value for id: 12
old 1: insert into project values('&pname',&id)
new 1: insert into project values('banking_system',12)

1 row created.

SQL> /
Enter value for pname: airline
Enter value for id: 11
old 1: insert into project values('&pname',&id)

34
new 1: insert into project values('airline',11)

1 row created.

SQL> /
Enter value for pname: payroll
Enter value for id: 12
old 1: insert into project values('&pname',&id)
new 1: insert into project values('payroll',12)

1 row created.

SQL> select * from project;

PNAME ID
-------------------- ----------
banking_system 11
banking_system 12
airline 11
payroll 12

SQL> select name,empv.id,pname from empv,project where empv.id=project.id;

NAME ID PNAME
-------------------- ---------- --------------------
john 11 banking_system
henry 12 banking_system
john 11 airline
henry 12 payroll

TO DISABLE THE RESPECTIVE CONSTRAINT

SQL> alter table empv disable constraint cons_pri;

Table altered.

SQL> insert into empv values('&name',&id);


Enter value for name: korth
Enter value for id: 12
old 1: insert into empv values('&name',&id)

35
new 1: insert into empv values('korth',12)

1 row created.

SQL> select * from empv;

NAME ID
-------------------- ----------
john 11
henry 12
korth 12

TO ENABLE THE RESPECTIVE CONSTRAINT

SQL> alter table empv enable constraint cons_pri;


alter table empv enable constraint cons_pri
*
ERROR at line 1:
ORA-02437: cannot validate (SCOTT.CONS_PRI) - primary key violated

SQL> update empv set id=13 where name='korth';

1 row updated.

SQL> select * from empv;

NAME ID
-------------------- ----------
john 11
henry 12
korth 13

SQL> alter table empv enable constraint cons_pri;

Table altered.

SQL> desc empv;


Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(20)
ID NOT NULL NUMBER

36
SQL> insert into empv values('&name',&id);
Enter value for name: smith
Enter value for id: 13
old 1: insert into empv values('&name',&id)

new 1: insert into empv values('smith',13)


insert into empv values('smith',13)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.CONS_PRI) violated

SQL> create table emp1(ename varchar2(15),eid number);

Table created.

SQL> create table dept1(dno number,dname varchar2(15));

Table created.

SQL> alter table emp1 add constraint con_eid primary key(eid);

Table altered.

SQL> alter table dept1 add constraint con_dno primary key(dno);

Table altered.

SQL> alter table emp1 add(dno number);

Table altered.

SQL> desc emp1;


Name Null? Type
----------------------------------------- -------- ----------------------------
ENAME VARCHAR2(15)
EID NOT NULL NUMBER
DNO NUMBER

SQL> alter table emp1 add constraint conf_dno foreign key(dno) references dept1(dno);

Table altered.

SQL> desc dept1;


Name Null? Type
----------------------------------------- -------- ----------------------------
DNO NOT NULL NUMBER

37
DNAME VARCHAR2(15)

SQL> insert into emp1 values('&ename',&eid,&dno);


Enter value for ename: x

Enter value for eid: 1


Enter value for dno: 1
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('x',1,1)
insert into emp1 values('x',1,1)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.CONF_DNO) violated - parent key not
found

SQL> insert into dept1 values(&dno,'&dname');


Enter value for dno: 1
Enter value for dname: it
old 1: insert into dept1 values(&dno,'&dname')
new 1: insert into dept1 values(1,'it')

1 row created.

SQL> /
Enter value for dno: 2
Enter value for dname: cse
old 1: insert into dept1 values(&dno,'&dname')
new 1: insert into dept1 values(2,'cse')

1 row created.

SQL> /
Enter value for dno: 3
Enter value for dname: ece
old 1: insert into dept1 values(&dno,'&dname')
new 1: insert into dept1 values(3,'ece')

1 row created.

SQL> insert into dept1 values(&dno,'&dname');


Enter value for dno: 1
Enter value for dname: eee
old 1: insert into dept1 values(&dno,'&dname')
new 1: insert into dept1 values(1,'eee')
insert into dept1 values(1,'eee')
*

38
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.CON_DNO) violated

SQL> select * from dept1;

DNO DNAME
---------- ---------------
1 it
2 cse
3 ece
SQL> insert into emp1 values('&ename',&eid,&dno);
Enter value for ename: x
Enter value for eid: 1
Enter value for dno: 1
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('x',1,1)

1 row created.

SQL> /
Enter value for ename: y
Enter value for eid: 2
Enter value for dno: 1
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('y',2,1)

1 row created.

SQL> /
Enter value for ename: a
Enter value for eid: 3
Enter value for dno: 1
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('a',3,1)

1 row created.

SQL> /
Enter value for ename: b
Enter value for eid: 4
Enter value for dno: 2
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('b',4,2)

1 row created.

39
SQL> /
Enter value for ename: c
Enter value for eid: 5

Enter value for dno: 2


old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('c',5,2)

1 row created.

SQL> /
Enter value for ename: d
Enter value for eid: 6
Enter value for dno: 3
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('d',6,3)

1 row created.

SQL> /
Enter value for ename: e
Enter value for eid: 6
Enter value for dno: 3
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('e',6,3)
insert into emp1 values('e',6,3)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.CON_EID) violated

SQL> /
Enter value for ename: e
Enter value for eid: 7
Enter value for dno: 3
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('e',7,3)

1 row created.

SQL> select * from emp1;

ENAME EID DNO


--------------- ---------- ----------
x 1 1
y 2 1

40
a 3 1
b 4 2
c 5 2
d 6 3

e 7 3

7 rows selected.

SQL> select * from dept1;

DNO DNAME
---------- ---------------
1 it
2 cse
3 ece
SQL> select * from emp1,dept1 where emp1.dno=dept1.dno;

ENAME EID DNO DNO DNAME


--------------- ---------- ---------- ---------- ---------------
x 1 1 1 it
y 2 1 1 it
a 3 1 1 it
b 4 2 2 cse
c 5 2 2 cse
d 6 3 3 ece
e 7 3 3 ece

7 rows selected.

SQL> select ename,dname from emp1,dept1 where emp1.dno=dept1.dno;

ENAME DNAME
--------------- ---------------
x it
y it
a it
b cse
c cse
d ece
e ece

7 rows selected.

SQL> select ename,dname from emp1,dept1 where emp1.dno=dept1.dno and dname='it';

41
ENAME DNAME
--------------- ---------------
x it
y it

a it

SQL> select ename,dno,dname from emp1,dept1 where emp1.dno=dept1.dno;


select ename,dno,dname from emp1,dept1 where emp1.dno=dept1.dno
*
ERROR at line 1:
ORA-00918: column ambiguously defined

SQL> select ename,emp1.dno,dname from emp1,dept1 where emp1.dno=dept1.dno;

ENAME DNO DNAME


--------------- ---------- ---------------
x 1 it
y 1 it
a 1 it
b 2 cse
c 2 cse
d 3 ece
e 3 ece

7 rows selected.

SQL> insert into emp1 values('&ename',&eid,&dno);


Enter value for ename: f
Enter value for eid: 8
Enter value for dno: 4
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('f',8,4)
insert into emp1 values('f',8,4)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.CONF_DNO) violated - parent key not
found

SQL> /
Enter value for ename: f
Enter value for eid: 8
Enter value for dno: 2
old 1: insert into emp1 values('&ename',&eid,&dno)
new 1: insert into emp1 values('f',8,2)

42
1 row created.

SQL> select * from emp1;

ENAME EID DNO


--------------- ---------- ----------
x 1 1
y 2 1
a 3 1
b 4 2
c 5 2
d 6 3
e 7 3
f 8 2

8 rows selected.

43
RESULT

Thus the various constraints were implemented and the tables were created using the
respective constraints. Hence the output was verified.

SQL APPLICATION 1

EX.NO:4a
DATE:

Consider the following relational schemas for the employee database.


Employee(ename,city,street)
Works(ename,companyname,salary)
Company(companyname,city)
Manages(ename,mname)

1. Find the names of all employees who work for the ‘fbc’.
2. Find the names, street addresses and cities of all employees who work for the ‘fbc’ and
earn more than 200000 per annum.
3. Find the names of all employees in this database who live in the same city as the
company for which they work.
4. Find the names of all employees who earn more than every employee of sbc.
5. Find the names of all employees who do not work for fbc.
6. Find the names of all employees who do not have manager.
7. Find the names of all employees who do have manager.
8. Identify all possible primary key and foreign key.
9. Create a view to store the companyname and the number of employees in each company
and do all possible manipulations on the view. If not justify your answer.
10. Find the companyname which has got the highest total salary.
11. Find the names of all employees whose first letter is ‘a’.
12. Delete the record of employee ‘john’.
13. Display the details of all employees in a sorted order.
14. Find the names of all employees who are living in Chennai.
15. Find the names of all employees who are not living in Bangalore and Hyderabad.
16. Update the salary of ‘bbc’ employees by Rs.1000.
17. Add a new column manager_no onto the manages relation.
18. Set a NOT NULL constraint for the salary column.
19. Find the names of all employees where fifth letter is ‘y’.
20. Find the names of all employees whose salary is in the range 100000 to 200000.
21. Create a view to store the employee name and the companyname and find out the
type of view.
22. Change the name of the companyname column to cname.

44
SQL> create table employee(ename varchar2(20),city varchar2(20),street varchar2(20));

Table created.

SQL> create table works(ename varchar2(20),companyname varchar2(20),salary number);

Table created.

SQL> create table company(companyname varchar2(20),city varchar2(20));

Table created.

SQL> create table manages(ename varchar2(20),mname varchar2(20));

Table created.

SQL> insert into employee values('&ename','&city','&street');


Enter value for ename: ajith
Enter value for city: chennai
Enter value for street: kamarajar
old 1: insert into employee values('&ename','&city','&street’)
new 1: insert into employee values('ajith','chennai','kamarajar’)

1 row created.

SQL> /
Enter value for ename: john
Enter value for city: bangalore
Enter value for street: ambedkar
old 1: insert into employee values('&ename','&city','&street’)
new 1: insert into employee values('john','bangalore','ambedkar’)

1 row created.

SQL> /
Enter value for ename: vijay
Enter value for city: hyderabad
Enter value for street: rajiv
old 1: insert into employee values('&ename','&city','&street’)
new 1: insert into employee values('vijay','hyderabad','rajiv’)

45
1 row created.

SQL> /

Enter value for ename: siva


Enter value for city: chennai
Enter value for street: kamarajar
old 1: insert into employee values('&ename','&city','&street’)
new 1: insert into employee values('siva','chennai','kamarajar’)

1 row created.

SQL> select * from employee;

ENAME CITY STREET


-------------------- -------------------- --------------------
ajith chennai kamarajar
john bangalore ambedkar
vijay hyderabad rajiv
siva chennai kamarajar

SQL> insert into works values('&ename','&companyname',&salary);


Enter value for ename: ajith
Enter value for companyname: fbc
Enter value for salary: 300000
old 1: insert into works values('&ename','&companyname',&salary)
new 1: insert into works values('ajith','fbc',300000)

1 row created.

SQL> /
Enter value for ename: john
Enter value for companyname: sbc
Enter value for salary: 150000
old 1: insert into works values('&ename','&companyname',&salary)
new 1: insert into works values('john','sbc',150000)

1 row created.

SQL> /

46
Enter value for ename: vijay
Enter value for companyname: bbc
Enter value for salary: 200000
old 1: insert into works values('&ename','&companyname',&salary)

new 1: insert into works values('vijay','bbc',200000)

1 row created.

SQL> /
Enter value for ename: siva
Enter value for companyname: fbc
Enter value for salary: 400000
old 1: insert into works values('&ename','&companyname',&salary)
new 1: insert into works values('siva','fbc',400000)

1 row created.

SQL> select * from works;

ENAME COMPANYNAME SALARY


-------------------- -------------------- ---------
ajith fbc 300000
john sbc 150000
vijay bbc 200000
siva fbc 400000

SQL> insert into company values('&companyname','&city');


Enter value for companyname: fbc
Enter value for city: chennai
old 1: insert into company values('&companyname','&city')
new 1: insert into company values('fbc','chennai')

1 row created.

SQL> /
Enter value for companyname: sbc
Enter value for city: bangalore
old 1: insert into company values('&companyname','&city')
new 1: insert into company values('sbc','bangalore')

1 row created.

47
SQL> /
Enter value for companyname: bbc
Enter value for city: hyderabad
old 1: insert into company values('&companyname','&city')

new 1: insert into company values('bbc','hyderabad')

1 row created.

SQL> select * from company;

COMPANYNAME CITY
-------------------- --------------------
fbc chennai
sbc bangalore
bbc hyderabad

SQL> insert into manages values('&ename','&mname');


Enter value for ename: ajith
Enter value for mname: smith
old 1: insert into manages values('&ename','&mname')
new 1: insert into manages values('ajith','smith')

1 row created.

SQL> /
Enter value for ename: john
Enter value for mname:
old 1: insert into manages values('&ename','&mname')
new 1: insert into manages values('john','')

1 row created.

SQL> /
Enter value for ename: vijay
Enter value for mname: henry
old 1: insert into manages values('&ename','&mname')
new 1: insert into manages values('vijay','henry')

1 row created.

SQL> /
Enter value for ename: siva
Enter value for mname:
old 1: insert into manages values('&ename','&mname')
new 1: insert into manages values('siva','')

48
1 row created.

SQL> select * from manages;

ENAME MNAME
-------------------- --------------------
ajith smith
john
vijay henry
siva

SQL> select ename from works where companyname='fbc';

ENAME
--------------------
ajith
siva

SQL> select ename,street,city from employee where ename in (select ename from works where
2 companyname='fbc' and salary>200000);

ENAME STREET CITY


-------------------- -------------------- --------------------
ajith kamarajar chennai
siva kamarajar chennai

SQL> select works.ename,street,city from employee inner join works on


employee.ename=works.ename
2 where companyname='fbc' and salary>200000;

ENAME STREET CITY


-------------------- -------------------- --------------------
ajith kamarajar chennai
siva kamarajar chennai

SQL> select employee.ename from employee,works,company where


employee.ename=works.ename
2 and employee.city=company.city and works.companyname=company.companyname;

ENAME

49
--------------------
ajith
john
siva

vijay

SQL> select employee.ename from employee inner join works on


employee.ename=works.ename
2 inner join company on employee.city=company.city and
works.companyname=company.companyname;

ENAME
--------------------
ajith
john
siva
vijay

SQL> select ename from works where salary>(select max(salary) from works where
companyname='sbc');

ENAME
--------------------
ajith
vijay
siva

SQL> select ename from works where salary >all (select max(salary)
2 from works where companyname='sbc');

ENAME
--------------------
ajith
vijay
siva
SQL> select ename from works where companyname not in ('fbc');

ENAME
--------------------
john
vijay

SQL> select ename from works where companyname!='fbc';

50
ENAME
--------------------
john

vijay

SQL> select ename from manages where mname is null;

ENAME
--------------------
john
siva

SQL> select ename from manages where mname is not null;

ENAME
--------------------
ajith
vijay

SQL> create table employee(ename varchar2(20) constraint con1 primary key,


2 city varchar2(20),street varchar2(20));

SQL> create table company(companyname varchar2(20) constraint con2 primary key,


2 city varchar2(20));

SQL> create table works(ename varchar2(20),companyname varchar2(20),salary number,


2 constraint con3 foreign key (ename) references employee(ename),constraint con4
3 foreign key (companyname) references company(companyname));

SQL> create table manages(ename varchar2(20),mname varchar2(20),constraint con5


2 foreign key (ename) references employee (ename));

SQL> create view v1(cname,no_of_employees) as (select companyname,count(ename) from


works
2 group by companyname);

51
View created.

SQL> select * from v1;

CNAME NO_OF_EMPLOYEES
-------------------- ---------------
bbc 1
fbc 2
sbc 1

SQL> update v1 set cname='hsbc' where no_of_employees=2;


update v1 set cname='hsbc' where no_of_employees=2
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

SQL> select companyname from (select companyname,sum(salary) from works group by


2 companyname having sum(salary)=(select max(sum(salary)) from works group by
companyname));

COMPANYNAME
--------------------
fbc

SQL> select ename from employee where ename like 'a%';

ENAME
--------------------
ajith

SQL> delete from employee where ename='john';

1 row deleted.

SQL> select * from employee;

ENAME CITY STREET


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

52
ajith chennai kamarajar
vijay hyderabad rajiv
siva chennai kamarajar

SQL> select * from employee order by ename;

ENAME CITY STREET


-------------------- -------------------- --------------------
ajith chennai kamarajar
siva chennai kamarajar
vijay hyderabad rajiv

SQL> select ename from employee where city in 'chennai';

ENAME
--------------------
ajith
siva

SQL> select ename from employee where city not in ('bangalore','hyderabad');

ENAME
--------------------
ajith
siva

SQL> update works set salary=salary+1000 where companyname='bbc';

1 row updated.

SQL> select * from works;

ENAME COMPANYNAME SALARY


-------------------- -------------------- ---------
ajith fbc 300000
john sbc 150000
vijay bbc 201000
siva fbc 400000

53
SQL> alter table manages add(manager_no number);

Table altered.

SQL> select * from manages;

ENAME MNAME MANAGER_NO


-------------------- -------------------- ----------
ajith smith
john
vijay henry
siva

SQL> create table works (ename varchar2(20),companyname varchar2(20),salary number


2 constraint con6 not null);

SQL> select ename from employee where ename like '____y%';

ENAME
--------------------
vijay

SQL> select ename from works where salary between 100000 and 200000;

ENAME
--------------------
john

SQL> create view v2 as (select ename,companyname from works);

View created.

54
SQL> select * from v2;

ENAME COMPANYNAME
-------------------- --------------------

ajith fbc
john sbc
vijay bbc
siva fbc

SQL> alter table works rename column companyname to cname;

Table altered.

SQL> select * from works;

ENAME CNAME SALARY


-------------------- -------------------- ---------
ajith fbc 300000
john sbc 150000
vijay bbc 201000
siva fbc 400000

RESULT:
Thus the sql application1 is executed and the required output is obtained

55
SQL APPLICATION-2
EX NO:4b
DATE:

Consider the company database. The schemas are

1.employee(eno,ename,dob,gender,doj,designation,basicpay,dno)
2.department(dno,dname)
3.project(pno,pname,dno)
4.workfor(eno,pno,dateworked,intime,outtime)

SQL> create table employee(eno number,ename varchar2(20),dob varchar2(20),gender


varchar2(20),
2 doj varchar2(20),designation varchar2(20),basicpay number,dno number);

Table created.

SQL> create table department(dno number,dname varchar2(20));

Table created.

SQL> create table project(pno number,pname varchar2(20),dno number);

Table created.

SQL> create table workfor(eno number,pno number,dateworked varchar2(20),intime


varchar2(20),
2 outtime varchar2(20));

Table created.

SQL> insert into employee


values(&eno,'&ename','&dob','&gender','&doj','&designation',&basicpay,
2 &dno);
Enter value for eno: 101
Enter value for ename: ram
Enter value for dob: 18 NOV 1990
Enter value for gender: male
Enter value for doj: 2 NOV 2005

56
Enter value for designation: manager
Enter value for basicpay: 30000
old 1: insert into employee
values(&eno,'&ename','&dob','&gender','&doj','&designation',&basicpay,

new 1: insert into employee values(101,'ram','18 NOV 1990','male','2 NOV


2005','manager',30000,
Enter value for dno: 1
old 2: &dno)
new 2: 1)

1 row created.

SQL> /
Enter value for eno: 102
Enter value for ename: elango
Enter value for dob: 21 JAN 1990
Enter value for gender: male
Enter value for doj: 3 FEB 2005
Enter value for designation: team leader
Enter value for basicpay: 25000
old 1: insert into employee
values(&eno,'&ename','&dob','&gender','&doj','&designation',&basicpay,
new 1: insert into employee values(102,'elango','21 JAN 1990','male','3 FEB 2005','team
leader',25
Enter value for dno: 2
old 2: &dno)
new 2: 2)

1 row created.

SQL> /
Enter value for eno: 103
Enter value for ename: rahul
Enter value for dob: 22 FEB 1989
Enter value for gender: male
Enter value for doj: 4 MAR 2005
Enter value for designation: team member
Enter value for basicpay: 15000
old 1: insert into employee
values(&eno,'&ename','&dob','&gender','&doj','&designation',&basicpay,
new 1: insert into employee values(103,'rahul','22 FEB 1989','male','4 MAR
2005','teammember',150
Enter value for dno: 2
old 2: &dno)

57
new 2: 2)

1 row created.

SQL> /
Enter value for eno: 104
Enter value for ename: sethu
Enter value for dob: 17 MAR 1982
Enter value for gender: male
Enter value for doj: 5 SEP 2005
Enter value for designation: teammember
Enter value for basicpay: 14000
old 1: insert into employee
values(&eno,'&ename','&dob','&gender','&doj','&designation',&basicpay,
new 1: insert into employee values(104,'sethu','17 MAR 1982','male','5 SEP
2005','teammember',140
Enter value for dno: 2
old 2: &dno)
new 2: 2)

1 row created.

SQL> /
Enter value for eno: 105
Enter value for ename: ajith
Enter value for dob: 25 SEP 1985
Enter value for gender: male
Enter value for doj: 2 AUG 2005
Enter value for designation: team member
Enter value for basicpay: 16000
old 1: insert into employee
values(&eno,'&ename','&dob','&gender','&doj','&designation',&basicpay,
new 1: insert into employee values(105,'ajith','25 SEP 1985','male','2 AUG 2005','team
member',160
Enter value for dno: 3
old 2: &dno)
new 2: 3)
1 row created.

SQL> select * from employee;

ENO ENAME DOB GENDER


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

58
DOJ DESIGNATION BASICPAY DNO
-------------------- -------------------- ---------- ----------
101 ram 18 NOV 1990 male
2 NOV 2005 manager 30000 1

102 elango 21 JAN 1990 male


3 FEB 2005 team leader 25000 2

103 rahul 22 FEB 1989 male


4 MAR 2005 teammember 15000 2

ENO ENAME DOB GENDER


---------- -------------------- -------------------- --------------------
DOJ DESIGNATION BASICPAY DNO
-------------------- -------------------- ---------- ----------
104 sethu 17 MAR 1982 male
5 SEP 2005 teammember 14000 2

105 ajith 25 SEP 1985 male


2 AUG 2005 team member 16000 3

SQL> insert into department values(&dno,'&dname');


Enter value for dno: 1
Enter value for dname: it
old 1: insert into department values(&dno,'&dname')
new 1: insert into department values(1,'it')

1 row created.

SQL> /
Enter value for dno: 2
Enter value for dname: cse
old 1: insert into department values(&dno,'&dname')
new 1: insert into department values(2,'cse')

1 row created.

SQL> /
Enter value for dno: 3
Enter value for dname: ece
old 1: insert into department values(&dno,'&dname')
new 1: insert into department values(3,'ece')

59
1 row created.

SQL> select * from department;

DNO DNAME
---------- --------------------
1 it
2 cse
3 ece

SQL> insert into project values(&pno,'&pname',&dno);


Enter value for pno: 201
Enter value for pname: banking
Enter value for dno: 2
old 1: insert into project values(&pno,'&pname',&dno)
new 1: insert into project values(201,'banking',2)

1 row created.

SQL> /
Enter value for pno: 202
Enter value for pname: airline
Enter value for dno: 1
old 1: insert into project values(&pno,'&pname',&dno)
new 1: insert into project values(202,'airline',1)

1 row created.

SQL> /
Enter value for pno: 203
Enter value for pname: accounting
Enter value for dno: 3
old 1: insert into project values(&pno,'&pname',&dno)
new 1: insert into project values(203,'accounting',3)

1 row created.

SQL> select * from project;

PNO PNAME DNO


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

60
201 banking 2
202 airline 1
203 accounting 3

SQL> insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime');


Enter value for eno: 101
Enter value for pno: 201
Enter value for dateworked: 2 NOV 2009
Enter value for intime: 9 am
Enter value for outtime: 5 pm
old 1: insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime')
new 1: insert into workfor values(101,201,'2 NOV 2009','9 am','5 pm')

1 row created.

SQL> /
Enter value for eno: 102
Enter value for pno: 202
Enter value for dateworked: 2 NOV 2009
Enter value for intime: 10 am
Enter value for outtime: 5 pm
old 1: insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime')
new 1: insert into workfor values(102,202,'2 NOV 2009','10 am','5 pm')

1 row created.

SQL> /
Enter value for eno: 101
Enter value for pno: 202
Enter value for dateworked: 2 NOV 2009
Enter value for intime: 6 pm
Enter value for outtime: 11 pm
old 1: insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime')
new 1: insert into workfor values(101,202,'2 NOV 2009','6 pm','11 pm')

1 row created.

SQL> /
Enter value for eno: 103
Enter value for pno: 203
Enter value for dateworked: 4 NOV 2009
Enter value for intime: 9 am
Enter value for outtime: 5 pm

61
old 1: insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime')
new 1: insert into workfor values(103,203,'4 NOV 2009','9 am','5 pm')

1 row created.

SQL> /
Enter value for eno: 104
Enter value for pno: 201
Enter value for dateworked: 5 NOV 2009
Enter value for intime: 10 am
Enter value for outtime: 6 pm
old 1: insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime')
new 1: insert into workfor values(104,201,'5 NOV 2009','10 am','6 pm')

1 row created.

SQL> /
Enter value for eno: 105
Enter value for pno: 202
Enter value for dateworked: 6 NOV 2009
Enter value for intime: 8 am
Enter value for outtime: 4 pm
old 1: insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime')
new 1: insert into workfor values(105,202,'6 NOV 2009','8 am','4 pm')

1 row created.

SQL> select * from workfor;

ENO PNO DATEWORKED INTIME


---------- ---------- -------------------- --------------------
OUTTIME
--------------------
101 201 2 NOV 2009 9 am
5 pm

102 202 2 NOV 2009 10 am


5 pm

101 202 2 NOV 2009 6 pm


11 pm

62
ENO PNO DATEWORKED INTIME
---------- ---------- -------------------- --------------------
OUTTIME
--------------------
103 203 4 NOV 2009 9 am
5 pm

104 201 5 NOV 2009 10 am


6 pm

105 202 6 NOV 2009 8 am


4 pm

6 rows selected.

1 List the details of employees who earn a basic pay that is less than the average basic
pay of every employees.

SQL> select * from employee where basicpay < (select avg(basicpay) from employee);

ENO ENAME DOB GENDER


---------- -------------------- -------------------- --------------------
DOJ DESIGNATION BASICPAY DNO
-------------------- -------------------- ---------- ----------
103 rahul 22 FEB 1989 male
4 MAR 2005 teammember 15000 2

104 sethu 17 MAR 1982 male


5 SEP 2005 teammember 14000 2

105 ajith 25 SEP 1985 male


2 AUG 2005 team member 16000 3

2. List the dno,no_of_employees in each department.

SQL> select dno,count(eno) as no_of_employees from employee group by dno;

63
DNO NO_OF_EMPLOYEES
---------- ---------------
1 1
2 3

3 1

3.List the details of employees who have worked in the projects controlled by cse department.

SQL> select * from employee where eno in (select eno from workfor where pno in (select pno
from
2 project where dno=(select dno from department where dname='cse')));

ENO ENAME DOB GENDER


---------- -------------------- -------------------- --------------------
DOJ DESIGNATION BASICPAY DNO
-------------------- -------------------- ---------- ----------
101 ram 18 NOV 1990 male
2 NOV 2005 manager 30000 1

104 sethu 17 MAR 1982 male


5 SEP 2005 teammember 14000 2

4. List the details of employees who earned a basic pay in the range of
10000 to 20000.
SQL> select * from employee where basicpay between 10000 and 20000;

ENO ENAME DOB GENDER


---------- -------------------- -------------------- --------------------
DOJ DESIGNATION BASICPAY DNO
-------------------- -------------------- ---------- ----------
103 rahul 22 FEB 1989 male
4 MAR 2005 teammember 15000 2

104 sethu 17 MAR 1982 male


5 SEP 2005 teammember 14000 2

105 ajith 25 SEP 1985 male


2 AUG 2005 team member 16000 3

5. List the eno,ename,dno,dateworked. If the employee worked in more than one project
in a day.

64
SQL> select employee.eno,ename,dno,dateworked from employee,workfor where employee.eno
in (select eno from (select eno,dateworked from workfor group by eno,dateworked having
count(pno)>1)) and dateworked in (select dateworked from (select eno,dateworked from
workfor group by eno,dateworked having count(pno)>1));

ENO ENAME DNO DATEWORKED


---------- -------------------- ---------- --------------------
101 ram 1 2nov2009
101 ram 1 2nov2009
101 ram 1 2nov2009

Consider the book database. The schemas are

1.book(title,author,publisher,year,price,country)

SQL> create table book(title varchar2(20),author varchar2(20),publisher varchar2(20),year


number
2 ,price number,country varchar2(20));

Table created.

SQL> insert into book values('&title','&author','&publisher',&year,&price,'&country');


Enter value for title: dbms
Enter value for author: cj.date
Enter value for publisher: pearson
Enter value for year: 2001
Enter value for price: 200
Enter value for country: usa
old 1: insert into book values('&title','&author','&publisher',&year,&price,'&country')
new 1: insert into book values('dbms','cj.date','pearson',2001,200,'usa')

1 row created.

SQL> /
Enter value for title: microprocessor
Enter value for author: ramesh
Enter value for publisher: tatamagraw
Enter value for year: 2006
Enter value for price: 480
Enter value for country: uk

65
old 1: insert into book values('&title','&author','&publisher',&year,&price,'&country')
new 1: insert into book values('microprocessor','ramesh','tatamagraw',2006,480,'uk')

1 row created.

SQL> /
Enter value for title: os
Enter value for author: silberschatz
Enter value for publisher: pearson
Enter value for year: 2002
Enter value for price: 600
Enter value for country: usa
old 1: insert into book values('&title','&author','&publisher',&year,&price,'&country')
new 1: insert into book values('os','silberschatz','pearson',2002,600,'usa')

1 row created.

SQL> /
Enter value for title: oops
Enter value for author: trivedi
Enter value for publisher: pearson
Enter value for year: 2003
Enter value for price: 500
Enter value for country: india
old 1: insert into book values('&title','&author','&publisher',&year,&price,'&country')
new 1: insert into book values('oops','trivedi','pearson',2003,500,'india')

1 row created.

SQL> /
Enter value for title: ds
Enter value for author: revathi
Enter value for publisher: tatamagraw
Enter value for year: 2005
Enter value for price: 390
Enter value for country:
old 1: insert into book values('&title','&author','&publisher',&year,&price,'&country')
new 1: insert into book values('ds','revathi','tatamagraw',2005,390,'')

1 row created.

SQL> select * from book;

TITLE AUTHOR PUBLISHER YEAR

66
-------------------- -------------------- -------------------- ----------
PRICE COUNTRY
---------- --------------------
dbms cj.date pearson 2001
200 usa

microprocessor ramesh tatamagraw 2006


480 uk

os silberschatz pearson 2002


600 usa

TITLE AUTHOR PUBLISHER YEAR


-------------------- -------------------- -------------------- ----------
PRICE COUNTRY
---------- --------------------
oops trivedi pearson 2003
500 india

ds revathi tatamagraw 2005


390

1. Display the title, author, publisher of all books except those published in the year
2002,2004,2005.
SQL> select title,author,publisher from book where year not in (2002,2004,2005);

TITLE AUTHOR PUBLISHER


-------------------- -------------------- --------------------
dbms cj.date pearson
microprocessor ramesh tatamagraw
oops trivedi pearson

2.Display title, author, publisher of all books published in the year 2002 and 2003.

SQL> select title,author,publisher from book where year in (2002,2003);

TITLE AUTHOR PUBLISHER


-------------------- -------------------- --------------------
os silberschatz pearson
oops trivedi pearson

67
3.List the title of all books written by authors who do not live in INDIA.

SQL> select title from book where country not in 'india';

TITLE
--------------------
dbms
microprocessor
os

4.Get the title of all books that have price greater than atleat one book published in the year
2004.

SQL> select title from book where price>(select max(price) from book where year=2005);

TITLE
--------------------
microprocessor
os
oops

5.Find the title of books having price in the range 300 and 400.

SQL> select title from book where price between 300 and 400;

TITLE
--------------------
ds

6. Find the names of the publisher who got the total price greater than Rs.1000.
SQL> select publisher from book group by publisher having sum(price)>1000;

PUBLISHER
--------------------
pearson

Consider the bank database. The schemas are

1.branch(bname,bcity,assets)
2.customer(cname,street,ccity)
3.account(accno,balance,bname)
4.loan(loanno,bname,amount)

68
5.depositor(cname,accno)
6.borrower(cname,loanno)

SQL> create table branch(bname varchar2(20),bcity varchar2(20),assets number);

Table created.

SQL> create table customer(cname varchar2(20),street varchar2(20),ccity varchar2(20));

Table created.

SQL> create table account(accno number,balance number,bname varchar2(20));

Table created.

SQL> create table loan(loanno number,bname varchar2(20),amount number);

Table created.

SQL> create table depositor(cname varchar2(20),accno number);

Table created.

SQL> create table borrower(cname varchar2(20),loanno number);

Table created.

SQL> insert into branch values('&bname','&bcity',&assets);


Enter value for bname: perryridge
Enter value for bcity: new york
Enter value for assets: 5000000
old 1: insert into branch values('&bname','&bcity',&assets)
new 1: insert into branch values('perryridge','new york',5000000)

1 row created.

SQL> /
Enter value for bname: adyar
Enter value for bcity: chennai
Enter value for assets: 8000000
old 1: insert into branch values('&bname','&bcity',&assets)
new 1: insert into branch values('adyar','chennai',8000000)

69
1 row created.

SQL> /
Enter value for bname: avadi
Enter value for bcity: chennai
Enter value for assets: 6000000
old 1: insert into branch values('&bname','&bcity',&assets)
new 1: insert into branch values('avadi','chennai',6000000)

1 row created.

SQL> /
Enter value for bname: ashoknagar
Enter value for bcity: bangalore
Enter value for assets: 7000000
old 1: insert into branch values('&bname','&bcity',&assets)
new 1: insert into branch values('ashoknagar','bangalore',7000000)

1 row created.

SQL> select * from branch;

BNAME BCITY ASSETS


-------------------- -------------------- ----------
perryridge new york 5000000
adyar chennai 8000000
avadi chennai 6000000
ashoknagar bangalore 7000000

SQL> insert into customer values('&cname','&street','&ccity');


Enter value for cname: yabesh
Enter value for street: nehru
Enter value for ccity: chennai
old 1: insert into customer values('&cname','&street','&ccity')
new 1: insert into customer values('yabesh','nehru','chennai')

1 row created.

SQL> /

70
Enter value for cname: siva
Enter value for street: gandi
Enter value for ccity: bangalore
old 1: insert into customer values('&cname','&street','&ccity')
new 1: insert into customer values('siva','gandi','bangalore')

1 row created.

SQL> /
Enter value for cname: loga
Enter value for street: netaji
Enter value for ccity: madurai
old 1: insert into customer values('&cname','&street','&ccity')
new 1: insert into customer values('loga','netaji','madurai')

1 row created.

SQL> /
Enter value for cname: mahesh
Enter value for street: rajiv
Enter value for ccity: chennai
old 1: insert into customer values('&cname','&street','&ccity')
new 1: insert into customer values('mahesh','rajiv','chennai')

1 row created.

SQL> select * from customer;

CNAME STREET CCITY


-------------------- -------------------- --------------------
yabesh nehru chennai
siva gandi bangalore
loga netaji madurai
mahesh rajiv chennai

SQL> insert into account values(&accno,&balance,'&bname');


Enter value for accno: 101
Enter value for balance: 40000
Enter value for bname: perryridge
old 1: insert into account values(&accno,&balance,'&bname')
new 1: insert into account values(101,40000,'perryridge')

1 row created.

SQL> /

71
Enter value for accno: 102
Enter value for balance: 50000
Enter value for bname: adyar
old 1: insert into account values(&accno,&balance,'&bname')
new 1: insert into account values(102,50000,'adyar')

1 row created.

SQL> /
Enter value for accno: 103
Enter value for balance: 60000
Enter value for bname: ashoknagar
old 1: insert into account values(&accno,&balance,'&bname')
new 1: insert into account values(103,60000,'ashoknagar')

1 row created.

SQL> select * from account;

ACCNO BALANCE BNAME


---------- ---------- --------------------
101 40000 perryridge
102 50000 adyar
103 60000 ashoknagar

SQL> insert into loan values(&loanno,'&bname',&amount);


Enter value for loanno: 201
Enter value for bname: adyar
Enter value for amount: 800
old 1: insert into loan values(&loanno,'&bname',&amount)
new 1: insert into loan values(201,'adyar',800)

1 row created.

SQL> /
Enter value for loanno: 202
Enter value for bname: avadi
Enter value for amount: 15000
old 1: insert into loan values(&loanno,'&bname',&amount)
new 1: insert into loan values(202,'avadi',15000)

1 row created.

SQL> /
Enter value for loanno: 203
Enter value for bname: perryridge

72
Enter value for amount: 1000
old 1: insert into loan values(&loanno,'&bname',&amount)
new 1: insert into loan values(203,'perryridge',1000)

1 row created.

SQL> select * from loan;

LOANNO BNAME AMOUNT


---------- -------------------- ----------
201 adyar 800
202 avadi 15000
203 perryridge 1000

SQL> insert into depositor values('&cname',&accno);


Enter value for cname: yabesh
Enter value for accno: 101
old 1: insert into depositor values('&cname',&accno)
new 1: insert into depositor values('yabesh',101)

1 row created.

SQL> /
Enter value for cname: siva
Enter value for accno: 102
old 1: insert into depositor values('&cname',&accno)
new 1: insert into depositor values('siva',102)

1 row created.

SQL> /
Enter value for cname: mahesh
Enter value for accno: 103
old 1: insert into depositor values('&cname',&accno)
new 1: insert into depositor values('mahesh',103)

1 row created.

SQL> select * from depositor;

CNAME ACCNO
-------------------- ----------
yabesh 101
siva 102
mahesh 103

73
SQL> insert into borrower values('&cname',&loanno);
Enter value for cname: yabesh
Enter value for loanno: 201
old 1: insert into borrower values('&cname',&loanno)
new 1: insert into borrower values('yabesh',201)

1 row created.

SQL> /
Enter value for cname: siva
Enter value for loanno: 202
old 1: insert into borrower values('&cname',&loanno)
new 1: insert into borrower values('siva',202)

1 row created.

SQL> /
Enter value for cname: loga
Enter value for loanno: 203
old 1: insert into borrower values('&cname',&loanno)
new 1: insert into borrower values('loga',203)

1 row created.

SQL> select * from borrower;

CNAME LOANNO
-------------------- ----------
yabesh 201
siva 202
loga 203

1.Find the customer names of all loans of over Rs.1200.

SQL> select cname from borrower where loanno in (select loanno from loan where
2 amount>1200);

CNAME
--------------------
siva

SQL> select cname from borrower join loan on loan.loanno=borrower.loanno where


amount>1200;

74
CNAME
--------------------
siva

2.Find the names of all customers who have more than Rs.1200 in their account.

SQL> select cname from depositor where accno in (select accno from account where
balance>1200);

CNAME
--------------------
yabesh
siva
mahesh

SQL> select cname from depositor join account on account.accno=depositor.accno where


2 balance>1200;

CNAME
--------------------
yabesh
siva
mahesh

3.Find the names of all customers who have either a loan or an account or both.

SQL> select cname from depositor union select cname from borrower;

CNAME
--------------------
loga
mahesh
siva
yabesh

4.Find the names of all customers who have both loan and account.
SQL> select cname from depositor intersect select cname from borrower;

CNAME
--------------------
siva
yabesh

75
5.Find the names of all customers who have only loan.
SQL> select cname from borrower minus select cname from depositor;

CNAME
--------------------

loga

6.Find the names of all customers who have only account.


SQL> select cname from depositor minus select cname from borrower;

CNAME
--------------------
mahesh

7.Find the names of all customers who have loan at perryridge bank.

SQL> select cname from borrower join loan on borrower.loanno=loan.loanno where


2 bname='perryridge';

CNAME
--------------------
loga

76
RESULT:
Thus the sql application2 is executed and the required output is obtained

VIEWS
EX NO: 5
DATE:

AIM
To create views for the table and perform operations on it.

DEFINITION

A view is an object that gives the user the logical view of data from the underlying table.
Any relation that is not part of the logical model but is made visible to the user as a virtual
relation is called a view. They are generally used to avoid duplication of data.

Views are created for the following reasons,


• Data simplicity
• To provide data security
• Structural simplicity (because view contains only limited number of rows and colmns)

TYPES OF VIEWS

• Updatable views – Allow data manipulation


• Read only views – Do not allow data manipulation

CREATION OF VIEWS - INSERTION, DELETION, UPDATION

SQL> create table emp(eno number(1),ename varchar2(20),bpay number(6),dno number(2));

Table created.

SQL> insert into emp values(&eno,'&ename',&bpay,&dno);


Enter value for eno: 1
Enter value for ename: Priya
Enter value for bpay: 12000
Enter value for dno: 1
old 1: insert into emp values(&eno,'&ename',&bpay,&dno)
new 1: insert into emp values(1,'Priya',12000,1)

1 row created.

77
SQL> /
Enter value for eno: 2
Enter value for ename: Helen
Enter value for bpay: 20000

Enter value for dno: 1


old 1: insert into emp values(&eno,'&ename',&bpay,&dno)
new 1: insert into emp values(2,'Helen',20000,1)

1 row created.

SQL> /
Enter value for eno: 3
Enter value for ename: Gayathri
Enter value for bpay: 35000
Enter value for dno: 2
old 1: insert into emp values(&eno,'&ename',&bpay,&dno)
new 1: insert into emp values(3,'Gayathri',35000,2)

1 row created.

SQL> /
Enter value for eno: 4
Enter value for ename: Swetha
Enter value for bpay: 16000
Enter value for dno: 3
old 1: insert into emp values(&eno,'&ename',&bpay,&dno)
new 1: insert into emp values(4,'Swetha',16000,3)

1 row created.

SQL> /
Enter value for eno: 5
Enter value for ename: Rohan
Enter value for bpay: 36000
Enter value for dno: 2
old 1: insert into emp values(&eno,'&ename',&bpay,&dno)
new 1: insert into emp values(5,'Rohan',36000,2)

1 row created.

SQL> select * from emp;

ENO ENAME BPAY DNO


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

78
1 Priya 12000 1
2 Helen 20000 1
3 Gayathri 35000 2
4 Swetha 16000 3
5 Rohan 36000 2

SQL> create table dept(dno number(1),dname varchar2(20));

Table created.

SQL> insert into dept values(&dno,'&dname');


Enter value for dno: 1
Enter value for dname: IT
old 1: insert into dept values(&dno,'&dname')
new 1: insert into dept values(1,'IT')

1 row created.

SQL> /
Enter value for dno: 2
Enter value for dname: CSE
old 1: insert into dept values(&dno,'&dname')
new 1: insert into dept values(2,'CSE')

1 row created.

SQL> /
Enter value for dno: 3
Enter value for dname: ECE
old 1: insert into dept values(&dno,'&dname')
new 1: insert into dept values(3,'ECE')

1 row created.

SQL> /
Enter value for dno: 4
Enter value for dname: EEE
old 1: insert into dept values(&dno,'&dname')
new 1: insert into dept values(4,'EEE')

1 row created.

SQL> select * from dept;

DNO DNAME
--------- --------------------

79
1 IT
2 CSE
3 ECE
4 EEE

SQL> create view view1 as select * from emp where dno=1;

View created.

SQL> select * from view1;

ENO ENAME BPAY DNO


--------- -------------------- --------- ---------
1 Priya 12000 1
2 Helen 20000 1

SQL> insert into view1 values(6,'Joe',50000,4);

1 row created.

SQL> select * from view1;

ENO ENAME BPAY DNO


--------- -------------------- --------- ---------
1 Priya 12000 1
2 Helen 20000 1

SQL> select * from emp;

ENO ENAME BPAY DNO


--------- -------------------- --------- ---------
1 Priya 12000 1
2 Helen 20000 1
3 Gayathri 35000 2
4 Swetha 16000 3
5 Rohan 36000 2
6 Joe 50000 4

6 rows selected.

SQL> update view1 set bpay=40000 where eno=1;

1 row updated.

SQL> select * from view1;

80
ENO ENAME BPAY DNO
--------- -------------------- --------- ---------
1 Priya 40000 1
2 Helen 20000 1

SQL> delete from view1 where ename='Helen';

1 row deleted.

SQL> select * from view1;

ENO ENAME BPAY DNO


--------- -------------------- --------- ---------
1 Priya 40000 1

SQL> select * from emp;

ENO ENAME BPAY DNO


--------- -------------------- --------- ---------
1 Priya 40000 1
3 Gayathri 35000 2
4 Swetha 16000 3
5 Rohan 36000 2
6 Joe 50000 4

CREATING VIEW WITH DISTINCT KEYWORD:

SQL> create view view2(deptno) as select distinct(dno) from emp;

View created.

SQL> select * from view2;

DEPTNO
---------
1
2
3
4

SQL> update view2 set deptno =11 where deptno=2;


update vnis2 set deptno =11 where deptno=2
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

81
SQL> insert into view2 values(11);
insert into vnis2 values(11)
*
ERROR at line 1:

ORA-01732: data manipulation operation not legal on this view

SQL> delete from view2 where deptno=1;


delete from vnis2 where deptno=1
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

CREATING VIEW WITH AGGREGATE FUNCTIONS:

SQL> create view view3 as select dno,max(bpay) from emp group by dno;
create view view3 as select dno,max(bpay) from emp group by dno
*
ERROR at line 1:
ORA-00998: must name this expression with a column alias

SQL> create view view3(dno,maximum) as select dno,max(bpay) from emp group by dno;

View created.

SQL> select * from view3;

DNO MAXIMUM
--------- ---------
1 40000
2 36000
3 16000
4 50000

SQL> insert into view3 values(5,20000);


insert into view3 values(5,20000)
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

SQL> delete from view3 where dno=1;


delete from view3 where dno=1

82
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

SQL> update view3 set maximum=90000 where dno=1;


update view3 set maximum=90000 where dno=1
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

SQL> select * from e234;

ENO ENAME PAY DNO


--------- -------------------- --------- ---------
1x 12000 1
2y 10000 1
3z 12000 2
4a 3456 2
5c 2345 3

SQL> create view v45 as select dno,count(eno),sum(pay) from e234 group by dno;
create view v45 as select dno,count(eno),sum(pay) from e234 group by dno
*
ERROR at line 1:
ORA-00998: must name this expression with a column alias

SQL> create view v45(dnum,no_of_emp,tot_pay) as select dno,count(eno),sum(pay) from e234


group by dno;

View created.

SQL> select * from v45;

DNUM NO_OF_EMP TOT_PAY


--------- --------- ---------
1 2 22000
2 2 15456
3 1 2345

SQL> update v45 set dnum=12 where dnum=1;


update v45 set dnum=12 where dnum=1
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

83
SQL> select * from v45;

DNUM NO_OF_EMP TOT_PAY


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

1 2 22000
2 2 15456
3 1 2345

SQL> select max(tot_pay) from v45;

MAX(TOT_PAY)
------------
22000

SQL> update v45 set dnum=11 where tot_pay=22000;


update v45 set dnum=11 where tot_pay=22000
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

SQL> delete from v45 where dnum=1;


delete from v45 where dnum=1
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

CREATING VIEW ON TWO TABLES:

SQL> create view view4 as select ename,dname from emp,dept where emp.dno=dept.dno;

View created.

SQL> select * from view4;

ENAME DNAME
-------------------- --------------------
Priya IT
Daisy IT
Gayathri CSE
Rohan CSE
Swetha ECE

84
Joe EEE

6 rows selected.

SQL> insert into view4 values('Frank','IT');

insert into view4 values('Frank','IT')


*
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-preserved table

SQL> delete from view4 where ename='Priya';


delete from view4 where ename='Priya'
*
ERROR at line 1:
ORA-01752: cannot delete from view without exactly one key-preserved table

SQL> update view4 set dname='ECE' where ename='Joe';


update view4 set dname='ECE' where ename='Joe'
*
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-preserved table

85
RESULT:

Thus views were studied and implemented.

DATACONTROL LANGUAGE COMMANDS

EX NO: 6
DATE:

AIM

To study the various data language commands (DCL) and implement them on the
database.

DESCRIPTION

The DCL language is used for controlling the access to the table and hence securing the
database. This language is used to provide certain priveleges to a particular user. Priveleges are
rights to be allocated. The privilege commands are namely,
• Grant
• Revoke
The various priveleges that can be granted or revoked are,
• Select
• Insert
• Delete
• Update
• References
• Execute
• All

GRANT COMMAND: It is used to create users and grant access to the database. It requires
database administrator (DBA) privilege, except that a user can change their password. A user can
grant access to their database objects to other users.

REVOKE COMMAND: Using this command , the DBA can revoke the granted database
priveleges from the user.

SYNTAX

GRANT COMMAND

Grant < database_priv [database_priv…..] > to <user_name> identified by <password>


[,<password…..];

86
Grant <object_priv> | All on <object> to <user | public> [ With Grant Option ];

REVOKE COMMAND

Revoke <database_priv> from <user [, user ] >;

Revoke <object_priv> on <object> from < user | public >;

<database_priv> -- Specifies the system level priveleges to be granted to the users or roles. This
includes create / alter / delete any object of the system.
<object_priv> -- Specifies the actions such as alter / delete / insert / references / execute / select /
update for tables.
<all> -- Indicates all the priveleges.
[ With Grant Option ] – Allows the recipient user to give further grants on the objects.
The priveleges can be granted to different users by specifying their names or to all users
by using the “Public” option.

EXAMPLES

Consider the following tables namely “DEPARTMENTS” and “EMPLOYEES”


Their schemas are as follows ,
Departments ( dept _no , dept_ name , dept_location );
Employees ( emp_id , emp_name , emp_salary );

SQL> Grant all on employees to abcde;

Grant succeeded.

SQL> Grant select , update , insert on departments to abcde with grant option;

Grant succeeded.

SQL> Revoke all on employees from abcde;

Revoke succeeded.

SQL> Revoke select , update , insert on departments from abcde;

Revoke succeeded.

87
RESULT

Thus all the commands were executed and their output were verified.

PROCEDURAL LANGUAGE/ STRUCTURAL QUERY


LANGUAGE

EX NO: 7
DATE:

AIM
To implement various programs using PL/SQL language.

PROGRAMS

TO DISPLAY HELLO MESSAGE


SQL> set serveroutput on;
SQL> declare
2 a varchar2(20);
3 begin
4 a:='Hello';
5 dbms_output.put_line(a);
6 end;
7 /
Hello

PL/SQL procedure successfully completed.

TO INPUT A VALUE FROM THE USER AND DISPLAY IT


SQL> set serveroutput on;
SQL> declare
2 a varchar2(20);
3 begin
4 a:=&a;
5 dbms_output.put_line(a);
6 end;
7 /
Enter value for a: 5
old 4: a:=&a;
new 4: a:=5;
5

88
PL/SQL procedure successfully completed.

GREATEST OF TWO NUMBERS


SQL> set serveroutput on;

SQL> declare
2 a number(7);
3 b number(7);
4 begin
5 a:=&a;
6 b:=&b;
7 if(a>b) then
8 dbms_output.put_line (' The grerater of the two is'|| a);
9 else
10 dbms_output.put_line (' The grerater of the two is'|| b);
11 end if;
12 end;
13 /
Enter value for a: 5
old 5: a:=&a;
new 5: a:=5;
Enter value for b: 9
old 6: b:=&b;
new 6: b:=9;
The grerater of the two is9

PL/SQL procedure successfully completed.

GREATEST OF THREE NUMBERS

SQL> set serveroutput on;


SQL> declare
2 a number(7);
3 b number(7);
4 c number(7);
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
9 if(a>b and a>c) then
10 dbms_output.put_line (' The greatest of the three is ' || a);
11 else if (b>c) then
12 dbms_output.put_line (' The greatest of the three is ' || b);
13 else
14 dbms_output.put_line (' The greatest of the three is ' || c);

89
15 end if;
16 end if;
17 end;
18 /
Enter value for a: 5

old 6: a:=&a;
new 6: a:=5;
Enter value for b: 7
old 7: b:=&b;
new 7: b:=7;
Enter value for c: 1
old 8: c:=&c;
new 8: c:=1;
The greatest of the three is 7

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 5 USING SIMPLE LOOP


SQL> set serveroutput on;
SQL> declare
2 a number:=1;
3 begin
4 loop
5 dbms_output.put_line (a);
6 a:=a+1;
7 exit when a>5;
8 end loop;
9 end;
10 /
1
2
3
4
5

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 4 USING WHILE LOOP


SQL> set serveroutput on;
SQL> declare
2 a number:=1;
3 begin
4 while(a<5)
5 loop
6 dbms_output.put_line (a);

90
7 a:=a+1;
8 end loop;
9 end;
10 /
1

2
3
4

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 5 USING FOR LOOP


SQL> set serveroutput on;
SQL> declare
2 a number:=1;
3 begin
4 for a in 1..5
5 loop
6 dbms_output.put_line (a);
7 end loop;
8 end;
9 /
1
2
3
4
5

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 5 IN REVERSE ORDER USING FOR LOOP


SQL> set serveroutput on;
SQL> declare
2 a number:=1;
3 begin
4 for a in reverse 1..5
5 loop
6 dbms_output.put_line (a);
7 end loop;
8 end;
9 /
5
4
3
2

91
1

PL/SQL procedure successfully completed.

TO CALCULATE AREA OF CIRCLE

SQL> set serveroutput on;


SQL> declare
2 pi constant number(4,2):=3.14;
3 a number(20);
4 r number(20);
5 begin
6 r:=&r;
7 a:= pi* power(r,2);
8 dbms_output.put_line (' The area of circle is ' || a);
9 end;
10 /
Enter value for r: 2
old 6: r:=&r;
new 6: r:=2;
The area of circle is 13

PL/SQL procedure successfully completed.

TO CREATE SACCOUNT TABLE


SQL> create table saccount ( accno number(5), name varchar2(20), bal number(10));

Table created.

SQL> insert into saccount values ( 1,'mala',20000);

1 row created.

SQL> insert into saccount values (2,'kala',30000);

1 row created.

SQL> select * from saccount;

ACCNO NAME BAL


--------- -------------------- ---------
1 mala 20000
2 kala 30000

SQL> set serveroutput on;


SQL> declare

92
2 a_bal number(7);
3 a_no varchar2(20);
4 debit number(7):=2000;
5 minamt number(7):=500;
6 begin

7 a_no:=&a_no;
8 select bal into a_bal from saccount where accno= a_no;
9 a_bal:= a_bal-debit;
10 if (a_bal > minamt) then
11 update saccount set bal=bal-debit where accno=a_no;
12 end if;
13 end;
14
15 /
Enter value for a_no: 1
old 7: a_no:=&a_no;
new 7: a_no:=1;

PL/SQL procedure successfully completed.

SQL> select * from saccount;

ACCNO NAME BAL


--------- -------------------- ---------
1 mala 18000
2 kala 30000

TO CREATE TABLE SROUTES


SQL> create table sroutes ( rno number(5), origin varchar2(20), destination varchar2(20), fare
numbe
r(10), distance number(10));

Table created.

SQL> insert into sroutes values ( 2, 'chennai', 'dindugal', 400,230);

1 row created.

SQL> insert into sroutes values ( 3, 'chennai', 'madurai', 250,300);

93
1 row created.

SQL> insert into sroutes values ( 6, 'thanjavur', 'palani', 350,370);

1 row created.

SQL> select * from sroutes;

RNO ORIGIN DESTINATION FARE DISTANCE


--------- -------------------- -------------------- --------- ---------
2 chennai dindugal 400 230
3 chennai madurai 250 300
6 thanjavur palani 350 370

SQL> set serveroutput on;


SQL> declare
2 route sroutes.rno % type;
3 fares sroutes.fare % type;
4 dist sroutes.distance % type;
5 begin
6 route:=&route;
7 select fare, distance into fares , dist from sroutes where rno=route;
8 if (dist < 250) then
9 update sroutes set fare=300 where rno=route;
10 else if dist between 250 and 370 then
11 update sroutes set fare=400 where rno=route;
12 else if (dist > 400) then
13 dbms_output.put_line('Sorry');
14 end if;
15 end if;
16 end if;
17 end;
18 /
Enter value for route: 3
old 6: route:=&route;
new 6: route:=3;

PL/SQL procedure successfully completed.

SQL> select * from sroutes;

RNO ORIGIN DESTINATION FARE DISTANCE


--------- -------------------- -------------------- --------- ---------
2 chennai dindugal 400 230

94
3 chennai madurai 400 300
6 thanjavur palani 350 370

TO CREATE SCA LCULATE TABLE


SQL> create table scalculate ( radius number(3), area number(5,2));

Table created.

SQL> desc scalculate;


Name Null? Type
----------------------------------------------------- -------- ------------------------------------
RADIUS NUMBER(3)
AREA NUMBER(5,2)

SQL> set serveroutput on;


SQL> declare
2 pi constant number(4,2):=3.14;
3 area number(5,2);
4 radius number(3);
5 begin
6 radius:=3;
7 while (radius <=7)
8 loop
9 area:= pi* power(radius,2);
10 insert into scalculate values (radius,area);
11 radius:=radius+1;
12 end loop;
13 end;
14 /

PL/SQL procedure successfully completed.

SQL> select * from scalculate;

RADIUS AREA
--------- ---------
3 28.26
4 50.24
5 78.5
6 113.04
7 153.86

TO CALCULATE FACTORIAL OF A GIVEN NUMBER


SQL> set serveroutput on;
SQL> declare
2 f number(4):=1;

95
3 i number(4);
4 begin
5 i:=&i;
6 while(i>=1)
7 loop

8 f:=f*i;
9 i:=i-1;
10 end loop;
11 dbms_output.put_line('The value is ' || f);
12 end;
13 /
Enter value for i: 5
old 5: i:=&i;
new 5: i:=5;
The value is 120

PL/SQL procedure successfully completed.

96
RESULT

Thus the various programs were implemented and their output was verified.

GOTO AND EXCEPTIONS


EX NO: 8
DATE:

AIM
To perform goto and exception handling mechanisms.

GOTO COMMAND

PURPOSE
The GOTO statement changes the flow of control within a PL/SQL block. The entry
point into such a block of code is marked using the tags. This statement makes use of the
<<user defined name>> to jump into the block of code for execution.
SYNTAX
GOTO <code block name> <<user defined name>>
CREATING THE TABLES ‘SPRODUCTMASTERS’ AND ‘SOLDPRICES’
SQL> create table sproductmasters( pno varchar2(10), sellprice number(10));

Table created.

SQL> insert into sproductmasters values('p1',3200);

1 row created.

SQL> insert into sproductmasters values('p2',4000);

1 row created.

SQL> insert into sproductmasters values('p3',6000);

1 row created.

SQL> select * from sproductmasters;

PNO SELLPRICE
---------- ---------
p1 3200
p2 4000
p3 6000

97
SQL> create table soldprices( pno varchar2(10), datechange varchar2(20),soldprices
number(10));

Table created.

OPERATION TO BE PERFORMED
If the price of a product is less than 4000 then change to 4000. The price change is to be
recorded on the old price table along with the product number and the date on which the price
was last changed using PL/SQL.

PROGRAM

1 declare
2 sellingprice number(10,2);
3 begin
4 select sellprice into sellingprice from sproductmasters where pno='p1';
5 if sellingprice < 4000
6 then
7 goto add_old_price;
8 else
9 dbms_output.put_line(' Current price is '|| sellingprice);
10 end if;
11 <<add_old_price>>
12 update sproductmasters set sellprice = 4000 where pno='p1';
13 insert into soldprices values('p1',sysdate,sellingprice);
14 dbms_output.put_line(' The new price of p1 is 4000 ');
15 end;
16 /

PROGRAM OUTPUT

The new price of p1 is 4000

PL/SQL procedure successfully completed.

DISPLAYING THE CONTENTS OF ‘SOLDPRICES’ TABLE

SQL> select * from soldprices;

PNO DATECHANGE SOLDPRICES


---------- -------------------- ----------
p1 27-AUG-08 3200

EXCEPTIONS

98
Exceptions are error handling mechanisms. They are of 2 types,
• Pre – defined exceptions
• User – defined exceptions

TO CREATE THE TABLE ‘SSITEMS’ ON WHICH THE EXCEPTION HANDLING


MECHANISMS ARE GOING TO BE PERFORMED

SQL> create table ssitems( id number(10), quantity number(10), actualprice number(10));

Table created.

SQL> insert into ssitems values(100,5,5000);

1 row created.

SQL> insert into ssitems values(101,6,9000);

1 row created.

SQL> insert into ssitems values(102,4,4000);

1 row created.

SQL> insert into ssitems values(103,2,2000);

1 row created.

SQL> select * from ssitems;

ID QUANTITY ACTUALPRICE
--------- --------- -----------
100 5 5000
101 6 9000
102 4 4000
103 2 2000

PRE – DEFINED EXCEPTIONS

SYNTAX

begin
sequence of statements;
exception
when < exception name > then

99
sequence of statements;
end;

EXAMPLE USING PL/SQL

SQL> set serveroutput on;


SQL> declare
2 price ssitems.actualprice % type;
3 begin
4 select actualprice into price from ssitems where quantity=10;
5 exception
6 when no_data_found then
7 dbms_output.put_line ('ssitems missing');
8 end;
9 /
ssitems missing

PL/SQL procedure successfully completed.

DISPLAYING THE UPDATED TABLE

SQL> select * from ssitems;

ID QUANTITY ACTUALPRICE
--------- --------- -----------
100 5 5000
101 6 9000
102 4 4000
103 2 2000

USER DEFINED EXCEPTONS

SYNTAX
declare
< exception name > exception;
begin
sequence of statements;
raise < exception name >;
exception
when < exception name > then
sequence of statements;
end;

EXAMPLE USING PL/SQL

100
SQL> set serveroutput on;
SQL> declare
2 zero_price exception;
3 price number(8,2);
4 begin

5 select actualprice into price from ssitems where id=103;


6 if price=0 or price is null then
7 raise zero_price;
8 end if;
9 exception
10 when zero_price then
11 dbms_output.put_line('Failed zero price');
12 end;
13 /

PL/SQL procedure successfully completed.

DISPLAYING THE UPDATED TABLE

SQL> select * from ssitems;

ID QUANTITY ACTUALPRICE
--------- --------- -----------
100 5 5000
101 6 9000
102 4 4000
103 2 2000

101
RESULT

Thus the goto statement and exceptions were executed and their respective output’s were
verified.

TRANSACTION CONTROL LANGUAGE


EX NO: 9
DATE:

AIM

To study the various TCL commands namely commit, rollback and savepoint.

DESCRIPTION

COMMIT: This command saves all the transactions to the database since the last commit or
rollback command.
ROLLBACK: This command is used to undo the transactions that have not been already saved
to the database.It can be used to undo transactions since the last commit or rollback command.
SAVEPOINT: This command is a point in transaction that you can roll the transaction back to
without rolling back the entire transmission.

CREATE THE TABLE ‘ITYR’

SQL> create table ityr(ename varchar(15),eid number(5),salary number(5));

Table created.

PROGRAM

SQL> set serveroutput on;


SQL> declare
2 t number(6);
3 n number(6);
4 s number(6);
5 begin
6 insert into ityr values('a',100,19000);
7 insert into ityr values('b',102,1000);
8 s:=&s;
9 n:=&n;
10 savepoint a;
11 update ityr set salary=salary+2000 where eid=s;
12 update ityr set salary=salary+1500 where eid=n;
13 select sum(salary) into t from ityr;

102
14 if(t>20000)
15 then
16 rollback to a;
17 else
18 dbms_output.put_line('no updation');

19 end if;
20 end ;
21 /
Enter value for s: 100
old 8: s:=&s;
new 8: s:=100;
Enter value for n: 102
old 9: n:=&n;
new 9: n:=102;

PL/SQL procedure successfully completed.

DISPLAYING THE UPDATED TABLE

SQL> select * from ityr;

ENAME EID SALARY


--------------- ---------- ----------
a 100 19000
b 102 1000

SQL> create table tyu(name varchar2(20));


Table created.

SQL> insert into tyu values('dfg');


1 row created.

Select*from tyu;
NAME
---------
dfg

SQL> rollback;
Rollback complete.

SQL> select * from tyu;


no rows selected

SQL> insert into tyu values('&name');


Enter value for name: xyz

103
old 1: insert into tyu values('&name')
new 1: insert into tyu values('xyz')
1 row created.
SQL> select * from tyu;
NAME

--------------------
xyz
wert
hjk

SQL> savepoint u;

Savepoint created.

SQL> delete from tyu where name='xyz';

1 row deleted.
Select*from tyu;

NAME
--------------------
wert
hjk

SQL> rollback to u;

Rollback complete.

SQL> select * from tyu;

NAME
--------------------
xyz
wert
hjk

104
RESULT

Thus the various commands were executed and the output was verified.

CURSORS
EX NO: 10
DATE:

AIM
To write PL/SQL blocks that implement the concept of for the 3 types of cursors namely,
• Cursor for loop
• Explicit cursor
• Implicit cursor

TO CREATE THE TABLE ‘SSEMPP’

SQL> create table ssempp( eid number(10), ename varchar2(20), job varchar2(20), sal number
(10),dnonumber(5));

Table created.

SQL> insert into ssempp values(1,'nala','lecturer',34000,11);

1 row created.

SQL> insert into ssempp values(2,'kala',' seniorlecturer',20000,12);

1 row created.

SQL> insert into ssempp values(5,'ajay','lecturer',30000,11);

1 row created.

SQL> insert into ssempp values(6,'vijay','lecturer',18000,11);

1 row created.

SQL> insert into ssempp values(3,'nila','professor',60000,12);

1 row created.

SQL> select * from ssempp;

105
EID ENAME JOB SAL DNO
--------- -------------------- -------------------- --------- ---------
1 nala lecturer 34000 11
2 kala seniorlecturer 20000 12

5 ajay lecturer 30000 11


6 vijay lecturer 18000 11
3 nila professor 60000 12

TO WRITE A PL/SQL BLOCK TO DISPLAY THE EMPOYEE ID AND EMPLOYEE


NAME USING CURSOR FOR LOOP

SQL> set serveroutput on;


SQL> declare
2 begin
3 for emy in (select eid,ename from ssempp)
4 loop
5 dbms_output.put_line('Employee id and employee name are '|| emy.eid ‘and’|| emy.ename);
6 end loop;
7 end;
8 /
Employee id and employee name are 1 and nala
Employee id and employee name are 2 and kala
Employee id and employee name are 5 and ajay
Employee id and employee name are 6 and vijay
Employee id and employee name are 3 and nila

PL/SQL procedure successfully completed.

TO WRITE A PL/SQL BLOCK TO UPDATE THE SALARY OF ALL EMPLOYEES


WHERE DEPARTMENT NO IS 11 BY 5000 USING CURSOR FOR LOOP AND TO
DISPLAY THE UPDATED TABLE

SQL> set serveroutput on;


SQL> declare
2 cursor cem is select eid,ename,sal,dno from ssempp where dno=11;
3 begin
4 --open cem;
5 for rem in cem
6 loop
7 update ssempp set sal=rem.sal+5000 where eid=rem.eid;
8 end loop;
9 --close cem;
10 end;
11 /

106
PL/SQL procedure successfully completed.

SQL> select * from ssempp;

EID ENAME JOB SAL DNO


--------- -------------------- -------------------- --------- ---------
1 nala lecturer 39000 11
2 kala seniorlecturer 20000 12
5 ajay lecturer 35000 11
6 vijay lecturer 23000 11
3 nila professor 60000 12

TO WRITE A PL/SQL BLOCK TO DISPLAY THE EMPLOYEE ID AND EMPLOYEE


NAME WHERE DEPARTMENT NUMBER IS 11 USING EXPLICIT CURSORS

1 declare
2 cursor cenl is select eid,sal from ssempp where dno=11;
3 ecode ssempp.eid%type;
4 esal empp.sal%type;
5 begin
6 open cenl;
7 loop
8 fetch cenl into ecode,esal;
9 exit when cenl%notfound;
10 dbms_output.put_line(' Employee code and employee salary are' || ecode ‘and’|| esal);
11 end loop;
12 close cenl;
13* end;
SQL> /
Employee code and employee salary are 1 and 39000
Employee code and employee salary are 5 and 35000
Employee code and employee salary are 6 and 23000

PL/SQL procedure successfully completed.

TO WRITE A PL/SQL BLOCK TO UPDATE THE SALARY BY 5000 WHERE THE


JOB IS LECTURER , TO CHECK IF UPDATES ARE MADE USING IMPLICIT
CURSORS AND TO DISPLAY THE UPDATED TABLE

SQL> declare
2 county number;
3 begin
4 update ssempp set sal=sal+10000 where job='lecturer';
5 county:= sql%rowcount;

107
6 if county > 0 then
7 dbms_output.put_line('The number of rows are '|| county);
8 end if;
9 if sql %found then
10 dbms_output.put_line('Employee record modification successful');

11 else if sql%notfound then


12 dbms_output.put_line('Employee record is not found');
13 end if;
14 end if;
15 end;
16 /
The number of rows are 3

Employee record modification successful

PL/SQL procedure successfully completed.

SQL> select * from ssempp;

EID ENAME JOB SAL DNO


--------- -------------------- -------------------- --------- ---------
1 nala lecturer 44000 11
2 kala seniorlecturer 20000 12
5 ajay lecturer 40000 11
6 vijay lecturer 28000 11
3 nila professor 60000 12

RESULT

108
Thus the various operations were performed on the table using cursors and the output was
verified.

TRIGGERS
EX NO: 11
DATE:

AIM

To study and implement the concept of triggers.

DEFINITION

A trigger is a statement that is executed automatically by the system as a sideeffect of a


modification to the database. The parts of a trigger are,
• Trigger statement: Specifies the DML statements and fires the trigger body. It also
specifies the table to which the trigger is associated.
• Trigger body or trigger action: It is a PL/SQL block that is executed when the triggering
statement is used.
• Trigger restriction: Restrictions on the trigger can be achieved

The different uses of triggers are as follows,


• To generate data automatically
• To enforce complex integrity constraints
• To customize complex securing authorizations
• To maintain the replicate table
• To audit data modifications

TYPES OF TRIGGERS

The various types of triggers are as follows,


• Before: It fires the trigger before executing the trigger statement.
• After: It fires the trigger after executing the trigger statement.
• For each row: It specifies that the trigger fires once per row.
• For each statement: This is the default trigger that is invoked. It specifies that the trigger
fires once per statement.

VARIABLES USED IN TRIGGERS

• :new

109
• :old

These two variables retain the new and old values of the column updated in the database. The
values in these variables can be used in the database triggers for data manipulation

SYNTAX

create or replace trigger triggername [before/after] {DML statements}


on [tablename] [for each row/statement]
begin
-------------------------
-------------------------
-------------------------
exception
end;

USER DEFINED ERROR MESSAGE

The package “raise_application_error” is used to issue the user defined error messages
Syntax: raise_application_error(error number,‘error message‘);
The error number can lie between -20000 and -20999.
The error message should be a character string.

TO CREATE THE TABLE ‘ITEMPLS’

SQL> create table itempls (ename varchar2(10), eid number(5), salary number(10));

Table created.

SQL> insert into itempls values('xxx',11,10000);

1 row created.

SQL> insert into itempls values('yyy',12,10500);

1 row created.

SQL> insert into itempls values('zzz',13,15500);

1 row created.

SQL> select * from itempls;

110
ENAME EID SALARY
---------- --------- ---------
xxx 11 10000
yyy 12 10500
zzz 13 15500

TO CREATE A SIMPLE TRIGGER THAT DOES NOT ALLOW INSERT UPDATE


AND DELETE OPERATIONS ON THE TABLE

SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2 begin
3 raise_application_error(-20010,'You cannot do manipulation');
4 end;
5
6 /

Trigger created.

SQL> insert into itempls values('aaa',14,34000);


insert into itempls values('aaa',14,34000)
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

SQL> delete from itempls where ename='xxx';


delete from itempls where ename='xxx'
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

SQL> update itempls set eid=15 where ename='yyy';


update itempls set eid=15 where ename='yyy'
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

TO DROP THE CREATED TRIGGER

SQL> drop trigger ittrigg;

111
Trigger dropped.

triggers
SQL> create table client_master(cno number,name varchar2(20),bal_due number(10,2));

Table created.

SQL> insert into client_master values(&cno,'&name',&bal_due);


Enter value for cno: 1
Enter value for name: x
Enter value for bal_due: 1000
old 1: insert into client_master values(&cno,'&name',&bal_due)
new 1: insert into client_master values(1,'x',1000)

1 row created.

SQL> /
Enter value for cno: 2
Enter value for name: y
Enter value for bal_due: 1000
old 1: insert into client_master values(&cno,'&name',&bal_due)
new 1: insert into client_master values(2,'y',1000)

1 row created.

SQL> /
Enter value for cno: 3
Enter value for name: z
Enter value for bal_due: 2000
old 1: insert into client_master values(&cno,'&name',&bal_due)
new 1: insert into client_master values(3,'z',2000)

1 row created.

SQL> create table auditclient(cno number,name varchar2(20),bal_due number(10,2),operation


varchar2(1
0),odate date);

Table created.

SQL> create trigger audit_trail after update or delete on client_master for each row
2 declare
3 oper varchar2(10);
4 cno number;

112
5 name varchar2(20);
6 bal_due number(10,2);
7 begin
8 if updating then
9 oper:='update';
10 end if;

11 if deleting then
12 oper:='delete';
13 end if;
14 cno:= :old.cno;
15 name:= :old.name;
16 bal_due:= :old.bal_due;
17 insert into auditclient values(cno,name,bal_due,oper,sysdate);
18 end;
19 /

Trigger created.

SQL> select cno,name,bal_due from client_master;

CNO NAME BAL_DUE


--------- -------------------- ---------
1x 1000
2y 1000
3z 2000

SQL> select cno,name,bal_due,operation,odate from auditclient;

no rows selected

SQL> update client_master set bal_due=2300 where cno=1;

1 row updated.

SQL> select cno,name,bal_due from client_master;

CNO NAME BAL_DUE


--------- -------------------- ---------
1x 2300
2y 1000
3z 2000

SQL> select cno,name,bal_due,operation,odate from auditclient;

CNO NAME BAL_DUE OPERATION ODATE

113
--------- -------------------- --------- ---------- ---------
1x 1000 update 11-AUG-09

SQL>

SQL> delete from client_master where cno=3;

1 row deleted.

SQL> select cno,name,bal_due from client_master;

CNO NAME BAL_DUE


--------- -------------------- ---------
1x 2300
2y 1000

SQL> select cno,name,bal_due,operation,odate from auditclient;

CNO NAME BAL_DUE OPERATION ODATE


--------- -------------------- --------- ---------- ---------
1x 1000 update 11-AUG-09
3z 2000 delete 11-AUG-09

SQL>

SQL> create table order1(ono number,oname varchar2(20));

Table created.

SQL> insert into order1 values(&ono,'&oname');


Enter value for ono: 1
Enter value for oname: fan
old 1: insert into order1 values(&ono,'&oname')
new 1: insert into order1 values(1,'fan')

1 row created.

SQL> /
Enter value for ono: 2
Enter value for oname: bulb
old 1: insert into order1 values(&ono,'&oname')
new 1: insert into order1 values(2,'bulb')

114
1 row created.

SQL> create table order2(ono number,odate varchar2(20));

Table created.

SQL> insert into order2 values(&ono,'&odate');


Enter value for ono: 1
Enter value for odate: 12/7/09
old 1: insert into order2 values(&ono,'&odate')
new 1: insert into order2 values(1,'12/7/09')

1 row created.

SQL> /
Enter value for ono: 2
Enter value for odate: 12/8/09
old 1: insert into order2 values(&ono,'&odate')
new 1: insert into order2 values(2,'12/8/09')

1 row created.

SQL> create or replace trigger order_det after delete on order1 for each row
2 begin
3 delete from order2 where ono=:old.ono;
4 end;
5 /

Trigger created.

SQL> select * from order1;

ONO ONAME
--------- --------------------
1 fan
2 bulb

SQL> select * from order2;

ONO ODATE
--------- --------------------
1 12/7/09
2 12/8/09

SQL> delete from order1 where ono=1;

115
1 row deleted.

SQL> select * from order1;

ONO ONAME

--------- --------------------
2 bulb

SQL> select * from order2;

ONO ODATE
--------- --------------------
2 12/8/09

SQL> select * from book2;

BID TITLE PRICE


--------- -------------------- ---------
1 dbms 300
2 cn 100

SQL> select * from order_list;

ONO BID QTY TOT_PR


--------- --------- --------- ---------
1 1 5 1000

SQL> create or replace trigger book_detail2 after update on book2 for each row when(new.price
> old.
price)
2 begin
3 update order_list set tot_pr= :new.price*qty where bid= :new.bid;
4 end;
5 /

Trigger created.

SQL> update book2 set price=400 where bid=1;

1 row updated.

SQL> select * from book2;

BID TITLE PRICE

116
--------- -------------------- ---------
1 dbms 400
2 cn 100

SQL> select * from order_list;

ONO BID QTY TOT_PR


--------- --------- --------- ---------
1 1 5 2000

117
RESULT

Thus the triggers were created , executed and their respective outputs were verified.

PROCEDURES AND FUNCTIONS


EX NO: 12
DATE:

AIM

To write PL/SQL programs that executes the concept of functions and procedures.

DEFINITION

A procedure or function is a logically grouped set of SQL and PL/SQL statements that
perform a specific task. They are essentially sub-programs. Procedures and functions are made
up of,
• Declarative part
• Executable part
• Optional exception handling part
These procedures and functions do not show the errors.

KEYWORDS AND THEIR PURPOSES

REPLACE: It recreates the procedure if it already exists.


PROCEDURE: It is the name of the procedure to be created.
ARGUMENT: It is the name of the argument to the procedure. Paranthesis can be omitted if no
arguments are present.
IN: Specifies that a value for the argument must be specified when calling the procedure ie. used
to pass values to a sub-program. This is the default parameter.
OUT: Specifies that the procedure passes a value for this argument back to it’s calling
environment after execution ie. used to return values to a caller of the sub-program.
INOUT: Specifies that a value for the argument must be specified when calling the procedure
and that procedure passes a value for this argument back to it’s calling environment after
execution.
RETURN: It is the datatype of the function’s return value because every function must return a
value, this clause is required.

PROCEDURES – SYNTAX

create or replace procedure <procedure name> (argument {in,out,inout} datatype ) {is,as}


118
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;

end;

FUNCTIONS – SYNTAX

create or replace function <function name> (argument in datatype,……) return datatype {is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;

CREATING THE TABLE ‘ITITEMS’ AND DISPLAYING THE CONTENTS

SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid
number(4));

Table created.

SQL> insert into ititems values(101, 2000, 500, 201);

1 row created.

SQL> insert into ititems values(102, 3000, 1600, 202);

1 row created.

SQL> insert into ititems values(103, 4000, 600, 202);

1 row created.

SQL> select * from ititems;

ITEMID ACTUALPRICE ORDID PRODID


--------- ----------- -------- ---------
101 2000 500 201
102 3000 1600 202
103 4000 600 202

119
PROGRAM FOR GENERAL PROCEDURE – SELECTED RECORD’S PRICE IS
INCREMENTED BY 500 , EXECUTING THE PROCEDURE CREATED AND
DISPLAYING THE UPDATED TABLE

SQL> create procedure itsum(identity number, total number) is

price number;
2 null_price exception;
3 begin
4 select actualprice into price from ititems where itemid=identity;
5 if price is null then
6 raise null_price;
7 else
8 update ititems set actualprice=actualprice+total where itemid=identity;
9 end if;
10 exception
11 when null_price then
12 dbms_output.put_line('price is null');
13 end;
14 /

Procedure created.

SQL> exec itsum(101, 500);

PL/SQL procedure successfully completed.

SQL> select * from ititems;

ITEMID ACTUALPRICE ORDID PRODID


--------- ----------- --------- ---------
101 2500 500 201
102 3000 1600 202
103 4000 600 202

PROCEDURE FOR ‘IN’ PARAMETER – CREATION, EXECUTION

SQL> set serveroutput on;


SQL> create procedure yyy (a IN number) is price number;
2 begin
3 select actualprice into price from ititems where itemid=a;
4 dbms_output.put_line('Actual price is ' || price);
5 if price is null then
6 dbms_output.put_line('price is null');
7 end if;

120
8 end;
9 /

Procedure created.

SQL> exec yyy(103);

Actual price is 4000

PL/SQL procedure successfully completed.

PROCEDURE FOR ‘OUT’ PARAMETER – CREATION, EXECUTION

SQL> set serveroutput on;


SQL> create procedure zzz (a in number, b out number) is identity number;
2 begin
3 select ordid into identity from ititems where itemid=a;
4 if identity<1000 then
5 b:=100;
6 end if;
7 end;
8 /

Procedure created.

SQL> declare
2 a number;
3 b number;
4 begin
5 zzz(101,b);
6 dbms_output.put_line('The value of b is '|| b);
7 end;
8 /
The value of b is 100

PL/SQL procedure successfully completed.

PROCEDURE FOR ‘INOUT’ PARAMETER – CREATION, EXECUTION

SQL> create procedure itit ( a in out number) is


2 begin
3 a:=a+1;
4 end;
5 /

Procedure created.

121
SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line(‘The updated value is ‘||a);

6 end;
7 /

The updated value is 8

PL/SQL procedure successfully completed.

SQL> select * from xbv;

NAME ID
-------------------- ----------
x 1
y 2

SQL> select * from bvx;

ID DNO
---------- ----------
1 11
2 12

SQL> create or replace procedure yu(a in out number) is


2 begin
3 update bvx set dno=dno+a where id=&id;
4 select dno into a from bvx where id=&id;
5 end;
6 /
Enter value for id: 1
old 3: update bvx set dno=dno+a where id=&id;
new 3: update bvx set dno=dno+a where id=1;
Enter value for id: 1
old 4: select dno into a from bvx where id=&id;
new 4: select dno into a from bvx where id=1;

Procedure created.

SQL> set serveroutput on;


SQL> declare
2 a number;

122
3 begin
4 a:=&a;
5 yu(a);
6 dbms_output.put_line('sal is'||a);
7 end;
8 /

Enter value for a: 500


old 4: a:=&a;
new 4: a:=500;
sal is511

PL/SQL procedure successfully completed.

SQL> select * from bvx;

ID DNO
---------- ----------
1 511
2 12

CREATE THE TABLE ‘ITTRAIN’ TO BE USED FOR FUNCTIONS

SQL>create table ittrain ( tno number(10), tfare number(10));

Table created.

SQL>insert into ittrain values (1001, 550);

1 row created.

SQL>insert into ittrain values (1002, 600);

1 row created.

SQL>select * from ittrain;

TNO TFARE
--------- ------------
1001 550
1002 600

PROGRAM FOR FUNCTION AND IT’S EXECUTION

SQL> create function aaa (trainnumber number) return number is


2 trainfunction ittrain.tfare % type;

123
3 begin
4 select tfare into trainfunction from ittrain where tno=trainnumber;
5 return(trainfunction);
6 end;
7 /
Function created.

SQL> set serveroutput on;


SQL> declare
2 total number;
3 begin
4 total:=aaa (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);
6 end;
7 /
Train fare is Rs.550

PL/SQL procedure successfully completed.

FACTORIAL OF A NUMBER USING FUNCTION — PROGRAM AND EXECUTION

SQL> create function itfact (a number) return number is


2 fact number:=1;
3 b number;
4 begin
5 b:=a;
6 while b>0
7 loop
8 fact:=fact*b;
9 b:=b-1;
10 end loop;
11 return(fact);
12 end;
13 /

Function created.

SQL> set serveroutput on;


SQL> declare
2 a number:=7;
3 f number(10);
4 begin
5 f:=itfact(a);

124
6 dbms_output.put_line(‘The factorial of the given number is’||f);
7 end;
8 /

The factorial of the given number is 5040

PL/SQL procedure successfully completed.

125
RESULT

Thus the PL/SQL programs were executed and their respective outputs were verified.

Ex.No.13 STUDY EXPERIMENT


Date:

NORMALIZATION:
Normalization is the process of decomposing the relation into fragments. It is a
formal technique for analysing relations based on their primary key and functional dependencies.
It is based on the concept of functional dependency.

FUNCTIONAL DEPENDENCY:
Functional dependency is a tool to measure the appropriateness of the attributes
grouping into relational schemas. It determines the relationship between the attributes. A F.D
from X to Y (set of attributes) exists if and only if for every instance of r, if two tuples in r agree
on the values of the attributes in X, then they agree on the values of the attributes in Y.

GENERAL FORMAT OF F.D:

X->Y

i.e. X determines Y or Y is functionally dependent on X.


Here X denotes a set of attributes on the left hand side i.e determinants
and Y denotes a set of attributes on the right hand side i.e. dependents.

Eg: emp(ssn,pno,hours,pname,plocation)
{ssn,pno}->{hours,pname,plocation}
Here ssn and pno are key attributes and they determine the other non key attributes such as
hours,pname,plocation.

TYPES OF F.D:
1.Full F.D
2.Partial F.D
3.Transitive F.D
4.Multivalued F.D
5.Join F.D

FULL F.D:
A F.d X->Y is a full F.D, if the dependency does not hold on the removal of any attribute A
from the set of attributes of X.

126
{X-|A|}->Y it does not hold.
Eg:emp(ssn,ename,bdate,address,dname,dno,mid)
{ssn,dno}->{ename,bdate,address,dname,mid}
Here non key attributes such as ename,bdate,address,dname,mgrid are entirely dependent on key
attributes such as ssn and dno.If any of the key attribute is lost then the dependency does not hold.

PARTIAL F.D:

A F.D X->Y is a partial F.D if some attribute A belongs to X can be removed from X and
the dependency still holds.
{X-|A|}->Y This dependency holds.
Eg:emp(ssn,pno,ename,pname,plocation}
FD1 {ssn,pno}->{pname,plocation}
Here if the key attribute ssn is lost,still the dependency holds and we can determine the other non
key attributes such as pname and plocation.
FD2 {ssn,pno}->{ename}
Here even if the key attribute pno is lost,still we can determine ename using ssn.
FD3 {pno}->{pname,plocation}
FD4 {ssn}->{ename}

Note:
In FD3, pname and plocation depend on a part of the key
In FD4,ename depends on a part of the key
If the LHS has single attribute, no need to check for partial dependencies.

TRANSITIVE F.D:
An attribute that is dependent on the attribute other than the key arrribute.
Eg:student(eno,ename,eclass,ehours,ecourse)
FD1 {eno}->{ename,eclass,ecourse}
FD2 {eclass}->{ehours}
FD3 {eno}->{ehours}
In FD1 the key attribute eno determines the other non key attributes.
In FD2 the non key attribute eclass determines other non key attribute ehours.
Therefore the key attribute eno determines the non key attribute ehours.

MULTIVALUED F.D:
A dependency from A to B is said to be multivalued dependency if for a value of A, there
exists multiple values of B.
Eg:branch(bno,sname,oname)
Branch
bno sname oname
B3 Ann Carol
B3 David Tina

127
{bno}->{sname}
{bno}->{oname}

If the two tuples agree in all the attributes of bno,then we can swap sname and oname and
get 2 new tuples.

Branch
bno sname oname
B3 Ann Carol
B3 David Tina
B3 Ann Tina
B3 David Carol

JOIN DEPENDENCY:
A relation R with subsets of the attributes of R denoted as R(A,B,…,Z) satisfies a join
dependency if and only if for every legal value of R is equal to the join of its projections on A,B,
…,Z.
Eg:service(flight,day_of_week,palne_type)
Service
flight Day_of_week Plane_type
106 Monday 747
106 Thursday 747
106 Monday 1011
106 Thursday 1011
204 Wednesday 707
204 Wednesday 727

service relation is decomposed into two relations namely


servday(flight,day_of_week)
flight Day_of_week
106 Monday
106 Thursday
204 Wednesday

servtype(flight,plane_type)
flight Plane_type
106 747
106 1011
204 707
204 727

If rejoin is done on servday and servtype relations, it is possible to reconstruct the original
relation service.There is no loss of information.
Suppose if any of the rows in service relation is deleted, then rejoin of servtype and servday
128
relations do not produce the original service relation.

VARIOUS NORMAL FORMS:

1.0NF :
It is the unnormalized form.It may have
1.Multivalued attributes

2.Composite attributes
3.Nested relations

2.1NF :
A relation in which the intersection of each row and column contains only one value.
i)Values should be atomic and indivisible.
ii)No repeating groups.
It does not contain multivalued attributes, composite attributes and nested relations.

3.2NF :
For a relation to be in 2NF, it should be in 1NF and there should be no partial dependency.

4. 3NF:
For relation to be in 3NF, it should be in 2NF and there should be no transitive
dependency.

5. BCNF (Boyce-Codd NF):


For a relation to be in BCNF form, all the determinants should be a candidate key and a
non-key attribute should not determine a key attribute.
[Candidate Keys are minimal super keys.Primary keys are candidate keys]

6. 4NF:
For a relation to be in 4NF form it should be in BCNF and there should be no non-trivial
multivalued dependency.

7. 5NF:
For a relation to be in 5NF form there should be no join dependency.

For eg, consider a table ClientRental

clientN cNam property pAddress rentSta rentFinis ren ownerN oName


o e No rt h t o
CR76 John PG4 Lawrence 1-Jul- 31-Aug- 35 CO40 Tina
Kay street,Glasgo 00 01 0 Murph
w y
PG16 1-Sep- CO93
Novar Dr 1-Sep- 02 45 Tony
street,Glasgo 01 0 Shaw

129
w

CR56 Aline PG4 Lawrence 1-Sep- 10-June- 35 CO40 Tina


Stewa Street,Glasg 99 00 0 Murph
rt ow y
PG36 1-Dec- CO93
Manor 10-oct- 01 37 Tony
Road,Glasgo 00 5 Shaw
PG16 w CO93
1-Nov- 10-Aug- Tony
Novar 02 03 45 Shaw
Dr,Glasgow 0

The ClientRental relation has the following functional dependencies:

FD1 clientNo, propertyNo -> rentStart, rentFinish (Primary key)


FD2 clientNo -> cName (Partial Dependency)
FD3 propertyNo -> pAddress, rent, ownerNo, oName (Partial Dependency)
FD4 ownerNo -> oName (Transitive Dependency)
FD5 clientNo,rentStart -> propertyNo, pAddress, rentFinish, rent, ownerNo,oName (Candidate
key)
FD6 propertyNo,rentStart -> clientNo,cName,rentFinish (Candidate key)

0NF :
The above table is in unnormalized form since it contains many repeating groups.
Client Rental(clientNo, cName, propertyNo, pAddress, rentStart, rentFinish, rent,
ownerNo, oName)

1NF :
To convert the 0NF form to 1NF form , remove the repeating group by placing the repeating
data, along with a copy of the original key attribute, in a separate relation.

Repeating Groups:
1.clientNo
2.cName

Primary Keys:
1.clientNo
2.propertyNo

So in order to remove the repeating groups,we decompose the relation ClientRental into

130
Client(clientNo,cName)
PropertyRentalOwner(clientNo, propertyNo, pAddress, rentStart, rentFinish, rent, ownerNo,
oName)

Identified F.D’s are


{clientNo} -> {cName}

{clientNo, propertyNo} -> {pAddress, rentStart, rentFinish, rent, ownerNo, oName}

1NF :
Client
clientNo cName
CR76 John Kay
CR56 Aline Stewart

PropertyRentalOwner
clientN property pAddress rentSta rentFin rent owner oName
o No rt ish No
CR76 PG4 Lawrence 1-Jul- 31- 350 CO40 Tina
street,Glas 00 Aug-01 Murph
gow y
CR76 PG16 Novar Dr 1-Sep- 1-Sep- 450 CO93 Tony
street,Glas 01 02 Shaw
gow
CR56 PG4 Lawrence 1-Sep- 10- 350 CO40 Tina
Street,Glas 99 June- Murph
gow 00 y
CR56 PG36 Manor 10-oct- 1-Dec- 375 CO93 Tony
Road,Glasg 00 01 Shaw
ow
CR56 PG16 Novar 1-Nov- 10- 450 CO93 Tony
Dr,Glasgo 02 Aug-03 Shaw
w

2NF :
Secondary normal form applies to relations with composite keys, i.e. the relations with a
primary key composed of two or more attributes. The normalization of 1NF relations to 2NF
involves the removal of partial dependencies. If it exists, we remove the functionality dependent
attributes from the relation by placing them in a new relation along with a copy of their
determinant.

1NF relations are


Client(clientNo,cName)
PropertyRentalOwner(clientNo, propertyNo, pAddress, rentStart, rentFinish, rent, ownerNo,

131
oName)

Ignore all relations with single key attribute.

Identified partial dependencies are

{propertyNo} -> pAddress, rent, ownerNo, oName


{clientNo, propertyNo} -> rentStart, rentFinish

Here without the key attribute clientNo,we can determine the other non key attributes with the
key attribute propertyNo.

To remove partial dependency we decompose the relation PropertyRentalOwner into


Rental(propertyNo, rentStart, rentFinish)
PropertyOwner(propertyNo, pAddress, rent, ownerNo, oName)

Client
clientNo cName
CR76 John Kay
CR56 Aline Stewart

Rental
clientNo propertyNo rentStart rentFinish
CR76 PG4 1-Jul-00 31-Aug-01

CR76 PG16 1-Sep-01 1-Sep-02


CR56 PG4 1-Sep-99 10-June-00
CR56 PG36 10-oct-00 1-Dec-01
CR56 PG16 1-Nov-02 10-Aug-03

PropertyOwner
propertyNo pAddress rent ownerNo oName
PG4 Lawrence 350 CO40 Tina Murphy
street,Glasgo
w
PG16 Novar Dr 450 CO93 Tony Shaw
street,Glasgo
w
PG36 Manor 375 CO93 Tony Shaw
Road,Glasgo
w

3NF :
The normalization from 2NF relations to 3NF involves the removal of transitive
dependencies. If it exists, we remove the transitively dependent attributes from the relation by

132
placing the attributes in a new relation along with a copy of the determinant.
Client and Rental relations do not have transitive dependencies.

2NF relations are


Client(clientNo,cName)

Rental(propertyNo, rentStart, rentFinish)


PropertyOwner(propertyNo, pAddress, rent, ownerNo, oName)

Ignore all relations with less than 3 attributes.


Identified transitive dependencies in PropertyOwner relations are
{propertyNo} -> {pAddress, rent, ownerNo, oName}
{ownerNo} -> {oName}
{propertyNo}->{oName}

Here the non key attribute oName is dependent on another non key attribute ownerNo.
Therefore to remove the transitive dependencies,we decompose the relation PropertyOwner
into two new relations
PropertyForRent( propertyNo, pAddress, rent, ownerNo)
Owner(ownerNo,oName)

PropertyForRent
propertyNo pAddress rent ownerName
PG4 Lawrence 350 CO40
street,Glasgow
PG16 Novar Dr 450 CO93
street,Glasgow
PG36 Manor 375 CO93
Road,Glasgow

Owner
ownerNo oName
CO40 Tina Murphy

CO93 Tony Shaw

BCNF :
The F.Ds in 3NF form are

{clientNo} -> {cName}


{clientNo,propertyNo} -> {rentStart,rentFinish}
{propertyNo} -> {pAddress,rent,ownerName}
{ownerNo} -> {oName}

133
Here all the determinants on the left hand side of the F.D i.e
clientNo,propertyNo,ownerNo are all candidate keys.
Hence all the 3NF relations are in BCNF normal form.

The relations in BCNf form are

Client(clientNo, cName)
Rental(propertyNo, rentStart, rentFinish)
PropertyForRent( propertyNo, pAddress, rent, ownerNo)
Owner(ownerNo,oName)

4NF:
The F.Ds are

{clientNo,propertyNo}->>{propertyNo}
This functional dependency is a trivial multivalued functional dependency and there is no non-
trivial MVD.

The relations in 4Nf form are


Client(clientNo, cName)
Rental(propertyNo, rentStart, rentFinish)
PropertyForRent( propertyNo, pAddress, rent, ownerNo)
Owner(ownerNo,oName)

5NF:
ClientRental <- Client U Rental U PropertyForRent U Owner
There is no lossy join dependency

The relations in 5Nf form are


Client(clientNo, cName)
Rental(propertyNo, rentStart, rentFinish)
PropertyForRent( propertyNo, pAddress, rent, ownerNo)
Owner(ownerNo,oName)

The normalized form of ClientRental relation is

PropertyForRent
propertyNo pAddress rent ownerName
PG4 Lawrence 350 CO40
street,Glasgow
PG16 Novar Dr 450 CO93
street,Glasgow
PG36 Manor 375 CO93
Road,Glasgow

134
Client
clientNo cName
CR76 John Kay
CR56 Aline Stewart

Rental
clientNo propertyNo rentStart rentFinish
CR76 PG4 1-Jul-00 31-Aug-01

CR76 PG16 1-Sep-01 1-Sep-02


CR56 PG4 1-Sep-99 10-June-00
CR56 PG36 10-oct-00 1-Dec-01
CR56 PG16 1-Nov-02 10-Aug-03

Owner
ownerNo oName
CO40 Tina Murphy

CO93 Tony Shaw

135
Result:
Thus the ClientRental relation is normalized

DATABASE DESIGN USING E-R DIAGRAMS


EXNO:14
DATE:

BANK DATABASE:

136
phoneno address

has Account
Customer

cname
cid
accno acctype

borro
ws

belong
s to

Loan
Branch

loanno loantype
branchname
city

HOSPITAL DATABASE:

137
bedno type
datein accounts
status
beds
amount
dateout
roomn Bed
o _ass
igne
d

Has_a
ccount

exa
phno min dob
es

doctors ssno patients ssno


name

Office
phone
name address
specialit phno
y

RALWAY TICKET RESERVATION DATABASE:

138
source destination
phoneno
age

board
Passenger Train
s

pid
pname trainno name

queues
at train_
ticket

buys

Reservation Ticket
Counter

boarding
countern ticketno
place place
o

fare

LIBRARY DATABASE:

139
pubid
author
Pub
lish publisher
book
ed
by

booki Publisher
price
d name

Sup
plie
Bor
d by
row
ed
by
Supplier
name

Member
member type supplier

Member address
memberid name Supplier
id

AIRLINE RESERVATION DATABASE:

140
address phoneno name state

Passenger arriv Airport


es at

pname
pid code city

airpo
board rt_tic
s buys ket

name

flight
Flight _tick Ticket
et

arriva departure ticketno dateofjo


l
urney

num
type fare seatno
ber

EMPLOYEE DATABASE:

141
name
empn
o
address
Dept
employee
Deptno name

phno
ecity department
Works
_on

Date_started

job

titl
e leve salary jobid
l

142
PROCEDURE FOR PROJECT CREATION

CREATING A FORM:
1.To open visual basic 6.0 goto start>>programs>>Microsoft visual studio
6.0>>visual basic6.0 or simply double click the icon on the desktop.
2.Open visual basic 6.0 with the new project in standardexe mode.
3.A window appears with name Project1 with Form1 in it.

Once a form is created to add another form project>>addform.

FORM DESIGN:
The Toolbox contains the textbox, combobox, command button, label.
Add the components to the form according to the project.

SOME OF THE COMPONENTS IN THE TOOLBOX:

1.label: Used to display the the names of the fields to be filled in the project. Eg
name, age…etc. It depends on the project to be created. The label’s caption is changed as per the
project.
2.command button: Te command button is used to perform a task. Eg: depositing an amount in
the bank database, withdrawal…
3.combobox: Allows us to select a data from a list.
4.textbox: The values are entered in the textbox.

All these components are identified by their name indicated in the properties window.
To use these components in the program the name of the component must be used.

CONNECTING BACK END(ORACLE):


1. To connect the database in oracle to the project we use adodc(ActiveX Data Object Data
Control) . Initially if this component is not available then goto project>>components>>Microsoft
ADO Data control 6.0 and then click on apply.

2.Now the component will be available in the toolbox. Add the component to the form.
Right click the adodc1 and then click ADODC properties.A property pages window will appear.
In the general tab use the CONNECTION STRING and build the connection.
After selecting the provider as MICROSOFT OLE DB PROVIDER FOR ORACLE.

3.Click on the connection tab. Enter the server name,username and password in the text boxes
that appear and click on test connection. If a message test connection succeeded is displayed
then the connection is correct otherwise redo the steps.

4.Click on the authentication tab and enter the username and password.

143
5.Click on the recordsource tab and command type—1-adcmdtext or 2-adcmdtable. For table
select the tablename from the dropdown list box. For text type the sql statement
Select * from tablename in command text(SQL).

USING DATA GRID FOR OUTPUT:


If the data grid is not available in the toolbox then goto project>>components>>Microsoft
datagrid control 6.0 and click on apply.
Connect the data grid to adodc1 by making the datasource of the datagrid as adodc1.

WRITING PROGRAMS FOR THE PROJECT:

SWITCHING OVER FROM FORM TO CODING:


Double click on the command button or the text box which has to contain
the code. A function with the name of the textbox will appear. The function will contain the
code for that command button or the text box.

INSERTING DATAS INTO THE ORACLE TABLE FROM VB:


Adodc1.recordset.addnew- to create a new record.
Adodc1.recordset.fields(“fieldname”)= textboxname.text- to copy the values in the textbox or
combobox to the field specified.
Adodc1.recordset.update- to update the values onto the table.
Call Adodc1.refresh – to refresh.

SEARCHING FOR A DATA:


In the general section of the program :
Dim s as string
In the command button (search)
S=”select * from tablename where searchfield=” & field1
This statement will retrieve the rows which satisfy the condition.

144
145
AIRLINE RESERVATION SYSTEM

EX NO:15
DATE:

FLIGHT BOOKING:

Private Sub bookflight_Click()


Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("flightno") = flightno.Text
Adodc1.Recordset.Fields("boardplace") = boardplace.Text
Adodc1.Recordset.Fields("destplace") = destplace.Text
Adodc1.Recordset.Fields("class") = class.Text
Adodc1.Recordset.Fields("name") = nametxt.Text
Adodc1.Recordset.Fields("gender") = gender.Text
Adodc1.Recordset.Fields("age") = agetxt.Text
Adodc1.Recordset.Fields("seatno") = seatno.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub

Private Sub gotopasdetails_Click()


passengerdetails.Show
End Sub

146
PASSENGER DETAILS:

Dim b As String

Private Sub BACK_Click()


airline.Show
End Sub

Private Sub Command1_Click()


b = "select * from airline where seatno=" & seatno.Text & " and flightno="
& flightno.Text
Adodc1.RecordSource = b
Call Adodc1.Refresh
End Sub

147
RESULT:
Thus Airline Reservation System is implemented.

148
BANK MANAGEMENT SYSTEM

EX.NO:16
DATE:

AIM:
To implement bank management system with visual basic as front end and oracle as
back end.

MAIN PAGE:

Private Sub Command1_Click()


Form2.Show
End Sub

Private Sub Command2_Click()


Form3.Show
End Sub

Private Sub Command3_Click(Index As Integer)


Form4.Show
End Sub

Private Sub Command4_Click()


End
End Sub
ACCOUNT CREATION:

149
Private Sub Command1_Click()
Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("name") = Text1.Text
Adodc1.Recordset.Fields("accno") = Text2.Text
Adodc1.Recordset.Fields("balance") = Text3.Text
Adodc1.Recordset.Fields("address") = Text4.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub

Private Sub Command2_Click()


Form1.Show
End Sub

AFTER CREATING ACCOUNT:


SQL> select * from bank;

NAME ACCNO BALANCE ADDRESS


-------------------- --------- --------- --------------------
SIVA 101 45000 CHENNAI
ADAM 102 5000 CHENNAI
YABESH 103 55000 CHENNAI

ACCOUNT DEPOSIT:

150
Dim a As String
Private Sub Command1_Click()
Adodc1.Recordset.Fields(2) = Adodc1.Recordset.Fields(2) + Text3.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub
Private Sub Text2_LostFocus()
a = "select * from bank where accno=" & Text2.Text
Adodc1.RecordSource = a
Call Adodc1.Refresh
End Sub

Private Sub Command2_Click()


Form1.Show
End Sub

AFTER DEPOSIT:
SQL> select * from bank;

NAME ACCNO BALANCE ADDRESS


-------------------- --------- --------- --------------------
SIVA 101 45000 CHENNAI
ADAM 102 5000 CHENNAI
YABESH 103 60000 CHENNAI
ACCOUNT WITHDRAW:

151
Dim a As String
Private Sub Command1_Click()
Adodc1.Recordset.Fields(2) = Adodc1.Recordset.Fields(2) - Text3.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub
Private Sub Text2_LostFocus()
a = "select * from bank where accno=" & Text2.Text
Adodc1.RecordSource = a
Call Adodc1.Refresh
End Sub

Private Sub Command2_Click()


Form1.Show
End Sub
AFTER WITHDRAW:

select * from bank;


NAME ACCNO BALANCE ADDRESS
-------------------- --------- --------- --------------------
SIVA 101 40000 CHENNAI
ADAM 102 5000 CHENNAI
YABESH 103 60000 CHENNAI

RESULT:
Thus bank management system is implemented.

152
EMPLOYEE PAYROLL SYSTEM

EX.NO:
DATE:17

AIM:
To implement employee payroll system with visual basic as front end and oracle as
back end.

MAIN PAGE:

Private Sub Command1_Click()


Form2.Show
End Sub

Private Sub Command2_Click()


Form3.Show
End Sub

Private Sub Command3_Click()


End
End Sub

153
ADD NEW:

Private Sub Command1_Click()


Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("name") = Text1.Text
Adodc1.Recordset.Fields("dept") = Text2.Text
Adodc1.Recordset.Fields("address") = Text3.Text
Adodc1.Recordset.Fields("id") = Text4.Text
Adodc1.Recordset.Fields("salary") = Text5.Text
Adodc1.Recordset.Fields("phno") = Text6.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
Call Adodc1.Refresh
Call Adodc1.Refresh
End Sub
Private Sub Command2_Click()
Form1.Show
End Sub
AFTER ADDING NEW DETAILS :
SQL> select * from ed;

NAME ID DEPT SALARY ADDRESS PHNO


-------------------- --------- -------------------- --------- -------------------- ---------
ISSAC 101 CSE 67000 CHENNAI 98766754
SIVA 102 CSE 70000 CHENNAI 98766866
YABESH 103 IT 75000 NELLAI 987668678

154
UPDATE SALARY :

Dim a As String
Private Sub Command1_Click()
Adodc1.Recordset.Fields(3) = Adodc1.Recordset.Fields(3) + Text3.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub

Private Sub Command2_Click()


Form1.Show
End Sub

Private Sub Text2_LostFocus()


a = "select *from ed where id=" & Text2.Text
Adodc1.RecordSource = a
Call Adodc1.Refresh
End Sub

AFTER UPDATING SALARY :


SQL> select * from ed;

NAME ID DEPT SALARY ADDRESS PHNO


-------------------- --------- -------------------- --------- -------------------- ---------
ISSAC 101 CSE 67000 CHENNAI 98766754
SIVA 102 CSE 70000 CHENNAI 98766866
YABESH 103 IT 80000 NELLAI 987668678

RESULT :
Thus employee payroll system is implemented.
155
HOSPITAL DATABASE
EX NO:18
DATE:

LOGIN:

Dim s, r As String

Private Sub submit_Click()


s = "vecita"
r = "ita"
If (s = usernametxt.Text And r = passwordtxt.Text) Then
patient.Show
Else
Call MsgBox("invalid username/password", vbCritical)
End If
End Sub

PATIENT :

156
Dim k As String

Private Sub ADMIT_Click()


Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("name") = nametxt.Text
Adodc1.Recordset.Fields("age") = agetxt.Text
Adodc1.Recordset.Fields("sex") = sextxt.Text
Adodc1.Recordset.Fields("patientid") = pitxt.Text
Adodc1.Recordset.Fields("phoneno") = phtxt.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub

Private Sub gotodoc_Click()


doctor.Show
End Sub

Private Sub pitxt_LostFocus()


k = "select * from patient where patientid=" & pitxt.Text
Adodc1.RecordSource = k
Call Adodc1.Refresh
End Sub

157
DOCTOR:

Dim a As String

Private Sub docidtxt_LostFocus()


a = "select * from doctor where doctorid= " & docidtxt.Text
Adodc1.RecordSource = a
Call Adodc1.Refresh
End Sub

Private Sub gotopatient_Click()


patient.Show
End Sub

Private Sub SUBMIT_Click()


Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("name") = nametxt.Text
Adodc1.Recordset.Fields("doctorid") = docidtxt.Text
Adodc1.Recordset.Fields("specialisation") = spltxt.Text
Adodc1.Recordset.Fields("phoneno") = phtxt.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub

158
RESULT :
Thus Hospital Dtabase system is implemented.

159
LIBRARY MANAGEMENT SYSTEM

EX.NO:19
DATE:

AIM:
To implement library management system with visual basic as front end and oracle as
back end.

MAIN PAGE:

Private Sub Command1_Click()


Form2.Show
End Sub

Private Sub Command2_Click()


Form3.Show
End Sub

Private Sub Command3_Click()


End
End Sub

160
ADD A BOOK:

Private Sub Command1_Click()


Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("bookid") = Text1.Text
Adodc1.Recordset.Fields("title") = Text2.Text
Adodc1.Recordset.Fields("author") = Text3.Text
Adodc1.Recordset.Fields("publisher") = Text4.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub

Private Sub Command2_Click()


Form1.Show
End Sub

AFTER ADDING A BOOK:

SQL> select * from library;

BOOKID TITLE AUTHOR PUBLISHER


--------- -------------------- -------------------- --------------------
101 DBMS SILBER PERSON
102 MICROPROCESSOR GAONKAR MC GRAW HILL
103 PQT DONALD GROSS JOHN WILEY&SONS LTD

161
SEARCHING A BOOK:

Dim a As String

Private Sub Command1_Click()


If a = "select * from library where bookid=" & Text1.Text Then
Adodc1.RecordSource = a
MsgBox ("book is available")
Else
MsgBox ("book is not available")
End If
Call Adodc1.Refresh
End Sub
Private Sub Command2_Click()
Form1.Show
End Sub
Private Sub Text1_LostFocus()
a = "select * from library where bookid=" & Text1.Text
Adodc1.RecordSource = a
Call Adodc1.Refresh

RESULT:
Thus library management system is implemented.

162
RAILWAY TICKET RESERVATION

EXNO:20
DATE:

BOOK A TICKET:

Private Sub book_Click()


Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("trainno") = trainno.Text
Adodc1.Recordset.Fields("boardplace") = board.Text
Adodc1.Recordset.Fields("dest") = dest.Text
Adodc1.Recordset.Fields("class") = class.Text
Adodc1.Recordset.Fields("name") = nametxt.Text
Adodc1.Recordset.Fields("sex") = sex.Text
Adodc1.Recordset.Fields("age") = agetxt.Text
Adodc1.Recordset.Fields("seatno") = seat_no.Text
Adodc1.Recordset.Update
Call Adodc1.Refresh
End Sub

Private Sub gotopasdetails_Click()


passenger_details.Show

End Sub

163
PASSENGER DETAILS:

Dim s As String

Private Sub gototicketreservation_Click()


TICKETRESERVATION.Show
End Sub

Private Sub SEARCH_Click()


s = "select * from ticket where seatno= " & seat_no.Text & "and trainno=" & train_no.Text
Adodc1.RecordSource = s
Call Adodc1.Refresh
End Sub

164
RESULT:
Thus Railway Ticket Reservation System is implemented.

165
MENU DESIGN AND DATA REPORT CREATION
EX NO:21
DATE:

CREATING A REPORT:

Step 1 :
Start a new project
Add a Data Environment and set the connection to point to the employee database created
earlier.
Add a command to the connection created in above step and edit the properties. Set the
Database Object to Table, and for the Object Name pick the table emp.

Step 2:
Add Data Report by :
Clicking on Project >> Add Data Report.
Note : If this option is not visible then
Click Project>>Components.
Click Designers tab.
Check the Data Report check box.
Click OK.
Report Designer will be displayed as shown below :
Set the following report propereties as given below :
DataSource field to: DataEnvironment1
DataMember field to: Command1

Data Report Section Description:

Report Header: Appears at the Beginning of the Report.


Report Footer: Appears at the End of the Report.
Page Header : Appears at the top of every page.
Page Footer : Appears at the end of every page.
Group Header:
A group is associated with a Command in the Data
Environment. You can use multiple groups to show data from
multiple Commands. Each group begins a new section based on
a command.
Group Footer: Ends a group section.
Detail:
This is where all the action happens. This is repeated over and
over for each record in the Database. so if you have 100 records

166
there will be 100 copies of this detail.
In the Data Environment window expand Command1 so that you can see each of the fields.
Now drag the required fields onto the Data Report window and drop it in the Detail section.
If you click on the left most one you will notice it is a Label, which will display the field
name and the rightmost one is a field (name:ReportTextBox) which will contain the data from
that field.
Drag the label in the page header section so that it should appear once per page and in
details section only the data will be displayed. It should appear as shown below :
Similarly drag other fields and adjust them.

Preview the Report


Set the Start Up property in the Project Properties.. as DataReport1.
Run the project. The result will be displayed as shown below :

How to call a report from a form


Open the Form called Form1.
Add a CommandButton to the form, and change the Caption to be "Preview". Now
doubleclick the CommandButton and place this code:
Private Sub Command1_Click()
DataReport1.Show
End Sub
Set the Start Up property in the Project Properties.. as Form1.
Run the project and click on the Preview button to see the report.

Here the menu is used for data report creation.

TO CREATE A MENU:
TOOLS>>MENUEDITOR
Caption:&employee_details
Name:mnuemployee_details
A menu is created.

167
FORM WITH MENU CREATED:

DATA REPORT FOR EMPLOYEE:

Private Sub mnuemployee_details_Click()


DataReport1.Show
End Sub

168
DATA REPORT FOR DEPARTMENT:

Private Sub mnudepartment_details_Click()


DataReport2.Show
End Sub

169
Procedure to do Menu design

EXAMPLE 1:

The end result of Example 1 will be a form containing a menu with two top-level items, File and Help.

The File menu, shown below, will have the following level-two items below it: New, Open, Save, Save As,
Print, and Exit. Note that separator bars appear above the Save, Print, and Exit items.

170
The Help menu contains just one level-two item below it, About.

Invoke the Menu Editor from the Tools menu item as shown below:

171
To build the menu described above, perform the following steps.

1 .Start a new VB project and invoke the Menu Editor using either method shown above (click the

Menu Editor toolbar icon or select the Menu Editor option from the Tools menu). The Menu

Editor screen appears, as shown below:

1. For "Caption", type &File (by placing the ampersand to the left of the "F", we establish "F" as an
access key for the File item it enables the user to drop down the File menu by keying "Alt+F" on
the keyboard in addition to clicking the "File" item with the mouse).

For "Name", type mnuFile.

172
Click the Next button
2. Click the "right-arrow" button (shown circled below). A ellipsis (...) will appear as the next item in
the menu list, indicating that this item is a level-two item (below "File").

For "Caption", type &New; for "Name", type mnuNew, and for "Shortcut", select Ctrl+N. By specifying a
shortcut, you allow the user to access the associated menu item by pressing that key combination. So
here, you are providing the user three ways of invoking the "New" function: (1) clicking File, then clicking
New on the menu; (2) keying Alt+F,N (because we set up an access key for "N" by placing an ampersand
to left of "N" in "New"); or (3) keying Ctrl+N.

Click the Next button……………………..

Result: Thus the Report is generated successfully

173

You might also like