Top Banner
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. 1
215

Database Management Systems

Nov 18, 2014

Download

Documents

SHIVALKAR J

Data definition language,Data Manipulation Language,TCL,Views,Triggers,Cursors,Report creation in Visual Basic
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Database Management Systems

DATA DEFINITION LANGUAGE COMMANDS

EX NO: 01DATE:

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

Page 2: Database Management Systems

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

Page 3: Database Management Systems

DATA MANIPULATION LANGUAGE COMMANDS-SET1

EX NO: 2aDATE: 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 – DUALDual 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.

3

Page 4: Database Management Systems

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

ADD_MONTHS(D,N): It returns date after adding the number of months specified with the function.

4

Page 5: Database Management Systems

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 TABLESQL> 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 aeronauticalbhavesh 102 18 nungambakkam marinepruthvik 103 20 anna nagar aerospacecharith 104 20 kilpauk mechanical

RENAMING THE TABLE ‘STUD’SQL> rename stud to studs;

Table renamed.

ARITHMETIC OPERATION

5

Page 6: Database Management Systems

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

SNAME stid------------------------------ ---------ashwin 201bhavesh 202pruthvik 203charith 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 nagarkilpauknungambakkam

USING THE WHERE CLAUSESQL> select sname,sage from studs where sage<=19;

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

SNAME SAREA SID------------------------------ -------------------- ----------bhavesh nungambakkam 102pruthvik anna nagar 103charith kilpauk 104IN PREDICATE

6

Page 7: Database Management Systems

SQL> select sname,sarea , sid from studs where sid in(102,104);

SNAME SAREA SID------------------------------ -------------------- ----------bhavesh nungambakkam 102charith kilpauk 104

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

SNAME SAREA------------------------------ --------------------ashwin anna nagarbhavesh nungambakkampruthvik anna nagar

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

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

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

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

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

UPDATING THE TABLESQL> alter table studs add ( spocket varchar2(20) );

Table altered.

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

7

Page 8: Database Management Systems

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 750bhavesh 102 18 nungambakkam marine500pruthvik 103 20 anna nagar aerospace250charith 104 20 kilpauk mechanical100

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

RESULT--------- 400

SQL> select min(spocket) result from studs;

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

SQL> select count(spocket) result from studs;

8

Page 9: Database Management Systems

RESULT--------- 4

SQL> select count(*) result from studs;

RESULT--------- 4

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

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

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

SQL> select sum(spocket) result from studs;

RESULT--------- 1600

NUMERIC FUNCTIONSSQL> 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--------- 15.36

9

Page 10: Database Management Systems

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

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

10

Page 11: Database Management Systems

4 rows updated.

SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT------------------------------ ---------- --------- -------------------- --------------------SPOCKET--------------------ashwin 101 18 anna nagar aeronautical750bhavesh 102 18 nungambakkam marine500pruthvik 103 18 anna nagar aerospace250charith 104 18 kilpauk mechanical100

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

SYSDATE RESULT

11

Page 12: Database Management Systems

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

Page 13: Database Management Systems

DATA MANIPULATION LANGUAGE COMMANDS-SET2

EX NO: 2bDATE: 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 CLAUSEThe 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 CLAUSEThe 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 thenatural join.

13

Page 14: Database Management Systems

ORDER BY CLAUSE

SQL> select * from emppp56;

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

SQL> select * from emppp56 order by na

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

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

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

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

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

DELETIONSQL> delete from studs where sid=101;

1 row deleted.

SQL> select * from studs;

14

Page 15: Database Management Systems

SNAME SID SAGE SAREA SDEPT------------------------------ ---------- --------- -------------------- --------------------SPOCKET-------------------bhavesh 102 18 nungambakkam marine500pruthvik 103 20 anna nagar aerospace250charith 104 20 kilpauk mechanical100

CREATING TABLES FOR DOING SET OPERATIONSTO CREATE PRODUCT TABLESQL> 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.

SQL> select * from product;

15

Page 16: Database Management Systems

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

TO CREATE SALE TABLESQL> 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 10001chair 805 10010desk 809 10110cot 813 11110sofa 817 10010SET OPERATIONSSQL> select prodname from product where prodno=10010 union select prodname from sale where prodno=10010;

16

Page 17: Database Management Systems

PRODNAME------------------------------chairsofa

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 OPERATIONSTO CREATE SSTUD1 TABLESQL> 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 chennaianand chennaikumar chennairavi chennai

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

17

Page 18: Database Management Systems

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 700anand it 650vasu cse 680ravi it 600

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

SNAME DEPT-------------------- ----------anand itprajan cseravi it

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

SNAME DEPT-------------------- ----------anand itprajan cseravi it

18

Page 19: Database Management Systems

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

SNAME DEPT-------------------- ----------prajan cseanand itravi itkumar

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

SNAME DEPT-------------------- ----------prajan cseanand itravi it cse

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

SNAME DEPT-------------------- ----------prajan cseanand itravi itkumar cse

NESTED QUERIES

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

SNAME--------------------anandprajanravi

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

19

Page 20: Database Management Systems

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

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

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

SQL> select sname from sstud1 where exists ( select sstud2.sname from sstud2

20

Page 21: Database Management Systems

2 where sstud1.sname=sstud2.sname );

SNAME--------------------prajananandravi

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

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 1a 2g 3d 4

SQL> alter table emppp56 rename column name to emp_name;

Table altered.

SQL> desc emppp56;

21

Page 22: Database Management Systems

Name Null? Type ----------------------------------------- -------- ---------------------------- EMP_NAME VARCHAR2(20) ID NUMBER

SQL> select * from emppp56;

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

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

22

Page 23: Database Management Systems

INTEGRITY CONSTRAINTSEX NO: 3DATE:

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

Integrity Constraints

1.Domain Constrainta)NULL CONSTRAINTB)NOT NULL CONSTRAINTc)CHECK CONSTRAINT

2. Entity Constrainta)UNIQUEb)PRIMARY KEY

3. Referential Constrainta)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: xEnter value for accno: 1old 1: insert into customer values('&cname',&accno)new 1: insert into customer values('x',1)

1 row created.

23

Page 24: Database Management Systems

SQL> /Enter value for cname: yEnter 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: zEnter value for accno: nullold 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 1y 2z

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

1 row updated.

SQL> select * from customer;

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

NOT NULL CONSTRAINT

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

24

Page 25: Database Management Systems

Table created.

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

1 row created.

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

1 row created.

SQL> /Enter value for cname: zEnter value for loan_no: nullold 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: aEnter 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

Page 26: Database Management Systems

x 1y 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: xEnter value for balance: 10000old 1: insert into withdraw values('&cname',&balance)new 1: insert into withdraw values('x',10000)

1 row created.

SQL> /Enter value for cname: yEnter value for balance: 200old 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: yEnter value for balance: 20000old 1: insert into withdraw values('&cname',&balance)new 1: insert into withdraw values('y',20000)

1 row created.

SQL> select * from withdraw;

CNAME BALANCE-------------------- ----------x 10000

26

Page 27: Database Management Systems

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: xEnter value for cname: tcsEnter value for place: chennaiold 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: yEnter value for cname: tcsEnter value for place: maaduraiold 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: yEnter value for cname: tcsEnter value for place: maduraiold 1: insert into company1 values('&emane','&cname','&place')new 1: insert into company1 values('y','tcs','madurai')

1 row created.

SQL> /

27

Page 28: Database Management Systems

Enter value for emane: zEnter value for cname: wiproEnter 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 chennaiy 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 unique);

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: tcsEnter value for location: vadapalaniold 1: insert into company values('&comp_name','&location')new 1: insert into company values('tcs','vadapalani')

28

Page 29: Database Management Systems

1 row created.

SQL> /Enter value for comp_name: tcsEnter value for location: adyarold 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: ctsEnter value for location: vadapalaniold 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: nullEnter value for location: solinganalurold 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: padiold 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")

SQL> /

29

Page 30: Database Management Systems

Enter value for comp_name: wiproEnter 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 vadapalaninull solinganalur

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

Table created.

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

1 row created.

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

1 row created.

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

1 row created.

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

30

Page 31: Database Management Systems

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.

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

31

Page 32: Database Management Systems

1 row updated.

SQL> select * from account;

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

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: xEnter value for accno: 1old 1: insert into depositor values('&cname',&accno)new 1: insert into depositor values('x',1)

1 row created.

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

1 row created.

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

1 row created.

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

32

Page 33: Database Management Systems

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 1x 2y 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: johnEnter value for id: 11old 1: insert into empv values('&name',&id)new 1: insert into empv values('john',11)

1 row created.

SQL> /Enter value for name: henryEnter value for id: 11old 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: henryEnter value for id: 12

33

Page 34: Database Management Systems

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 11henry 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_systemEnter value for id: 11old 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_systemEnter value for id: 12old 1: insert into project values('&pname',&id)new 1: insert into project values('banking_system',12)

1 row created.

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

34

Page 35: Database Management Systems

1 row created.

SQL> /Enter value for pname: payrollEnter value for id: 12old 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 11banking_system 12airline 11payroll 12

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

NAME ID PNAME-------------------- ---------- --------------------john 11 banking_systemhenry 12 banking_systemjohn 11 airlinehenry 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: korthEnter value for id: 12old 1: insert into empv values('&name',&id)new 1: insert into empv values('korth',12)

35

Page 36: Database Management Systems

1 row created.

SQL> select * from empv;

NAME ID-------------------- ----------john 11henry 12korth 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 11henry 12korth 13

SQL> alter table empv enable constraint cons_pri;

Table altered.

SQL> desc empv; Name Null? Type ----------------------------------------- -------- ---------------------------- NAME VARCHAR2(20) ID NOT NULL NUMBER

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

36

Page 37: Database Management Systems

Enter value for name: smithEnter value for id: 13old 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 DNAME VARCHAR2(15)

37

Page 38: Database Management Systems

SQL> insert into emp1 values('&ename',&eid,&dno);Enter value for ename: x

Enter value for eid: 1Enter value for dno: 1old 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 notfound

SQL> insert into dept1 values(&dno,'&dname');Enter value for dno: 1Enter value for dname: itold 1: insert into dept1 values(&dno,'&dname')new 1: insert into dept1 values(1,'it')

1 row created.

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

1 row created.

SQL> /Enter value for dno: 3Enter value for dname: eceold 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: 1Enter value for dname: eeeold 1: insert into dept1 values(&dno,'&dname')new 1: insert into dept1 values(1,'eee')insert into dept1 values(1,'eee')*ERROR at line 1:

38

Page 39: Database Management Systems

ORA-00001: unique constraint (SCOTT.CON_DNO) violated

SQL> select * from dept1;

DNO DNAME---------- --------------- 1 it 2 cse 3 eceSQL> insert into emp1 values('&ename',&eid,&dno);Enter value for ename: xEnter value for eid: 1Enter value for dno: 1old 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: yEnter value for eid: 2Enter value for dno: 1old 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: aEnter value for eid: 3Enter value for dno: 1old 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: bEnter value for eid: 4Enter value for dno: 2old 1: insert into emp1 values('&ename',&eid,&dno)new 1: insert into emp1 values('b',4,2)

1 row created.

39

Page 40: Database Management Systems

SQL> /Enter value for ename: cEnter value for eid: 5

Enter value for dno: 2old 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: dEnter value for eid: 6Enter value for dno: 3old 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: eEnter value for eid: 6Enter value for dno: 3old 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: eEnter value for eid: 7Enter value for dno: 3old 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 1y 2 1a 3 1

40

Page 41: Database Management Systems

b 4 2c 5 2d 6 3

e 7 3

7 rows selected.

SQL> select * from dept1;

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

ENAME EID DNO DNO DNAME--------------- ---------- ---------- ---------- ---------------x 1 1 1 ity 2 1 1 ita 3 1 1 itb 4 2 2 csec 5 2 2 csed 6 3 3 ecee 7 3 3 ece

7 rows selected.

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

ENAME DNAME--------------- ---------------x ity ita itb csec csed ecee ece

7 rows selected.

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

ENAME DNAME

41

Page 42: Database Management Systems

--------------- ---------------x ity 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 ity 1 ita 1 itb 2 csec 2 csed 3 ecee 3 ece

7 rows selected.

SQL> insert into emp1 values('&ename',&eid,&dno);Enter value for ename: fEnter value for eid: 8Enter value for dno: 4old 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 notfound

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

42

Page 43: Database Management Systems

1 row created.

SQL> select * from emp1;

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

8 rows selected.

RESULT

43

Page 44: Database Management Systems

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:4aDATE:

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

Page 45: Database Management Systems

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: ajithEnter value for city: chennaiEnter value for street: kamarajarold 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: johnEnter value for city: bangaloreEnter value for street: ambedkarold 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: vijayEnter value for city: hyderabadEnter value for street: rajivold 1: insert into employee values('&ename','&city','&street’)new 1: insert into employee values('vijay','hyderabad','rajiv’)

45

Page 46: Database Management Systems

1 row created.

SQL> /

Enter value for ename: sivaEnter value for city: chennaiEnter value for street: kamarajarold 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 kamarajarjohn bangalore ambedkarvijay hyderabad rajivsiva chennai kamarajar

SQL> insert into works values('&ename','&companyname',&salary);Enter value for ename: ajithEnter value for companyname: fbcEnter value for salary: 300000old 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: johnEnter value for companyname: sbcEnter value for salary: 150000old 1: insert into works values('&ename','&companyname',&salary)new 1: insert into works values('john','sbc',150000)

1 row created.

SQL> /Enter value for ename: vijay

46

Page 47: Database Management Systems

Enter value for companyname: bbcEnter value for salary: 200000old 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: sivaEnter value for companyname: fbcEnter value for salary: 400000old 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 300000john sbc 150000vijay bbc 200000siva fbc 400000

SQL> insert into company values('&companyname','&city');Enter value for companyname: fbcEnter value for city: chennaiold 1: insert into company values('&companyname','&city')new 1: insert into company values('fbc','chennai')

1 row created.

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

1 row created.

SQL> /

47

Page 48: Database Management Systems

Enter value for companyname: bbcEnter value for city: hyderabadold 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 chennaisbc bangalorebbc hyderabad

SQL> insert into manages values('&ename','&mname');Enter value for ename: ajithEnter value for mname: smithold 1: insert into manages values('&ename','&mname')new 1: insert into manages values('ajith','smith')

1 row created.

SQL> /Enter value for ename: johnEnter 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: vijayEnter value for mname: henryold 1: insert into manages values('&ename','&mname')new 1: insert into manages values('vijay','henry')

1 row created.

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

48

Page 49: Database Management Systems

1 row created.

SQL> select * from manages;

ENAME MNAME-------------------- --------------------ajith smithjohnvijay henrysiva

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

ENAME--------------------ajithsiva

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

Page 50: Database Management Systems

ajithjohnsiva

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

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

ENAME--------------------ajithvijaysiva

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

ENAME--------------------ajithvijaysivaSQL> select ename from works where companyname not in ('fbc');

ENAME--------------------johnvijay

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

50

Page 51: Database Management Systems

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

vijay

SQL> select ename from manages where mname is null;

ENAME--------------------johnsiva

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

ENAME--------------------ajithvijay

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

Page 52: Database Management Systems

View created.

SQL> select * from v1;

CNAME NO_OF_EMPLOYEES-------------------- ---------------bbc 1fbc 2sbc 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-------------------- -------------------- --------------------ajith chennai kamarajar

52

Page 53: Database Management Systems

vijay hyderabad rajivsiva chennai kamarajar

SQL> select * from employee order by ename;

ENAME CITY STREET-------------------- -------------------- --------------------ajith chennai kamarajarsiva chennai kamarajarvijay hyderabad rajiv

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

ENAME--------------------ajithsiva

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

ENAME--------------------ajithsiva

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

1 row updated.

SQL> select * from works;

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

53

Page 54: Database Management Systems

SQL> alter table manages add(manager_no number);

Table altered.

SQL> select * from manages;

ENAME MNAME MANAGER_NO-------------------- -------------------- ----------ajith smithjohnvijay henrysiva

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.

SQL> select * from v2;

54

Page 55: Database Management Systems

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

ajith fbcjohn sbcvijay bbcsiva fbc

SQL> alter table works rename column companyname to cname;

Table altered.

SQL> select * from works;

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

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

55

Page 56: Database Management Systems

SQL APPLICATION-2EX NO:4bDATE:

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: 101Enter value for ename: ramEnter value for dob: 18 NOV 1990Enter value for gender: maleEnter value for doj: 2 NOV 2005Enter value for designation: manager

56

Page 57: Database Management Systems

Enter value for basicpay: 30000old 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: 1old 2: &dno)new 2: 1)

1 row created.

SQL> /Enter value for eno: 102Enter value for ename: elangoEnter value for dob: 21 JAN 1990Enter value for gender: maleEnter value for doj: 3 FEB 2005Enter value for designation: team leaderEnter value for basicpay: 25000old 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',25Enter value for dno: 2old 2: &dno)new 2: 2)

1 row created.

SQL> /Enter value for eno: 103Enter value for ename: rahulEnter value for dob: 22 FEB 1989Enter value for gender: maleEnter value for doj: 4 MAR 2005Enter value for designation: team memberEnter value for basicpay: 15000old 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',150Enter value for dno: 2old 2: &dno)new 2: 2)

57

Page 58: Database Management Systems

1 row created.

SQL> /Enter value for eno: 104Enter value for ename: sethuEnter value for dob: 17 MAR 1982Enter value for gender: maleEnter value for doj: 5 SEP 2005Enter value for designation: teammemberEnter value for basicpay: 14000old 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',140Enter value for dno: 2old 2: &dno)new 2: 2)

1 row created.

SQL> /Enter value for eno: 105Enter value for ename: ajithEnter value for dob: 25 SEP 1985Enter value for gender: maleEnter value for doj: 2 AUG 2005Enter value for designation: team memberEnter value for basicpay: 16000old 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',160Enter value for dno: 3old 2: &dno)new 2: 3)1 row created.

SQL> select * from employee;

ENO ENAME DOB GENDER---------- -------------------- -------------------- --------------------DOJ DESIGNATION BASICPAY DNO

58

Page 59: Database Management Systems

-------------------- -------------------- ---------- ---------- 101 ram 18 NOV 1990 male2 NOV 2005 manager 30000 1

102 elango 21 JAN 1990 male3 FEB 2005 team leader 25000 2

103 rahul 22 FEB 1989 male4 MAR 2005 teammember 15000 2

ENO ENAME DOB GENDER---------- -------------------- -------------------- --------------------DOJ DESIGNATION BASICPAY DNO-------------------- -------------------- ---------- ---------- 104 sethu 17 MAR 1982 male5 SEP 2005 teammember 14000 2

105 ajith 25 SEP 1985 male2 AUG 2005 team member 16000 3

SQL> insert into department values(&dno,'&dname');Enter value for dno: 1Enter value for dname: itold 1: insert into department values(&dno,'&dname')new 1: insert into department values(1,'it')

1 row created.

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

1 row created.

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

59

Page 60: Database Management Systems

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: 201Enter value for pname: bankingEnter value for dno: 2old 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: 202Enter value for pname: airlineEnter value for dno: 1old 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: 203Enter value for pname: accountingEnter value for dno: 3old 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---------- -------------------- ---------- 201 banking 2

60

Page 61: Database Management Systems

202 airline 1 203 accounting 3

SQL> insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime');Enter value for eno: 101Enter value for pno: 201Enter value for dateworked: 2 NOV 2009Enter value for intime: 9 amEnter value for outtime: 5 pmold 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: 102Enter value for pno: 202Enter value for dateworked: 2 NOV 2009Enter value for intime: 10 amEnter value for outtime: 5 pmold 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: 101Enter value for pno: 202Enter value for dateworked: 2 NOV 2009Enter value for intime: 6 pmEnter value for outtime: 11 pmold 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: 103Enter value for pno: 203Enter value for dateworked: 4 NOV 2009Enter value for intime: 9 amEnter value for outtime: 5 pmold 1: insert into workfor values(&eno,&pno,'&dateworked','&intime','&outtime')

61

Page 62: Database Management Systems

new 1: insert into workfor values(103,203,'4 NOV 2009','9 am','5 pm')

1 row created.

SQL> /Enter value for eno: 104Enter value for pno: 201Enter value for dateworked: 5 NOV 2009Enter value for intime: 10 amEnter value for outtime: 6 pmold 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: 105Enter value for pno: 202Enter value for dateworked: 6 NOV 2009Enter value for intime: 8 amEnter value for outtime: 4 pmold 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 am5 pm

102 202 2 NOV 2009 10 am5 pm

101 202 2 NOV 2009 6 pm11 pm

62

Page 63: Database Management Systems

ENO PNO DATEWORKED INTIME---------- ---------- -------------------- --------------------OUTTIME-------------------- 103 203 4 NOV 2009 9 am5 pm

104 201 5 NOV 2009 10 am6 pm

105 202 6 NOV 2009 8 am4 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 male4 MAR 2005 teammember 15000 2

104 sethu 17 MAR 1982 male5 SEP 2005 teammember 14000 2

105 ajith 25 SEP 1985 male2 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;

DNO NO_OF_EMPLOYEES

63

Page 64: Database Management Systems

---------- --------------- 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 male2 NOV 2005 manager 30000 1

104 sethu 17 MAR 1982 male5 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 male4 MAR 2005 teammember 15000 2

104 sethu 17 MAR 1982 male5 SEP 2005 teammember 14000 2

105 ajith 25 SEP 1985 male2 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.

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

64

Page 65: Database Management Systems

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: dbmsEnter value for author: cj.dateEnter value for publisher: pearsonEnter value for year: 2001Enter value for price: 200Enter value for country: usaold 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: microprocessorEnter value for author: rameshEnter value for publisher: tatamagrawEnter value for year: 2006Enter value for price: 480Enter value for country: ukold 1: insert into book values('&title','&author','&publisher',&year,&price,'&country')new 1: insert into book values('microprocessor','ramesh','tatamagraw',2006,480,'uk')

65

Page 66: Database Management Systems

1 row created.

SQL> /Enter value for title: osEnter value for author: silberschatzEnter value for publisher: pearsonEnter value for year: 2002Enter value for price: 600Enter value for country: usaold 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: oopsEnter value for author: trivediEnter value for publisher: pearsonEnter value for year: 2003Enter value for price: 500Enter value for country: indiaold 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: dsEnter value for author: revathiEnter value for publisher: tatamagrawEnter value for year: 2005Enter value for price: 390Enter 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-------------------- -------------------- -------------------- ---------- PRICE COUNTRY

66

Page 67: Database Management Systems

---------- --------------------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 pearsonmicroprocessor ramesh tatamagrawoops 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 pearsonoops trivedi pearson

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

67

Page 68: Database Management Systems

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

TITLE--------------------dbmsmicroprocessoros

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

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)5.depositor(cname,accno)6.borrower(cname,loanno)

68

Page 69: Database Management Systems

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: perryridgeEnter value for bcity: new yorkEnter value for assets: 5000000old 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: adyarEnter value for bcity: chennaiEnter value for assets: 8000000old 1: insert into branch values('&bname','&bcity',&assets)new 1: insert into branch values('adyar','chennai',8000000)

1 row created.

69

Page 70: Database Management Systems

SQL> /Enter value for bname: avadiEnter value for bcity: chennaiEnter value for assets: 6000000old 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: ashoknagarEnter value for bcity: bangaloreEnter value for assets: 7000000old 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 5000000adyar chennai 8000000avadi chennai 6000000ashoknagar bangalore 7000000

SQL> insert into customer values('&cname','&street','&ccity');Enter value for cname: yabeshEnter value for street: nehruEnter value for ccity: chennaiold 1: insert into customer values('&cname','&street','&ccity')new 1: insert into customer values('yabesh','nehru','chennai')

1 row created.

SQL> /Enter value for cname: sivaEnter value for street: gandi

70

Page 71: Database Management Systems

Enter value for ccity: bangaloreold 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: logaEnter value for street: netajiEnter value for ccity: maduraiold 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: maheshEnter value for street: rajivEnter value for ccity: chennaiold 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 chennaisiva gandi bangaloreloga netaji maduraimahesh rajiv chennai

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

1 row created.

SQL> /Enter value for accno: 102Enter value for balance: 50000

71

Page 72: Database Management Systems

Enter value for bname: adyarold 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: 103Enter value for balance: 60000Enter value for bname: ashoknagarold 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: 201Enter value for bname: adyarEnter value for amount: 800old 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: 202Enter value for bname: avadiEnter value for amount: 15000old 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: 203Enter value for bname: perryridgeEnter value for amount: 1000old 1: insert into loan values(&loanno,'&bname',&amount)

72

Page 73: Database Management Systems

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: yabeshEnter value for accno: 101old 1: insert into depositor values('&cname',&accno)new 1: insert into depositor values('yabesh',101)

1 row created.

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

1 row created.

SQL> /Enter value for cname: maheshEnter value for accno: 103old 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 101siva 102mahesh 103

SQL> insert into borrower values('&cname',&loanno);Enter value for cname: yabesh

73

Page 74: Database Management Systems

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

1 row created.

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

1 row created.

SQL> /Enter value for cname: logaEnter value for loanno: 203old 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 201siva 202loga 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;

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

74

Page 75: Database Management Systems

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

SQL> select cname from depositor join account on account.accno=depositor.accno where 2 balance>1200;

CNAME--------------------yabeshsivamahesh

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

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

CNAME--------------------sivayabesh

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

75

Page 76: Database Management Systems

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

Page 77: Database Management Systems

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

VIEWSEX NO: 5DATE:

AIMTo 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: 1Enter value for ename: PriyaEnter value for bpay: 12000Enter value for dno: 1old 1: insert into emp values(&eno,'&ename',&bpay,&dno)new 1: insert into emp values(1,'Priya',12000,1)

1 row created.

SQL> /Enter value for eno: 2

77

Page 78: Database Management Systems

Enter value for ename: HelenEnter value for bpay: 20000

Enter value for dno: 1old 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: 3Enter value for ename: GayathriEnter value for bpay: 35000Enter value for dno: 2old 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: 4Enter value for ename: SwethaEnter value for bpay: 16000Enter value for dno: 3old 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: 5Enter value for ename: RohanEnter value for bpay: 36000Enter value for dno: 2old 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--------- -------------------- --------- --------- 1 Priya 12000 1 2 Helen 20000 1 3 Gayathri 35000 2

78

Page 79: Database Management Systems

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: 1Enter value for dname: ITold 1: insert into dept values(&dno,'&dname')new 1: insert into dept values(1,'IT')

1 row created.

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

1 row created.

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

1 row created.

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

1 row created.

SQL> select * from dept;

DNO DNAME --------- -------------------- 1 IT 2 CSE 3 ECE

79

Page 80: Database Management Systems

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;

ENO ENAME BPAY DNO--------- -------------------- --------- ---------

80

Page 81: Database Management Systems

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

SQL> insert into view2 values(11);insert into vnis2 values(11)

81

Page 82: Database Management Systems

*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 *ERROR at line 1:ORA-01732: data manipulation operation not legal on this view

82

Page 83: Database Management Systems

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--------- -------------------- --------- --------- 1 x 12000 1 2 y 10000 1 3 z 12000 2 4 a 3456 2 5 c 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

SQL> select * from v45;

83

Page 84: Database Management Systems

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 ITDaisy ITGayathri CSERohan CSESwetha ECEJoe EEE

6 rows selected.

84

Page 85: Database Management Systems

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

RESULT:

85

Page 86: Database Management Systems

Thus views were studied and implemented.

DATACONTROL LANGUAGE COMMANDS

EX NO: 6DATE:

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

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

REVOKE COMMAND

86

Page 87: Database Management Systems

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.

RESULT

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

87

Page 88: Database Management Systems

PROCEDURAL LANGUAGE/ STRUCTURAL QUERY LANGUAGE

EX NO: 7DATE:

AIM To implement various programs using PL/SQL language.

PROGRAMS

TO DISPLAY HELLO MESSAGESQL> 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 ITSQL> 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: 5old 4: a:=&a;new 4: a:=5;5

PL/SQL procedure successfully completed.

GREATEST OF TWO NUMBERS

88

Page 89: Database Management Systems

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: 5old 5: a:=&a;new 5: a:=5;Enter value for b: 9old 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); 15 end if; 16 end if; 17 end; 18 /

89

Page 90: Database Management Systems

Enter value for a: 5

old 6: a:=&a;new 6: a:=5;Enter value for b: 7old 7: b:=&b;new 7: b:=7;Enter value for c: 1old 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 LOOPSQL> 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 /12345

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 4 USING WHILE LOOPSQL> set serveroutput on;SQL> declare 2 a number:=1; 3 begin 4 while(a<5) 5 loop 6 dbms_output.put_line (a); 7 a:=a+1; 8 end loop; 9 end; 10 /

90

Page 91: Database Management Systems

1

234

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 5 USING FOR LOOPSQL> 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 /12345

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 5 IN REVERSE ORDER USING FOR LOOPSQL> 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 /54321

PL/SQL procedure successfully completed.

91

Page 92: Database Management Systems

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: 2old 6: r:=&r;new 6: r:=2;The area of circle is 13

PL/SQL procedure successfully completed.

TO CREATE SACCOUNT TABLESQL> 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 2 a_bal number(7); 3 a_no varchar2(20); 4 debit number(7):=2000; 5 minamt number(7):=500;

92

Page 93: Database Management Systems

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: 1old 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 SROUTESSQL> create table sroutes ( rno number(5), origin varchar2(20), destination varchar2(20), fare number(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);

1 row created.

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

93

Page 94: Database Management Systems

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: 3old 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 3 chennai madurai 400 300 6 thanjavur palani 350 370

TO CREATE SCA LCULATE TABLE

94

Page 95: Database Management Systems

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 NUMBERSQL> set serveroutput on;SQL> declare 2 f number(4):=1; 3 i number(4); 4 begin 5 i:=&i; 6 while(i>=1)

95

Page 96: Database Management Systems

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: 5old 5: i:=&i;new 5: i:=5;The value is 120

PL/SQL procedure successfully completed.

RESULT

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

96

Page 97: Database Management Systems

GOTO AND EXCEPTIONSEX NO: 8DATE:

AIMTo perform goto and exception handling mechanisms.

GOTO COMMAND

PURPOSEThe 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 3200p2 4000p3 6000

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

97

Page 98: Database Management Systems

Table created.

OPERATION TO BE PERFORMEDIf 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

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

98

Page 99: Database Management Systems

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 sequence of statements; end; EXAMPLE USING PL/SQL

99

Page 100: Database Management Systems

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

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

100

Page 101: Database Management Systems

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

RESULT

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

101

Page 102: Database Management Systems

TRANSACTION CONTROL LANGUAGEEX NO: 9DATE:

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; 14 if(t>20000) 15 then 16 rollback to a; 17 else

102

Page 103: Database Management Systems

18 dbms_output.put_line('no updation'); 19 end if; 20 end ; 21 /Enter value for s: 100old 8: s:=&s;new 8: s:=100;Enter value for n: 102old 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 19000b 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: xyzold 1: insert into tyu values('&name')new 1: insert into tyu values('xyz')1 row created.SQL> select * from tyu;

103

Page 104: Database Management Systems

NAME

--------------------xyzwerthjk

SQL> savepoint u;

Savepoint created.

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

1 row deleted.Select*from tyu;

NAME--------------------werthjk

SQL> rollback to u;

Rollback complete.

SQL> select * from tyu;

NAME--------------------xyzwerthjk

RESULT

104

Page 105: Database Management Systems

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

CURSORSEX NO: 10DATE:

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

EID ENAME JOB SAL DNO--------- -------------------- -------------------- --------- --------- 1 nala lecturer 34000 11

105

Page 106: Database Management Systems

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 nalaEmployee id and employee name are 2 and kalaEmployee id and employee name are 5 and ajayEmployee id and employee name are 6 and vijayEmployee 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 /

PL/SQL procedure successfully completed.

SQL> select * from ssempp;

106

Page 107: Database Management Systems

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 39000Employee code and employee salary are 5 and 35000Employee 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; 6 if county > 0 then 7 dbms_output.put_line('The number of rows are '|| county); 8 end if; 9 if sql %found then

107

Page 108: Database Management Systems

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

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

108

Page 109: Database Management Systems

TRIGGERSEX NO: 11DATE:

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

109

Page 110: Database Management Systems

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

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

110

Page 111: Database Management Systems

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 manipulationORA-06512: at "STUDENT.ITTRIGG", line 2ORA-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 manipulationORA-06512: at "STUDENT.ITTRIGG", line 2ORA-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 manipulationORA-06512: at "STUDENT.ITTRIGG", line 2ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

TO DROP THE CREATED TRIGGER

SQL> drop trigger ittrigg;

Trigger dropped.

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

111

Page 112: Database Management Systems

Table created.

SQL> insert into client_master values(&cno,'&name',&bal_due);Enter value for cno: 1Enter value for name: xEnter value for bal_due: 1000old 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: 2Enter value for name: yEnter value for bal_due: 1000old 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: 3Enter value for name: zEnter value for bal_due: 2000old 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(10),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; 5 name varchar2(20); 6 bal_due number(10,2); 7 begin 8 if updating then 9 oper:='update'; 10 end if;

112

Page 113: Database Management Systems

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--------- -------------------- --------- 1 x 1000 2 y 1000 3 z 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--------- -------------------- --------- 1 x 2300 2 y 1000 3 z 2000

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

CNO NAME BAL_DUE OPERATION ODATE--------- -------------------- --------- ---------- --------- 1 x 1000 update 11-AUG-09

SQL>

113

Page 114: Database Management Systems

SQL> delete from client_master where cno=3;

1 row deleted.

SQL> select cno,name,bal_due from client_master;

CNO NAME BAL_DUE--------- -------------------- --------- 1 x 2300 2 y 1000

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

CNO NAME BAL_DUE OPERATION ODATE--------- -------------------- --------- ---------- --------- 1 x 1000 update 11-AUG-09 3 z 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: 1Enter value for oname: fanold 1: insert into order1 values(&ono,'&oname')new 1: insert into order1 values(1,'fan')

1 row created.

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

1 row created.

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

Table created.

114

Page 115: Database Management Systems

SQL> insert into order2 values(&ono,'&odate');Enter value for ono: 1Enter value for odate: 12/7/09old 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: 2Enter value for odate: 12/8/09old 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;

1 row deleted.

SQL> select * from order1;

ONO ONAME

115

Page 116: Database Management Systems

--------- -------------------- 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--------- -------------------- --------- 1 dbms 400 2 cn 100

SQL> select * from order_list;

116

Page 117: Database Management Systems

ONO BID QTY TOT_PR--------- --------- --------- --------- 1 1 5 2000

RESULT

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

117

Page 118: Database Management Systems

PROCEDURES AND FUNCTIONSEX NO: 12DATE:

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} variable declaration; constant declaration; begin PL/SQL subprogram body; exception exception PL/SQL block;

118

Page 119: Database Management Systems

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

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

119

Page 120: Database Management Systems

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; 8 end; 9 /

Procedure created.

SQL> exec yyy(103);

120

Page 121: Database Management Systems

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.

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

121

Page 122: Database Management Systems

6 end; 7 /

The updated value is 8

PL/SQL procedure successfully completed.

SQL> select * from xbv;

NAME ID-------------------- ----------x 1y 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: 1old 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: 1old 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; 3 begin 4 a:=&a; 5 yu(a); 6 dbms_output.put_line('sal is'||a); 7 end; 8 /

122

Page 123: Database Management Systems

Enter value for a: 500old 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; 3 begin 4 select tfare into trainfunction from ittrain where tno=trainnumber; 5 return(trainfunction); 6 end; 7 /Function created.

123

Page 124: Database Management Systems

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); 6 dbms_output.put_line(‘The factorial of the given number is’||f); 7 end; 8 /

The factorial of the given number is 5040

124

Page 125: Database Management Systems

PL/SQL procedure successfully completed.

RESULT

Thus the PL/SQL programs were executed and their respective outputs were verified.

125

Page 126: Database Management Systems

Ex.No.13 STUDY EXPERIMENTDate:

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

126

Page 127: Database Management Systems

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 keyIn FD4,ename depends on a part of the keyIf 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 onameB3 Ann CarolB3 David Tina

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

127

Page 128: Database Management Systems

Branchbno sname onameB3 Ann CarolB3 David TinaB3 Ann TinaB3 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_type106 Monday 747106 Thursday 747106 Monday 1011106 Thursday 1011204 Wednesday 707204 Wednesday 727

service relation is decomposed into two relations namelyservday(flight,day_of_week)

flight Day_of_week106 Monday106 Thursday204 Wednesday

servtype(flight,plane_type)flight Plane_type106 747106 1011204 707204 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 relations do not produce the original service relation.

VARIOUS NORMAL FORMS:

1.0NF : It is the unnormalized form.It may have 1.Multivalued attributes

128

Page 129: Database Management Systems

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

clientNo

cName

propertyNo

pAddress rentStart

rentFinish

rent

ownerNo

oName

CR76 John Kay

PG4

PG16

Lawrence street,Glasgow

Novar Dr street,Glasgow

1-Jul-00

1-Sep-01

31-Aug-01

1-Sep-02

350

450

CO40

CO93

Tina Murphy

Tony Shaw

CR56 Aline Stewart

PG4

PG36

Lawrence Street,Glasgow

Manor Road,Glasgo

1-Sep-99

10-oct-00

10-June-00

1-Dec-01

350

375

CO40

CO93

Tina Murphy

Tony Shaw

129

Page 130: Database Management Systems

PG16 w

Novar Dr,Glasgow

1-Nov-02

10-Aug-03 45

0

CO93Tony Shaw

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

Primary Keys:1.clientNo2.propertyNo

So in order to remove the repeating groups,we decompose the relation ClientRental into 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 :ClientclientNo cName

130

Page 131: Database Management Systems

CR76 John Kay

CR56 Aline Stewart

PropertyRentalOwnerclientNo

propertyNo

pAddress rentStart

rentFinish

rent ownerNo

oName

CR76 PG4 Lawrence street,Glasgow

1-Jul-00

31-Aug-01

350 CO40 Tina Murphy

CR76 PG16 Novar Dr street,Glasgow

1-Sep-01

1-Sep-02

450 CO93 Tony Shaw

CR56 PG4 Lawrence Street,Glasgow

1-Sep-99

10-June-00

350 CO40 Tina Murphy

CR56 PG36 Manor Road,Glasgow

10-oct-00

1-Dec-01

375 CO93 Tony Shaw

CR56 PG16 Novar Dr,Glasgow

1-Nov-02

10-Aug-03

450 CO93 Tony Shaw

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 areClient(clientNo,cName)PropertyRentalOwner(clientNo, propertyNo, pAddress, rentStart, rentFinish, rent, ownerNo, 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.

131

Page 132: Database Management Systems

To remove partial dependency we decompose the relation PropertyRentalOwner intoRental(propertyNo, rentStart, rentFinish)PropertyOwner(propertyNo, pAddress, rent, ownerNo, oName)

ClientclientNo cNameCR76 John KayCR56 Aline Stewart

RentalclientNo propertyNo rentStart rentFinishCR76 PG4 1-Jul-00 31-Aug-01

CR76 PG16 1-Sep-01 1-Sep-02CR56 PG4 1-Sep-99 10-June-00CR56 PG36 10-oct-00 1-Dec-01CR56 PG16 1-Nov-02 10-Aug-03

PropertyOwnerpropertyNo pAddress rent ownerNo oNamePG4 Lawrence

street,Glasgow

350 CO40 Tina Murphy

PG16 Novar Dr street,Glasgow

450 CO93 Tony Shaw

PG36 Manor Road,Glasgow

375 CO93 Tony Shaw

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 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 areClient(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

132

Page 133: Database Management Systems

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

PropertyForRentpropertyNo pAddress rent ownerNamePG4 Lawrence

street,Glasgow350 CO40

PG16 Novar Dr street,Glasgow

450 CO93

PG36 Manor Road,Glasgow

375 CO93

OwnerownerNo oNameCO40 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}

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)

133

Page 134: Database Management Systems

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 areClient(clientNo, cName)Rental(propertyNo, rentStart, rentFinish)PropertyForRent( propertyNo, pAddress, rent, ownerNo)Owner(ownerNo,oName)

5NF:ClientRental <- Client U Rental U PropertyForRent U OwnerThere is no lossy join dependency

The relations in 5Nf form areClient(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 ownerNamePG4 Lawrence

street,Glasgow350 CO40

PG16 Novar Dr street,Glasgow

450 CO93

PG36 Manor Road,Glasgow

375 CO93

ClientclientNo cName

CR76 John Kay

CR56 Aline Stewart

RentalclientNo propertyNo rentStart rentFinishCR76 PG4 1-Jul-00 31-Aug-01

134

Page 135: Database Management Systems

CR76 PG16 1-Sep-01 1-Sep-02CR56 PG4 1-Sep-99 10-June-

00CR56 PG36 10-oct-00 1-Dec-01CR56 PG16 1-Nov-02 10-Aug-03

OwnerownerNo oNameCO40 Tina Murphy

CO93 Tony Shaw

Result:Thus the ClientRental relation is normalized

DATABASE DESIGN USING E-R DIAGRAMSEXNO:14DATE:

BANK DATABASE:

135

Page 136: Database Management Systems

HOSPITAL DATABASE:

136

Customer has

cname

cid

Account

Loan

borrows

accno

phoneno address

acctype

loanno loantype

Branch

belongs to

citybranchname

Page 137: Database Management Systems

RALWAY TICKET RESERVATION DATABASE:

137

beds

doctors patients

accountsbedno type

status

roomno

dateout

amount

examines

Has_account

datein

dob

ssno

name

addressphno

phno

name

ssno

speciality

Office phone

Bed_assigned

Page 138: Database Management Systems

LIBRARY DATABASE:

138

Passenger boards

TicketReservation

Counter

Train

train_ticket

buys

queues at

pid

destinationsource

boarding place

ticketno

phoneno

nametrainno

age

pname

fare

counterno

place

Page 139: Database Management Systems

AIRLINE RESERVATION DATABASE:

139

bookpublisher

member supplier

author

price Publisher name

bookid

Supplier name

memberidSupplier id

address

Published by

Borrowed by

Supplied by

pubid

Member type

Member name

Page 140: Database Management Systems

EMPLOYEE DATABASE:

140

Passenger

pid

TicketFlight

Airport

name

type

phoneno

pname

citycode

number

address

fare

departure

seatno

ticketno

state

dateofjourney

name

arrival

boards

flight_tick

et

buys airport_ticket

arrives at

Page 141: Database Management Systems

141

employee

job

department

empno

name

address

title leve

l

salaryjobid

Date_started

Deptno Dept name

Works_on

phno

ecity

Page 142: Database Management Systems

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.

142

Page 143: Database Management Systems

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.

143

Page 144: Database Management Systems

144

Page 145: Database Management Systems

AIRLINE RESERVATION SYSTEM

EX NO:15DATE:

FLIGHT BOOKING:

Private Sub bookflight_Click()Adodc1.Recordset.AddNewAdodc1.Recordset.Fields("flightno") = flightno.TextAdodc1.Recordset.Fields("boardplace") = boardplace.TextAdodc1.Recordset.Fields("destplace") = destplace.TextAdodc1.Recordset.Fields("class") = class.TextAdodc1.Recordset.Fields("name") = nametxt.TextAdodc1.Recordset.Fields("gender") = gender.TextAdodc1.Recordset.Fields("age") = agetxt.TextAdodc1.Recordset.Fields("seatno") = seatno.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd Sub

Private Sub gotopasdetails_Click()passengerdetails.Show End Sub

145

Page 146: Database Management Systems

PASSENGER DETAILS:

Dim b As String

Private Sub BACK_Click()airline.ShowEnd Sub

Private Sub Command1_Click()b = "select * from airline where seatno=" & seatno.Text & " and flightno=" & flightno.TextAdodc1.RecordSource = bCall Adodc1.RefreshEnd Sub

146

Page 147: Database Management Systems

RESULT: Thus Airline Reservation System is implemented.

147

Page 148: Database Management Systems

BANK MANAGEMENT SYSTEM

EX.NO:16DATE:

AIM: To implement bank management system with visual basic as front end and oracle as back end.

MAIN PAGE:

Private Sub Command1_Click()Form2.ShowEnd Sub

Private Sub Command2_Click()Form3.ShowEnd Sub

Private Sub Command3_Click(Index As Integer)Form4.ShowEnd Sub

Private Sub Command4_Click()EndEnd SubACCOUNT CREATION:

148

Page 149: Database Management Systems

Private Sub Command1_Click()Adodc1.Recordset.AddNewAdodc1.Recordset.Fields("name") = Text1.TextAdodc1.Recordset.Fields("accno") = Text2.TextAdodc1.Recordset.Fields("balance") = Text3.TextAdodc1.Recordset.Fields("address") = Text4.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd Sub

Private Sub Command2_Click()Form1.ShowEnd Sub

AFTER CREATING ACCOUNT:SQL> select * from bank;

NAME ACCNO BALANCE ADDRESS-------------------- --------- --------- --------------------SIVA 101 45000 CHENNAIADAM 102 5000 CHENNAIYABESH 103 55000 CHENNAI

ACCOUNT DEPOSIT:

149

Page 150: Database Management Systems

Dim a As StringPrivate Sub Command1_Click()Adodc1.Recordset.Fields(2) = Adodc1.Recordset.Fields(2) + Text3.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd SubPrivate Sub Text2_LostFocus()a = "select * from bank where accno=" & Text2.TextAdodc1.RecordSource = aCall Adodc1.RefreshEnd Sub

Private Sub Command2_Click()Form1.ShowEnd Sub

AFTER DEPOSIT:SQL> select * from bank;

NAME ACCNO BALANCE ADDRESS-------------------- --------- --------- --------------------SIVA 101 45000 CHENNAIADAM 102 5000 CHENNAIYABESH 103 60000 CHENNAIACCOUNT WITHDRAW:

150

Page 151: Database Management Systems

Dim a As StringPrivate Sub Command1_Click()Adodc1.Recordset.Fields(2) = Adodc1.Recordset.Fields(2) - Text3.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd SubPrivate Sub Text2_LostFocus()a = "select * from bank where accno=" & Text2.TextAdodc1.RecordSource = aCall Adodc1.RefreshEnd Sub

Private Sub Command2_Click()Form1.ShowEnd SubAFTER WITHDRAW:

select * from bank;NAME ACCNO BALANCE ADDRESS-------------------- --------- --------- --------------------SIVA 101 40000 CHENNAIADAM 102 5000 CHENNAIYABESH 103 60000 CHENNAI

RESULT: Thus bank management system is implemented.

151

Page 152: Database Management Systems

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

Private Sub Command2_Click()Form3.ShowEnd Sub

Private Sub Command3_Click()EndEnd Sub

152

Page 153: Database Management Systems

ADD NEW:

Private Sub Command1_Click()Adodc1.Recordset.AddNewAdodc1.Recordset.Fields("name") = Text1.TextAdodc1.Recordset.Fields("dept") = Text2.TextAdodc1.Recordset.Fields("address") = Text3.TextAdodc1.Recordset.Fields("id") = Text4.TextAdodc1.Recordset.Fields("salary") = Text5.TextAdodc1.Recordset.Fields("phno") = Text6.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshCall Adodc1.RefreshCall Adodc1.RefreshEnd SubPrivate Sub Command2_Click()Form1.ShowEnd SubAFTER ADDING NEW DETAILS :SQL> select * from ed;

NAME ID DEPT SALARY ADDRESS PHNO-------------------- --------- -------------------- --------- -------------------- ---------ISSAC 101 CSE 67000 CHENNAI 98766754SIVA 102 CSE 70000 CHENNAI 98766866YABESH 103 IT 75000 NELLAI 987668678

153

Page 154: Database Management Systems

UPDATE SALARY :

Dim a As StringPrivate Sub Command1_Click()Adodc1.Recordset.Fields(3) = Adodc1.Recordset.Fields(3) + Text3.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd Sub

Private Sub Command2_Click()Form1.ShowEnd Sub

Private Sub Text2_LostFocus()a = "select *from ed where id=" & Text2.TextAdodc1.RecordSource = aCall Adodc1.RefreshEnd Sub

AFTER UPDATING SALARY :SQL> select * from ed;

NAME ID DEPT SALARY ADDRESS PHNO-------------------- --------- -------------------- --------- -------------------- ---------ISSAC 101 CSE 67000 CHENNAI 98766754SIVA 102 CSE 70000 CHENNAI 98766866YABESH 103 IT 80000 NELLAI 987668678

RESULT : Thus employee payroll system is implemented.

154

Page 155: Database Management Systems

HOSPITAL DATABASEEX NO:18DATE:

LOGIN:

Dim s, r As String

Private Sub submit_Click()s = "vecita"r = "ita"If (s = usernametxt.Text And r = passwordtxt.Text) Then patient.ShowElse Call MsgBox("invalid username/password", vbCritical) End IfEnd Sub

PATIENT :

155

Page 156: Database Management Systems

Dim k As String

Private Sub ADMIT_Click()Adodc1.Recordset.AddNewAdodc1.Recordset.Fields("name") = nametxt.TextAdodc1.Recordset.Fields("age") = agetxt.TextAdodc1.Recordset.Fields("sex") = sextxt.TextAdodc1.Recordset.Fields("patientid") = pitxt.TextAdodc1.Recordset.Fields("phoneno") = phtxt.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd Sub

Private Sub gotodoc_Click()doctor.ShowEnd Sub

Private Sub pitxt_LostFocus()k = "select * from patient where patientid=" & pitxt.TextAdodc1.RecordSource = kCall Adodc1.RefreshEnd Sub

156

Page 157: Database Management Systems

DOCTOR:

Dim a As String

Private Sub docidtxt_LostFocus()a = "select * from doctor where doctorid= " & docidtxt.TextAdodc1.RecordSource = aCall Adodc1.RefreshEnd Sub

Private Sub gotopatient_Click()patient.ShowEnd Sub

Private Sub SUBMIT_Click()Adodc1.Recordset.AddNewAdodc1.Recordset.Fields("name") = nametxt.TextAdodc1.Recordset.Fields("doctorid") = docidtxt.TextAdodc1.Recordset.Fields("specialisation") = spltxt.TextAdodc1.Recordset.Fields("phoneno") = phtxt.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd Sub

157

Page 158: Database Management Systems

RESULT : Thus Hospital Dtabase system is implemented.

158

Page 159: Database Management Systems

LIBRARY MANAGEMENT SYSTEM

EX.NO:19DATE:

AIM: To implement library management system with visual basic as front end and oracle as back end.

MAIN PAGE:

Private Sub Command1_Click()Form2.ShowEnd Sub

Private Sub Command2_Click()Form3.ShowEnd Sub

Private Sub Command3_Click()EndEnd Sub

159

Page 160: Database Management Systems

ADD A BOOK:

Private Sub Command1_Click()Adodc1.Recordset.AddNewAdodc1.Recordset.Fields("bookid") = Text1.TextAdodc1.Recordset.Fields("title") = Text2.TextAdodc1.Recordset.Fields("author") = Text3.TextAdodc1.Recordset.Fields("publisher") = Text4.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd Sub

Private Sub Command2_Click()Form1.ShowEnd 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

160

Page 161: Database Management Systems

SEARCHING A BOOK:

Dim a As String

Private Sub Command1_Click()If a = "select * from library where bookid=" & Text1.Text ThenAdodc1.RecordSource = aMsgBox ("book is available")ElseMsgBox ("book is not available")End IfCall Adodc1.RefreshEnd SubPrivate Sub Command2_Click()Form1.ShowEnd SubPrivate Sub Text1_LostFocus()a = "select * from library where bookid=" & Text1.TextAdodc1.RecordSource = aCall Adodc1.Refresh

RESULT: Thus library management system is implemented.

161

Page 162: Database Management Systems

RAILWAY TICKET RESERVATION

EXNO:20DATE:

BOOK A TICKET:

Private Sub book_Click()Adodc1.Recordset.AddNewAdodc1.Recordset.Fields("trainno") = trainno.TextAdodc1.Recordset.Fields("boardplace") = board.TextAdodc1.Recordset.Fields("dest") = dest.TextAdodc1.Recordset.Fields("class") = class.TextAdodc1.Recordset.Fields("name") = nametxt.TextAdodc1.Recordset.Fields("sex") = sex.TextAdodc1.Recordset.Fields("age") = agetxt.TextAdodc1.Recordset.Fields("seatno") = seat_no.TextAdodc1.Recordset.UpdateCall Adodc1.RefreshEnd Sub

Private Sub gotopasdetails_Click()passenger_details.Show

End Sub

162

Page 163: Database Management Systems

PASSENGER DETAILS:

Dim s As String

Private Sub gototicketreservation_Click()TICKETRESERVATION.ShowEnd Sub

Private Sub SEARCH_Click()s = "select * from ticket where seatno= " & seat_no.Text & "and trainno=" & train_no.TextAdodc1.RecordSource = sCall Adodc1.RefreshEnd Sub

163

Page 164: Database Management Systems

RESULT: Thus Railway Ticket Reservation System is implemented.

164

Page 165: Database Management Systems

MENU DESIGN AND DATA REPORT CREATIONEX NO:21DATE:

CREATING A REPORT:

Step 1 :Start a new projectAdd 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 thenClick 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: DataEnvironment1DataMember 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 DataEnvironment. You can use multiple groups to show data frommultiple Commands. Each group begins a new section based ona command.Group Footer: Ends a group section.Detail: This is where all the action happens. This is repeated over andover for each record in the Database. so if you have 100 recordsthere will be 100 copies of this detail.

165

Page 166: Database Management Systems

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 ReportSet 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 formOpen 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.ShowEnd SubSet 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_detailsA menu is created.

166

Page 167: Database Management Systems

FORM WITH MENU CREATED:

DATA REPORT FOR EMPLOYEE:

Private Sub mnuemployee_details_Click()DataReport1.ShowEnd Sub

167

Page 168: Database Management Systems

DATA REPORT FOR DEPARTMENT:

Private Sub mnudepartment_details_Click()DataReport2.ShowEnd Sub

168

Page 169: Database Management Systems

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.

 

169

Page 170: Database Management Systems

The Help menu contains just one level-two item below it, About.

 

Invoke the Menu Editor from the Tools menu item as shown below:

 

170

Page 171: Database Management Systems

 

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.

171

Page 172: Database Management Systems

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

172