You are on page 1of 74

M.Sc.I.T.

Part I Paper IV, Section II: Advanced Database Management Systems


Practical Solution No.1 Vertical Fragmentation Creating table emp SQL> create table emp(eno integer,ename varchar(60),address varchar(50),email varchar(18),salary integer); Table created. Inserting values in table emp SQL> Insert into emp values (&eno,'&ename','&address','&email',&salary); Enter value for eno: 1 Enter value for ename: John Enter value for address: Newyork Enter value for email: john@yahoo.com Enter value for salary: 2100 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (1,'John','Newyork','john@yahoo.com',2100) 1 row created. SQL> / Enter value for eno: 2 Enter value for ename: Leena Enter value for address: UK Enter value for email: Leena@yahoo.com Enter value for salary: 3000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (2,'Leena','UK','Leena@yahoo.com',3000) 1 row created. SQL> / Enter value for eno: 3 Enter value for ename: Neena Enter value for address: virginia Enter value for email: Neena@yahoo.com Enter value for salary: 500 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (3,'Neena','virginia','Neena@yahoo.com',500) 1 row created. SQL> / Enter value for eno: 4 Enter value for ename: Durvesh Enter value for address: England Enter value for email: durvesh@gmail.com

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Enter value for salary: 900 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (4,'Durvesh','England','durvesh@gmail.com',900) 1 row created. SQL> / Enter value for eno: 5 Enter value for ename: Sahil Enter value for address: Amsterdam Enter value for email: sahil@gmail.com Enter value for salary: 5000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (5,'Sahil','Amsterdam','sahil@gmail.com',5000) 1 row created. SQL> / Enter value for eno: 6 Enter value for ename: Rohit Enter value for address: USA Enter value for email: Rohit@yahoo.com Enter value for salary: 20000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (6,'Rohit','USA','Rohit@yahoo.com',20000) 1 row created. SQL> / Enter value for eno: 7 Enter value for ename: Hitesh Enter value for address: Canada Enter value for email: Hitesh@yahoo.com Enter value for salary: 30000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (7,'Hitesh','Canada','Hitesh@yahoo.com',30000) 1 row created. SQL> / Enter value for eno: 8 Enter value for ename: Sandy Enter value for address: Germany Enter value for email: sandy@yahoo.com Enter value for salary: 45000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (8,'Sandy','Germany','sandy@yahoo.com',45000)

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
1 row created. SQL> / Enter value for eno: 9 Enter value for ename: Preeti Enter value for address: India Enter value for email: Preeti@yahoo.com Enter value for salary: 4000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (9,'Preeti','India','Preeti@yahoo.com',4000) 1 row created. SQL> / Enter value for eno: 10 Enter value for ename: Scott Enter value for address: India Enter value for email: Scott@yahoo.com Enter value for salary: 50000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (10,'Scott','India','Scott@yahoo.com',50000) 1 row created. SQL> select * from emp@link1; ENO ENAME ADDRESS EMAIL SALARY ---------- ------------------------------------------------------------ -----------------------------------1 John Newyork john@yahoo.com 2100 2 3 4 5 6 7 8 9 10 10 rows selected. Creating table emp1 SQL> create table emp1 as (Select eno,ename,address from emp); Leena Neena Durvesh Sahil Rohit Hitesh Sandy Preeti Scott UK virginia England Amsterdam USA Canada Germany India India Leena@yahoo.com Neena@yahoo.com durvesh@gmail.com sahil@gmail.com Rohit@yahoo.com Hitesh@yahoo.com sandy@yahoo.com Preeti@yahoo.com Scott@yahoo.com 3000 500 900 5000 20000 30000 45000 4000 50000

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Table created. SQL> select * from emp1@link2; ENO ENAME ADDRESS ---------- ------------------------------------------------------------ --------------1 John Newyork 2 3 4 5 6 7 8 9 10 10 rows selected. Creating table emp2 SQL> create table emp2 as (Select eno,email,salary from emp); Table created. SQL> select * from emp2@link3; ENO ---------1 2 3 4 5 6 7 8 EMAIL ------------john@yahoo.com Leena@yahoo.com Neena@yahoo.com durvesh@gmail.com sahil@gmail.com Rohit@yahoo.com Hitesh@yahoo.com sandy@yahoo.com SALARY ---------2100 3000 500 900 5000 20000 30000 45000 Leena Neena Durvesh Sahil Rohit Hitesh Sandy Preeti Scott UK virginia England Amsterdam USA Canada Germany India India

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
9 10 10 rows selected. Find the salary of an employee where employee number is known SQL> select emp2.eno@link3,emp2.salary@link3 from emp2@link3 where emp2.eno@link3=5; ENO ---------5 6 Find the email where the employee name is known SQL> select emp1.ename@link2,emp2.email@link3 from emp2@link3,emp1@link2 where emp1.eno@link2=emp2.eno@link3 and emp1.ename@link2='Scott'; ENAME -----------------Scott EMAIL -----------------Scott@yahoo.com SALARY ---------5000 Preeti@yahoo.com Scott@yahoo.com 4000 50000

Find the employee name and email where employee number is known SQL> select emp1.eno@link2,emp1.ename@link2,emp2.email@link3 from emp1@link2,emp2@link3 where emp1.eno@link2=emp2.eno@link3 and emp2.eno@link3=7; ENO 7 ENAME Hitesh EMAIL Hitesh@yahoo.com

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

Find the employee name whose salary>2000 SQL> select emp1.ename@link2,emp2.salary@link3 from emp1@link2,emp2@link3 where emp1.eno@link2=emp2.eno@link3 and emp2.salary@link3>2000;

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
ENAME John Leena Sahil Rohit Hitesh Sandy Preeti Scott 8 rows selected. Conclusion: Thus the above practical demonstrates the concept of vertical fragmentation. SALARY 2100 3000 5000 20000 30000 45000 4000 50000

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

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Practical Solution No. 2 Horizontal Fragmentation Creating table emp SQL> create table emp(eno integer,ename varchar(60),address varchar(50),email varchar(18),salary integer); Table created.

Inserting values in table emp SQL> Insert into emp values (&eno,'&ename','&address','&email',&salary); Enter value for eno: 1 Enter value for ename: John Enter value for address: Newyork Enter value for email: john@yahoo.com Enter value for salary: 10000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (1,'John','Newyork','john@yahoo.com',10000) 1 row created. SQL> / Enter value for eno: 2 Enter value for ename: Geeta Enter value for address: UK Enter value for email: geeta@yahoo.com Enter value for salary: 10000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (2,'Geeta','UK','geeta@yahoo.com',10000) 1 row created. SQL> / Enter value for eno: 3 Enter value for ename: Hitesh Enter value for address: Virginia Enter value for email: Hitesh@yahoo.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (3,'Hitesh','Virginia','Hitesh@yahoo.com',15000) 1 row created. SQL> / Enter value for eno: 4

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Enter value for ename: Rohit Enter value for address: USA Enter value for email: rohit@yahoo.com Enter value for salary: 10000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (4,'Rohit','USA','rohit@yahoo.com',10000) 1 row created. SQL> / Enter value for eno: 5 Enter value for ename: Raj Enter value for address: Russia Enter value for email: raj@gmail.com Enter value for salary: 19000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (5,'Raj','Russia','raj@gmail.com',19000) 1 row created. SQL> / Enter value for eno: 6 Enter value for ename: Preeti Enter value for address: India Enter value for email: aniha@gmail.com Enter value for salary: 12000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (6,'Preeti','India','aniha@gmail.com',12000) 1 row created. SQL> / Enter value for eno: 7 Enter value for ename: Scott Enter value for address: NewZealand Enter value for email: scott@yahoo.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (7,'Scott','NewZealand','scott@yahoo.com',15000) 1 row created. SQL> / Enter value for eno: 8 Enter value for ename: Seema Enter value for address: Canada Enter value for email: seema@yahoo.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (8,'Seema','Canada','seema@yahoo.com',15000)

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
1 row created. SQL> / Enter value for eno: 9 Enter value for ename: Sahil Enter value for address: Africa Enter value for email: ahil@gmail.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (9,'Sahil','Africa','ahil@gmail.com',15000) 1 row created. SQL> / Enter value for eno: 10 Enter value for ename: Atif Enter value for address: America Enter value for email: atif@yahoo.com Enter value for salary: 10000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (10,'Atif','America','atif@yahoo.com',10000) 1 row created.

SQL> select * from emp@link1; ENO 1 2 3 4 5 6 7 8 9 10 ENAME John Geeta Hitesh Rohit Raj Preeti Scott Seema Sahil Atif ADDRESS Newyork UK Virginia USA Russia India NewZealand Canada Africa America EMAIL john@yahoo.com geeta@yahoo.com Hitesh@yahoo.com rohit@yahoo.com raj@gmail.com aniha@gmail.com scott@yahoo.com seema@yahoo.com ahil@gmail.com atif@yahoo.com SALARY 10000 10000 15000 10000 19000 12000 15000 15000 15000 10000 ---------- ------------------------------------------------------------ ------------------------------------

10 rows selected.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Creating table emp1 SQL> create table emp1 as (select eno,ename,address,email,salary from emp where salary=10000); Table created. SQL> select * from emp1@link2; ENO 1 2 4 Atif ENAME John Geeta Rohit America ADDRESS Newyork UK USA EMAIL john@yahoo.com geeta@yahoo.com rohit@yahoo.com atif@yahoo.com 10000 SALARY 1000 10000 10000 10 ---------- ------------------------------------------------------------ ------------------------------------

Creating table emp2 SQL> create table emp2 as (select eno,ename,address,email,salary from emp where salary>10000 and salary<=20000); Table created. SQL> select * from emp2@link3; ENO 3 5 6 7 8 9 ENAME Hitesh Raj Preeti Scott Seema Sahil ADDRESS Virginia Russia India NewZealand Canada Africa EMAIL Hitesh@yahoo.com raj@gmail.com aniha@gmail.com scott@yahoo.com seema@yahoo.com ahil@gmail.com SALARY 15000 19000 12000 15000 15000 15000 ---------- ------------------------------------------------------------ -----------------------------------

6 rows selected.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Find the salary of all employees SQL> select ename,salary from emp1@link2 union select ename,salary from emp2@link3 union select ename,salary from emp@link1 ENAME Preeti Atif Geeta John Scott Hitesh Raj Rohit Sahil Seema 10 rows selected. Find the email of all employees where salary = 15000. SQL> select emp2.email@link3,emp2.salary@link3 from emp2@link3 where emp2.salary@link3=15000; EMAIL -----------------Hitesh@yahoo.com scott@yahoo.com seema@yahoo.com ahil@gmail.com SALARY ---------15000 15000 15000 15000 SALARY 12000 10000 10000 10000 15000 15000 19000 10000 15000 15000

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

Find the employee name and email where employee number is known. SQL> select emp1.eno@link2,emp1.ename@link2,emp1.email@link2 from emp1@link2 where emp1.eno@link2=2 union select

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
emp2.eno@link3,emp2.ename@link3,emp2.email@link3 from emp2@link3 where emp2.eno@link3=2; ENO 2 ENAME Geeta EMAIL geeta@yahoo.com ---------- ------------------------------------------------------------ ------------------

Find the employee name and address where employee number is known. SQL> select emp1.eno@link2,emp1.ename@link2,emp1.address@link2 from emp1@link2 where emp1.eno@link2=5 union select emp2.eno@link3,emp2.ename@link3,emp2.address@link3 from emp2@link3 where emp2.eno@link3=5; ENO ENAME ADDRESS ---------- ------------------------------------------------------------ -----------------------------------5 Raj Russia Conclusion: Thus the above practical demonstrates the concept of horizontal fragmentation.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Practical Solution No. 3 Replication of Database Creating table emp SQL> create table emp(eno integer,ename varchar(60),address varchar(50),email varchar(18),salary integer); Table created. Inserting values in table emp SQL> Insert into emp values (&eno,'&ename','&address','&email',&salary); Enter value for eno: 1 Enter value for ename: John Enter value for address: canada Enter value for email: john@yahoo.com Enter value for salary: 10000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (1,'John','canada','john@yahoo.com',10000) 1 row created. SQL> / Enter value for eno: 2 Enter value for ename: geeta Enter value for address: virginia Enter value for email: geeta@yahoo.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (2,'geeta','virginia','geeta@yahoo.com',15000) 1 row created. SQL> / Enter value for eno: 3 Enter value for ename: Neeta Enter value for address: UK Enter value for email: neeta@yahoo.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (3,'Neeta','UK','neeta@yahoo.com',15000) 1 row created. SQL> / Enter value for eno: 4 Enter value for ename: Raj Enter value for address: england

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Enter value for email: raj@gmail.com Enter value for salary: 6000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (4,'Raj','england','raj@gmail.com',6000) 1 row created. SQL> / Enter value for eno: 5 Enter value for ename: Pooja Enter value for address: India Enter value for email: pooja@yahoo.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (5,'Pooja','India','pooja@yahoo.com',15000) 1 row created. SQL> / Enter value for eno: 6 Enter value for ename: Sahil Enter value for address: Amsterdam Enter value for email: sahil@yahoo.com Enter value for salary: 8000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (6,'Sahil','Amsterdam','sahil@yahoo.com',8000) 1 row created. SQL> / Enter value for eno: 7 Enter value for ename: Tom Enter value for address: Japan Enter value for email: tom@yahoo.com Enter value for salary: 15000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (7,'Tom','Japan','tom@yahoo.com',15000) 1 row created. SQL> / Enter value for eno: 8 Enter value for ename: Jerry Enter value for address: Malaysia Enter value for email: jerry@yahoo.com Enter value for salary: 4000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (8,'Jerry','Malaysia','jerry@yahoo.com',4000)

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

1 row created. SQL> / Enter value for eno: 9 Enter value for ename: Mini Enter value for address: London Enter value for email: mini@yahoo.com Enter value for salary: 9000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (9,'Mini','London','mini@yahoo.com',9000) 1 row created. SQL> / Enter value for eno: 10 Enter value for ename: Mickey Enter value for address: Florida Enter value for email: mickey@yahoo.com Enter value for salary: 50000 old 1: Insert into emp values (&eno,'&ename','&address','&email',&salary) new 1: Insert into emp values (10,'Mickey','Florida','mickey@yahoo.com',50000) 1 row created. SQL> select * from emp@link1; ENO ENAME ADDRESS EMAIL SALARY ---------- ------------------------------------------------------------ -----------------------------------1 John canada john@yahoo.com 10000 2 3 4 5 6 7 8 9 10 geeta Neeta Raj Pooja Sahil Tom Jerry Mini Mickey virginia UK england India Amsterdam Japan Malaysia London Florida geeta@yahoo.com neeta@yahoo.com raj@gmail.com pooja@yahoo.com sahil@yahoo.com tom@yahoo.com jerry@yahoo.com mini@yahoo.com mickey@yahoo.com 15000 15000 6000 15000 8000 15000 4000 9000 50000

10 rows selected. Find the salary of all employees.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
SQL> select emp.eno@link1,emp.ename@link1,emp.salary@link2 from emp@link1,emp@link2 where emp.eno@link1=emp.eno@link2; ENO 1 2 3 4 5 6 7 8 9 10 10 rows selected. Find the email of all employees where salary=15000. SQL> select emp.eno@link1,emp.email@link2 from emp@link1,emp@link2 where emp.eno@link1=emp.eno@link2 and emp.salary@link1=15000; ENAME john geeta Neeta Raj Pooja Sahil Tom Jerry Mini Mickey SALARY 10000 15000 15000 6000 15000 8000 15000 4000 9000 50000

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

ENO ---------2 3 5 7

EMAIL -----------------geeta@yahoo.com Neeta@yahoo.com pooja@yahoo.com tom@yahoo.com

Find the employee name and email where employee number is known. SQL> select emp.eno@link1, emp.ename@link1,emp.email@link2 from emp@link1,emp@link2 where emp.eno@link1=2 and emp.eno@link2=2;

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
ENO 2 ENAME geeta EMAIL geeta@yahoo.com

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

Find the employee name and address where employee number is known. SQL> select emp.eno@link1,emp.ename@link1,emp.address@link2 from emp@link1,emp@link2 where emp.eno@link1=2 and emp.eno@link2=2; ENO ENAME ADDRESS ---------- ------------------------------------------------------------ -----------------------------------2 geeta Virginia Conclusion: Thus the above practical demonstrates the concept of replication.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Practical Solution No. 4 Object Oriented Databases Creating types and tables SQL> Create or replace type AddrType1 as object (Pincode number (5), Street char (20), City varchar2(50), state varchar2(40), no number(4) ); Type created. SQL> create or replace type BranchType as object (address AddrType1, phone1 integer, phone2 integer ); Type created. SQL> create or replace type BranchTableType as table of BranchType; 2 / Type created. SQL> create or replace type AuthorType as object (name varchar2 (50), addr AddrType1) 2/ Type created. SQL> create table Authors of AuthorType; Table created. SQL> create or replace type AuthorListType as varray(10) of ref AuthorType 2/ Type created. SQL> create or replace type PublisherType as object(name varchar2(50), addr AddrType1, branches BranchTableType) SQL> / Type created. SQL> create table Publishers of PublisherType NESTED TABLE branches STORE as branchtable SQL> / Table created.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
SQL> create table books(title varchar2(50), year date, published_by ref PublisherType, authors AuthorListType) SQL> / Table created. Inserting values in the tables SQL> insert into Authors values('Sangoi', AddrType1(7000,'Dalal street', 'mumbai', 'maharashtra',1007)); 1 row created. SQL> insert into Authors values('Rabiner', AddrType1(7007,'Singh street', 'mumbai', 'maharashtra',1006)); 1 row created. SQL> insert into Authors values('Schiller',AddrType1(7008,'Pali street', 'nasik', 'maharashtra',1008)); 1 row created. SQL> insert into Authors values('Jerry',AddrType1(7003,'Tagore street', 'mumbai', 'maharashtra',1003)); 1 row created. SQL> insert into Authors values('Sangoi',AddrType1(7008,'Dalal street', 'mumbai', 'maharashtra',1007)); 1 row created. SQL> insert into Authors values ('A.K.Mehta', AddrType1 (7006,'Nehru street','mumbai', 'maharashtra',1005)); 1 row created SQL> insert into Authors values ('Ramakrishnan', AddrType1(8002,'Thakur street', 'pune','maharashtra',13)); 1 row created

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
SQL> insert into Authors values('Richard',AddrType1(7002,'Flower street','pune', 'maharashtra',03)); 1 row created. SQL> select * from Authors; NAME ADDR (PINCODE, STREET, CITY, STATE, NO) -------------------------------------------------------------------------------Sangoi ADDRTYPE1 ( 7000, 'Dalal street , 'mumbai', 'maharashtra', 1007) Rabiner Schiller ADDRTYPE1 ( ADDRTYPE1 ( 7007, 7008, 'Singh street ', 'mumbai', 'Pali street ', 'nasik', 'maharashtra', 1006) 'maharashtra', 1008)

NAME ADDR (PINCODE, STREET, CITY, STATE, NO) -------------------------------------------------------------------------------Jerry ADDRTYPE1 ( 7003, 'Tagore street ', 'mumbai', 'maharashtra', 1003) Sangoi ADDRTYPE1 ( 7008, 'Dalal street ', 'mumbai', 'maharashtra', 1007) 'Nehru street , 'mumbai', 'maharashtra', 1005) STATE, NO)

A.K.Mehta ADDRTYPE1 ( 7006,

NAME ADDR (PINCODE, STREET, CITY, -------------------------------------------------------------------------------Ramakrishnan ADDRTYPE1 (8002, 'Thakur street ', 'pune', Richard ADDRTYPE1 (7002, 'Flower street , 'pune',

'maharashtra', 13) 'maharashtra', 3)

8 rows selected. Inserting values in table Publishers SQL> insert into Publishers values('Raj', AddrType1(4002,'Park street', 'mumbai', 'maharashtra',03), BranchTableType(BranchType(AddrType1(5002,'Pali street', 'mumbai','maharashtra',03),23406,69896))); 1 row created. SQL> insert into Publishers values('Rohit',AddrType1(7007,'Lovely street','mumbai', 'maharashtra',07), BranchTableType(BranchType(AddrType1(7007,'K street','mumbai', 'maharashtra',1007),4543545,8676775)));

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

1 row created. SQL> insert into Publishers values('Tata',AddrType1(7008,'Jewel street','mumbai', 'maharashtra',27),BranchTableType(BranchType(AddrType1(1002,'Diamond street','nasik', 'maharashtra',1007),456767,7675757))); 1 row created. SQL> insert into Publishers values('Mcgrew', AddrType1(7002,'South street','pune', 'maharashtra',1007), BranchTableType(BranchType(AddrType1(1002,'South street','pune', 'maharashtra',1007),4543545,8676775))); 1 row created. SQL> insert into Publishers values('Tata', AddrType1(6002,'Gold street','nasik', 'maharashtra',1007), BranchTableType(BranchType(AddrType1(6002,'South street', 'nasik','mha',1007),4543545,8676775))); 1 row created.

SQL> select * from Publishers; NAME ADDR (PINCODE, STREET, CITY, STATE, NO) -------------------------------------------------------------------------------BRANCHES(ADDRESS(PINCODE, STREET, CITY, STATE, NO), PHONE1, PHONE2) -------------------------------------------------------------------------------Raj ADDRTYPE1(4002, 'Park street ', 'mumbai', 'maharashtra', 3) BRANCHTABLETYPE(BRANCHTYPE(ADDRTYPE1(5002, 'Pali street ', 'mumbai', 'maharashtra', 3), 23406, 69896)) Rohit ADDRTYPE1(7007, 'Lovely street ', 'mumbai', 'maharashtra', 7)

NAME -------------------------------------------------ADDR(PINCODE, STREET, CITY, STATE, NO)

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
-------------------------------------------------------------------------------BRANCHES(ADDRESS(PINCODE, STREET, CITY, STATE, NO), PHONE1, PHONE2) -------------------------------------------------------------------------------BRANCHTABLETYPE(BRANCHTYPE(ADDRTYPE1(7007, 'K street ', 'mumbai', 'maharashtra', 1007), 4543545, 8676775)) Tata ADDRTYPE1(7008, 'Jewel street ', 'mumbai', 'maharashtra', 27) BRANCHTABLETYPE(BRANCHTYPE(ADDRTYPE1(1002, 'Diamond street ', 'nasik', 'maharashtra', 1007), 456767, 7675757)) NAME -------------------------------------------------ADDR(PINCODE, STREET, CITY, STATE, NO) -------------------------------------------------------------------------------BRANCHES(ADDRESS(PINCODE, STREET, CITY, STATE, NO), PHONE1, PHONE2) -------------------------------------------------------------------------------Mcgrew ADDRTYPE1(7002, 'South street ', 'pune', 'maharashtra', 1007) BRANCHTABLETYPE(BRANCHTYPE(ADDRTYPE1(1002, 'South street ', 'pune', 'maharashtra', 1007), 4543545, 8676775)) Tata NAME -------------------------------------------------ADDR(PINCODE, STREET, CITY, STATE, NO) -------------------------------------------------------------------------------BRANCHES(ADDRESS(PINCODE, STREET, CITY, STATE, NO), PHONE1, PHONE2) -------------------------------------------------------------------------------ADDRTYPE1(6002, 'Gold street ', 'nasik', 'maharashtra', 1007) BRANCHTABLETYPE(BRANCHTYPE(ADDRTYPE1(6002, 'South street ', 'nasik', 'mha ', 1007), 4543545, 8676775)) Inserting values in table books SQL> insert into books 2 select 'IP','28-may-1983', ref (pub), AuthorListType(ref(aut)) from 3 Publishers pub,Authors aut where pub.name='Tata' and aut.name='Richard'; 1 row created. SQL> insert into books 2 select 'ADBMS','09-jan-1890',ref(pub), AuthorListType(ref(aut)) from 3 Publishers pub,Authors aut where pub.name='Mcgrew' and aut.name='Sangoi';

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

1 row created. SQL> insert into books 2 select 'c prog','25-may-1983', ref (pub),AuthorListType(ref(aut)) from 3 Publishers pub,Authors aut where pub.name='Raj' and aut.name='Ramkrishnan.'; 2 rows created. List all the authors that have the same pin code as their publisher SQL> select a.name from Authors a, Publishers p where a.addr.pincode = p.addr.pincode;

NAME ------------------------------------------------Richard Rabiner Schiller Sangoi

List of all books that have two or more Authors SQL> select * from books b where 1 < (select count (*) from table (b.authors)); no rows selected List the name of the publisher that has the most branches SQL> Select p.name from publishers p, table (p.branches) group by p.name having count(*)> = all (select count(*) from publishers p, table(p.branches) group by name); NAME --------------------------------------------------

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Tata

Name of authors who have not published more than a book SQL> select a.name from authors a, books b, table (b.authors) v where v.column_value = ref(a) group by a.name having count(*) = 1; no rows selected

List all the authors who have published more than one book & Name of authors who have published books with atleast two different publishers SQL> select a.name from authors a, books b, table (b.authors) v where v.column_value = ref(a) group by a.name having count(*) > 1; NAME -------------------------------------------------Richard Sangoi List all books (title) where the same author appears more than once on the list of authors (assuming that an integrity constraint requiring that the name of an author is unique in a list of authors has not been specified) SQL> select title from authors a, books b, table (b.authors) v where v.column_value = ref(a) group by title having count(*) > 1; TITLE -------------------------------------------------ADBMS IP Conclusion: Thus the above practical demonstrates the concept of Object Oriented databases.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Multimedia Databases Practical Solution No. 5[A] Creating table emp1 SQL> create table emp1 2 ( 3 Eno number(5), 4 Ename varchar2(50), 5 Eaddress varchar2(40), 6 photo long raw 7 ) 8 / Table created. Creating Table Company SQL> create table company 2 (eno number(5), 3 age number(3), 4 designation varchar2(30) 5 ) 6 / Table created. Inserting into table emp import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.sql.*; public class MMDB extends JFrame implements ActionListener { JLabel label1; JLabel lbleno; JLabel lblename;

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
JLabel lbladdress; JTextField txteno; JTextField txtename; JTextField txtaddress; JTextField txtfilepath; JButton insert; JButton browse; static String filename=null; File file; Connection con; PreparedStatement ps; static int fileno=0; public MMDB() { super("Multimedia Database"); label1=new JLabel("Enter file path :"); label1.setFont(new Font("Verdana",Font.PLAIN,12)); txtfilepath=new JTextField(25); txtfilepath.setFont(new Font("Verdana",Font.PLAIN,12)); lbleno=new JLabel("Enter the employee no"); txteno=new JTextField(10); lblename=new JLabel("Enter the employee name"); txtename=new JTextField(10); lbladdress=new JLabel("Enter the employee address"); txtaddress=new JTextField(10); browse=new JButton("Browse"); browse.setMnemonic('W'); browse.setFont(new Font("Verdana",Font.PLAIN,12)); insert=new JButton("Insert"); insert.setMnemonic('I'); insert.setFont(new Font("Verdana",Font.PLAIN,12)); getContentPane().setLayout(new FlowLayout());

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
getContentPane().add(lbleno); getContentPane().add(txteno); getContentPane().add(lblename); getContentPane().add(txtename); getContentPane().add(lbladdress); getContentPane().add(txtaddress); getContentPane().add(label1); getContentPane().add(txtfilepath); getContentPane().add(browse); getContentPane().add(insert); insert.addActionListener(this); browse.addActionListener(this); setSize(800,600); setVisible(true); } public void actionPerformed(ActionEvent evt) { if (evt.getSource()==browse) { open(); } if (evt.getSource()==insert) { Insertdata(); } } public static void main(String a[]) { new MMDB(); } public void Insertdata() { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:ds2", "system", "tiger");

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
file=new File(txtfilepath.getText()); FileInputStream fis=new FileInputStream(file); ps=con.prepareStatement("insert into emp1 values(?,?,?,?)"); ps.setInt(1,Integer.parseInt(txteno.getText())); ps.setString(2,txtename.getText()); ps.setString(3,txtaddress.getText()); ps.setBinaryStream(4,fis,(int)file.length()); ps.executeUpdate(); con.close(); System.out.println("Inserted...."); } catch(Exception e) { System.out.println(e.getMessage()); } } public void open() { FileDialog fd=new FileDialog(this,"Select File",FileDialog.LOAD); fd.show(); if(fd.getFile()!=null){ txtfilepath.setText(fd.getDirectory()+fd.getFile()); filename=fd.getFile(); } } }

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Output:

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Retrieving values from table emp1 import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.sql.*; public class retriveimage1 extends JFrame { static JComboBox imageid; JLabel label1,label2; JButton save; static String Imagename=""; String filename=""; ImageIcon image; JLabel imagelabel; Connection con; Statement statement; byte[] imageBytes=new byte[2048]; public retriveimage1() { super("Multimedia Database"); label1=new JLabel("Select Image No:"); label1.setFont(new Font("Verdana",Font.PLAIN,12)); label2=new JLabel("Your selected Image name is:"); label2.setFont(new Font("Verdana",Font.PLAIN,12)); imageid =new JComboBox(); imageid.setFont(new Font("Verdana",Font.PLAIN,12)); imageid.setRequestFocusEnabled(true);

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
fillid(); imagelabel=new JLabel(); save=new JButton("Save"); save.setMnemonic('S'); save.setFont(new Font("Verdana",Font.PLAIN,12)); getContentPane().setLayout(new FlowLayout()); getContentPane().add(label1); getContentPane().add(imageid); getContentPane().add(label2); getContentPane().add(save); getContentPane().add(imagelabel); setSize(800,600); setVisible(true); imageid.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try{ getImage(); }catch(Exception e) {System.out.println("Error"+e.getMessage());} } }); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { save(); } });

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
} public void fillid() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:ds1", "system", "tiger"); statement=con.createStatement(); String SQL="SELECT eno FROM emp1 ORDER BY eno"; ResultSet resultset=statement.executeQuery(SQL); while(resultset.next()) imageid.addItem(resultset.getString(1)); } catch(Exception e) { System.out.println(e.getMessage()); } } public void getImage() { Imagename=""; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:ds1", "system", "tiger"); statement=con.createStatement(); String SQL="SELECT * FROM emp1 WHERE eno="+imageid.getSelectedItem(); ResultSet resultset=statement.executeQuery(SQL); while(resultset.next()) {

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Imagename=resultset.getString("ename"); imageBytes=resultset.getBytes("photo"); } image=new ImageIcon(imageBytes); imagelabel.setIcon(image); label2.setText("Your selected Image name is : "+Imagename); resultset.close(); statement.close(); con.close(); } catch(Exception e) { System.out.println(e.getMessage()); } } public void save() { FileDialog fd=new FileDialog(this,"Save File",FileDialog.SAVE); fd.setFile(Imagename); fd.show(); if(fd.getFile()!=null) { filename=fd.getDirectory()+fd.getFile(); try { FileOutputStream fos = new FileOutputStream(new File(filename)); fos.write(imageBytes); fos.close(); } catch(Exception e)

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
{ System.out.println("File not saved..."); } } } public static void main(String args[]) { new retriveimage1(); } }

Inserting values in Table Company SQL> insert into company values (1, 21, 'Jr. Application Programmer'); 1 row created. SQL> insert into company values (2, 33, 'Sr. Application Programmer'); 1 row created. SQL> insert into company values (3, 28, 'Project Manager'); 1 row created.

SQL> insert into company values (4, 28, 'Jr. Application Programmer'); 1 row created. SQL> insert into company values (5, 36, 'Sr. Application Programmer'); 1 row created. SQL> insert into company values (6, 21, 'Project Manager'); 1 row created.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

SQL> select * from company; ENO 1 2 3 4 5 6 AGE 21 33 28 28 36 21 DESIGNATION Jr. Application Programmer Sr. Application Programmer Project Manager Jr. Application Programmer Sr. Application Programmer Project Manager

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

Find the name and designation of all the employees SQL> select ename, designation from Emp1, company where Emp1.eno = company.eno; ENAME Rahul Raj Rajiv Sheetal Divya Jobby DESIGNATION Jr. Application Programmer Sr. Application Programmer Project Manager Jr. Application Programmer Sr. Application Programmer Project Manager

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

Find the name and age of all the employees SQL> select ename, age from Emp1, company where Emp1.eno = company.eno ENAME Rahul Raj Rajiv Sheetal Divya AGE 21 33 28 28 36

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

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Jobby 21

Find the name and photo of a particular employee.

Conclusion: Thus the above practical demonstrates the concept of multimedia databases.

Practical Solution No. 5[B] Creating table Singer SQL> create table Singer ( Sno integer, Sname char(20), Address char(100), AudioClip blob,primary key (Sno)); Table created.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Creating Table Company SQL> create table Company(Sno integer, Age integer, primary key (Sno)); Table created. Inserting values in table singer import java.awt.*; import java.net.*; import javax.media.*; public class AudioPlayer { static Player player; static Component visualComponent; public AudioPlayer(String StrFile) { String mediaFile =""; URL mediaURL = null; try{ mediaURL = new URL ( "file:/"+StrFile); System.out.println(mediaURL); player = Manager.createPlayer(mediaURL); if ( player != null) { //player.addControllerListener(this); } else { System.err.println("Fail to create player "+mediaURL); } player.prefetch(); player.start(); }catch(Exception a){} } } File: AudioDemo.java import java.io.*; import java.sql.*; import javax.swing.*; public class AudioDemo {

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
public static void main (String args[]) throws Exception { Connection Con; Statement Stat; ResultSet Res; PreparedStatement PrepStatSinger , PrepStatCompany; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Con = DriverManager.getConnection("jdbc:odbc:dataS","system","pass"); Stat = Con.createStatement(); int IntSno,IntAge; String StrSname, StrAddress,StrPath,StrQueryEmployee, StrQueryCompany,StrQuery1,StrQuery2; Blob BlobPhoto; File FileAudio; BufferedReader br = new BufferedReader( new InputStreamReader( System.in)); int IntC ; System.out.println("Insert : 1 View : 2 "); IntC = Integer.parseInt(br.readLine()); switch(IntC) { case 1: System.out.println("Enter Singer Information"); System.out.println("Singer Number : "); IntSno = Integer.parseInt(br.readLine()); System.out.println("Singer Name : "); StrSname = br.readLine(); System.out.println("Singer Age :"); IntAge = Integer.parseInt(br.readLine()); System.out.println("Singer Address : "); StrAddress = br.readLine(); System.out.println("Singers Song File Path : "); StrPath = br.readLine(); FileAudio = new File(StrPath); FileInputStream fp = new FileInputStream(FileAudio); byte BytPic[]; PrepStatSinger = Con.prepareStatement("Insert into Singer values(?,?,?,?)"); PrepStatCompany= Con.prepareStatement("Insert into Company values(?,?)"); //Inserting parameters into prepared statements PrepStatSinger.setInt(1,IntSno); PrepStatSinger.setString(2,StrSname); PrepStatSinger.setString(3,StrAddress); PrepStatSinger.setBinaryStream(4,fp,(int) fp.available()); PrepStatCompany.setInt(1,IntSno); PrepStatCompany.setInt(2,IntAge); PrepStatSinger.executeUpdate();

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
PrepStatCompany.executeUpdate(); PrepStatSinger.close(); PrepStatCompany.close(); break;//break of main 1 case 2: System.out.println ("Enter Query Number 1 or 2 "); int IntChoice = Integer.parseInt(br.readLine()); switch(IntChoice) { case 1: StrQuery1 = "Select S.Sname , C.Age from Singer S , Company C where S.Sno = C.Sno "; Res = Stat.executeQuery(StrQuery1); System.out.println("Name \t Age"); while (Res.next()) System.out.println(Res.getString("Sname")+"\t"+Res.getString("Age")+"\n"); Res.close(); Stat.close(); break; case 2: System.out.println ("Enter Singer number to hear Audio Clip"); int IntSngNo = Integer.parseInt(br.readLine()); StrQuery2 = "Select * from Singer where Sno = "+IntSngNo; Res = Stat.executeQuery(StrQuery2); System.out.println("Name \t "); Res.next(); byte SongByte[] = Res.getBytes("AudioClip"); FileOutputStream Fp = new FileOutputStream("C:/Temp.mp3"); Fp.write(SongByte); Fp.close(); new AudioPlayer("C:/Temp.mp3"); Res.close(); Stat.close(); break; default: System.out.println("Option not recognized"); }//end of switch inner break;//end of switch 2 main }//end of swithc main //Stat.executeQuery(StrQueryCompany); Con.close(); }//END OF MAIN METHOD }//END OF CLASS Inserting values in table Company:

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
SQL> insert into company values (1, 21); 1 row created. SQL> insert into company values (2, 33); 1 row created. SQL> insert into company values (3, 28); 1 row created. SQL> insert into company values (4, 28); 1 row created. SQL>select * from Company; ENO AGE ---------- ---------1 2 3 4 21 33 28 28

Find name and age of all singers SQL> select sname, age from Singer, Company where Singer.sno = Company.sno SNAME ---------Mithun Meena Rahul Raj AGE ---------21 33 28 28

Find name and audio clip of a particular singer

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Conclusion: Thus the above practical demonstrates the concept of multimedia databases.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Practical Solution No. 5[C] Creating table Singer SQL> create table Singer ( Sno integer, Sname char(20), Address char(100), VideoClip blob,primary key (Sno)); Table created Creating table Company SQL> create table Company(Sno integer, Age integer, primary key (Sno)); Table created. Inserting in table Singer import javax.swing.*; import javax.media.*; import java.awt.*; import java.awt.event.*; import java.net.*; public class VideoPlayer extends JFrame implements ControllerListener { Player videoPlayer; URL videoUrl; Component visualComponent; public VideoPlayer(String StrPath)throws Exception { super("Video Player"); setVisible(true); setSize(800,600); getContentPane().setLayout(new BorderLayout()); videoUrl = new URL ("file:/"+StrPath); videoPlayer = Manager.createPlayer(videoUrl); videoPlayer.addControllerListener(this); videoPlayer.prefetch(); videoPlayer.start(); }

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

public synchronized void controllerUpdate(ControllerEvent event) { if ( event instanceof RealizeCompleteEvent) { if ((visualComponent = videoPlayer.getVisualComponent()) != null) getContentPane().add("Center",visualComponent); validate(); } else if ( event instanceof PrefetchCompleteEvent) { videoPlayer.start(); } } }//end of class File VideoDemo.java: import java.io.*; import java.sql.*; import javax.swing.*; public class VideoDemo { public static void main (String args[]) throws Exception { Connection Con; Statement Stat; ResultSet Res; PreparedStatement PrepStatSinger , PrepStatCompany; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Con = DriverManager.getConnection("jdbc:odbc:dataS","system","pass"); Stat = Con.createStatement(); int IntSno,IntAge; String StrSname, StrAddress, StrPath,StrQuery1,StrQuery2; File FileVideo; BufferedReader br = new BufferedReader( new InputStreamReader( System.in)); int IntC ; System.out.println("Insert : 1 View : 2 "); IntC = Integer.parseInt(br.readLine()); switch(IntC) { case 1: System.out.println("Enter Singer Information");

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
System.out.println("Singer Number : "); IntSno = Integer.parseInt(br.readLine()); System.out.println("Singer Name : "); StrSname = br.readLine(); System.out.println("Singer Age :"); IntAge = Integer.parseInt(br.readLine()); System.out.println("Singer Address : "); StrAddress = br.readLine(); System.out.println("Singers Video File Path : "); StrPath = br.readLine(); FileVideo = new File(StrPath); FileInputStream fp = new FileInputStream(FileVideo); byte BytPic[]; PrepStatSinger = Con.prepareStatement("Insert into Singer values(?,?,?,?)"); PrepStatCompany= Con.prepareStatement("Insert into Company values(?,?)"); //Inserting parameters into prepared statements PrepStatSinger.setInt(1,IntSno); PrepStatSinger.setString(2,StrSname); PrepStatSinger.setString(3,StrAddress); PrepStatSinger.setBinaryStream(4,fp,(int) fp.available()); PrepStatCompany.setInt(1,IntSno); PrepStatCompany.setInt(2,IntAge); PrepStatSinger.executeUpdate(); PrepStatCompany.executeUpdate(); PrepStatSinger.close(); PrepStatCompany.close(); break;//break of main 1 case 2: System.out.println ("Enter Query Number 1 or 2 "); int IntChoice = Integer.parseInt(br.readLine()); switch(IntChoice) { case 1: StrQuery1 = "Select S.Sname , C.Age from Singer S , Company C where S.Sno = C.Sno "; Res = Stat.executeQuery(StrQuery1); System.out.println("Name \t Age"); while (Res.next()) System.out.println(Res.getString("Sname") +"\t"+Res.getString("Age")+"\n");

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
Res.close(); Stat.close(); break; case 2: System.out.println ("Enter Singer number to watch Video Clip"); int IntSngNo = Integer.parseInt(br.readLine()); StrQuery2 = "Select * from Singer where Sno = "+IntSngNo; Res = Stat.executeQuery(StrQuery2); System.out.println("Name \t "); byte[] SongByte = new byte[2048]; while(Res.next()) SongByte = Res.getBytes("VedioClip"); FileOutputStream Fp = new FileOutputStream("C:/Temp.mpg"); Fp.write(SongByte); Fp.close(); new VideoPlayer("C:/Temp.mpg"); Res.close(); Stat.close(); break; default: System.out.println("Option not recognized"); }//end of switch inner break;//end of switch 2 main }//end of swithc main //Stat.executeQuery(StrQueryCompany); Con.close(); }//END OF MAIN METHOD }//END OF CLASS Inserting values in table Company: SQL> insert into company values (1, 21); 1 row created. SQL> insert into company values (2, 33); 1 row created. SQL> insert into company values (3, 28); 1 row created. SQL> insert into company values (4, 28);

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems
1 row created. SQL>select * from Company; ENO AGE ---------- ---------1 2 3 4 21 33 28 28

Find name and age of all singers SQL> select sname, age from Singer, Company where Singer.sno = Company.sno SNAME ---------Mithun Ashtavi Rahul Raj AGE ---------21 23 28 28

Find name and audio clip of a particular singer

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Conclusion: Thus the above practical demonstrates the concept of multimedia databa

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Practical Solution No. 6 Temporal Databases [A] create table tblemp_appnt(accountno number(6),name varchar2(15),recruitmentdate date,retirementdate date) INSERT INTO tblEmp_Appnt values(101,'rajesh',to_date('2-3-2001','DD-MM-YYYY'),to_date('13-04-2005','DD-MMYYYY')); INSERT INTO tblEmp_Appnt values(102,'john',to_date('12-8-2002','DD-MM-YYYY'),to_date('12-07-2004','DD-MMYYYY')); INSERT INTO tblEmp_Appnt values(103,'suresh',to_date('11-3-2002','DD-MM-YYYY'),to_date('13-07-2005','DD-MMYYYY')); INSERT INTO tblEmp_Appnt values(104,'nilesh',to_date('2-3-2003','DD-MM-YYYY'),to_date('13-09-2005','DD-MMYYYY')); INSERT INTO tblEmp_Appnt values(105,'ritesh',to_date('8-7-2000','DD-MM-YYYY'),to_date('2-3-2001','DD-MMYYYY')); SQL> select * from tblEmp_Appnt; [B] create table tbl_shares(company_name varchar2(10),no_shares number(5),price number(5),transaction_time varchar2(6)); insert into tbl_Shares values('Reliance',10000,500,to_date('11:45','hh24:mi')); insert into tbl_Shares values('IFlex',20000,950,to_date('11:15','hh24:mi')); insert into tbl_Shares values('IMax',10000,250,to_date('11:22','hh24:mi')); insert into tbl_Shares values(Reliance',950,20000,to_date('17:00','hh24:mi')); insert into tbl_Shares values('Raymonds',5000,450,to_date('17:00','hh24:mi')); insert into tbl_Shares values('Raymonds',5000,450,to_date('11:45','hh24:mi'));

SQL>alter session set nls_date_format = 'HH24:MI'; Firing queries on above tables:

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Query1 SQL> select * from tblEmp_Appnt where RecruitementDate= to_date('1-02-1985','ddmm-yyyy'); ACCOUNT NO ---------106 NAME --------------rajesh RECRUITEM RETIREMEN ----------------01-FEB-85 31-JAN-00

Query2 SQL> select * from tblEmp_Appnt where RetirementDate = to_date('23-07-2010','ddmm-yyyy') ACCOUNT NO ---------101 NAME --------------john RECRUITEM --------23-JUL-80 RETIREMEN --------23-JUL-10

Query3 SQL>select company_name from tbl_shares where price>100 and transaction_time='11.45' COMPANY_NA ---------Reliance Raymonds Query4 SQL>select company_name from tbl_shares where price in(select max(price) from tbl_shares)and transaction_time='17:00' COMPANY_NA ---------Reliance

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Practical Solution No. 7 Active Databases Creating Table emp SQL> create table emp(eno integer primary key,ename varchar(20),hrs number(8),pno integer,super_no integer CONSTRAINT sup UNIQUE); Table created. Inserting values in table emp SQL> insert into Emp values (1,'Nita', 7, 10, 1001); 1 row created. SQL> insert into Emp values (2,'Sita', 5, 20, 1002); 1 row created. SQL> insert into Emp values(3,'Rahul',3,10,1003); 1 row created. SQL> insert into Emp values (4,'Raj', 1, 20, 1004); 1 row created. SQL> insert into Emp values (5,'Sahil', 5, 30, 1005); 1 row created. SQL> insert into Emp values (6,'Rohit', 8, 40, 1006); 1 row created. SQL> insert into Emp values (7,'Riya', 3, 30, 1007); 1 row created. SQL> insert into Emp values (8,'Pooja', 12, 40, 1008); 1 row created. SQL> insert into Emp values (9,'aarti', 1, 10, 1009); 1 row created. SQL> select * from Emp;

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Creating Table project SQL> create table project(pno integer primary key, pname varchar(20), thrs number(8), super_no integer CONSTRAINT supfk references emp(super_no)); Table created. Inserting values in table project SQL> insert into project values (10,'Mobile Communication', 10, 1001); 1 row created. SQL> insert into project values (20,'Simulation', 6, 1002); 1 row created. SQL> insert into project values (30,'ACN', 5, 1005); 1 row created. SQL> insert into project values (40,'ADBMS', 5, 1008); 1 row created. SQL> select * from project; PNO PNAME THRS SUPER_NO ---------- ----------------------------- ---------10 Mobile Communication 10 1001 20 30 40 Simulation ACN ADBMS 6 9 5 1002 1005 1008

Creating a trigger to insert a new employee tuple and display the new total hours from project table. SQL> create or replace Trigger thrs after insert on emp for each row when (New.pno IS NOT NULL) 2 begin 3 update project 4 set thrs=thrs + :New.hrs 5 where pno=:New.pno;

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

6 end; 7/ Trigger created. SQL> insert into emp values (11,'Nina', 4, 30, 1011); 1 row created. SQL> select * from project; PNO PNAME THRS SUPER_NO ---------- ----------------------------- ---------10 Mobile Communication 10 1001 20 30 40 Simulation ACN ADBMS 6 9 5 1002 1005 1008

Creating a trigger to change the hours of existing employee and display the new total hours from project table. SQL> create Trigger thrs1 after update of hrs on emp for each row when (New.pno IS NOT NULL) 2 begin 3 update project 4 set thrs=thrs+:New.hrs-:Old.hrs 5 where pno=:New.pno; 6 end; 7/ Trigger created.

SQL> update emp 2 set hrs=10 3 where eno=11 4/ 1 row updated. SQL> select * from project; PNO PNAME ---------- -------------------THRS SUPER_NO ---------- ----------

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

10 20 30 40

Mobile Communication Simulation ACN ADBMS

10 6 9 5

1001 1002 1005 1008

Creating a trigger to change the project of an employee and display the new total hours from project table. SQL> create Trigger thrs2 after update of pno on emp for each row when(New.pno IS NOT NULL) 2 begin 3 update project 4 set thrs=thrs+:New.hrs-:Old.hrs 5 where pno=:New.pno; 6 end; 7 / Trigger created. SQL> update emp 2 set pno=10 3 where eno=2 4 / 1 row updated. SQL> update emp 2 set pno=20 3 where eno=7; 1 row updated SQL> select * from project; PNO PNAME THRS SUPER_NO ---------- ----------------------------- ---------10 Mobile Communication 10 1001 20 30 40 Simulation ACN ADBMS 6 9 5 1002 1005 1008

Creating a trigger for deleting the project of an employee . SQL> create trigger thrs4 after delete on emp for each row when (OLD.pno IS NOT NULL)

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

2 begin 3 update project 4 set thrs=thrs-:OLD.hrs 5 where pno=:OLD.pno; 6 end; 7/ Trigger created. SQL> delete from emp where eno=11; 1 row deleted. SQL> select * from project; PNO PNAME THRS SUPER_NO ---------- ----------------------------- ---------10 Mobile Communication 10 1001 20 30 40 Simulation ACN ADBMS 6 9 5 1002 1005 1008

Conclusion: Thus the above practical demonstrates the concept of active databases. Practical Solution No. 8 XML Databases

Creating table emp_xml SQL> create table emp_xml(dept_id number(4), employee_spec XMLtype) SQL> / Table created Inserting values in table emp_xml SQL> insert into emp_xml values(1,XMLtype( 2 '<emp id="1"> 3 <name> urmila </name> 4 <email>urmila@yahoo.com</email> 5 <acc_no>23456</acc_no> 6 <mgr_email>rupa.shah@hotmail.com</mgr_email>

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

7 <doj>12/12/2003</doj> 8 </emp>')) 9/ 1 row created SQL> insert into emp_xml values(1,XMLtype( 2 '<emp id="2"> 3 <name> anisha </name> 4 <email>ani@yahoo.com</email> 5 <acc_no>234346</acc_no> 6 <mgr_email>rupa.shah@hotmail.com</mgr_email> 7 <doj>2/6/2003</doj> 8 </emp>')) 9/ 1 row created SQL> insert into emp_xml values(1,XMLtype( 2 '<emp id="3"> 3 <name> megha </name> 4 <email>meghabhatt@yahoo.com</email> 5 <acc_no>2343456</acc_no> 6 <mgr_email>megha.bhatt@hotmail.com</mgr_email> 7 <doj>24/5/2001</doj> 8 </emp>')) 9> / 1 row created. SQL> insert into emp_xml values(1,XMLtype( 2 '<emp id="4"> 3 <name> nina </name> 4 <email>ninashah@yahoo.com</email> 5 <acc_no>2343678</acc_no> 6 <mgr_email>ekta.shah@hotmail.com</mgr_email> 7 <doj>21/5/2002</doj> 8 </emp>')) 9/ 1 row created SQL> insert into emp_xml values(1,XMLtype( 2 '<emp id="5"> 3 <name> nisha </name> 4 <email>nishashah@yahoo.com</email> 5 <acc_no>2343345</acc_no> 6 <mgr_email>nisha.shah@hotmail.com</mgr_email>

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

7 <doj>1/8/2002</doj> 8 </emp>')) 9/ 1 row created SQL> insert into emp_xml values(1,XMLtype( 2 '<emp id="6"> 3 <name> seeta </name> 4 <email>seetamehta@yahoo.com</email> 5 <acc_no>2343890</acc_no> 6 <mgr_email>seeta.mehta@hotmail.com</mgr_email> 7 <doj>2/1/2001</doj> 8 </emp>')) 9/ 1 row created SQL> insert into emp_xml values(2,XMLtype( 2 '<emp id="7"> 3 <name> meena </name> 4 <email>meenagupta@yahoo.com</email> 5 <acc_no>23433898</acc_no> 6 <mgr_email>falguni.shah@hotmail.com</mgr_email> 7 <doj>4/9/2002</doj> 8 </emp>')) 9 / 1 row created SQL> insert into emp_xml values(2,XMLtype( 2 '<emp id="8"> 3 <name> sandeep </name> 4 <email>sagupta@yahoo.com</email> 5 <acc_no>23567898</acc_no> 6 <mgr_email>sweta.shah@hotmail.com</mgr_email> 7 <doj>4/4/2004</doj> 8 </emp>')) 9/ 1 row created.

Retrieve the names of employee SQL> select e.employee_spec.extract('//name/text()').getStringVal() "EMP_NAME" from emp_xml e;

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Output: EMP_NAME -------------------------------------------------------------------------------sharmila anita ekta nancy falguni sweta aarti sandy 8 rows selected. Retrieve the acc_no of employees SQL>select e.employee_spec.extract('//acc_no/text()').getStringVal() 2 "Acc_No" from emp_xml e; Output: Acc_No -----------------------------------------------------------------------------23456 234346 2343456 2343678 2343345 2343890 23433898 23567898 8 rows selected Retrieve the names, acc_no, email of employees SQL> select e.employee_spec.extract('//name/text()').getStringVal() 2 "NAME",e.employee_spec.extract('//acc_no/text()').getStringVal() 3 "ACC_NO",e.employee_spec.extract('//email/text()').getStringVal()

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

4 "EMAIL" from emp_xml e 5/ Output: NAME ACC_NO EMAIL -------------------------------------------------------------------------------sharmila 23456 dave@yahoo.com anita 234346 ani@yahoo.com ekta 2343456 ektabhatt@yahoo.com nancy 2343678 nancyshah@yahoo.com falguni 2343345 falgunishah@yahoo.com sweta 2343890 swetamehta@yahoo.com aarti 23433898 aartigupta@yahoo.com sandy 23567898 sagupta@yahoo.com 8 rows selected Update the 3rd record from the table and display the name of an employee SQL> update emp_xml e set employee_spec=XMLtype('<emp id="3"> 2 <name> megha </name> 3 <email>meghabhatt@yahoo.com</email> 4 <acc_no>2343456</acc_no> 5 <mgr_email>megha.bhatt@hotmail.com</mgr_email> 6 <doj>24/5/2001</doj> 7 <update>This is the updated record</update> 8 </emp>') 9 where 10 e.employee_spec.extract('//acc_no/text()').getStringVal() 11 =2343456 12> / 1 row updated SQL> select e.employee_spec.extract('//name/text()').getStringVal()"NAME", 2 e.employee_spec.getClobVal() "EMP_SPECIFICATION" 3 from emp_xml e where 4 e.employee_spec.extract('//acc_no/text()').getStringVal()=2343456 5> / Output: NAME ------------------------------------------------------------------------------EMP_SPECIFICATION ------------------------------------------------------------------------------megha <emp id="3"> <name> megha </name> <email>meghabhatt@yahoo.com</email> <acc_no>2343456</acc_no> <mgr_email>megha.bhatt@hotmail.com</mgr_email>

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

<doj>24/5/2001</doj> <update>This is the updated record</update> </emp> Delete the 4th record from the table SQL> delete from emp_xml e 2 where e.employee_spec.extract('//acc_no/text()').getStringVal() 3 =2343678 4 / 1 row deleted. SQL> select e.employee_spec.extract('//name/text()').getStringVal() "NAME" from 2 emp_xml e 3 / Output: NAME -------------------------------------------------------------------------------sharmila anita ekta falguni sweta aarti 6 rows selected Conclusion: Thus the above practical demonstrates the concept of XML Databases.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Practical Solution No.9 Spatial Databases Creating table university SQL>create table university_(mkt_id number primary key, name varchar2(32), shape mdsys.sdo_geometry)

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

2\ Table created. Inserting values in the table university SQL> insert into university values(1,'abc', mdsys.sdo_geometry( 2003, -- 2-dimensional polygon null, null, mdsys.sdo_elem_info_array(1,1003,3), -- one rectangle (1003 =exterior) mdsys.sdo_ordinate_array(1,1, 5,7) -- only 2 points needed to -- define rectangle (lower left and upper right) with -- cartesian-coordinate data ) ) 1 row created. SQL> insert into university values( 2, 'pqr', mdsys.sdo_geometry( 2003, -- 2-dimensional polygon null, null, mdsys.sdo_elem_info_array(1,1003,1), -- one polygon (exterior polygon ring) mdsys.sdo_ordinate_array(5,1, 8,1, 8,6, 5,7, 5,1) ) ) 1 row created. SQL> insert into university values( 3, 'mno', mdsys.sdo_geometry( 2003, -- 2-dimensional polygon null, null, mdsys.sdo_elem_info_array(1,1003,1), -- one polygon (exterior polygon ring) mdsys.sdo_ordinate_array(3,3, 6,3, 6,5, 4,5, 3,3) ) ) 1 row created.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

SQL>insert into university values( 4, xyz, mdsys.sdo_geometry( 2003, -- 2-dimensional polygon null,null,mdsys.sdo_elem_info_array(1,1003,4), -- one circle mdsys.sdo_ordinate_array(8,7, 10,9, 8,11) ) ) 1 row created. SQL>insert into user_sdo_geom_metadata values ( university_15, shape, mdsys.sdo_dim_array( mdsys.sdo_dim_element(x, 0, 20, 0.005), mdsys.sdo_dim_element(y, 0, 20, 0.005) ), null -- srid ) 1 row created. Creating Index create index university_spatial_idx on university(shape) indextype is mdsys.spatial_index; Index created. Find the topological intersection of two geometries SQL> select sdo_geom.sdo_intersection(c_a.shape, c_c.shape, 0.005) from university c_a, university c_c where c_a.name = 'abc' and c_c.name = 'mno'; Output: sdo_geom.sdo_intersection(c_a.shape,c_c.shape,0.005)(sdo_gtype, sdo_srid, sdo_po -------------------------------------------------------------------------------sdo_geometry(2003, null, null, sdo_elem_info_array(1, 1003, 1), sdo_ordinate_arr ay(4, 5, 3, 3, 5, 3, 5, 5, 4, 5)) Find whether two geometric figures are equivalent to each other

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

SQL>select sdo_geom.relate(c_b.shape, 'anyinteract', c_d.shape, 0.005) from university c_b, university_15 c_d where c_b.name = 'pqr' and c_d.name = 'xyz'; Output: sdo_geom.relate(c_b.shape,'anyinteract',c_d.shape,0.005) --------------------------------------------------------false

SQL>select sdo_geom.relate(c_b.shape, 'anyinteract', c_a.shape, 0.005) from university_15 c_b, university c_a where c_b.name = 'pqr' and c_a.name = 'abc'; Output: sdo_geom.relate(c_b.shape,'anyinteract',c_a.shape,0.005) -------------------------------------------------------true

Find the areas of all direction locations SQL>select name, sdo_geom.sdo_area(shape, 0.005) from university; Output: name sdo_geom.sdo_area(shape,0.005) -------------------------------- -----------------------------abc 24 pqr 16.5 mno 5 xyz 12.5663706

Find the area of only one location abc SQL>select c.name, sdo_geom.sdo_area(c.shape, 0.005) from university c where c.name = 'abc'; Output:

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

name sdo_geom.sdo_area(c.shape,0.005) -------------------------------- -------------------------------abc 24

Find the distance between two geometries SQL>select sdo_geom.sdo_distance(c_b.shape, c_d.shape, 0.005) from university_15 c_b, university_15 c_d where c_b.name = 'pqr' and c_d.name = 'xyz'; Output: sdo_geom.sdo_distance(c_b.shape,c_d.shape,0.005) -----------------------------------------------.846049894 Conclusion: Thus the above practical demonstrates the concept of Spatial Databases. Prolog Programming Practical Solution No.10[a]

Towers of Hanoi puzzle This object of this famous puzzle is to move N disks from the left peg to the right peg using the center peg as an auxiliary holding peg. At no time can a larger disk be placed upon a smaller disk. The following diagram depicts the starting setup for N=3 disks.

Fig. 2.3

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Here is a recursive Prolog program that solves the puzzle. It consists of two clauses. move(1,X,Y,_) :write('Move top disk from '), write(X), write(' to '), write(Y), nl. move(N,X,Y,Z) :N>1, M is N-1, move(M,X,Z,Y), move(1,X,Y,_), move(M,Z,Y,X). The variables filled in by '_' (or any variables beginning with underscore) are 'don't-care' variables. Prolog allows these variables to freely match any structure, but no variable binding results from this gratuitous matching. Here is what happens when Prolog solves the case N=3. ?- move(3,left,right,center). Move top disk from left to right Move top disk from left to center Move top disk from right to center Move top disk from left to right Move top disk from center to left Move top disk from center to right Move top disk from left to right yes The first clause in the program describes the move of a single disk. The second clause declares how a solution could be obtained, recursively. For example, a declarative reading of the second clause for N=3, X=left, Y=right, and Z=center amounts to the following: move(3,left,right,center) if move(2,left,center,right) and ] * move(1,left,right,center) and move(2,center,right,left). ] ** This declarative reading of the clause is obviously correct. The procedural reading is closely related to the declarative interpretation of the recursive clause. The procedural interpretation would go something like this: In order to satisfy the goal ?- move(3,left,right,center) do this : satisfy the goal ?-move(2,left,center,right), and then satisfy the goal ?-move(1,left,right,center), and then satisfy the goal ?-move(2,center,right,left).

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Also, we could write the declarative readings for N=2: move(2,left,center,right) if ] * move(1,left,right,center) and move(1,left,center,right) and move(1,right,center,left). move(2,center,right,left) if ] ** move(1,center,left,right) and move(1,center,right,left) and move(1,left,right,center). Now substitute the bodies of these last two implications for the heads and one can "see" the solution that the prolog goal generates. move(3,left,right,center) if move(1,left,right,center) and move(1,left,center,right) and * move(1,right,center,left) and --------------------------move(1,left,right,center) and --------------------------move(1,center,left,right) and move(1,center,right,left) and ** move(1,left,right,center). A procedural reading for this last big implication should be obvious. This example illustrates well three major operations of Prolog: 1) Goals are matched against the head of a rule, and 2) the body of the rule (with variables appropriately bound) becomes a new sequence of goals, repeatedly, until 3) some base goal or condition is satisfied, or some simple action is taken (like printing something). The variable matching process is called unification.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Practical Solution No.10[b]

Two factorial definitions Two predicate definitions that calculate the factorial function are in file 2_2.pl, which the reader can view by clicking on the 'Code' link at the bottom of this page. The first of these definitions is: factorial(0,1). factorial(N,F) :N>0, N1 is N-1, factorial(N1,F1), F is N * F1. This program consists of two clauses. The first clause is a unit clause, having no body. The second is a rule, because it does have a body. The body of the second clause is on the right side of the ':-' which can be read as "if". The body consists of literals separated by commas ',' each of which can be read as "and". The head of a clause is the whole clause if the clause is a unit clause, otherwise the head of a clause is the part appearing to the left of the colon in ':-'. A declarative reading of the first (unit) clause says that "the factorial of 0 is 1" and the second clause declares that "the factorial of N is F if N>0 and N1 is N-1 and the factorial of N1 is F1 and F is N*F1". The Prolog goal to calculate the factorial of the number 3 responds with a value for W, the goal variable: ?- factorial(3,W). W=6

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Consider the following clause tree constructed for the literal 'factorial(3,W)'. As explained in the previous section, the clause tree does not contain any free variables, but instead has instances (values) of variables. Each branching under a node is determined by a clause in the original program, using relevant instances of the variables; the node is determined by some instance of the head of a clause and the body literals of the clause determine the children of the node in the clause tree.

Fig. 2.2 All of the arithmetic leaves are true by evaluation (under the intended interpretation), and the lowest link in the tree corresponds to the very first clause of the program for factorial. That first clause could be written factorial(0,1) :- true. and, in fact, ?- true is a Prolog goal that always succeeds (true is built-in). For the sake of brevity, we have not drawn 'true' leaves under the true arithmetic literals. The program clause tree provides a meaning of the program for the goal at the root of the tree. That is, 'factorial(3,6)' is a consequence of the Prolog program, because there is a clause tree rooted at 'factorial(3,6)' all of whose leaves are true. The literal 'factorial(5,2)' is, on the other hand, not a consequence of the program because there is no clause tree rooted at 'factorial(5,2)' having all true leaves. Thus the meaning of the program for the literal 'factorial(5,2)' is that it is false. In fact, ?- factorial(3,6). yes ?- factorial(5,2). no as expected. Clause trees are so-called AND-trees, since, in order for the root to be a consequence of the program, each of its subtrees must also be rooted at literals which

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

are themselves consequences of the program. We will have more to say about clause trees later. We have indicated that clause trees provide a meaning or semantics for programs. We will see another approach to program semantics in Chapter 6. Clause trees do provide an intuitive, as well as a correct, approach to program semantics. We will need to distinguish between the program clause trees and so-called Prolog derivation trees. The clause trees are "static" and can be drawn for a program and goal regardless of the particular procedural goal-satisfaction mechanism. Roughly speaking, the clause trees correspond to the declarative reading of the program. Derivation trees, on the other hand, take into account the variable-binding mechanism of Prolog and the order that subgoals are considered. Derivation trees are discussed in Section 3.1 (but see the animation below). A trace of a Prolog execution also shows how variables are bound in order to satisfy goals. The following sample shows how a typical Prolog tracer is turned on and off. ?- trace. % The debugger will first creep -- showing everything (trace). yes [trace] ?- factorial(3,X). (1) 0 Call: factorial(3,_8140) ? (1) 1 Head [2]: factorial(3,_8140) ? (2) 1 Call (built-in): 3>0 ? (2) 1 Done (built-in): 3>0 ? (3) 1 Call (built-in): _8256 is 3-1 ? (3) 1 Done (built-in): 2 is 3-1 ? (4) 1 Call: factorial(2, _8270) ? ... (1) 0 Exit: factorial(3,6) ? X=6 [trace] ?- notrace. % The debugger is switched off yes The animated tree below gives another look at the derivation tree for the Prolog goal 'factorial(3,X)'. To start (or to restart) the animation, simply click on the "Step" button. The title of this section referred to two factorial definitions. Here is the other one, with the same predicate name, but using three variables. factorial(0,F,F).

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

factorial(N,A,F) :N > 0, A1 is N*A, N1 is N -1, factorial(N1,A1,F). For this version, use the following type of a goal: ?- factorial(5,1,F). F=120 The second parameter in the definition is a so called an accumulating parameter. This version is properly tail recursive. It is very important for the student to complete the following exercises. Exercise 2.2.1 Using the first factorial program, show explicitly that there cannot possibly be an clause tree rooted at 'factorial(5,2)' having all true leaves. Exercise 2.2.2 Draw an clause tree for the goal 'factorial(3,1,6)' having all true leaves, in a fashion similar to that done for factorial(3,6) previously. How do the two programs differ with regard to how they compute factorial? Also, trace the goal 'factorial(3,1,6)' using Prolog.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Practical Solution No.10[c]

Map colorings A famous problem in mathematics concerns coloring adjacent planar regions. Like cartographic maps, it is required that, whatever colors are actually used, no two adjacent regions may not have the same color. Two regions are considered adjacent provided they share some boundary line segment. Consider the following map.

Fig. 1 We have given numerical names to the regions. To represent which regions are adjacent, consider also the following graph.

Fig. 2

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Here we have erased the original boundaries and have instead drawn an arc between the names of two regions, provided they were adjacent in the original drawing. In fact, the adjacency graph will convey all of the original adjacency information. A Prolog representation for the adjacency information could be represented by the following unit clauses, or facts. adjacent(1,2). adjacent(1,3). adjacent(1,4). adjacent(1,5). adjacent(2,3). adjacent(2,4). adjacent(3,4). adjacent(4,5). adjacent(2,1). adjacent(3,1). adjacent(4,1). adjacent(5,1). adjacent(3,2). adjacent(4,2). adjacent(4,3). adjacent(5,4).

If these clauses were loaded into Prolog, we could observe the following behavior for some goals. ?- adjacent(2,3). yes ?- adjacent(5,3). no ?- adjacent(3,R). R=1; R=2; R=4; no One could declare colorings for the regions in Prolog also using unit clauses. color(1,red,a). color(1,red,b). color(2,blue,a). color(2,blue,b). color(3,green,a). color(3,green,b). color(4,yellow,a). color(4,blue,b). color(5,blue,a). color(5,green,b). Here we have encoded 'a' and 'b' colorings. We want to write a Prolog definition of a conflictive coloring, meaning that two adjacent regions have the same color. For example, here is a Prolog clause, or rule to that effect. conflict(Coloring) :adjacent(X,Y), color(X,Color,Coloring), color(Y,Color,Coloring). For example, ?- conflict(a). no ?- conflict(b).

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

yes ?- conflict(Which). Which = b Here is another version of 'conflict' that has more logical parameters. conflict(R1,R2,Coloring) :adjacent(R1,R2), color(R1,Color,Coloring), color(R2,Color,Coloring). Prolog allows and distinguishes the two definitions of 'conflict'; one has one logical parameter ('conflict/1') and the other has three ('conflict/3'). Now we have ?- conflict(R1,R2,b). R1 = 2 R2 = 4 ?- conflict(R1,R2,b),color(R1,C,b). R1 = 2 R2 = 4 C = blue The last goal means that regions 2 and 4 are adjacent and both are blue. Grounded instances like 'conflict(2,4,b)' are said to be consequences of the Prolog program. One way to demonstrate such a consequence is to draw a program clause tree having the consequence as the root of the tree, use clauses of the program to branch the tree, and eventually produce a finite tree having all true leaves. For example, the following clause tree can be constructed using fully grounded instances (no variables) of clauses of the program.

Fig. .3 To learn more about the visual logic tool used to automatically make digrams like the one in the previous display, click here. The bottom leftmost branch drawn in the tree corresponds to the unit clause adjacent(2,4). which is equivalent in Prolog to the clause adjacent(2,4) :- true.

M.Sc.I.T. Part I Paper IV, Section II: Advanced Database Management Systems

Now, on the other hand, 'conflict(1,3,b)' is not a consequence of the Prolog program because it is not possible to construct a finite finite clause tree using grounded clauses of P containing all 'true' leaves. Likewise, 'conflict(a)' is not a consequence of the program, as one would expect. We will have more to say about program clause trees in subsequent sections. We will revisit the coloring problem again in Section 2.9, where we will develop a Prolog program that can compute all possible colorings (given colors to color with). The famous Four Color Conjecture was that no planar map requires more than four different colors. This was proved by Appel and Haken (1976). The solution used a computer program (not Prolog) to check on many specific cases of planar maps, in order to rule out possible troublesome cases. The map in in Fig. 2.1.1 does require at least four colors; for example ...

Fig. 4 .

You might also like