CP4152 DP Lab Manual
CP4152 DP Lab Manual
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.
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';
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;
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;
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);
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 '',
AVG()
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM()
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;
Result:
Set Operations
UNION
UNION ALL
GROUP BY
HAVING
The SQL UNION Operator
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)
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;
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 .
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 .
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:
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;
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:
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
What is a DTD?
A DTD defines the structure and the legal elements and attributes of an
XML document.
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)>
]>
!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"
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!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; ©right;</footer>
</note>
OUTPUT:
XML Schema
An XML Schema describes the structure of an XML document, just like a DTD.
XML Schema
<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:
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.
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
<price>29.99</price>
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>
<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.
<element></element>
<element />
Result:
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
<xsd:element name=“root”>
<xsd:sequence>
<xsd:sequence>
<xsd:sequence>
</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 Example
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
What is XQuery?
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.
Here, the XML document is named as courses.xml and xqy file is named
as courses.xqy
courses.xml
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.}
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.
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.
Result:
Thus Databases using MongoDB, DynamoDB, Voldemort Key Value
Distributed Data Store Hbase and Neo4j were created and implemented.