0% found this document useful (0 votes)
27 views

cp4152 Database Practices Lab

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

cp4152 Database Practices Lab

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

INDEX

NAME OF THE EXERCISE Pg.


S.No DATE SIGN
/ EXPERIMENT No
Ex.no:1

Create table using data definition language ,create alter, drop, enforce a
foreign key ,primary key ,check, not null constraints and creating views

AIM : Creating Tables and altering the Tables

Procedure:
Mysql>Create table passenger2(passportId Integer Primary
Key,Name varchar(10) NotNull,Age Integer Not Null,Sex
char,Address varchar(20) Not Null);

Mysql> desc
passenger2;

USING ALTER COMMAND

Adding Extra
column to
Existing
Table
Mysql>Alter table passenger3 add column TicketNo varchar(10);

Mysql>Alter Table passenger3 add Foreign key(TicketNo) references Ticket(TicketNo);

Mysql>Alter Table passenger3 Modify column Name varchar(20);


Mysql>Alter table passenger drop foreign key fk1;

Mysql> Alter table passenger2 Drop column TicketNo;


PRIMARY KEY
The PRIMARY KEY constraint consists of one column or multiple columns with values
that uniquely identify each row in the table.

CREATE TABLE ConstraintDemo3


(
ID INT PRIMARY KEY,
Name VARCHAR(50) NULL
)

INSERT INTO ConstraintDemo3 ([ID],[NAME]) VALUES (1,'John')


GO
INSERT INTO ConstraintDemo3 ([NAME]) VALUES ('Fadi')
GO
INSERT INTO ConstraintDemo3 ([ID],[NAME]) VALUES (1,'Saeed')
GO

CHECK Constraint

It is used to restrict the value of a column between a range. It performs check on the
values, before storing them into the database. Its like condition checking before saving
data into a column.

Create table student(


S id int NOT NULL CHECK(s id >0),
Name varchar(60) Not NULL,
Age int
);
UNIQUE constraint

The UNIQUE constraint in SQL is used to ensure that no duplicate values will be
inserted into a specific column or combination of columns that are participating in the
UNIQUE constraint and not part of the PRIMARY KEY

CREATE TABLE ConstraintDemo2


(
ID INT UNIQUE,
Name VARCHAR(50) NULL
)

INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (1,'Ali')


GO
INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (2,'Ali')
GO
INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (NULL,'Adel')
GO
INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (1,'Faris')
GO

Not null constraints


By default, the columns are able to hold NULL values. A NOT NULL constraint in SQL
is used to prevent inserting NULL values into the specified column, considering it as a
not accepted value for that column. This means that you should provide a valid SQL
NOT NULL value to that column in the INSERT or UPDATE statements, as the column
will always contain data.

USE SQLShackDemo
GO
CREATE TABLE ConstraintDemo1
(
ID INT NOT NULL,
Name VARCHAR(50) NULL

INSERT INTO ConstraintDemo1 ([ID],[NAME]) VALUES (1,'Ali')


GO
INSERT INTO ConstraintDemo1 ([ID]) VALUES (2)
GO
INSERT INTO ConstraintDemo1 ([NAME]) VALUES ('Fadi')
GO
Creating View
The query that defines the sales_staffview references only rows in department 5.
Furthermore, the CHECK OPTION creates the view with the constraint (named
sales_staff_cnst) that INSERT and UPDATE statements issued against the view cannot
result in rows that the view cannot select.

Creating Views (With and Without Check Option)

1. SQL> CREATE VIEW sales_staff AS


2. 2 SELECT fname, ssn, dno
3. 3 FROM employee
4. 4 WHERE dno =5
5. 5 WITH CHECK OPTION CONSTRAINT sales_staff_cnst;
6. View created.

2. Selecting from a View SQL>

select * from sales_staff;

3. Drop View SQL>

DROP VIEW sales_staff;

RESULT
Create alter, drop, enforce a foreign key ,primary key ,check, not null constraints
and creating views was successfully created.
Ex.no:2
Create table using Data manipulation language, insert, delete, update.

AIM: Create a DML Commands are used to manage data within the scheme objects.

Procedure:

INSERT COMMAND ON BUS2 & PASSENGER2 RELATIONS

mysql> select * from Bus2; Empty set (0.00

sec) mysql> insert into Bus2

values(1234,'Hyderabad','Tirupathi');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Bus2

values(2345,'Hyderabad','Banglore');

Query OK, 1 row affected (0.01 sec)

mysql> insert into Bus2

values(23,'Hyderabad','Kolkata');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Bus2

values(45,'Tirupathi','Banglore');Query

OK, 1 row affected (0.03 sec)

mysql> insert into Bus2

values(34,'Hyderabad','Chennai');

Query OK, 1 row affected (0.03

sec)
mysql> select * from Bus2;

mysql> select * from

Passenger2; Empty set (0.00 sec)

mysql> insert into Passenger2

values(145,'Ramesh',45,'M','abc123');Query

OK, 1 row affected (0.05 sec)

mysql> insert into Passenger2

values(278,'Geetha',36,'F','abc124');

Query OK, 1 row affected (0.02 sec)

mysql> insert into Passenger2

values(4590,'Ram',30,'M','abc12');Query

OK, 1 row affected (0.03 sec)


mysql> insert into Passenger2

values(6789,'Ravi',50,'M','abc14');Query

OK, 1 row affected (0.03 sec)

mysql> insert into Passenger2

values(5622,'Seetha',32,'F','abc55');Query

OK, 1 row affected (0.03 sec)

mysql> select * from Passenger2;

UPDATE COMMAND ON BUS2 RELATION

UPDATE Selected Rows & Multiple Rows


mysql> Update Bus2 SET Source='Secundrabad' where BusNo=1234; Query

OK, 1 row affected (0.05 sec)Rows matched: 1 Changed: 1 Warnings: 0

DELETE COMMAND ON BUS2 RELATION

DELETES Selected Rows and Multiple Rows

mysql> Delete from Bus2 where BusNo=1234; Query OK,

1 row affected (0.05 sec)mysql> select * from Bus2;


RESULT
DML Commands are used to manage data within the scheme objects.
successfully created.
Ex no:3
Practice Cartesian product, equi join, left outer join,
right outer join, full outer join

Aim: Create cartesian product, equi join, left outer join, right outer join, full outer join

Procedure:
CARTESIAN JOIN

The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of
records from two or more joined tables. Thus, it equates to an inner join where the join-
condition always evaluates to either True or where the join-condition is absent from the
statement.

SELECT table1.column1, table2.column2...


FROM table1, table2 [, table3 ]

+ + + +
|OID | DATE | CUSTOMER_ID | AMOUNT |
+ + + +- +
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+ + + +- +
let us join these two tables using CARTESIAN JOIN
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS;

ID | NAME | AMOUNT | DATE |


+ + +- + +
| 1 | Ramesh | 3000 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1500 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1560 | 2009-11-20 00:00:00 |
| 1 | Ramesh | 2060 | 2008-05-20 00:00:00 |
| 2 | Khilan | 3000 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 2 | Khilan | 2060 | 2008-05-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 2060 | 2008-05-20 00:00:00 |
| 4 | Chaitali | 3000 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | 3000 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1500 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1560 | 2009-11-20 00:00:00 |
| 5 | Hardik | 2060 | 2008-05-20 00:00:00 |
| 6 | Komal | 3000 | 2009-10-08 00:00:00 |
| 6 | Komal | 1500 | 2009-10-08 00:00:00 |
| 6 | Komal | 1560 | 2009-11-20 00:00:00 |
| 6 | Komal | 2060 | 2008-05-20 00:00:00 |
| 7 | Muffy | 3000 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1500 | 2009-10-08 00:00:00 |

Equi join

An equijoin is an operation that combines multiple tables based on equality or matching


column values in the associated tables.

1. SELECT column_name (s)


2. FROM table_name1, table_name2,....., table_nameN
3. WHERE table_name1.column_name = table_name2.column_name;

1. mysql> SELECT cust. customer_name, bal.balance


2. FROM customer AS cust, balance AS bal
3. WHERE cust.account = bal.account_num;

LEFT Outer Join

The left outer join returns a resultset table with the matched data from the two tables and
then the remaining rows of the left table and null from the right table's columns.

SELECT column-name-list FROM

table-name1 LEFT OUTER JOIN table-name2

ON table-name1.column-name = table-name2.column-name;

SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id = class_info.id);

ID NAME ID
1 abhi 1
2 adam 2
3 alex 3
4 anu null
5 ashish null
ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Output

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

RIGHT Outer Join

The right outer join returns a result set table with the matched data from the two
tables being joined, then the remaining rows of the right table and null for the
remaining left table's columns.

SELECT column-name-list FROM


table-name1 RIGHT OUTER JOIN table-name2

ON table-name1.column-name = table-name2.column-name;

SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id = class_info.id);

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

null null 7 NOIDA

null null 8 PANIPAT

Full Outer Join

The full outer join returns a resultset table with the matched data of two table then
remaining rows of both left table and then the right table.

SELECT column-name-list FROM

table-name1 FULL OUTER JOIN table-name2

ON table-name1.column-name = table-name2.column-name;
SELECT * FROM class FULL OUTER JOIN class_info ON (class.id = class_info.id);

ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
4 anu null null
5 ashish null null
null null 7 NOIDA
null null 8 PANIPAT

RESULT
Cartesian product, equi join, left outer join, right outer join, full outer join was
successfully created.
Ex.no:4
Set aggregate functions, set operation and nested queries

Aim : Create using aggregate functions, set operation and nested queries

Procedure:

SQL aggregation function

It is used to perform the calculations on multiple rows of a single column of a table. It


returns a single value.

It is also used to summarize the data.

COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
o COUNT(*)
o or
o COUNT( [ALL|DISTINCT] expression )
Table name: Product mast
PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output: 5
2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

1. SELECT SUM(COST)
2. FROM
PRODUCT_MAST; 3. 670
4. 670

Table name: Product mast

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Output:540
3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:67.00

4. MAX Function

MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;

Output:30
5. MIN Function

MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.

Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:10

Set operation

The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
2. UnionAll
3. Intersect
4. Minus

1. Union
o The SQL Union operation is used to combine the result of two or more SQL
SELECT queries.
o In the union operation, all the number of datatype and columns must be same in
both the tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its result set.

Syntax

1. SELECT column_name FROM table1


2. UNION
3. SELECT column_name FROM table2;
First table

ID NAME

1 Jack

2 Harry

3 Jackson

Second table:
ID NAME

3 Jackson

4 Stephan

5 David
1. SELECT * FROM First
2. UNION
3. SELECT * FROM Second;

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David
2. Union All

Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:

1. SELECT column_name FROM table1


2. UNION ALL
3. SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

1. SELECT * FROM First


2. UNION ALL
3. SELECT * FROM Second;
ID NAME

1 Jack

2 Harry
3 Jackson

3 Jackson

4 Stephan

5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax

1. SELECT column_name FROM table1


2. INTERSECT
3. SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

1. SELECT * FROM First


2. INTERSECT
3. SELECT * FROM Second;
ID NAME

3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to
display the rows which are present in the first query but absent in the second
query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
1. SELECT column_name FROM table1
2. MINUS
3. SELECT column_name FROM table2;

Example

Using the above First and Second table.

1. SELECT * FROM First


2. MINUS
3. SELECT * FROM Second;
ID NAME

1 Jack

2 Harry

Nested queries

A nested query in SQL contains a query inside another query. The result of the inner query will
be used by the outer query. For instance, a nested query can have two SELECT statements, one
on the inner query and the other on the outer query.

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE]
)

The SELECT query inside the brackets (()) is the inner query, and the SELECT query outside
the brackets is the outer query. The result of the inner query is used by the outer query.

CREATE TABLE employee (


id NUMBER PRIMARY KEY,
name VARCHAR2(100) NOT NULL,
salary NUMBER NOT NULL,
role VARCHAR2(100) NOT NULL
);
CREATE TABLE awards(
id NUMBER PRIMARY KEY,
employee_id NUMBER NOT NULL,
award_date DATE NOT NULL
);
INSERT INTO employees VALUES (1, 'Augustine Hammond', 10000, 'Developer');
INSERT INTO employees VALUES (2, 'Perice Mundford', 10000, 'Manager');
INSERT INTO employees VALUES (3, 'Cassy Delafoy', 30000, 'Developer');
INSERT INTO employees VALUES (4, 'Garwood Saffen', 40000, 'Manager');
INSERT INTO employees VALUES (5, 'Faydra Beaves', 50000, 'Developer');
INSERT INTO awards VALUES(1, 1, TO_DATE('2022-04-01', 'YYYY-MM-DD'));
INSERT INTO awards VALUES(2, 3, TO_DATE('2022-05-01', 'YYYY-MM-DD'));

RESULT:
Aggregate functions, set operation and nested queries was successfully created.
Ex No:5

Create transaction control language commit, roll back, save points

Aim: Create transaction control language commit, roll back, save points
Procedure:

COMMIT

COMMIT command in SQL is used to save all the transaction-related changes permanently to
the disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used, the
changes made by these commands are permanent only after closing the current session. So
before closing the session, one can easily roll back the changes made by the DDL commands.
Hence, if we want the changes to be saved permanently to the disk without closing the session,
we will use the commit command.

1. COMMIT;
mysql> USE school;

To create a table named t_school, we will execute the following query:

mysql> CREATE TABLE t_school(ID INT, School_Name VARCHAR(40),


Number_Of_Students IN T, Number_Of_Teachers INT, Number_Of_Classrooms INT,
EmailID VARCHAR(40));
1. mysql> SELECT *FROM t_school;

ID School_Name Number_Of_Students Number_Of_Teachers Number_Of_Classrooms EmailID

1 Boys Town 1000 80 12 [email protected]


Public School m

2 Guru Govind 800 35 15 [email protected]


Singh m

Public School
3 Delhi 1200 30 10 [email protected]
m
Public School
4 Ashoka 1110 40 40 [email protected]
Universal
School
5 Calibers 9000 31 50 [email protected]

English Medium
School
1. mysql> COMMIT;

2. SAVEPOINT

We can divide the database operations into parts. For example, we can consider all the insert
related queries that we will execute consecutively as one part of the transaction and the delete
command as the other part of the transaction. Using the SAVEPOINT command in SQL, we can
save these different parts of the same transaction using different names. For example, we can
save all the insert related queries with the savepoint named INS. To save all the insert related
queries in one savepoint, we have to execute the SAVEPOINT query followed by the savepoint
name after finishing the insert command execution.

1. SAVEPOINT savepoint_name;
3. ROLLBACK

While carrying a transaction, we must create savepoints to save different parts of the transaction.
According to the user's changing requirements, he/she can roll back the transaction to different
savepoints. Consider a scenario: We have initiated a transaction followed by the table creation
and record insertion into the table. After inserting records, we have created a savepoint INS.
Then we executed a delete query, but later we thought that mistakenly we had removed the
useful record. Therefore in such situations, we have an option of rolling back our transaction. In
this case, we have to roll back our transaction using the ROLLBACK command to the savepoint
INS, which we have created before executing the DELETE query.
1. ROLLBACK TO savepoint_name;
2. mysql> ROLLBACK TO Insertion;
3. mysql> SELECT *FROM t_school;

I School Number_Of_Stude Number_Of_Teach Number_Of_Classro EmailID


D Name nts ers oms

1 Boys 1000 80 12 btps15@gmail.


Town co mm
Public
Schoo
l
2 Guru 800 35 15 ggps25@gmail.
Govind co mm
Singh
Public
School

3 Delhi 1200 30 10 dps101@gmail.


Public co mm
Schoo
l
4 Ashok 1110 40 40 [email protected]
a om m
Univer
s al
School
5 Calibers 900 31 50 [email protected]
English
Medium

RESULT:
Transaction control language commit, roll back, save points was successfully
done.
Ex no :6
Row level and statement level triggers

Aim : Implementing Row level and statement level triggers

Statement level triggers and other is row level trigger. The Statement level trigger will be fired
for every transaction not for every row. It will fire whenever the trigger event occurs on the
specified table. It will not check how many rows are impacting with statement level trigger.

Procedure:
Syntax :

Create or replace Trigger Trigger name

BEFORE/AFTER INSERT/UPDATE/DELETE ON table_name

Begin

SQL statements;

END;

Step 1 : Create table named Employee

create table Employee


( emp_id number,
ename varchar2(100)
);

Step 2 : Insert values in employee table

insert into Employee values (1,’Amit’);


insert into Employee values (2,’Pradnya’);

Step 3 : Write the Code for Trigger


create or replace trigger T_Statement_Level
before update —Before updating the table named Employee trigger needs to be fired
on Employee
begin
DBMS_OUTPUT.PUT_LINE(‘Trigger Fired Before Update’);
end;
Step 4 : Testing of Trigger
update Employee
set ename=’Rahul’;

output

Trigger fired Before Update

2 rows updated

Row level trigger

1. The row level trigger will always used for each row statement. If the for each
row statement is there then that trigger is called as row level trigger.
2. It will fire once for each row affected by triggering event. It will not fire
for transaction.
3. It will not fire if triggering event is not impacting the rows.

Step 1 : Lets create Employee table


drop table Employee;

create table Employee


( emp_id number,
ename varchar2(100)
);

insert into Employee values (1,’Amit’);


insert into Employee values (2,’Pradnya’);
With first step we have inserted the values in employee table.

Step 2 : Lets create a trigger using for each row statement.


create or replace trigger T1_Row_level_example
before update —Before updating the employee table

on Employee
for each row
begin
DBMS_OUTPUT.PUT_LINE(‘Row Level trigger executed’);
end;
The above statement will create a row level trigger.

Step 3 : Testing the trigger

To test the trigger we require to update the employee

table, Update Employee set Ename=’Rahul’;


We are updating the Employee table without any condition. So the trigger will be fired twice.

The output will be,

Row Level trigger executed

Row Level trigger executed

Updated two rows


The trigger will run twice as two rows are processed and added :new value to those two rows.

Step 4 : Test trigger without processing rows


Lets fire the second statement,

Update Employee set Ename=’Rahul’ where 1=2;


The 1=2 is always false condition so this will not execute the trigger.

output

0 rows updated

RESULT:
Row level and statement level triggers successfully created
Ex no :7

Creating XML documents,document type definition and XML Schema

Aim : Implementing XML documents,document type definition and XML Schema

Procedure:

XML

An XML document is a basic unit of XML information composed of elements and other markup
in an orderly package. An XML document can contains wide variety of data. For example,
database of numbers, numbers representing molecular structure or a mathematical equation.
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>aws</company>
<phone>(011) 123-4567</phone>
</contact-info>

Document type definition:

The DTD starts with <!DOCTYPE> delimiter.


An element tells the parser to parse the document from the specified root element.
DTD identifier is an identifier for the document type definition, which may be the
path to a file on the system or URL to a file on the internet. If the DTD is pointing
to external path, it is called External Subset.
The square brackets [ ] enclose an optional list of entity declarations
called Internal Subset.
Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To refer
it as internal DTD, standalone attribute in XML declaration must be set to yes. This means, the
declaration works independent of an external source.
Syntax
Following is the syntax of internal DTD −
<!DOCTYPE root-element [element-declarations]>
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Start Declaration − Begin the XML declaration with the following statement.
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
DTD − Immediately after the XML header, the document type declaration follows, commonly
referred to as the DOCTYPE −
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations.
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
External DTD
In external DTD elements are declared outside the XML file. They are accessed by specifying
the system attributes which may be either the legal .dtd file or a valid URL. To refer it as
external DTD, standalone attribute in the XML declaration must be set as no. This means,
declaration includes information from the external source.
Syntax
Following is the syntax for external DTD −
<!DOCTYPE root-element SYSTEM "file-name">
where file-name is the file with .dtd extension.
Example
The following example shows external DTD usage −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd is as shown −
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe
and validate the structure and the content of XML data. XML schema defines the elements,
attributes and data types. Schema element supports Namespaces. It is similar to a database
schema that describes the data in a database.
Syntax
You need to declare a schema in your XML document as follows −
Example
The following example shows how to use schema −
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an XML
document can take.
Elements
As we saw in the XML - Elements chapter, elements are the building blocks of XML document.
An element can be defined within an XSD as follows −
<xs:element name = "x" type = "y"/>
Definition Types
You can define XML schema elements in the following ways −
Simple Type
Simple type element is used only in the context of the text. Some of the predefined simple types
are: xs:integer, xs:boolean, xs:string, xs:date. For example −
<xs:element name = "phone_number" type = "xs:int" />
Complex Type
A complex type is a container for other element definitions. This allows you to specify which
child elements an element can contain and to provide some structure within your XML
documents. For example −
<xs:element name = "Address">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in the XML
document

RESULT:
XML documents,document type definition and XML Schema successfully created
Ex no :8
Relational database to store the XML documents as a text and data elements

Aim : Implementing Relational database to store the XML documents as a text and data
elements

Procedure:

Store DTD in DTD repository Register a XML column with type:

XMLCLOB: for large XML documents;


XMLVARCHAR: for small XML documents,
XMLFile:for XML documents stored outside DB2 Create a DAD file
To specify any “side tables” for indexing Enable the XML column
Creates side tables as per DAD

Add necessary triggers and other meta information Insert XML document Side tables get
automatically

StorageType conversion
XMLVarCharFromFile(),.. Retrieval: Cast Functions
Varchar(XMLVarChar) Update
Cast functions or storage UDFs
Update(xmlobj, path,value) Selection using XPATH
WHERE Extractvarchar(order, ‘/order/Customer’) LIKE “%IBM%’
Or, use side tables

to store data from an XML file into SQL database with 2 tables. The XML file looks like this
(the full file has more Document nodes):
<Documents>
<Document>
<Number>110</Number>
<Date>2020-10-23</Date>
<TotalPrice>3800</TotalPrice>
<Items>
<Item>
<SKU>001234</SKU>
<Name>FirstItem</Name>
<Quantity>10</Quantity>
<Price>1550</Price>
</Item>
<Item>
<SKU>001235</SKU>
<Name>SecondItem</Name>
<Quantity>8</Quantity>
<Price>1200</Price>
</Item>
<Item>
<SKU>001236</SKU>
<Name>ThirdItem</Name>
<Quantity>21</Quantity>
<Price>1050</Price>
</Item>
</Items>
</Document>
</Documents>

The SQL database has 2 tables. One for Documents, and the other one for Items.
create table Document(
DocumentId int identity(1,1) not null primary key,
Number int not null,
[Date] date not null,
TotalPrice money not null
);

create table Item(


ItemId int identity(1,1) not null primary key,
SKU int not null,
[Name] nvarchar(30) not null,
Quantity int not null,
Price money not null,
DocumentId int not null foreign key references Document(DocumentId)
);
[Serializable]
[XmlRoot("Document")]
public class DocumentMetadata
{
[XmlElement("Number")]
public int Number { get; set; }

[XmlElement("Date")]
public DateTime Date { get; set; }

[XmlElement("TotalPrice")]
public int TotalPrice { get; set; }
}

[MetadataType(typeof(DocumentMetadata))]
public partial class Document
{

}
XDocument xDoc = XDocument.Load(XmlFile);
List<Document> documentList = xDoc.Descendants("Document").Select(document => new
Document
{
Number = Convert.ToInt32(document.Element("Number").Value),
Date = Convert.ToDateTime(document.Element("Date").Value),
TotalPrice = Convert.ToInt32(document.Element("TotalPrice").Value),
}).ToList();

using (DocumentsEntities entity = new DocumentsEntities())


{
foreach (var doc in documentList)
{
var dbDoc = entity.Documents.Where(x => x.Number.Equals(d.Number)).FirstOrDefault();

if (dbDoc != null)
{
dbDoc.Number = doc.Number;
dbDoc.Date = doc.Date;
dbDoc.TotalPrice = doc.TotalPrice;
}
else
{
entity.Documents.Add(doc);
}
}
entity.SaveChanges();

Selecting/Extracting XMLType
Instance Extract()
Obtains the node/nodes from the document identified by the XPath (subset of) expression
Use getStringVal() or getNumberVal() to get scalar content Select
p.poDoc.extract(‘/PO/PONO/text()’).getnumberval() From po_xml_tab p; ExistsNode()

Checks if the given XPath evaluates in at least a single XML element or text node
Useful for filtering as well as for functional indexes Select
e.poDoc.extract(‘//PONO/text()’).getNumberVal() as pono From po_xml_tab e
Where e.podoc.existsnode(‘/Po/PONO’) = 1 and poid > 1
Functions to convert from XMLType to other type

RESULT:
Relational database to store the XML documents as a text and data elements was created
Ex no :9
XML querying

Aim : create and implementing database using XML querying

Procedure

Retrieving entire XML documents


To retrieve all of the XML documents stored in the column named INFO and values
from the CID primary key column, issue the following SELECT statement:
SELECT cid, info FROM customer~
his query returns the two stored XML documents.
Retrieving and filtering XML values
To query within the XML documents in the INFO column, issue the following SELECT
statement, which uses the XMLQUERY function to invoke an XQuery expression:
SELECT XMLQUERY (
'declare default element namespace "http://posample.org";
for $d in $doc/customerinfo
return <out>{$d/name}</out>'
passing INFO as "doc")
FROM Customer as c
WHERE XMLEXISTS ('declare default element namespace "http://posample.org";
$i/customerinfo/addr[city="Toronto"]' passing c.INFO as "i")~

In the XMLQUERY function, a default namespace is first specified. This namespace matches the
namespace of the documents previously inserted. The for clause specifies iteration through the
<customerinfo> elements in each document from the Info column. The INFO column is
specified by using the passing clause, which binds the INFO column to the variable
named doc that is referenced in the for clause. The return clause then constructs an <out>
element, which contains the <name> element from each iteration of the for clause.

The WHERE clause uses the XMLEXISTS predicate to consider only a subset of the documents
in the Info column. This filtering yields only those documents that have a <city> element (along
the path specified) with a value of Toronto.

The SELECT statement returns the following constructed element:


<out xmlns="http://posample.org"><name>Kathy Smith</name></out>
Using db2-fn:sqlquery with parameters

To pass a value to the SQL fullselect in the db2-fn:sqlquery function, run the following
query:

VALUES XMLQUERY (
'declare default element namespace "http://posample.org";
for $d in db2-fn:sqlquery(
''SELECT INFO FROM CUSTOMER WHERE Cid = parameter(1)'',
$testval)/customerinfo
return <out>{$d/name}</out>'
passing 1000 as "testval" )~

The XMLQUERY function passes the value 1000 to the XQuery expression by using the
identifier testval. The XQuery expression then passes the value to the db2-fn:sqlquery function
by using the PARAMETER scalar function.

The XQuery expression returns the following constructed element:

<out xmlns="http://posample.org">
<name>Kathy Smith</name>
</out>
Querying in an XQuery context

DB2® XQuery offers two built-in functions specifically for use with DB2 databases: db2-
fn:sqlquery and db2-fn:xmlcolumn. db2-fn:sqlquery retrieves a sequence that is the result table
of an SQL fullselect. db2-fn:xmlcolumn retrieves a sequence from an XML column.

If your query invokes an XQuery expression directly, you must prefix it with the case-insensitive
keyword XQUERY.

Retrieving entire XML documents


To retrieve all of the XML documents previously inserted into the INFO column, you
can use XQuery with either db2-fn:xmlcolumn or db2-fn:sqlquery.
Using db2-fn:xmlcolumn
To retrieve all XML documents in the INFO column, run the following query:
XQUERY db2-fn:xmlcolumn ('CUSTOMER.INFO')~

Names in SQL statements are automatically converted to uppercase by default.


Therefore, when you created the CUSTOMER table by using the CREATE TABLE SQL
statement, the names of the table and columns were made uppercase. Because XQuery is
case sensitive, you must be careful to use the correct case when specifying the table and
column names when using db2-fn:xmlcolumn.

This query is equivalent to the SQL query SELECT Info FROM Customer.

Using db2-fn:sqlquery
To retrieve all XML documents in the INFO column, run the following query:
XQUERY db2-fn:sqlquery ('SELECT Info FROM Customer')~

You do not have to specify the INFO and CUSTOMER names in uppercase because the
SELECT statement is processed in an SQL context and is therefore not case sensitive.

Retrieving partial XML documents


Instead of retrieving an entire XML document, you can retrieve fragments of the
document and filter on values present in the document by using XQuery with
either db2-fn:xmlcolumn or db2-fn:sqlquery.
Using db2-fn:xmlcolumn
To return elements containing <name> nodes for all documents in the Info column that
have a <city> element (along the path specified) with a value of Toronto, run the
following query:

XQUERY declare default element namespace "http://posample.org";


for $d in db2-fn:xmlcolumn('CUSTOMER.INFO')/customerinfo
where $d/addr/city="Toronto"
return <out>{$d/name}</out>~

The db2-fn:xmlcolumn function retrieves a sequence from the INFO column of the
CUSTOMER table. The for clause binds the variable $d to each <customerinfo>
element in the CUSTOMER.INFO column. The where clause restricts the items to only
those that have a <city> element (along the path specified) with a value of Toronto.
The return clause constructs the returned XML value. This value is an element <out>
that contains the <name> element for all documents that satisfy the condition specified
in the where clause, as follows:

<out xmlns="http://posample.org">
<name>
Kathy Smith
</name>
</out>
Using db2-fn:sqlquery
To issue a fullselect within an XQuery expression, run the following query:

XQUERY declare default element namespace "http://posample.org";


for $d in db2-fn:sqlquery(
'SELECT INFO
FROM CUSTOMER
WHERE Cid < 2000')/customerinfo
where $d/addr/city="Toronto"
return <out>{$d/name}</out>~

RESULT:
Implementing database using XML querying was successfully done
Ex no :10

Creating a database using MongoDB,DynamoDB,Voldemort Key-Value


Distributed Data store Hbase and Neo4j

Aim: Creating a database using MongoDB,DynamoDB,Voldemort Key-Value


Distributed Data store Hbase and Neo4j

MongoDB use DATABASE_NAME is used to create database. The command will create a new
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 use a database with name <mydb>, then use DATABASE statement would be as
follows −
>use mydb
switched to db mydb
To check your currently selected database, use the command db
>db
mydb
f you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at
least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb
0.23012GB
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 will delete
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
if you want to delete new database <mydb>, then dropDatabase() command would be as
follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local
0.78125GB
test 0.23012GB

Traditional DB
In a traditional relational database management system (RDBMS), you have a table for users and
a table for updates. A foreign key represents the one-to-many relationship between users and
updates. Getting a user's updates is as simple as making a SQL query like "SELECT * FROM
updates WHERE updates.user_id = users.user_id". The problem with a traditional RDBMS is
that scaling becomes more difficult as you exceed the capabilities of the single machine.
Simple secondary index that stores a list of element ids
index: user_id => [update_id]
updates: update_id => update_data
Secondary index paged by month
index: user_id, month => [update_id]
updates: update_id => update_data VStack underlying Voldemort stores
stack: user_id, page_id => update_id, next_page, previous_page
updates: update_id => update_data
// iterating over a VStack
VStack<Integer, String> myUpdates =
new VStack<Integer, String>(1337 /* example userid */,
storeClient /* Voldemort StoreClient */);
for (String update : myUpdates) {
System.out.println(update);
}

Select All Documents in a Collection

This operation uses a filter predicate of {}, which corresponds to the following SQL statement:

SELECT * FROM inventory

Specify Equality Condition

The following example selects from the inventor collection all documents where
the statu equals "D":

This operation uses a filter predicate of { status: "D" }, which corresponds to the following SQL
statement:

SELECT * FROM inventory WHERE status = "D"

Specify Conditions Using Query Operators

The following example retrieves all documents from the inventory collection
where statu equals either "A" or "D":

db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
Specify Conditions Using Query Operators

A query filter document can use the query operators to specify conditions in the following form:

{ <field1>: { <operator1>: <value1> }, ... }


MongoDB Shell

The following example retrieves all documents from the inventory collection
where statu equals either "A" or "D":

db.inventory.find( { status: { $in: [ "A", "D" ] } } )

The operation uses a filter predicate of { status: { $in: [ "A", "D" ] } }, which corresponds to the
following SQL statement:

SELECT * FROM inventory WHERE status in ("A", "D")

Refer to the Query and Projection Operators document for the complete list of MongoDB query
operators.

Specify AND Conditions

A compound query can specify conditions for more than one field in the collection's documents.
Implicitly, a logical AN conjunction connects the clauses of a compound query so that the
query selects the documents in the collection that match all the conditions.

The following example retrieves all documents in the inventory collection where

the statu "A" qty


equals and is less than ($lt) 30:

db.inventory.find( { status: "A", qty: { $lt: 30 } } )


MongoDB Shell

The operation uses a filter predicate of { status: "A", qty: { $lt: 30 } }, which corresponds to the
following SQL statement:

SELECT * FROM inventory WHERE status = "A" AND qty < 30


Specify OR Conditions

Using
operator, you can specify a compound query that joins each clause with a
the
OR conjunction so that the query selects the documents in the collection that match at
logical
least one condition.

The following example retrieves all documents in the collection where

the statu "A" qty


equals or is less than ($lt) 30:

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )


MongoDB Shell

The operation uses a filter predicate of { $or: [ { status: 'A' }, { qty: { $lt: 30 } } ] }, which
corresponds to the following SQL statement:

SELECT * FROM inventory WHERE status = "A" OR qty < 30

RESULT:

Creation of database using Mongo DB, Dynamo DB, Voldemort Key-Value Distributed Data
store Hbase and Neo4j was successfully done
Ex no :11
Implementing access control in relational database

Aim:
Implementing access control in relational database

Procedure

A relational database stores data in relations which are expected to satisfy some simple
mathematical properties.

The columns of the table are called attributes and the rows are called tuples. There is no
signicance to the order of the columns or rows. Duplicate rows with identical values for all
columns are not allowed.

There is an important distinction between relation schemes and relation instances. The relation
scheme gives us the names of the attributes as well as the permissible values for each attribute.
The set of permissible values for an attribute is said to be the attribute's domain. The relation
instance gives us the tuples of the relation at a given instant.

EMPLOYEE relation EMPLOYEE(NAME, DEPT, RANK, OFFICE, SALARY,


SUPERVISOR)

Let the domain of the NAME, DEPT, RANK, OFFICE, and SUPERVISOR attributes be
character strings, and the domain of the SALARY attribute be integers.
A particular instance of the EMPLOYEE relation,

NAME DEPT RANK OFFICE SALARY SUPERVISOR Rao Electrical Engg Professor KH252
50,000 Jones Kaplan Computer Sci Researcher ST125 35,000 Brown Brown Computer Sci
Professor ST257 55,000 Black Jones Electrical Engg Chairman KH143 45,000 Black Black
Administration Dean ST101 60,000 NULL

The CREATE Statement Consider the EMPLOYEE relation discussed earlier. The relation
scheme is dened in SQL by the following command.

Consider the EMPLOYEE relation discussed earlier.

The relation scheme is denied in SQL by the following command.

CREATE TABLE EMPLOYEE ( NAME CHARACTER NOT NULL, DEPT


CHARACTER, RANK CHARACTER, OFFICE CHARACTER, SALARY INTEGER,
SUPERVISOR CHARACTER, PRIMARY KEY (NAME), FOREIGN KEY (DEPT)
REFERENCES DEPARTMENT, FOREIGN KEY (SUPERVISOR) REFERENCES
EMPLOYEE )

INSERT and DELETE Statements The EMPLOYEE table is initially empty. Tuples are inserted
into it by means of the SQL INSERT statement. For example, the last tuple of the relation
instance discussed above is inserted by the following statement.

INSERT INTO EMPLOYEE(NAME, DEPT, RANK, OFFICE, SALARY, SUPERVISOR)


VALUES VALUES(`Black, `Administration', `Dean', `ST101', 60000, NULL)

The remaining tuples can be similarly inserted. Insertion of the tuples for Brown and Jones must
respectively precede insertion of the tuples for Kaplan and Rao, so as to maintain referential
integrity. Alternately, these tuples can be inserted in any order with NULL managers which are
later updated to their actual values. There is a DELETE statement to delete tuples from a
relation.

The SELECT Statement Retrieval of data

. For example, the NAME, SALARY and SUPERVISOR data for employees in the Computer
Sci department is extracted as follows
SELECT NAME, SALARY, SUPERVISOR FROM EMPLOYEE WHERE DEPT =
`Computer Sci'

The WHERE clause in a SELECT statement is optional. SQL also allows the retrieved records to
be grouped together for statistical computations by means of built-in statistical functions. For
example, the following query gives the average salary for employees in each department.

SELECT DEPT, AVG(SALARY) FROM EMPLOYEE GROUP BY DEPT

The UPDATE Statement Finally the UPDATE statement allows one or more attributes
of existing tuples in a relation to be modified.
For example, the following statement gives all employees in the ComputerSci department a raise
of $1000.

UPDATE EMPLOYEE SET SALARY = SALARY + 1000 WHERE DEPT = `Computer

Sci' This statement selects those tuples in EMPLOYEE which have the value of Computer Sci
for the DEPT attribute.

It then increases the value of the SALARY attribute for all these tuples by $1000 each.

The GRANT Statement The owner of a relation can grant one or more access privileges to
another user. This can be done with or without the GRANT OPTION. If the owner grants, say,
SELECT with the GRANT OPTION the user receiving this grant can further grant SELECT to
other users.

The latter GRANT can be done in turn with or without the GRANT OPTION at the granting
user's discretion. The general format of a grant operation in SQL is as follows.

GRANT privileges [ON relation] TO users [WITH GRANT]

RESULT:
Implementing access control in relational database was successfully done

You might also like