0% found this document useful (0 votes)
31 views60 pages

CP4152 DP Lab Manual

The document outlines exercises for practicing Data Definition Language (DDL) and Data Manipulation Language (DML) in SQL, including commands for creating, altering, and deleting tables, as well as inserting, updating, and deleting records. It also covers various types of joins (equi join, left outer join, right outer join, and full outer join) and aggregate functions (COUNT, AVG, SUM, MIN, MAX). Additionally, it discusses set operations such as UNION and UNION ALL with examples of table creation and data manipulation.

Uploaded by

jefferjam716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views60 pages

CP4152 DP Lab Manual

The document outlines exercises for practicing Data Definition Language (DDL) and Data Manipulation Language (DML) in SQL, including commands for creating, altering, and deleting tables, as well as inserting, updating, and deleting records. It also covers various types of joins (equi join, left outer join, right outer join, and full outer join) and aggregate functions (COUNT, AVG, SUM, MIN, MAX). Additionally, it discusses set operations such as UNION and UNION ALL with examples of table creation and data manipulation.

Uploaded by

jefferjam716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

EX NO:1 Practicing Data Definition Language and Data

Manipulation Language
Date:

AIM:
To practice the database Data Definition Language and Data Manipulation
Language.
Data Definition Language
The data definition language is used to create an object, alter the structure
of an object and also drop already created object. The Data Definition
Languages used for table definition can be classified into following:
 Create table command
 Alter table command
 Drop table command
Data Manipulation Language
 Insert, Delete, Update
Creating of Tables on Student:
Table is a primary object of database, used to store data in form of rows
and columns. It is created using following command:
Create Table (column1 datatype(size), column2 datatype(size),column(n)
datatype(size));
Example(Create)
create table student(name varchar(50),rollNo int(10),branch varchar(5));

Desc command
Describe command is external command . The describe command is used
to view the structure of a table as follows.

MySQL [college]> desc students;


Inserting of Tables on Student:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);
Example:
MySQL [college]> insert into students values(1,'ashish','java');
Query OK, 1 row affected (0.177 sec)

MySQL [college]> Insert into students values(2,’rahul’,’C++’);


Query OK, 1 row affected (0.040 sec)
MySQL [college]> select * from students;

The SQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Example:
update students set roll_no=roll_no+10 where student_name='ashish';
MySQL [college]> update students set roll_no=roll_no+10 where

student_name='ashish';

Query OK, 1 row affected (0.148 sec)


Rows matched: 1 Changed: 1 Warnings: 0
MySQL [college]>
MySQL [college]> update students set roll_no=roll_no+10 where
student_name='ashish';
Query OK, 1 row affected (0.127 sec)
Rows matched: 1 Changed: 1 Warnings: 0
MySQL [college]> select * from students;
MySQL [college]> update students12 set student_name='aman' where
roll_no=2;
ERROR 1146 (42S02): Table 'college.students12' doesn't exist
MySQL [college]> update students 12 set student_name='aman' where
roll_no=2;
MySQL [college]> select * from students;

The SQL DELETE Statement:


DELETE:

The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;
Example:
delete from students where roll_no=11;
MySQL [college]> delete from students where roll_no=11;
Query OK, 0 rows affected (0.023 sec)
MySQL [college]> select * from students;

MySQL [college]> delete from students where roll_no=21;


Query OK, 1 row affected (0.118 sec)
MySQL [college]> select * from students;
MySQL [college]> delete from students where student_name= 'divya';
Query OK, 0 rows affected (0.001 sec)
MySQL [college]> select * from students;
MySQL [college]> delete from students where student_name= 'aman';
Query OK, 1 row affected (0.037 sec)
MySQL [college]> select * from students;

Enforce Primary Key:


MySQL [college]> CREATE TABLE t1 (
-> id INT PRIMARY KEY,
-> `desc` VARCHAR(30)
-> );
Query OK, 0 rows affected (0.243 sec)
MySQL [college]> select * from t1;

Result:

Thus the DDL and DML Language commands were practiced and
implemented.
EX NO:2a Practicing EquiJoin, Left Outer Join, Right Outer Join and
Full Outer Join
Date:
AIM:
To practice the Equi Join, Left Outer Join, Right Outer Join and Full Outer
Join commands .
Description:
Inner Join
Inner join, includes only those tuples that satisfy the matching criteria.
EQUI Join
When a theta join uses only equivalence condition, it becomes a equi join.
Natural Join(⋈)
Natural join can only be performed if there is a common attribute (column)
between the relations.
Outer Join
In an outer join, along with tuples that satisfy the matching criteria.
Left Outer Join( )
In the left outer join, operation allows keeping all tuple in the left relation.
Right Outer join( )
In the right outer join, operation allows keeping all tuple in the right relation.
Inner Join Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Example:
Create Table as t1,t2
MySQL [college]> CREATE TABLE t1 (
-> id INT PRIMARY KEY,
-> `desc` VARCHAR(30)
-> );
Query OK, 0 rows affected (0.243 sec)
MySQL [college]> select * from t1;
Empty set (0.001 sec)
MySQL [college]> create table t1(id int primary key,'desc' varchar(30));
MySQL [college]> desc t1;
MySQL [college]> CREATE TABLE t2 (
-> id INT PRIMARY KEY,
-> `desc` VARCHAR(30)
-> );
MySQL [college]> desc t2;

Insert the values to t1,t2:

MySQL [college]> INSERT INTO t1 VALUES


-> (1, 'ID 1 in t1'),
-> (2, 'ID 2 in t1'),
-> (3, 'ID 3 in t1');
Query OK, 3 rows affected (0.107 sec)
Records: 3 Duplicates: 0 Warnings: 0
MySQL [college]> desc t1;

MySQL [college]> select * from t1;

MySQL [college]> INSERT INTO t2 VALUES


-> (2, 'ID 2 in t2'),
-> (3, 'ID 3 in t2'),
-> (4, 'ID 4 in t2');
Query OK, 3 rows affected (0.125 sec)
Records: 3 Duplicates: 0 Warnings: 0
MySQL [college]> select * from t2;
INNER JOIN QUERY Example
SELECT * FROM t1 INNER JOIN t2;
Example:
MySQL [college]> SELECT *
-> FROM t1 INNER JOIN t2;
MySQL [college]> SELECT *
-> FROM t1 INNER JOIN t2;
MySQL [college]> SELECT *
-> FROM t1 INNER JOIN t2 ON t1.id = t2.id;
MySQL [college]> SELECT *
-> FROM t1 INNER JOIN t2 ON t1.id = t2.id;

Normal Join:
SELECT * FROM t1 JOIN t2 ON t1.id = t2.id;
Example:
MySQL [college]> SELECT *
-> FROM t1 JOIN t2 ON t1.id = t2.id;
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id;
MySQL [college]> SELECT *
-> FROM t1 LEFT JOIN t2 ON t1.id = t2.id;
MySQL [college]> SELECT *
-> FROM t1 LEFT JOIN t2 USING (id);

MySQL [college]> SELECT t1.id, t1.desc


-> FROM t1 LEFT JOIN t2 USING (id)
-> WHERE t2.id IS NULL;
RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT *FROM t1 RIGHT JOIN t2 ON t1.id = t2.id;
MySQL [college]> SELECT *
-> FROM t1 RIGHT JOIN t2 ON t1.id = t2.id;
MySQL [college]> SELECT *
-> FROM t1 RIGHT JOIN t2 USING (id);

Result:
Thus the Equi Join, Left Outer Join, Right Outer Join and Full Outer Join
commands were practiced and implemented.
EX NO:2b Practicing Aggregate Functions
Date:

AIM:
To practice the Aggregate Functions commands .
Aggregate Functions
COUNT()
AVG
SUM()
MIN()
MAX()
COUNT()
The COUNT() function returns the number of rows that matches a
specified criterion.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Table Creation(Product table)
MySQL [college]> CREATE TABLE IF NOT EXISTS products (
-> productID INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> productCode CHAR(3) NOT NULL DEFAULT '',
-> name VARCHAR(30) NOT NULL DEFAULT '',
-> quantity INT UNSIGNED NOT NULL DEFAULT 0,
-> price DECIMAL(7,2) NOT NULL DEFAULT 99999.99,
-> PRIMARY KEY (productID)
-> );
Query OK, 0 rows affected (0.132 sec)
MySQL [college]> SHOW TABLES;
MySQL [college]> DESCRIBE products;
MySQL [college]> SHOW CREATE TABLE products \G
*************************** 1. row ***************************
Table: products
Create Table: CREATE TABLE `products` (
`productID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`productCode` char(3) NOT NULL DEFAULT '',

`name` varchar(30) NOT NULL DEFAULT '',


`quantity` int(10) unsigned NOT NULL DEFAULT '0',
`price` decimal(7,2) NOT NULL DEFAULT '99999.99',
PRIMARY KEY (`productID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.009 sec)

MySQL [college]> INSERT INTO products VALUES (1001, 'PEN', 'Pen


Red', 5000, 1.23);
Query OK, 1 row affected (0.068 sec)
MySQL [college]> INSERT INTO products VALUES
-> (NULL, 'PEN', 'Pen Blue', 8000, 1.25),
-> (NULL, 'PEN', 'Pen Black', 2000, 1.25);
Query OK, 2 rows affected (0.102 sec)
Records: 2 Duplicates: 0 Warnings: 0
MySQL [college]> INSERT INTO products (productCode, name,
quantity, price) VALUES
-> ('PEC', 'Pencil 2B', 10000, 0.48),
-> ('PEC', 'Pencil 2H', 8000, 0.49);

MySQL [college]> INSERT INTO products (productCode, name) VALUES


('PEC', 'Pencil HB');
MySQL [college]> INSERT INTO products values (NULL, NULL, NULL,
NULL, NULL);
MySQL [college]> SELECT * FROM products;
COUNT(*)
SELECT COUNT(*) AS `Count` FROM products;
MySQL [college]> SELECT COUNT(*) AS `Count` FROM products;
MySQL [college]> SELECT productCode, COUNT(*) FROM products
GROUP BY productCode;
MySQL [college]> SELECT productCode, COUNT(*) AS count
-> FROM products
-> GROUP BY productCode
-> ORDER BY count DESC;

AVG()

The AVG() function returns the average value of a numeric column.

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM()

The SUM() function returns the total sum of a numeric column.

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
MIN()

The MIN() function returns the smallest value of the selected column.

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX()

The MAX() function returns the largest value of the selected column.

MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example:
SELECT MAX(price), MIN(price), AVG(price), STD(price),
SUM(quantity) FROM products;

MySQL [college]> SELECT MAX(price), MIN(price), AVG(price), STD(price), SUM(quantity)

-> FROM products;

MySQL [college]> SELECT productCode, MAX(price) AS `Highest Price`,


MIN(price) AS `Lowest Price`
-> FROM products
-> GROUP BY productCode;
2 rows in set (0.001 sec)
MySQL [college]> SELECT productCode, MAX(price), MIN(price),
-> CAST(AVG(price) AS DECIMAL(7,2)) AS `Average`,
-> CAST(STD(price) AS DECIMAL(7,2)) AS `Std Dev`,
-> SUM(quantity)
-> FROM products
-> GROUP BY productCode;

MySQL [college]> SELECT


-> productCode AS `Product Code`,
-> COUNT(*) AS `Count`,
-> CAST(AVG(price) AS DECIMAL(7,2)) AS `Average`
-> FROM products
-> GROUP BY productCode
-> HAVING Count >=3;

MySQL [college]> SELECT


-> productCode,
-> MAX(price),
-> MIN(price),
-> CAST(AVG(price) AS DECIMAL(7,2)) AS `Average`,
-> SUM(quantity)
-> FROM products
-> GROUP BY productCode
-> WITH ROLLUP;

Result:

Thus the Aggregate Functions commands were implemented.


EX NO:2c Practicing Set Operations
Date:
AIM:
To practice the Set Operations commands .

Set Operations
UNION
UNION ALL
GROUP BY
HAVING
The SQL UNION Operator

The UNION operator is used to combine the result-set of two or


more SELECT statements.

 Every SELECT statement within UNION must have the same


number of columns
 The columns must also have similar data types
 The columns in every SELECT statement must also be in the same
order

UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Table Creation:
MySQL [college]> CREATE TABLE EmployeeUK
-> (
-> EmployeeId INT PRIMARY KEY,
-> FirstName VARCHAR(50),
-> LastName VARCHAR(50),
-> Gender VARCHAR(10),
-> Department VARCHAR(20)
-> );
Query OK, 0 rows affected (0.460 sec)

MySQL [college]> INSERT INTO EmployeeUK VALUES(1, 'Pranaya',


'Rout', 'Male','IT');
Query OK, 1 row affected (0.095 sec)
MySQL [college]> INSERT INTO EmployeeUK VALUES(2, 'Priyanka',
'Dewangan', 'Female','IT');
Query OK, 1 row affected (0.130 sec)
MySQL [college]> INSERT INTO EmployeeUK VALUES(3, 'Preety',
'Tiwary', 'Female','HR');
Query OK, 1 row affected (0.142 sec)
MySQL [college]> INSERT INTO EmployeeUK VALUES(4, 'Subrat',
'Sahoo', 'Male','HR');
Query OK, 1 row affected (0.223 sec)
MySQL [college]> INSERT INTO EmployeeUK VALUES(5, 'Anurag',
'Mohanty', 'Male','IT');
Query OK, 1 row affected (0.374 sec)
MySQL [college]> INSERT INTO EmployeeUK VALUES(6, 'Rajesh',
'Pradhan', 'Male','HR');
Query OK, 1 row affected (0.154 sec)
MySQL [college]> INSERT INTO EmployeeUK VALUES(7, 'Hina',
'Sharma', 'Female','IT');
Query OK, 1 row affected (0.151 sec)
MySQL [college]> CREATE TABLE EmployeeUSA
-> (
-> EmployeeId INT PRIMARY KEY,
-> FirstName VARCHAR(50),
-> LastName VARCHAR(50),
-> Gender VARCHAR(10),
-> Department VARCHAR(20)
-> );
Query OK, 0 rows affected (0.170 sec)
MySQL [college]>
MySQL [college]> INSERT INTO EmployeeUSA VALUES(1, 'James',
'Pattrick', 'Male','IT');
Query OK, 1 row affected (0.096 sec)
MySQL [college]> INSERT INTO EmployeeUSA VALUES(2,
'Priyanka', 'Dewangan', 'Female','IT');
Query OK, 1 row affected (0.160 sec)
MySQL [college]> INSERT INTO EmployeeUSA VALUES(3, 'Sara',
'Taylor', 'Female','HR');
Query OK, 1 row affected (0.170 sec)
MySQL [college]> INSERT INTO EmployeeUSA VALUES(4, 'Subrat',
'Sahoo', 'Male','HR');
Query OK, 1 row affected (0.153 sec)
MySQL [college]> INSERT INTO EmployeeUSA VALUES(5,
'Sushanta', 'Jena', 'Male','HR');
Query OK, 1 row affected (0.297 sec)
MySQL [college]> INSERT INTO EmployeeUSA VALUES(6, 'Mahesh',
'Sindhey', 'Female','HR');
Query OK, 1 row affected (0.054 sec)
MySQL [college]> INSERT INTO EmployeeUSA VALUES(7, 'Hina',
'Sharma', 'Female','IT');
Query OK, 1 row affected (0.083 sec)
MySQL [college]> desc EmployeeUK;

MySQL [college]> desc EmployeeUSA;

UNION()
SELECT FirstName, LastName, Gender, Department FROM
EmployeeUK
-> UNION
-> SELECT FirstName, LastName, Gender, Department FROM
EmployeeUSA;
MySQL [college]> SELECT FirstName, LastName, Gender,
Department FROM EmployeeUK
-> UNION
-> SELECT FirstName, LastName, Gender, Department FROM
EmployeeUSA;
UNION ALL()
SELECT FirstName, LastName, Gender, Department FROM
EmployeeUK
-> UNION ALL
-> SELECT FirstName, LastName, Gender, Department FROM
EmployeeUSA;
MySQL [college]> SELECT FirstName, LastName, Gender, Department
FROM EmployeeUK
-> UNION ALL
-> SELECT FirstName, LastName, Gender, Department FROM
EmployeeUSA;

MySQL [college]> SELECT FirstName, LastName, Gender,


Department FROM EmployeeUK
-> UNION
-> SELECT FirstName, LastName, Gender, Department FROM
EmployeeUSA
-> ORDER BY FirstName;
MySQL [college]> SELECT * FROM EmployeeUK
-> WHERE FirstName NOT IN (SELECT FirstName FROM
EmployeeUSA);

Result:
Thus the Set Operations commands were practiced and implemented.
EX NO:2d Practicing Transaction Control Language
Date:
AIM:
To practice the Transaction Control Language commands .

Transaction Control Language

 Commit,
 Rollback and
 Save Points

Commit()
Rollback()

Result:
Thus the Transaction Control Language commands were practiced and
implemented.
EX NO:3 Distributed Database Design and Implementation
Date:
AIM:
To design and implenet a Distributed Database Design and Implementation .

Steps of Distributed Database Design


There are in general several design alternatives.
Top-down approach:
First the general concepts, the global framework are defined, after then the
details. Down-top approach: first the detail modules are defined, after then
the global framework.
If the system is built up from a scratch, the top-down method is more
accepted. If the system should match to existing systems or some modules
are yet ready, the down-top method is usually used.
General design steps according to the structure:
- analysis of the external, application requirements
- design of the global schema
- design of the fragmentation
- design of the distribution schema
- design of the local schemes
- design of the local physical layers
DDBMS -specific design steps:
- design of the fragmentation
- design of the distribution schema During the requirement analysis
phase, also the fragmentation and
distribution requirements are considered.

Down-Top Design
Usually existing and heterogeneous databases are integrated into a common
distributed system.
Steps of integration:
- Common data model selection
As the different component databases may have different data models and
the DDBMS should based on a single, common data model, the first step is
to convert the different models into a common model. The common model
is usually an intermediate model, different from the data model of the
components
- Translation of each local schema into the common model
The different schema element descriptions should be converted into this
common model.
- Integration of the local schema into a common global schema
Beside the collection of the component descriptions, the integration should
deal with the matching of the different semantic elements and with the
resolving of the different types of inconsistency.
- Design the translation between the global and local schemes
To access all of the components on a homogeneous way, a conversion
procedure should be applied.
Goals of the Fragmentation and Distribution Design
Local processing
It is desirable to perform as much tasks as possible at the local level, i.e.
without any access to the other sites. The local processing provides an easier
management and a more efficient execution.
Although a complete locality is an aim from the performance point of view,
it can not be realized due to the distribution requirements of the system.
Availability and reliability of the DDB
It is desirable to distribute the data over different sites to provide higher
availability. Thus, in the case of site failures a site can replace the other, no
service or functionality will be lost. The replication, distribution is a useful
method to perform a recovery if the data on some site would be destroyed.
Distribution of processing load
It is desirable to distribute the processing power over the different sites to
provide a higher throughput. The different processing steps of a complex
task will be distributed among several sites enabling a parallel processing
too.
Storage cost reduction
It may be cost effective if not every site is equipped with the same high
performance and costly elements. It is enough to install only some of such
specialized sites, the others can use it in a shared way. We should find the
trade-off of these requirements
Horizontal Fragmentation
The relation is partitioned horizontally into fragments..
Primary fragmentation: the assignment of the tuple depends on the
attribute values of the tuple
Derived fragmentation: the assignment of the tuple depends not on the
attributes of this tuple, but on the attributes of another tuple(s).
Horizontal Fragmentation Example 1
The sample table to be fragmented:
Employee(Name, Department, Skill, Salary)
The applications requiring access to the Employee table:
Application 1: it will access the employees in the department with
Department id = 1.
Application 2: it will access the programmers independently from their
departments
The relevant simple predicates - for application 1: Department = 1 - for
application 2: Skill = ‘Programmer’
Predication set:
P = { Department = 1, Skill = ‘Programmer’}
The minterm predicates:
Department = 1 AND Skill = ‘Programmer’
Department = 1 AND Skill <> ‘Programmer’
Department <> 1 AND Skill = ‘Programmer’
Department <> 1 AND Skill <> ‘Programmer’
A not relevant predicate:
Salary > 250000
Vertical Fragmentation
The assignment of the data elements in a table is based on the attribute
identifier of the data. In this case the different projections are the content of
the fragments.
Fragmentation rule:
Every attribute must belong to at least one fragment, and every fragment
must have a tuple identifier.
Vertical partitioning: every attribute is contained in only one fragment.
Vertical clustering: an attribute may be contained in more than one
fragments.
Vertical fragmentation There are two main heuristics methods to perform
the vertical fragmentation:
- split approach : a global relation schema is recursive split into disjoint
segments
- grouping approach : the single attributes are progressively grouped into
larger segments The main steps in the design of the vertical fragmentation
- analyze the applications (A1,A2,A3,A4)
- analyze the queries (Q1,Q2,Q3,Q4)
- determine the reference-matrix (1: Qi references Aj , 0: not)

Result:
Thus a Distributed Database was designed and Implemented.
EX NO:4 Practicing Triggers

Date:
AIM:
To practice the Triggers commands .

Triggers
MySQL Triggers
We assume that you are habituated with "MySQL Stored Procedures", if not
you can read our MySQL Procedures tutorial. You can use the following
statements of MySQL procedure in triggers:

 Compound statements (BEGIN / END)


 Variable declaration (DECLARE) and assignment (SET)
 Flow-of-control statements
(IF, CASE, WHILE, LOOP, WHILE, REPEAT, LEAVE, ITERATE)
 Condition declarations
 Handler declarations
 Syntax:
 CREATE
 [DEFINER = { user | CURRENT_USER }]
 TRIGGER trigger_name
 trigger_time trigger_event
 ON tbl_name FOR EACH ROW
 trigger_body
 trigger_time: { BEFORE | AFTER }
 trigger_event: { INSERT | UPDATE | DELETE }

Example:
MySQL [college]> CREATE TABLE account (acct_num INT, amount
DECIMAL(10,2));
Query OK, 0 rows affected (0.184 sec)
CREATE TRIGGER ins_sum BEFORE INSERT ON account
-> FOR EACH ROW SET @sum = @sum + NEW.amount;
Sample Examples:
MySQL [college]> CREATE TRIGGER ins_sum BEFORE INSERT ON
account
-> FOR EACH ROW SET @sum = @sum + NEW.amount;
Query OK, 0 rows affected (0.373 sec)
MySQL [college]> desc account;
MySQL [college]> select * from account;
Empty set (0.001 sec)
MySQL [college]> SET @sum = 0;
Query OK, 0 rows affected (0.000 sec)
MySQL [college]> INSERT INTO account
VALUES(137,14.98),(141,1937.50),(97,-100.00);
Query OK, 3 rows affected (0.185 sec)
Records: 3 Duplicates: 0 Warnings: 0
MySQL [college]> SELECT @sum AS 'Total amount inserted';
MySQL [college]> DROP TRIGGER test.ins_sum;

MySQL [college]> CREATE TRIGGER ins_transaction BEFORE INSERT ON


account
-> FOR EACH ROW PRECEDES ins_sum
-> SET
-> @deposits = @deposits + IF(NEW.amount>0,NEW.amount,0),
-> @withdrawals = @withdrawals + IF(NEW.amount<0,-
NEW.amount,0);
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to
use near 'ins_sum
SET
@deposits = @deposits + IF(NEW.amount>0,NEW.amount,0),' at line 2
MySQL [college]> CREATE TRIGGER ins_sum BEFORE INSERT ON
account
-> FOR EACH ROW SET @sum = @sum + NEW.amount;
ERROR 1235 (42000): This version of MySQL doesn't yet support 'multiple
triggers with the same action time and event for one table'
MySQL [college]> delimiter //
MySQL [college]> CREATE TRIGGER upd_check BEFORE UPDATE ON
account
-> FOR EACH ROW
-> BEGIN
-> IF NEW.amount < 0 THEN
-> SET NEW.amount = 0;
-> ELSEIF NEW.amount > 100 THEN
-> SET NEW.amount = 100;
-> END IF;
-> END;//
Query OK, 0 rows affected (0.301 sec)

MySQL [college]> delimiter ;


MySQL [college]>

Result:
Thus the Triggers commands were practiced and implemented.
EX NO:5 Accessing a Relational Database using PHP
Date:

AIM:
To Access a Relational Database using PHP.

Steps:
The steps required to access data from a table in a database provided by
MYSQL can be summarized as follows:

 Establish or open a connection to the MYSQL server.


 Select a database.
 Execute the query against the database.
 Process the result returned by the server.
 Close the connection

Craete Table in Phpmyadmin :


Step1: Create table as Player

INSERT INTO `players` (`id`, `surname`, `firstname`, `nickname`, `avatar`)


VALUES (NULL, 'pate', 'Andrew', 'arp', NULL), (NULL, 'anim', 'rose', '',
NULL);
INSERT INTO `Games` (`id`, `surname`, `firstname`, `nickname`, `avatar`)
VALUES (NULL, 'pate', 'Andrew', 'arp', NULL), (NULL, 'anim', 'rose', '',
NULL);
Step 3: Make a relation to the database and table using Phpmyadmin(Please
write the steps in ur word)
PHP Code:
&lt;?php
$servername&nbsp;=&nbsp;"localhost";
$database =&nbsp;"database";
$username&nbsp;=&nbsp;"username";
$password&nbsp;=&nbsp;"password";
$charset&nbsp;=&nbsp;"utf8mb4";
try {
$dsn&nbsp;=&nbsp;"mysql:host=$servername;dbname=$database;charset=$ch
arset";
$pdo&nbsp;=&nbsp;new&nbsp;PDO($dsn,&nbsp;$username,&nbsp;$passwor
d);
$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo “Connection Okay”;
return $pdo
}
catch&nbsp;(PDOException&nbsp;$e)
{
echo “Connection failed: ”. $e-&gt;getMessage();
}
?&gt;

Result:
Thus a Relational Database using PHP was accessed and implemented.
EX NO:6 Creating XML Documents, Document Type Definition and
XML Schema
Date:
AIM:
To Create XML Documents, Document Type Definition and XML Schema.
XML DTD

An XML document with correct syntax is called "Well Formed".

An XML document validated against a DTD is both "Well Formed" and


"Valid".

What is a DTD?

DTD stands for Document Type Definition.

A DTD defines the structure and the legal elements and attributes of an
XML document.

Valid XML Documents

A "Valid" XML document is "Well Formed", as well as it conforms to the rules


of a DTD:

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


<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML DTD

The purpose of a DTD is to define the structure and the legal elements and
attributes of an XML document:

Note.dtd:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

The DTD above is interpreted like this:

 !DOCTYPE note - Defines that the root element of the document is note
 !ELEMENT note - Defines that the note element must contain the
elements: "to, from, heading, body"
 !ELEMENT to - Defines the to element to be of type "#PCDATA"
 !ELEMENT from - Defines the from element to be of type "#PCDATA"
 !ELEMENT heading - Defines the heading element to be of type
"#PCDATA"
 !ELEMENT body - Defines the body element to be of type "#PCDATA"

Tip: #PCDATA means parseable character data.


Using DTD for Entity Declaration

A DOCTYPE declaration can also be used to define special characters or


strings, used in the document:

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

<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>
OUTPUT:

XML Schema

An XML Schema describes the structure of an XML document, just like a DTD.

An XML document with correct syntax is called "Well Formed".

An XML document validated against an XML Schema is both "Well Formed"


and "Valid".

XML Schema

XML Schema is an XML-based alternative to DTD:

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>

</xs:element>
The Schema above is interpreted like this:

 <xs:element name="note"> defines the element called "note"


 <xs:complexType> the "note" element is a complex type
 <xs:sequence> the complex type is a sequence of elements
 <xs:element name="to" type="xs:string"> the element "to" is of type
string (text)
 <xs:element name="from" type="xs:string"> the element "from" is of
type string
 <xs:element name="heading" type="xs:string"> the element "heading" is
of type string
 <xs:element name="body" type="xs:string"> the element "body" is of
type string

Result:
Thus the Documents, Document Type Definition and XML Schema was created
and implemented.
EX NO:7 Using a Relational Database to store the XML documents as text
Date:
AIM:
To Use a Relational Database to store the XML documents as text
XML document
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 Document Example

A simple document is shown in the following example −


<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
The following image depicts the parts of XML document.
Result:

Thus a Relational Database to store the XML documents as text was used
and implemented.
EX NO: 8 Using a Relational Database to store the XML documents as
data elements
Date:
AIM:
To Use a Relational Database to store the XML documents as data
elements.
XML Elements

An XML document contains XML Elements.

What is an XML Element?

An XML element is everything from (including) the element's start tag to


(including) the element's end tag.

<price>29.99</price>

An element can contain:

 text
 attributes
 other elements
 or a mix of the above

<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

In the example above:

<title>, <author>, <year>, and <price> have text content because they contain
text (like 29.99).
<bookstore> and <book> have element contents, because they contain
elements.

<book> has an attribute (category="children").

Empty XML Elements

An element with no content is said to be empty.

In XML, you can indicate an empty element like this:

<element></element>

You can also use a so called self-closing tag:

<element />

Result:

Thus a Relational Database to store the XML documents as data elements


was used and implemented.
EX NO:9a Extracting XML Documents from Relational
Databases Date:

AIM:
To Extract XML Documents from Relational Databases.
Extracting XML Documents from Relational Databases
1. Creating Hierarchical XML Views over Flat or Graph-Based Data
XML uses a hierarchical (tree) model to represent documents. The database
systems with the most widespread use follow the flat relational data model.
When we add referential integrity constraints, a relational schema can be
considered to be a graph structure (for example, see Figure 3.7). Similarly, the
ER model represents data using graph-like structures (for example, see Figure
7.2). We saw in Chapter 9 that there are straightforward mappings between the
ER and relational models, so we can conceptually represent a relational
database schema using the corresponding ER schema. Although we will use the
ER model in our discussion and examples to clarify the conceptual differences
between tree and graph models, the same issues apply to converting relational
data to XML.
We will use the simplified UNIVERSITY ER schema shown in Figure 12.8 to
illustrate our discussion. Suppose that an application needs to extract XML
documents for student, course, and grade information from
the UNIVERSITY database. The data needed for these documents is contained
in the database attributes of the entity

XML SCHEMA CODE AS


XML schema document with course as the root.

<xsd:element name=“root”>

<xsd:sequence>

<xsd:element name=“course” minOccurs=“0” maxOccurs=“unbounded”>

<xsd:sequence>

<xsd:element name=“cname” type=“xsd:string” />


<xsd:element name=“cnumber” type=“xsd:unsignedInt” />

<xsd:element name=“section” minOccurs=“0” maxOccurs=“unbounded”>

<xsd:sequence>

<xsd:element name=“secnumber” type=“xsd:unsignedInt” />

<xsd:element name=“year” type=“xsd:string” />


<xsd:element name=“quarter” type=“xsd:string” />
<xsd:element name=“student” minOccurs=“0”
maxOccurs=“unbounded”><xsd:sequence>
<xsd:element name=“ssn” type=“xsd:string” /><xsd:element name=“sname”
type=“xsd:string” /><xsd:element name=“class” type=“xsd:string”
/><xsd:element name=“grade” type=“xsd:string” />

</xsd:sequence>

</xsd:element>

</xsd:sequence>

</xsd:element>

</xsd:sequence>

</xsd:element>

</xsd:sequence>

</xsd:element>
OUTPUT:

Result:
Thus the XML Documents from Relational Databases was extracted and
implemented.
EX NO:9b XML Querying

Date:
AIM:
To USE XML Querying.
XQuery?

XQuery is to XML what SQL is to databases.

XQuery is designed to query XML data.

XQuery Example
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

What is XQuery?

 XQuery is the language for querying XML data


 XQuery for XML is like SQL for databases
 XQuery is built on XPath expressions
 XQuery is supported by all major databases
 XQuery is a W3C Recommendation

XQuery and XPath

XQuery 1.0 and XPath 2.0 share the same data model and support the same
functions and operators. If you have already studied XPath you will have no
problems with understanding XQuery.

XQuery - Examples of Use

XQuery can be used to:

 Extract information to use in a Web Service


 Generate summary reports
 Transform XML data to XHTML
 Search Web documents for relevant information

XQuery First Example

Here, the XML document is named as courses.xml and xqy file is named
as courses.xqy

courses.xml

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


2. <courses>
3. <course category="JAVA">
4. <title lang="en">Learn Java in 3 Months.</title>
5. <trainer>Sonoo Jaiswal</trainer>
6. <year>2008</year>
7. <fees>10000.00</fees>
8. </course>
9. <course category="Dot Net">
10. <title lang="en">Learn Dot Net in 3 Months.</title>
11. <trainer>Vicky Kaushal</trainer>
12. <year>2008</year>
13. <fees>10000.00</fees>
14. </course>
15. <course category="C">
16. <title lang="en">Learn C in 2 Months.</title>
17. <trainer>Ramesh Kumar</trainer>
18. <year>2014</year>
19. <fees>3000.00</fees>
20. </course>
21. <course category="XML">
22. <title lang="en">Learn XML in 2 Months.</title>
23. <trainer>Ajeet Kumar</trainer>
24. <year>2015</year>
25. <fees>4000.00</fees>
26. </course>
27.</courses>

courses.xqy
1. for $x in doc("courses.xml")/courses/course
2. where $x/fees>5000
3. return $x/title

This example will display the title elements of the courses whose fees are
greater than 5000.

XQueryTester.java

1. import java.io.File;
2. import java.io.FileInputStream;
3. import java.io.FileNotFoundException;
4. import java.io.InputStream;
5.
6. import javax.xml.xquery.XQConnection;
7. import javax.xml.xquery.XQDataSource;
8. import javax.xml.xquery.XQException;
9. import javax.xml.xquery.XQPreparedExpression;
10.import javax.xml.xquery.XQResultSequence;
11.
12.import com.saxonica.xqj.SaxonXQDataSource;
13.
14. public class XQueryTester {
15. public static void main(String[] args){
16. try {
17. execute();
18. }
19.
20. catch (FileNotFoundException e) {
21. e.printStackTrace();
22. }
23.
24. catch (XQException e) {
25. e.printStackTrace();
26. }
27. }
28.
29. private static void execute() throws FileNotFoundException, XQException{
30. InputStream inputStream = new FileInputStream(new File("courses.xqy"));
31. XQDataSource ds = new SaxonXQDataSource();
32. XQConnection conn = ds.getConnection();
33. XQPreparedExpression exp = conn.prepareExpression(inputStream);
34. XQResultSequence result = exp.executeQuery();
35. while (result.next()) {
36. System.out.println(result.getItemAsString(null));
37. }
38. }
39.}

Execute XQuery against XML

Put the above three files to a same location. We put them on desktop in a
folder name XQuery2. Compile XQueryTester.java using console. You
must have JDK 1.5 or later installed on your computer and classpaths are
configured.

Compile:

javac XQueryTester.java

Execute:

java XQueryTester

Output:

Result:
Thus the XML Querying were used and implemented.

EX NO:10 Creating Databases using MongoDB, DynamoDB,


Voldemort Key-Value Distributed Data Store Hbase and Neo4j.
Date:
AIM:
To Creating Databases using MongoDB, DynamoDB, Voldemort Key
Value Distributed Data Store Hbase and Neo4j

The use Command

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
If 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
local0.78125GB
mydb 0.23012GB
test 0.23012GB
In MongoDB default database is test. If you didn't create any database, then
collections will be stored in test database.

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)

Result:
Thus Databases using MongoDB, DynamoDB, Voldemort Key Value
Distributed Data Store Hbase and Neo4j were created and implemented.

You might also like