Database Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

TABLE OF CONTENTS

PAGE
EX.NO EXPERIMENT NAME NO

1. DDL, DML, DQL, TCL

Simple Queries, Nested Queries, Sub


2.
Queries and Joins

3. Views, Sequences, Synonyms

4. Distributed Database

5. Query Processing

6. Xml Schema

7.
Case Study-Mongo DB
Exercise: 1
Date: DDL, DML, DQL, TCL

Aim:

To execute and verify DDL, DML, DQL, TCL commands.

Procedure:

Data Definition Language (DDL)

SQL> create table employee1(eno number(15), ename varchar(15), salary number(16), dob
date);
Table created.

SQL> desc employee1;

Name Null? Type


ENO NUMBER(15)
ENAME VARCHAR2(15)
SALARY NUMBER(16)
DOB DATE

SQL> alter table employee1 modify(ename varchar(20));


Table altered.

SQL> alter table employee1 add designation varchar(20);


Table altered.

SQL> alter table employee1 drop column dob;


Table altered.

SQL> alter table employee1 rename column designation to desgn;


Table altered.

SQL> desc employee1;

Name Null? Type

ENO NUMBER(15)
ENAME VARCHAR2(20)
SALARY NUMBER(16)
DESGN VARCHAR2(20)

SQL> rename employee1 to emp;


Table renamed.

SQL> truncate table emp;


Table truncated.

SQL> desc emp;

Name Null? Type


ENO NUMBER(15)
ENAME VARCHAR2(20)
SALARY NUMBER(16)
DESGN VARCHAR2(20)

SQL> drop table emp;


Table dropped.

SQL> desc emp;


Object does not exist.

Data Manipulation Language (DML)

SQL> create table employee(eno number(15),ename varchar(15), salary number(16),dob date);


Table created.

SQL> desc employee;

Name Null? Type


ENO NUMBER(15)
ENAME VARCHAR2(15)
SALARY NUMBER(16)
DOB DATE

EXAMPLE FOR INSERTION STATEMENT

SQL> insert into employee values(1,'kavi',35000,'14-jul-85')


1 row created.
SQL> insert into employee values(2,'keerthi',32000,'18-oct-87')
1 row created.

SQL> insert into employee values(3,'geetha',28000,'4-jun-86')


1 row created.

SQL> insert into employee values(4,'ganesh',35000,'9-jan-83')


1 row created.

SQL> insert into employee values(5,'dinesh',46000,'26-feb-84')


1 row created.

DISPLAY ALL INFORMATION FROM EMPLOYEE TABLE.

SQL> select * from employee;

ENO ENAME SALARY DOB

1 kavi 35000 14-JUL-85


2 keerthi 32000 18-OCT-87
3 geetha 28000 04-JUN-86
4 ganesh 35000 09-JAN-83
5 dinesh 46000 26-FEB-84

EXAMPLE FOR UPDATE STATEMENT

SQL> update employee set salary=40000 where eno=2;


1 row updated.

SQL> select * from employee;

ENO ENAME SALARY DOB

1 kavi 35000 14-JUL-85


2 keerthi 40000 18-OCT-87
3 geetha 28000 04-JUN-86
4 ganesh 35000 09-JAN-83
5 dinesh 46000 26-FEB-84

EXAMPLE FOR DELETION STATEMENT

SQL> delete from employee where eno=4;


1 row deleted.

SQL> select * from employee;


ENO ENAME SALARY DOB

1 kavi 35000 14-JUL-85


2 keerthi 40000 18-OCT-87
3 geetha 28000 0 4-JUN-86
5 dinesh 46000 26-FEB-84

Data Query Language (DQL)

DISPLAY ALL INFORMATION FROM EMPLOYEE TABLE.

SQL> select * from employee;

ENO ENAME SALARY DOB

1 kavi 35000 14-JUL-85


2 keerthi 32000 18-OCT-87

DISPLAY ALL INFORMATION FROM EMPLOYEE TABLE WHEN EMPLOYEE


NUMBER IS 1

SQL> select * from employee where eno=1;

ENO ENAME SALARY DOB

1 kavi 35000 14-JUL-85

DISPLAY EMPLOYEE NAMES FROM EMPLOYEE TABLE

SQL> select ename from employee;

ENAME
kavi
keerthi

DISPLAY ALL INFORMATION FROM EMPLOYEE TABLE WHEN EMPLOYEE


NUMBER IS 1 AND SALARY IS 40000
SQL> select * from employee where eno=1 and salary=40000;
no rows selected

SQL> select * from employee where eno=1 and salary=35000;

ENO ENAME SALARY DOB


--------- -------- --------- ---------
1 kavi 35000 14-JUL-85

DISPLAY ALL INFORMATION FROM EMPLOYEE TABLE WHEN EMPLOYEE


NUMBER IS 1 OR SALARY IS 40000

SQL> select * from employee where eno=1 or salary=40000;

ENO ENAME SALARY DOB


1 kavi 35000 14-JUL-85

DISPLAY EMPLOYEE NAMES IN ASCENDING ORDER

SQL> select * from employee order by ename;

ENO ENAME SALARY DOB

1 kavi 35000 14-JUL-85


2 keerthi 40000 18-OCT-87

DISPLAY EMPLOYEE NAMES IN DESCENDING ORDER

SQL> select * from employee order by ename desc;

ENO ENAME SALARY DOB

2 keerthi 40000 18-OCT-87


1 kavi 35000 14-JUL-85

DISPLAY EMPLOYEE NAMES WHO HAVE NAMES STARTING WITH LETTER K

SQL> select * from employee where ename like 'k%';

ENO ENAME SALARY DOB

1 kavi 35000 14-JUL-85


2 keerthi 40000 18-OCT-87

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


ENO ENAME SALARY DOB
1 kavi 35000 14-JUL-85

DISPLAY EMPLOYEE NAMES WHO HAVE NAMES ENDING WITH LETTER ‘K’

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


No data found

DISPLAY SALARY FROM EMPLOYEE TABLE WITHOUT DUPLICATION

SQL> select distinct salary from employee;

SALARY
35000
32000
Transaction Control Language (TCL)

SQL> create table tcl(roll int, name varchar(35));


Table created.

SQL> insert into tcl values(1, 'rrr');

SQL> select * from tcl;


ROLL NAME

1 ravi
2 aarav
3 kumar

CREATE SAVEPOINT
SQL> savepoint s1;
Savepoint created.

COMMIT
SQL> commit; set auto commit =1;
Commit complete.

QL> delete from tcl where roll=3;


1 row deleted.

SQL> select * from tcl;


ROLL NAME

1 ravi
2 aarav
ROLLBACK
SQL> rollback;
Rollback complete.

SQL> select * from tcl;


ROLL NAME

1 ravi
2 aarav
3 kumar
Result:

Thus the all DDL, DML, DQL, TCL commands are executed and verified successfully.
Exercise: 2
Date: Simple Queries, Nested Queries, Sub Queries and
Joins
Aim:

To execute and verify the SQL commands using Simple Queries, Nested Queries, Sub Queries
and Joins.

Procedure:

2.1 Simple and sub queries

SQL> create table customers (id int , name varchar(20) , age int , address varchar(20) , salary
numeric(5)) ;
Table created.

SQL> insert into customers values(1, 'ramesh', 35,'erode', 5000) ;


1 row created.

SQL> insert into customers values(2, 'aarav', 2,'canada', 25000) ;


1 row created.

SQL> select *from customers where id in (select id from customers where salary > 10000);

ID NAME AGE ADDRESS SALARY

1 ramesh 35 US 5000
2 aarav 2 canada 25000

SQL> update customers set salary = salary * 0.50 where age in (select age from customers where
age = 2 );
1 row updated.

SQL> select * from customers


ID NAME AGE ADDRESS SALARY
1 ramesh 35 US 2500
2 aarav 2 canada 12500

SQL> create table customers_bkp (id int , name varchar(20) , age int , address v
archar(20) , salary numeric(5)) ;
Table created.

SQL> insert into customers_bkp select * from customers where id in (select id from customers) ;
2 rows created.

SQL> select * from customers_bkp

ID NAME AGE ADDRESS SALARY

1 ramesh 35 US 2500
2 aarav 2 canada 12500

SQL> delete from customers where age in (select age from customers_bkp where age = 35);
1 row deleted.

SQL> select * from customers_bkp;

ID NAME AGE ADDRESS SALARY

1 ramesh 35 erode 2500

Nested Queries:

SQL> select * from studentdetail;

ID FIRSTNAME LASTNAME AGE SUBJECT GAMES

100 ragul sharma 10 science cricket


101 anjali bhaguat 12 maths football
102 sekar gupta 13 maths cricket

SQL> select id,firstname from studentdetail where firstname in(select •


firstname from studentdetail where subject='science');

ID FIRSTNAME
100 ragul

SQL> create table mathsgroup(id number(10),name varchar(15));


Table created.

TO GROUP ALL THE STUDENTS WHO STUDY MATHS IN A TABLE


MATHSGROUP
SQL> insert into mathsgroup(id,name) select id,firstname || lastname from studentdetail where
subject='maths';
2 rows created.

SQL> select * from mathsgroup;

ID NAME
101 anjali bhaguat
102 sekar gupta

SQL> select id, (select name from mathsgroup where id=101) as name, age, subject, games from
studentdetail where id=101;

ID NAME AGE SUBJECT GAMES


101 anjali bhaguat 12 maths football

Joins:

SQL> select *from table_a;

ID NAME

1 Private
2 Money
3 Ninja
4 Sun

SQL> select *from table_b;

ID NAME

1 Road
2 Private
3 Dark
4 Ninja

SQL> SELECT * FROM TABLE_A INNER JOIN TABLE_B ON


TABLE_A.NAME=TABLE_B.NAME;

ID NAME ID NAME

1 Private 2 Private
3 Ninja 4 Ninja

SQL> SELECT * FROM TABLE_A FULL OUTER JOIN TABLE_B ON


TABLE_A.NAME=TABLE_B.NAME;

ID NAME ID NAME

1 Road
1 Private 2 Private
3 Dark
3 Ninja 4 Ninja
2 Money
4 Sun

6 rows selected.

SQL> SELECT * FROM TABLE_A LEFT OUTER JOIN TABLE_B ON


TABLE_A.NAME=TABLE_B.NAME;

ID NAME ID NAME

1 Private 2 Private
3 Ninja 4 Ninja
2 Money
4 Sun
SQL> SELECT * FROM TABLE_A LEFT OUTER JOIN TABLE_B ON
TABLE_A.NAME=TABLE_B.NAME WHERE TABLE_B.ID IS NULL;

ID NAME ID NAME

2 Money
4 Sun

SQL> SELECT * FROM TABLE_A FULL OUTER JOIN TABLE_B ON


TABLE_A.NAME=TABLE_B.NAME WHERE TABLE_A.ID IS NULL OR TABLE_B.ID IS
NULL;

ID NAME ID NAME

1 Road
3 Dark
2 Money
4 Sun

Result

Thus the SQL commands using Simple Queries, Nested Queries, Sub Queries and Joins are
executed and verified successfully.
Exercise: 3
Date: Views, Sequences, Synonyms

Aim:

To execute and verify the SQL commands for Views, Sequences and synonyms.

Procedure:

VIEWS

SQL> select * from employee;

ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000

CREATING VIEWS AND DML OPERATIONS WITH VIEWS.

SQL> create view employeeview as select * from employee;


View created.

SQL> select * from employeeview;

ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000

SQL>insert into employeeview values(3,'naveena',27000)


1 row created.

SQL> select * from employeeview;


ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000
3 naveena 27000
3 rows selected.

SQL> select * from employee;

ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000
3 naveena 27000
3 rows selected.

SQL> update employeeview set ename='kayal' where eno=3;


1 row updated.

SQL> select * from employeeview;

ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000
3 kayal 27000
3 rows selected.

SQL> select * from employee;

ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000
3 kayal 27000
3 rows selected.

SQL> delete from employeeview where eno=3;


1 row deleted.
SQL> select * from employeeview;

ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000
2 rows selected.

SQL> select * from employee;

ENO ENAME SALARY

1 kavitha 20000
2 prabu 40000
2 rows selected.

SQL> create view empview as select eno,ename from employee with read only;
View created.

SQL> select * from empview;

ENO ENAME
1 kavitha
2 prabu
2 rows selected.

SQL>insert into empview values(7,'suriya')

ERROR at line 1:
ORA-01733: virtual column not allowed here

SEQUENCE

SQL> create sequence seq;


Sequence created.

SQL> select seq.nextval from dual;


NEXTVAL

SQL> /

NEXTVAL

SQL> create sequence seq1 maxvalue 2 cycle nocache;


Sequence created.

SQL> select seq1.nextval from dual;

NEXTVAL

1
SQL> /

NEXTVAL

2
SQL> /

NEXTVAL

1
SQL> /
NEXTVAL

SYNONYMS

SQL> create synonym mysyn1 for employee;


Synonym created.

SQL> select * from mysyn1;


ENO ENAME SALARY

1 kavitha 25000
2 prabu 26000
2 rows selected.

INDEX
SQL> create index a_index on employee(ename);
Index created.

SQL> ALTER INDEX a_index RENAME TO aa_index;


Index altered

SQL> DROP INDEX aa_index;


Index dropped.

RESULT:

Thus execute and verify the SQL commands for Views, Sequences and synonyms.
Exercise:4
Distributed Database
Date:

AIM
To implement distributed database for a book store using four different sites.

DISTRIBUTED DATABASE:
A distributed database is a database in which storage devices are not all attached to a
common processing unit such as the CPU, controlled by a distributed database management
system. Data may be stored in multiple computers, located in same physical location; or may be
dispersed over a network of interconnected computers.

Fragmentation
The relation is fragmented into several relations in such a way that the actual relation
could be reconstructed from the fragments and then the fragments are scattered to different
locations. Two schemes of fragmentation: Horizontal fragmentation - splits the relation by
assigning each tuple of relation to one or more fragments. Vertical fragmentation - splits the
relation by decomposing the schema of relation.

Site 1:

Table Creation
SQL> create table books as (select * from exam21.books where price<=20);

Table created.

SQL> select * from books;

no rows selected

SQL> desc books;


Name Null? Type

ISBN NUMBER(10)

AUTHOR VARCHAR2(20)

TOPIC VARCHAR2(20)

TOTALSTOCK NUMBER(5)

PRICE NUMBER(10)

SQL> select * from books;

no rows selected

Grant Permission
SQL> grant all on books to exam32;

Grant succeeded.

SQL> grant all on books to exam33;

Grant succeeded.

SQL> grant all on books to exam34;

Grant succeeded.

Table Creation
SQL> create table bookstore as (select * from exam21.bookstore where zip <=25000);

Table created.

SQL> select * from bookstore;

STORENO CITY STATE ZIP INVENTORYVALUE

1 cbe TN 10000 120

2 CHENNAI TN 25000 150

SQL> commit;
Commit complete.

Grant Permission
SQL> grant all on bookstore to exam32;

Grant succeeded.

SQL> grant all on bookstore to exam33;

Grant succeeded.

SQL> grant all on bookstore to exam34;

Grant succeeded.

SQL> commit;

Commit complete.

Site 2:

Table Creation
SQL> create table books as (select * from exam21.books where price between 20 and 50);

Table created.

SQL> select* from books;

ISBN AUTHOR TOPIC TOTALSTOCK PRICE

1002 kalaiselvi ds 25 50

1003 priya dbms 34 25

1005 vidhya nis 12 39

1007 ramya tfcs 10 22

SQL> commit;

Commit complete.
Grant Permission
SQL> grant all on books to exam31;

Grant succeeded.

SQL> grant all on books to exam33;

Grant succeeded.

SQL> grant all on books to exam34;

Grant succeeded.

Table Creation
SQL> create table bookstore as (select * from exam21.bookstore where zip between 25001 and
50000);

Table created.

SQL> select * from bookstore;

STORENO CITY STATE ZIP INVENTORYVALUE

3 TRISSUR KERALA 30000 100

5 POTHANUR TN 38000 123

SQL> commit;

Commit complete.

Grant Permission
SQL> grant all on bookstore to exam31;

Grant succeeded.

SQL> grant all on bookstore to exam33;

Grant succeeded.
SQL> grant all on bookstore to exam34;

Grant succeeded.

SQL> select * from books;

ISBN AUTHOR TOPIC TOTALSTOCK PRICE

1002 kalaiselvi ds 25 50

1003 priya dbms 34 25

1005 vidhya nis 12 39

1007 ramya tfcs 10 22

Site 3:

Table Creation
SQL> create table books as (select * from exam21.books where price between 51 and 100);

Table created.

SQL> select * from books;

ISBN AUTHOR TOPIC TOTALSTOCK PRICE

1004 saranya cns 23 99

1006 krishna toc 15 67

SQL> insert into books values(1009,'sathya','db',50,53);

1 row created.

SQL> select * from books;

ISBN AUTHOR TOPIC TOTALSTOCK PRICE

1004 saranya cns 23 99

1006 krishna toc 15 67


1009 sathya db 50 53

SQL> commit;

Commit complete.

Grant Permission
SQL> grant all on books to exam31;

Grant succeeded.

SQL> grant all on books to exam32;

Grant succeeded.

SQL> grant all on books to exam34;

Grant succeeded.

Table Creation
SQL> create table bookstore as(select * from exam21.bookstore where zip between 50001 and
75000);

Table created.

SQL> select * from bookstore;

STORENO CITY STATE ZIP INVENTORYVALUE

4 TIRUPUR TN 72000 178

7 BANGLORE KARNATAKA 53000 167

SQL> commit;

Commit complete.

Grant Permission
SQL> grant all on bookstore to exam31;

Grant succeeded.

SQL> grant all on bookstore to exam32;


Grant succeeded.

SQL> grant all on bookstore to exam34;

Grant succeeded.

Site 4:

Table Creation
SQL> create table books as (select * from exam21.books where price>100);

Table created.

SQL> select * from books;

ISBN AUTHOR TOPIC TOTALSTOCK PRICE

1001 kalaiselvi dbms 10 120

1008 subha wsn 45 130

SQL> commit;

Commit complete.

Grant Permission
SQL> grant all on books to exam31;

Grant succeeded.

SQL> grant all on books to exam32;

Grant succeeded.

SQL> grant all on books to exam33;

Grant succeeded.

Table Creation
SQL> create table bookstore as (select * from exam21.bookstore where zip between 75001 and
99999);

Table created.
SQL> select * from bookstore;

STORENO CITY STATE ZIP INVENTORYVALUE

6 KOCHIN KERALA 79000 167

8 HYDERABAD A P 88888 143

SQL> commit;

Commit complete

Grant Permission
SQL> grant all on bookstore to exam31;

Grant succeeded.

SQL> grant all on bookstore to exam32;

Grant succeeded.

SQL> grant all on bookstore to exam33;

Grant succeeded.

RESULT:
Thus the above program for distributed database will be executed successfully.
Exercise: 5
Query Processing
Date:

AIM:
To implement Query Optimizer with Relational Algebraic expression construction and
execution plan generation for choosing an efficient execution strategy for processing the various
query in employee table.

QUERY PROCESSING:
Query processing is a set of activities involving in getting the result of a query expressed
in a high-level language. These activities include parsing the queries and translate them
into expressions. The cost of processing of query is dominated by the disk access.
EXPLAIN PLAN output shows how Oracle runs the SQL statement when the statement was
explained. The execution and explain plan happen on different databases. Even if the schemas
are the same, the optimizer can choose different execution plans if the costs are different.

STEP1:

WORKING WITH ORACLE 11G

 Install the software in oracle11g folder


 To install follow the steps given below
Step 1:Enter into oracle 11g folder and click on the setup

Step 2:Click on next


Step 3:Click on I Agree the terms in the license agreement radio button and
click next
Step 4:The following wizard will appear click next

Step 5:Type the required password and re-enter it then click next

Step 6:Click on install


Step 7:Wait till the process completes
Step 8:Click on finish to complete installation

STEP 2:

 After installation to connect to the database follow the steps below


 Select All programsOracle Database 11g Express EditionRun SQL Command Line
 In “RUN SQL COMMAND LINE” window do the following.
By Default enter the

username as “system” and

password as “admin”
SQL> connect

Enter user-name: system //ENTER THE USER NAME AS SYSTEM

Enter password: //USE THE PASSWORD GIVEN DURING


INSTALLATION OF ORACLE 11G

Connected.
STEP 3:

TO CREATE THE TABLE branch_office


SQL> create table branch_office(branchno number(15) primary key,street varchar2(20),city
varchar2(20),postcode number(10));

Table created.

SQL>descbranch_office;

Name Null? Type

BRANCHNO NOT NULL NUMBER(15)

STREET VARCHAR2(20)

CITY VARCHAR2(20)

POSTCODE NUMBER(10)

STEP 4:

TO DESIGN EMPLOYEE DATABASE AND TEST THE ALGORITHM


WITH FOLLOWING SAMPLE QUERIES

TO CREATE THE TABLE employee_details


SQL> create table employee_details(eid number(10) primary key,ename varchar2(20),sex
varchar2(10),salary number(10),exp number(5),position
varchar2(20),branchnonumber(15),constraint fk_br foreign key(branchno) references
branch_office(branchno));

Table created.

SQL>descemployee_details;

Name Null? Type

EID NOT NULL NUMBER(10)


ENAME VARCHAR2(20)

SEX VARCHAR2(10)

SALARY NUMBER(10)

EXP NUMBER(5)

POSITION VARCHAR2(20)

BRANCHNO NUMBER(15)

STEP 5:

TO INSERT VALUES INTO THE TABLE branch_office


SQL> insert into branch_officevalues(&branchno,'&street','&city',&postcode);

Enter value for branchno: 1001

Enter value for street: 22 Deer Rd

Enter value for city: London

Enter value for postcode: 675675

old 1: insert into branch_office values(&branchno,'&street','&city',&postcode)

new 1: insert into branch_office values(1001,'22 Deer Rd','London',675675)

1 row created.

SQL> /

Enter value for branchno: 1002

Enter value for street: 16 agrilst

Enter value for city: aderdeen

Enter value for postcode: 657677

old 1: insert into branch_office values(&branchno,'&street','&city',&postcode)

new 1: insert into branch_office values(1002,'16 agril st','aderdeen',657677)

1 row created.

SQL> /
Enter value for branchno: 1003

Enter value for street: 14 Main st

Enter value for city: London

Enter value for postcode: 465457

old 1: insert into branch_office values(&branchno,'&street','&city',&postcode)

new 1: insert into branch_office values(1003,'14 Main st','London',465457)

1 row created.

SQL> select * from branch_office;

BRANCHNO STREET CITY POSTCODE

1001 22 Deer Rd London 675675

1002 16 agrilstaderdeen 657677

1003 14 Main st London 465457

STEP 6:

TO INSERT VALUES INTO THE TABLE employee_details


SQL> insert into
employee_detailsvalues(&eid,'&ename','&sex',&salary,&exp,'&position',&branchno);

Enter value for eid: 1

Enter value for ename: kalaiselvi

Enter value for sex: Female

Enter value for salary: 35000

Enter value for exp: 6

Enter value for position: Manager

Enter value for branchno: 1001

old 1: insert into employee_details


values(&eid,'&ename','&sex',&salary,&exp,'&position',&branchno
new 1: insert into employee_details values(1,'kalaiselvi','Female',35000,6,'Manager',1001)

1 row created.

SQL> /

Enter value for eid: 2

Enter value for ename: sangeetha

Enter value for sex: Female

Enter value for salary: 45000

Enter value for exp: 8

Enter value for position: manager

Enter value for branchno: 1001

old 1: insert into employee_details


values(&eid,'&ename','&sex',&salary,&exp,'&position',&branchno

new 1: insert into employee_details values(2,'sangeetha','Female',45000,8,'manager',1001)

1 row created.

SQL> /

Enter value for eid: 3

Enter value for ename: venkat

Enter value for sex: Male

Enter value for salary: 40000

Enter value for exp: 4

Enter value for position: Asst manager

Enter value for branchno: 1002

old 1: insert into employee_details


values(&eid,'&ename','&sex',&salary,&exp,'&position',&branchno

new 1: insert into employee_details values(3,'venkat','Male',40000,4,'Asst manager',1002)

1 row created.
SQL> /

Enter value for eid: 4

Enter value for ename: gugan

Enter value for sex: Male

Enter value for salary: 50000

Enter value for exp: 7

Enter value for position: Manager

Enter value for branchno: 1003

old 1: insert into employee_details


values(&eid,'&ename','&sex',&salary,&exp,'&position',&branchno

new 1: insert into employee_details values(4,' gugan','Male',50000,7,'Manager',1003)

1 row created.

SQL> select * from employee_details;

EID ENAME SEX SALARY EXP POSITION BRANCHNO

1 kalaiselvi Female 35000 6 Manager 1001

2 sangeetha Female 45000 8 manager 1001

3 venkat Male 40000 4 Asst manager 1002

4 gugan Male 50000 7 Manager 1003

STEP 7:

To Create the plan_table


SQL> @?/rdbms/admin/utlxplan (if not)

Table created.
 Utlxpaln is a script to create plan_table by default.
 It stores the result of each query.
 This command appends the results of each query into the plan_table.
 Inordertoshow the result of current query we want to delete the plan_table
manually.
STEP 8:

Execute first query and view the output in plan_table


 SQL> explain plan for
 2 selecteid,ename from employee_details where exp>5;

 Explained.

 SQL> select * from table(dbms_xplan.display);

 PLAN_TABLE_OUTPUT
 

 Plan hash value: 3805994106

 -

 

 | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time

 |

 

 


 PLAN_TABLE_OUTPUT
 

 | 0 | SELECT STATEMENT | | 4 | 152 | 2 (0)| 00:0

 0:01 |

 |* 1 | TABLE ACCESS FULL| EMPLOYEE_DETAILS | 4 | 152 | 2 (0)| 00:0

 0:01 |

 

 


 Predicate Information (identified by operation id):

 PLAN_TABLE_OUTPUT
 

 

 1 - filter("EXP">5)

 Note
 
 - dynamic sampling used for this statement (level=2)

 17 rows selected.

STEP 9:

TO FIND ALL MANAGERS WORKING AT LONDON BRANCH


 SQL> select e.eid,e.ename,e.position,b.branchno,b.city from employee_detailse,branch_office b
where
 e.branchno=b.branchno and b.city='London' and e.position='manager';

 EID ENAME POSITION BRANCHNO
 
 CITY
 
 1 kalaiselvi manager 1001
 London

 2 sangeetha manager 1003
 London

 SQL> explain plan for
 selecte.eid,e.ename,e.position,b.branchno,b.city from employee_detailse,branch_office b where
 e.branchno=b.branchno and b.city='London' and e.position='manager';
 Explained

 SQL> select * from table(dbms_xplan.display);

 PLAN_TABLE_OUTPUT


 Plan hash value: 3701986280





 | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Tim

 e |






 PLAN_TABLE_OUTPUT


 | 0 | SELECT STATEMENT | | 2 | 150 | 5 (20)| 00:

 00:01 |

 |* 1 | HASH JOIN | | 2 | 150 | 5 (20)| 00:

 00:01 |

 |* 2 | TABLE ACCESS FULL| BRANCH_OFFICE | 2 | 50 | 2 (0)| 00:

 00:01 |

 |* 3 | TABLE ACCESS FULL| EMPLOYEE_DETAILS | 3 | 150 | 2 (0)| 00:

 00:01 |

 PLAN_TABLE_OUTPUT








 Predicate Information (identified by operation id):


 1 - access("E"."BRANCHNO"="B"."BRANCHNO")
 2 - filter("B"."CITY"='London')
 3 - filter("E"."POSITION"='manager')

 PLAN_TABLE_OUTPUT

 Note

 - dynamic sampling used for this statement (level=2)

 21 rows selected.


 SQL> Explain plan for
 selecte.eid,e.ename,e.position,b.branchno,b.city from employee_detailse,branch_office b where
 b.city='London' and e.position='manager' and e.branchno=b.branchno;
 Explained

 SQL> select * from table(dbms_xplan.display);

 PLAN_TABLE_OUTPUT


 Plan hash value: 3701986280





 | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Tim

 e |






 PLAN_TABLE_OUTPUT


 | 0 | SELECT STATEMENT | | 2 | 150 | 5 (20)| 00:

 00:01 |

 |* 1 | HASH JOIN | | 2 | 150 | 5 (20)| 00:

 00:01 |

 |* 2 | TABLE ACCESS FULL| BRANCH_OFFICE | 2 | 50 | 2 (0)| 00:

 00:01 |

 |* 3 | TABLE ACCESS FULL| EMPLOYEE_DETAILS | 3 | 150 | 2 (0)| 00:

 00:01 |

 PLAN_TABLE_OUTPUT
 


 

 


 Predicate Information (identified by operation id):
 

 1 - access("E"."BRANCHNO"="B"."BRANCHNO")
 2 - filter("B"."CITY"='London')
 3 - filter("E"."POSITION"='manager')

 PLAN_TABLE_OUTPUT
 

 Note
 
 - dynamic sampling used for this statement (level=2)

 21 rows selected.


 SQL> Explain plan for
 selecte.eid,e.ename,e.position,b.branchno,b.city from employee_detailse,branch_office b where
 b.city='London' and e.branchno=b.branchno and e.position='manager';
 Explained
 The same output of above mentioned query

 SQL> Explain plan for
 selecte.eid,e.ename,e.position,b.branchno,b.city from employee_detailse,branch_office b where
 b.city='London' and e.branchno=b.branchno and e.position='manager' order by e.eiddesc;
 Explained
 SQL> select * from table(dbms_xplan.display);

 PLAN_TABLE_OUTPUT


 Plan hash value: 100843091





 | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Ti

 me |






 PLAN_TABLE_OUTPUT


 | 0 | SELECT STATEMENT | | 2 | 150 | 6 (34)| 00

 :00:01 |

 | 1 | SORT ORDER BY | | 2 | 150 | 6 (34)| 00

 :00:01 |

 |* 2 | HASH JOIN | | 2 | 150 | 5 (20)| 00

 :00:01 |

 |* 3 | TABLE ACCESS FULL| BRANCH_OFFICE | 2 | 50 | 2 (0)| 00

 :00:01 |

 PLAN_TABLE_OUTPUT



 |* 4 | TABLE ACCESS FULL| EMPLOYEE_DETAILS | 3 | 150 | 2 (0)| 00

 :00:01 |






 Predicate Information (identified by operation id):
 


 PLAN_TABLE_OUTPUT
 

 2 - access("E"."BRANCHNO"="B"."BRANCHNO")
 3 - filter("B"."CITY"='London')
 4 - filter("E"."POSITION"='manager')

 Note
 
 - dynamic sampling used for this statement (level=2)

 22 rows selected.

RESULT:

Thus the above program for implementation of query processing was executed
successfully.
Exercise:6
XML SCHEMA
Date:

AIM:
To design XML Schema for the company database of Department, Employee, and Project
and execute a query using XPATH, XQUERY and implement a storage structure for storing
XML.

XML:
Extensible Markup Language (XML) is an abbreviated version of Standard Generalized
Markup Language (SGML), for the exchange of structured documents over the Internet. Unlike
HTML, XML readily enables the definition, transmission, validation, and interpretation of data
between differing computing platforms and applications.

XML SCHEMA:
An XML schema is a single file or collection of files that serve as the framework for
defining the data content, format and structure of an XML document. A well written schema
expresses agreed upon vocabularies and allows computers to validate the data against the rules
written to describe the data. It provides a means for defining the structure and content of XML
documents.

XPath:
XPath is syntax for accessing parts of an XML document. It uses a path structure to
define XML elements. It has a library of standard functions. It is one of the main components of
XQuery and XSLT.

XQuery:
XQuery was devised primarily as a query language for data stored in XML form. So its
main role is to get information out of XML databases — this includes relational databases that
store XML data, or that present an XML view of the data they hold.
TOOLS REQURIED :
 XmlValidator - XML Schema
 BaseX - Xpath and Xquery
 MYSQL above 5.1 - Storage structure for storing XML database
PROCEDURE:
1. Create XML file for department, employee and project.
2. Validate the XML file using Schema.
3. Xpath be used to locate the particular path in a file.
4. Implemenet the queries using Xquery and XPath.
5. The structure of Xquery is “FLWOR” is For – Let – Where – Order by – Return.
6. Store XML document into MySql Database using Load XML file.
XML AND XML SCHEMA FOR COMPANY DATABASE:
Company database contains the following tables
 Department
 Company
 Employee
DEPARTMENT:
Department table contains the following fields in XML file

 deptName
 deptNo
 deptManagerSSN
 deptManagerStart Date
 deptLocation
XML for Department:
depart.xml
<?xml version="1.0" encoding="UTF-8"?>
<company xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespace
SchemaLocation="depart.xsd">

<dept name="Research">
<ditem deptno="1"
deptname="Research"
deptmanagerssn="empssn1"
deptmanagerstartdate="1997-07-01"
deptlocation="Coimbatore"/>
</dept>,
<dept name="Adminstration">
<ditem deptno="2"
deptname="Admistration"
deptmanagerssn="empssn2"
deptmanagerstartdate="1999-11-19"
deptlocation="Chennai"/>
</dept>,
<dept name="Purchase">
<ditem deptno="3"
deptname="Purchase"
deptmanagerssn="empssn3"
deptmanagerstartdate="1987-05-09"
deptlocation="Bangalore"/>
</dept>,
<dept name="Sales">
<ditem deptno="4"
deptname="Sales"
deptmanagerssn="empssn4"
deptmanagerstartdate="1995-05-25"
deptlocation="Mumbai"/>
</dept>

<dept name="Financial">
<ditem deptno="5"
deptname="Financial"
deptmanagerssn="empssn5"
deptmanagerstartdate="1991-12-20"
deptlocation="Chennai"/>
</dept>
</company>

XML Schema for Department:


depart.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns: xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="company">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" ref="dept"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="dept">
<xs:complexType>
<xs:sequence>
<xs:element ref="ditem"/>
</xs:sequence>
<xs:attribute name="name" use="required" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="ditem">
<xs:complexType>
<xs:attribute name="deptlocation" use="required" type="xs:string"/>
<xs:attribute name="deptmanagerssn" use="required" type="xs:string"/>
<xs:attribute name="deptmanagerstartdate" use="required" type="xs:string"/>
<xs:attribute name="deptname" use="required" type="xs:string"/>
<xs:attribute name="deptno" use="required" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:schema>

EMPLOYEE:
Employee table contains the following fields

 empName
 empSSN
 empSex
 empSalary
 empBirthDate
 empDeptNo
 empSupervisorSSN
 empAddress
 empWorksOn
XML for Employee:
employ.xml
<?xml version="1.0" encoding="UTF-8"?>

<employees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespace


SchemaLocation= "employ.xsd">

<employee department="Research">

<eitem empname="Vijay"

empssn="empssn1"

empsex="male"

empsalary="50000"
empbirthdate="1987-10-19"

empdeptno="1"

empsupervisorssn="0"

empaddress="address1"

empworkon="25"/>

<eitem empname="Shiva"

empssn="empssn6"

empsex="female"

empsalary="24000"

empbirthdate="1990-10-19"

empdeptno="1"

empsupervisorssn="empssn1"

empaddress="address1"

empworkon="7"/>

<eitem empname="Thomas"

empssn="empssn10"

empsex="female"

empsalary="25000"

empbirthdate="1991-09-30"

empdeptno="1"

empsupervisorssn="empssn1"
empaddress="address1"

empworkon="8"/>

</employee>,

<employee department="Adminstration">

<eitem empname="Moni"

empssn="empssn2"

empsex="female"

empsalary="47000"

empbirthdate="1989-01-01"

empdeptno="2"

empsupervisorssn="0"

empaddress="address2"

empworkon="25"/>

</employee>,

<employee department="Purchase">

<eitem empname="Gowtham"

empssn="empssn3"

empsex="male"

empsalary="30000"

empbirthdate="1991-04-09"

empdeptno="3"
empsupervisorssn="0"

empaddress="address3"

empworkon="9"/>

<eitem empname="JaiVidhya"

empssn="empssn7"

empsex="female"

empsalary="27000"

empbirthdate="1991-04-09"

empdeptno="3"

empsupervisorssn="empssn3"

empaddress="address3"

empworkon="21"/>

</employee>,

<employee department="Sales">

<eitem empname="Uma"

empssn="empssn4"

empsex="female"

empsalary="37000"

empbirthdate="1991-04-09"

empdeptno="4"

empsupervisorssn="0"
empaddress="address4"

empworkon="14"/>

</employee>,

<employee department="Finacial">

<eitem empname="Praveen"

empssn="empssn5"

empsex="male"

empsalary="32000"

empbirthdate="1991-04-09"

empdeptno="5"

empsupervisorssn="0"

empaddress="address2"

empworkon="12"/>

<eitem empname="Sathish"

empssn="empssn9"

empsex="male"

empsalary="32000"

empbirthdate="1991-17-07"

empdeptno="5"

empsupervisorssn="empssn5"

empaddress="address9"
empworkon="11"/>

</employee>

</employees>

XML Schema for Employee:


employ.xsd

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">


<xs:element name="employees">

<xs:complexType mixed="true">

<xs:sequence>

<xs:element minOccurs="0" maxOccurs="unbounded" ref="employee"/>

</xs:sequence>

</xs:complexType>

</xs:element>

<xs:element name="employee">

<xs:complexType>

<xs:sequence>

<xs:element maxOccurs="unbounded" ref="eitem"/>

</xs:sequence>

<xs:attribute name="department" use="required" type="xs:string"/>

</xs:complexType>

</xs:element>
<xs:element name="eitem">

<xs:complexType>

<xs:attribute name="empaddress" use="required" type="xs:string"/>

<xs:attribute name="empbirthdate" use="required" type="xs:string"/>

<xs:attribute name="empdeptno" use="required" type="xs:integer"/>

<xs:attribute name="empname" use="required" type="xs:string"/>

<xs:attribute name="empsalary" use="required" type="xs:integer"/>

<xs:attribute name="empsex" use="required" type="xs:string"/>

<xs:attribute name="empssn" use="required" type="xs:string"/>

<xs:attribute name="empsupervisorssn" use="required" type="xs:string"/>

<xs:attribute name="empworkon" use="required" type="xs:integer"/>

</xs:complexType>

</xs:element>

</xs:schema>

PROJECT:
Project table contains the following fields in XML

 projName
 projNo
 projLocation
 projDeptNo
 projWorker
XML for Project:
proj.xml
<?xml version="1.0" encoding="UTF-8"?>

<projects xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespace


SchemaLocation="proj.xsd">

<project no="1">

<prjitem prjno="1"

prjname="Cloud Computing"

prjlocation="location1"

prjdeptno="1"

prjwrk="5"/>

</project>,

<project no="2">

<prjitem prjno="2"

prjname="DataBase"

prjlocation="location2"

prjdeptno="2"

prjwrk="7"/>

</project>

<project no="3">

<prjitem prjno="3"

prjname="Networks"

prjlocation="location3"
prjdeptno="3"

prjwrk="11"/>

</project>,

<project no="4">

<prjitem prjno="4"

prjname="Management System"

prjlocation="location4"

prjdeptno="4"

prjwrk="6"/>

</project>,

<project no="5">

<prjitem prjno="5"

prjname="Accounting"

prjlocation="location5"

prjdeptno="5"

prjwrk="17"/>

</project>

</projects>

XML Schema for Project:


proj.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault=
"qualified">

<xs:element name="projects">

<xs:complexType mixed="true">

<xs:sequence>

<xs:element minOccurs="0" maxOccurs="unbounded" ref="project"/>

</xs:sequence>

</xs:complexType>

</xs:element>

<xs:element name="project">

<xs:complexType>

<xs:sequence>

<xs:element ref="prjitem"/>

</xs:sequence>

<xs:attribute name="no" use="required" type="xs:integer"/>

</xs:complexType>

</xs:element>

<xs:element name="prjitem">

<xs:complexType>

<xs:attribute name="prjdeptno" use="required" type="xs:integer"/>

<xs:attribute name="prjlocation" use="required" type="xs:string"/>


<xs:attribute name="prjname" use="required" type="xs:string"/>

<xs:attribute name="prjno" use="required" type="xs:integer"/>

<xs:attribute name="prjwrk" use="required" type="xs:integer"/>

</xs:complexType>

</xs:element>

</xs:schema>

a. Implement the following queries using XQuery and Xpath


i. Retrieve the department name, manager name, and manager salary for every
department’.
<html>
<body>
<h1>Companys</h1>
<ul>
{
for $x in doc("depart.xml")//ditem,
$y in doc("employ.xml")//eitem
order by $x/@deptname, $y/@empname, $y/@empsalary
where $x/@deptmanagerssn = $y/@empssn
order by $x/@deptno
return <li>Department: {data($x/@deptname)} -- Manager: {data($y/@empname)} --
ManagerSalary: {data($y/@empsalary)}</li>
}
</ul>
</body>
</html>
OUTPUT :
<html>
<body>
<h1>Companys</h1>
<ul>

<li>Department: Research -- Manager: Vijay -- ManagerSalary: 50000</li>


<li>Department: Admistration -- Manager: Moni -- ManagerSalary: 47000</li>
<li>Department: Purchase -- Manager: Gowtham -- ManagerSalary: 30000</li>
<li>Department: Sales -- Manager: Uma -- ManagerSalary: 37000</li>
<li>Department: Financial -- Manager: Praveen -- ManagerSalary: 32000</li>

</ul>
</body>
</html>
ii. Retrieve the employee name, supervisor name and employee salary for each employee
who works in the Research Department.

<html>
<body>
<h1>Companys</h1>
<ul>
{
for $x in doc("depart.xml")//ditem[@deptname = "Research"],
$y in doc("employ.xml")//eitem
where $y/@empsupervisorssn = $x/@deptmanagerssn
return <li Employeename="{$y/@empname}" Employeesalary="{$y/@empsalary}" >
{
attribute Suprevisior
{
for $z in doc("employ.xml")//eitem
where $z/@empssn = $x/@deptmanagerssn
return $z/@empname
}
}</li>
}
</ul>
</body>
</html>

OUTPUT :
<html>
<body>
<h1>Companys</h1>
<ul>
<li> Employeename="Shiva" Employeesalary="24000" Suprevisior="Vijay" </li>
<li> Employeename="Thomas" Employeesalary="25000" Suprevisior="Vijay" </li>
</ul>
</body>
</html>

iii. Retrieve the project name, controlling department name, number of employees and
total hours worked per week on the project for each project.

<html>
<body>
<h1>Company</h1>
<ul>
{
for $d in distinct-values(doc("employ.xml")//eitem/@empdeptno),
$p in doc("proj.xml")//prjitem[@prjdeptno=$d],
$de in doc("depart.xml")//ditem[@deptno=$d]
let $items := doc("employ.xml")//eitem[@empdeptno=$d]
where $p/@prjdeptno = $de/@deptno
order by $de/@deptno
return <li Projectname="{$p/@prjname}" DepartmentName="{$de/@deptname}"
Deptno="{$d}" TotalHrWorked="{$p/@prjwrk}" empNoEmp="{count($items)}" />
}
</ul>
</body>
</html>

OUTPUT:
<html>
<body>
<h1>Company</h1>
<ul>
<li> Projectname="Cloud Computing" DepartmentName="Research" Deptno="1"
TotalHrWorked="5" empNoEmp="3"</li>
<li>Projectname="DataBase" DepartmentName="Admistration" Deptno="2"
TotalHrWorked="7" empNoEmp="1"</li>
<li> Projectname="Networks" DepartmentName="Purchase" Deptno="3"
TotalHrWorked="11" empNoEmp="2"</li>
<li> Projectname="Management System" DepartmentName="Sales" Deptno="4"
TotalHrWorked="6" empNoEmp="1"</li>
<li> Projectname="Accounting" DepartmentName="Financial" Deptno="5"
TotalHrWorked="17" empNoEmp="2"</li>

</ul>
</body>
</html>
iv. Retrieve the project name, controlling department name, number of employees and
total hours worked per week on the project for each project with more than one employee
working on it

<html>
<body>
<h1>Company</h1>
<ul>

{
for $d in distinct-values(doc("employ.xml")//eitem/@empdeptno),
$p in doc("proj.xml")//prjitem[@prjdeptno=$d],
$de in doc("depart.xml")//ditem[@deptno=$d]
let $items := doc("employ.xml")//eitem[@empdeptno=$d]
where $p/@prjdeptno = $de/@deptno
order by $de/@deptno
return <li Projectname="{$p/@prjname}" DepartmentName="{$de/@deptname}"
Deptno="{$d}" TotalHrWorked="{$p/@prjwrk}" empNoEmp="{count($items)>1}" />
}
</ul>
</body>
</html>

OUTPUT :

<html>
<body>
<h1>Company</h1>
<ul>

<li> Projectname="Cloud Computing" DepartmentName="Research" Deptno="1"


TotalHrWorked="5" empNoEmp="true"</li>
<li> Projectname="DataBase" DepartmentName="Admistration" Deptno="2"
TotalHrWorked="7" empNoEmp="false"</li>
<li> Projectname="Networks" DepartmentName="Purchase" Deptno="3"
TotalHrWorked="11" empNoEmp="true"</li>
<li> Projectname="Management System" DepartmentName="Sales" Deptno="4"
TotalHrWorked="6" empNoEmp="false"</li>
<li> Projectname="Accounting" DepartmentName="Financial" Deptno="5"
TotalHrWorked="17" empNoEmp="true"</li>

</ul>
</body>
</html>
b. Implement a storage structure for storing XML database and test with the
above schema.

TO CREATE DATABASE

mysql> create database xml;

Query OK, 1 row affected (0.00 sec)

TO USE DATABASE

mysql> use xml;

Database changed

CHECK TABLES IN DATABASE

mysql> show tables;

Empty set (0.00 sec)

TO CREATE TABLE FOR DEPARTMENT


mysql> create table dept (deptno varchar(20), deptname varchar(20), deptmanagerssn
varchar(20), deptmanagerstartdate date, deptlocation varchar(20));

Query OK, 0 rows affected (0.28 sec)

TO CREATE TABLE FOR EMPLOYEE

mysql> create table emp (empname varchar(20), empssn varchar(20),empsex varchar(

20), empsalary varchar(20), empbirthdate date, empdeptno varchar(20), empsupervisorssn


varchar(20), empaddress varchar(20), empworkon varchar(20));

Query OK, 0 rows affected (0.11 sec)

TO CREATE TABLE FOR PROJECT

mysql> create table proj (projname varchar(20),projno varchar(20),projlocation varchar(20),


projdeptno varchar(20), projwrk varchar(20));

Query OK, 0 rows affected (0.15 sec)

CHECK TABLES IN DATABASE

mysql> show tables;

+ +

| Tables_in_xml |

+ +

| dept |

| emp |

| proj |

+ +

6 rows in set (0.00 sec)


TO INSERT A XML FILE INTO DEPARTMENT DATABASE

mysql> LOAD XML LOCAL INFILE 'C:/Users/JPS/Desktop/Books/depart.xml'

-> INTO TABLE dept

-> ROWS IDENTIFIED BY '<ditem>';

Query OK, 5 rows affected, 5 warnings (0.06 sec)

Records: 5 Deleted: 0 Skipped: 0 Warnings: 5

VIEW A DEPARTMENT TABLE IN DATABASE

mysql> select * from dept;

+ + + + + +

| deptno | deptname | deptmanagerssn | deptmanagerstartdate | deptlocation |


+ + + + + +

|1 | Research | empssn1 | 1997-07-01 | Coimbatore |

|2 | Admistration | empssn2 | 1999-11-19 | Chennai |

|3 | Purchase | empssn3 | 1987-05-09 | Bangalore |

|4 | Sales | empssn4 | 1995-05-25 | Mumbai |

|5 | Financial | empssn5 | 1991-12-20 | Chennai |

+ + + + + +

5 rows in set (0.00 sec)


TO INSERT A XML FILE INTO EMPLOYEE DATABASE

mysql> LOAD XML LOCAL INFILE 'C:/Users/JPS/Desktop/Books/employ.xml'

-> INTO TABLE emp

-> ROWS IDENTIFIED BY '<eitem>';

Query OK, 9 rows affected, 1 warning (0.04 sec)

Records: 9 Deleted: 0 Skipped: 0 Warnings: 0

VIEW A EMPLOYEE TABLE IN DATABASE

mysql> select * from emp;

+ + + + + + +

+ + +

| empname | empssn | empsex | empsalary | empbirthdate | empdeptno | empsupervisorssn |


empaddress | empworkon |

+ + + + + + +

+ + +

| Vijay | empssn1 | male | 50000 | 1987-10-19 | 1 |0

| address1 | 25 |

| Shiva | empssn6 | female | 24000 | 1990-10-19 | 1 | empssn1

| address1 | 7 |

| Thomas | empssn10 | female | 25000 | 1991-09-30 | 1 | empssn1

| address1 | 8 |

| Moni | empssn2 | female | 47000 | 1989-01-01 | 2 |0

| address2 | 25 |

| Gowtham | empssn3 | male | 30000 | 1991-04-09 | 3 |0

| address3 | 9 |

| JaiVidhya | empssn7 | female | 27000 | 1991-04-09 | 3 | empssn3

| address3 | 21 |

| Uma | empssn4 | female | 37000 | 1991-04-09 | 4 |0

| address4 | 14 |

| Praveen | empssn5 | male | 32000 | 1991-04-09 | 5 |0

| address2 | 12 |

| Sathish | empssn9 | male | 32000 | 0000-00-00 | 5 | empssn5

| address9 | 11 |
+ + + + + + +

+ + +

9 rows in set (0.00 sec)

TO INSERT A XML FILE INTO PROJECT DATABASE

mysql> LOAD XML LOCAL INFILE 'C:/Users/JPS/Desktop/Books/proj.xml'

-> INTO TABLE proj

-> ROWS IDENTIFIED BY '<prjitem>';

Query OK, 5 rows affected (0.07 sec)

Records: 5 Deleted: 0 Skipped: 0 Warnings: 0

VIEW A PROJECT TABLE IN DATABASE

mysql> select * from proj;


+ + + + + +

| projname | projno | projlocation | projdeptno | projwrk |

+ + + + + +

| Cloud Computing |1 | location1 |1 |5 |

| DataBase |2 | location2 |2 |7 |

| Networks | 3 | location3 |3 | 11 |

| Management System | 4 | location4 |4 |6 |

| Accounting |5 | location5 |5 | 17 |

+ + + + + +

5 rows in set (0.00 sec)

RESULT:
Thus the XML Schema for the company database of Department, Employee, and Project using
XPATH, XQUERY and storage structure was implemented successfully
CASE STUDY-MONGO DB

introduction
MongoDB is a cross-platform, document oriented database that provides, high performance,high
availability, and easy scalability. MongoDB works on concept of collection and document.

Database
Database is a physical container for collections. Each database gets its own set of files on thefile
system. A single MongoDB server typically has multiple databases.

Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents within
a collection can have different fields. Typically, all documents in a collection are of similar or
related purpose.

Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schemameans
that documents in the same collection do not need to have the same set of fields or structure, and
common fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.

RDBMS MongoDB

Database Database

Table Collection

Tuple/Row Document

Column Field

Table Join Embedded Documents

Primary Key (Default key _id provided bymongodb


Primary Key
itself)

Database Server and Client

Mysqld/Oracle Mongod

mysql/sqlplus Mongo

7
Sample Document
Following example shows the document structure of a blog site, which is simply a commaseparated key value
pair.

{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}

_id is a 12 bytes hexadecimal number which assures the uniqueness of every document.
Youcan provide _id while inserting the document. If you don’t provide then MongoDB provides aunique id for
every document. These 12 bytes first 4 bytes for the current timestamp, next 3bytes for machine id, next 2 bytes for
process id of MongoDB server and remaining 3 bytes are simple incremental VALUE.
2. MONGO DB -ADVANTAGE

Any relational database has a typical schema design that shows number of tables and therelationship between these
tables. While in MongoDB, there is no concept of relationship.

Advantages of MongoDB over RDBMS


 Schema less: MongoDB is a document database in which one collection holds different documents. Number of
fields, content and size of the document can differ from one document to another.

 Structure of a single object is clear.

 No complex joins.

 Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query
language that's nearly as powerful as SQL.

 Tuning.

 Ease of scale-out: MongoDB is easy to scale.

 Conversion/mapping of application objects to database objects not needed.

 Uses internal memory for storing the (windowed) working set, enabling faster accessof data.

Why Use MongoDB?


 Document Oriented Storage: Data is stored in the form of JSON style documents.
 Index on any attribute
 Replication and high availability
 Auto-sharding
 Rich queries
 Fast in-place updates
 Professional support by MongoDB

Where to Use MongoDB?


 Big Data
 Content Management and Delivery
 Mobile and Social Infrastructure
 User Data Management
 Data Hub
3. MONGO DB -ENVIRONMENTS

Let us now see how to install MongoDB on Windows.

Install MongoDB on Windows


To install MongoDB on Windows, first download the latest release of MongoDB from
http://www.mongodb.org/downloads. Make sure you get correct version of MongoDB depending upon your
Windows version. To get your Windows version, open command promptand execute the following command.

C:\>wmic os get osarchitecture


OSArchitecture
64-bit
C:\>
32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for testing and evaluation
purposes.
Now extract your downloaded file to c:\ drive or any other location. Make sure the name of the extracted folder is
mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version].Here [version] is the version of MongoDB
download.
Next, open the command prompt and run the following command.

C:\>move mongodb-win64-* mongodb


1 dir(s) moved.
C:\>
In case you have extracted the MongoDB at different location, then go to that path by usingcommand cd
FOOLDER/DIR and now run the above given process.
MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\data\db.
So you need to create this folder using the Command Prompt. Executethe following command sequence.

C:\>md data
C:\md data\db
If you have to install the MongoDB at a different location, then you need to specify an alternate path for \data\db by
setting the path dbpath in mongod.exe. For the same, issue the following commands.
In the command prompt, navigate to the bin directory present in the MongoDB installationfolder. Suppose my
installation folder is D:\set up\mongodb

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"
This will show waiting for connections message on the console output, which indicates thatthe mongod.exe process is
running successfully.
Now to run the MongoDB, you need to open another command prompt and issue the followingcommand.

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
This will show that MongoDB is installed and run successfully. Next time when you runMongoDB, you need
to issue only commands.

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"


D:\set up\mongodb\bin>mongo.exe

Install MongoDB on Ubuntu


Run the following command to import the MongoDB public GPG key −

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10


Create a /etc/apt/sources.list.d/mongodb.list file using the following command.

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen'


| sudo tee /etc/apt/sources.list.d/mongodb.list
Now issue the following command to update the repository −

sudo apt-get update


Next install the MongoDB by using the following command −

apt-get install mongodb-10gen=2.2.3


In the above installation, 2.2.3 is currently released MongoDB version. Make sure to installthe latest version always.
Now MongoDB is installed successfully.

Start MongoDB
sudo service mongodb start

sudo service mongodb stop

Stop MongoDB

Restart MongoDB
sudo service mongodb restart
To use MongoDB run the following command.

mongo
This will connect you to running MongoDB instance.

MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list ofcommands as shown in
the following screenshot.
MongoDB Statistics
To get stats about MongoDB server, type the command db.stats() in MongoDB client. This will show the database
name, number of collection and documents in the database. Output of the command is shown in the following
screenshot.

The use Command


MongoDB use DATABASE_NAME is used to create database. The command will create anew database if it
doesn't exist, otherwise it will return the existing database.

Syntax
Basic syntax of use DATABASE statement is as follows:

use DATABASE_NAME

Example
If you want to create a database with name <mydb>, then use DATABASE statement wouldbe as follows:

>use mydb
switched to db mydb
To check your currently selected database, use the command db

>db
mydb
If you want to check your databases list, use the command show dbs.

>show dbs
test 0.23012GB
local 0.78125GB
>db.movie.insert({"name":"tutorials point"})
test 0.23012GB
>show dbs
local 0.78125GB

Your created database (mydb) is not present in list. To display database, you need to insertat least one document into
it
In MongoDB default database is test. If you didn't create any database, then collections willbe stored in test database.

In this chapter, we will see how to drop a database using MongoDB command.

The dropDatabase() Method


MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax
Basic syntax of dropDatabase() command is as follows:

db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it willdelete default 'test'
database.

Example
First, check the list of available databases by using the command, show dbs.

>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
The createCollection() Method
MongoDB db.createCollection(name, options) is used to create collection.

Syntax
Basic syntax of createCollection() command is as follows:

db.createCollection(name, options)

In the command, name is name of collection to be created. Options is a document and isused to specify
configuration of collection.

Parameter Type Description

Name String Name of the collection to be created

(Optional) Specify options about memorysize and


Options Document
indexing

Options parameter is optional, so you need to specify only the name of the collection.Following is the list of
options you can use:

Field Type Description

(Optional) If true, enables a capped collection. Capped collection is a


fixed size collection that automatically overwrites its oldest entries when
Capped Boolean it reaches its maximum size. If you specify true, you need to specify
size parameter also.

(Optional) If true, automatically create index on _id field.Default value is


autoIndexID Boolean
false.

(Optional) Specifies a maximum size in bytes for a cappedcollection. If


Size number capped is true, then you need to specify this field also.
(Optional) Specifies the maximum number of documentsallowed in the
max number
capped collection.

While inserting the document, MongoDB first checks size field of capped collection, then itchecks max field.

Examples
Basic syntax of createCollection() method without options is as follows:

>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.

>show collections
mycollection
system.indexes
The following example shows the syntax of createCollection() method with few importantoptions:

>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800,


max : 10000 } )
{ "ok" : 1 }
>
In MongoDB, you don't need to create collection. MongoDB creates collection automatically,when you insert some
document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

You might also like