Database Lab Manuallllllllllllllllllll
Database Lab Manuallllllllllllllllllll
AIM:
To create a data base and write SQL queries to retrieve information from the
database.
DESCRIPTION:
DataDefinitionLanguage
DDL (Data Definition Language) statements are used to create,change the
objectsofadatabase.TypicallyadatabaseadministratorisresponsibleforusingDDLstatement
s or pro-duction databasesin a large database system. The commands usedare:
• Create-Itisused tocreateatable.
• Alter-Thiscommandisusedtoaddanewcolumn,modifytheexistingcolumndefi-
nitionandtoincludeordropintegrityconstraint.
• Drop-It willdeletethetablestructureprovidedthetableshouldbeempty.
• Truncate-Ifthereisnofurtheruseofrecordsstoredinatableand
thestructurehastoberetained,andthenthe recordsalonecanbe deleted.
• Desc-Thisisusedtoviewthestructureofthe table.
PROCEDURE:
Step1: Createtablebyusingcreatetable command withcolumn name,datatypeand
size.Step2:Displaythe tablebyusingdesccommand.
Step3: Add anynewcolumnwiththeexisting tablebyalter
tablecommand.Step4:Modifytheexistingtablewithmodifycommand.
Step5: Deletetherecordsinfilesbytruncate
command.Step6:Deletethe Entiretable bydropcommand
1. Create
Syntax:
Createtabletablename(column_name1datatype(size),c
olumn_name2datatype(size),column_name3datatype(
size),………);
Example:
SQL>CreatetableStudent(Stud_namechar(20),Stud_idvarchar2(10),Stud_deptvar
char2(20),Stud_agenumber(5));
Tablecreated.
SQL>desc Student;
Name Null?Type
STUD_NAME CHAR(20)VAR
STUD_IDSTU CHAR2(10)VAR
D_DEPTSTU CHAR2(20)NU
D_AGE MBER(5)
2. Altertable
Syntax:
Alter table tablename add(column_name
datatype(size));Altertabletablenamemodify(column_nameda
tatype(size));Altertable tablename drop(column_name);
Example:
SQL>desc Student;
Name Null?Type
STUD_NAME CHAR(20)
STUD_ID VARCHAR2(10)
STUD_DEPT VARCHAR2(20)
STUD_AGE NUMBER(5)
STUD_ADDR VARCHAR2(20)
SQL>AltertableStudentmodify(Stud_agenumber(10));Ta
ble altered.
SQL>desc Student;
STUD_NAME CHAR(20)
STUD_ID VARCHAR2(10)
STUD_DEPT VARCHAR2(20)
STUD_AGE NUMBER(10)
STUD_ADDR VARCHAR2(20)
SQL>AltertableStudentdrop(Stud_agenumber(10));Ta
ble altered.
SQL>desc Student;
STUD_NAME CHAR(20)VAR
STUD_IDSTU CHAR2(10)VAR
D_DEPTSTUD CHAR2(20)VAR
_ADDR CHAR2(20)
3. TruncateTable
Syntax:
Truncatetabletablename;
Example:
SQL>Truncatetable Student;
Tabletruncated.
SQL>descStudent
Name Null?Type
STUD_NAME CHAR(20)
STUD_ID VARCHAR2(10)
STUD_DEPT VARCHAR2(20)
STUD_AGE NUMBER(10)
STUD_ADDR VARCHAR2(20)
4. DropTable
Syntax:
Droptabletablename;
Example:
SQL>desc Student;
ERROR:ORA-04043:objectStudentdoesnotexist
Result:
AIM:
To Study and Practice Insertion, Deletion, Modifying, Altering, Updating and
Viewing records based on conditions in RDBMS.
DESCRIPTION:
Data Manipulation Language
DMLcommandsarethemostfrequentlyusedSQLcommandsandisusedtoqueryandma
nipulatethe existing database objects. Some of the commands are
1. Insert
2. Select
3. Update
4. Delete
PROCEDURE:
Step1:Createtable byusingcreatetable
command.Step2:Insertvaluesintothetable
Step3:Deleteanyrecords
fromthetableStep4:Updateanyvaluesinth
etable.
Step5: Displaythevaluesfromthetablebyusing selectcommand.
SQL>CreatetableStudent(Stud_namechar(20),Stud_idvarchar2(10),Stud_dept
varchar2(20),Stud_agenumber(5));
Tablecreated.
SQL>desc Student;
Name Null? Type
STUD_NAME CHAR(20)VAR
STUD_IDSTU CHAR2(10)VAR
D_DEPTSTU CHAR2(20)NU
D_AGE MBER(5)
1. Insert:This is used to add one or more rows to a table. The values are separated
bycom-mas and the data types char and date are enclosed in apostrophes. The values
mustbrenteredinthesame orderastheyaredefined.
Syntax:
Insertintotablenamevalues(‘&column_name1’,‘&column_name1’,‘&column_name
1’,…..);
Example:
SQL>InsertintoStudent1values(‘&stud_name’,‘&stud_id’,‘&stud_dept’,‘&stud_ag
e’);
Enter value for stud_name:
RamEntervalueforstud_id:101Ent
er value for stud_dept:
MECHEntervalueforstud_age:14
old 1: Insert into Student1 values(‘&stud_name’, ‘&stud_id’,
‘&stud_dept’,‘&stud_age’)
new1:InsertintoStudent1values(‘Ram’,‘101’,‘MECH’, ‘14’)
1rowcreated.
SQL>InsertintoStudent1values(‘&stud_name’,‘&stud_id’,‘&stud_dept’,‘&stud_ag
e’);
Entervalueforstud_name:VickyE
ntervalueforstud_id:102Enter
valueforstud_dept:EEEEntervalu
eforstud_age:15
old1:InsertintoStudent1values(‘&stud_name’,‘&stud_id’,‘&stud_dept’,‘&stud_age
’)
new1:InsertintoStudent1values(‘Vicky’, ‘102’,‘EEE’, ‘15’)
1rowcreated.
SQL>InsertintoStudent1values(‘&stud_name’,‘&stud_id’,‘&stud_dept’,‘&stud_ag
e’);
Enter value for
stud_name:SarathEntervalueforst
ud_id:103Enter
valueforstud_dept:CSEEntervalu
eforstud_age:15
old 1: Insert into Student1 values(‘&stud_name’, ‘&stud_id’,
‘&stud_dept’,‘&stud_age’)
new1:InsertintoStudent1values(‘Sarath’,‘102’,‘CSE’,‘15’)
1rowcreated.
SQL>InsertintoStudent1values(‘&stud_name’,‘&stud_id’,‘&stud_dept’,‘&stud_ag
e’);
Entervalue
forstud_name:DeviEnter
valueforstud_id: 104Enter value
for stud_dept:
EEEEntervalueforstud_age:14
old1:InsertintoStudent1values(‘&stud_name’,‘&stud_id’,‘&stud_dept’,‘&stud_age
’)
new1:InsertintoStudent1values(‘Devi’, ‘104’,‘EEE’,‘14’)
1rowcreated.
3. UpdateCommand:Itisusedtoalterthecolumnvalues inatable.Asinglecolumnmaybe
updatedormorethanonecolumncouldbeupdated.
Syntax:
Updatetablenamesetcolumn_name=’value’wherecondition;
Example:
SQL>UpdateStudent1setstud_id=’109’wherestud_name=’Sarath’;1row
updated.
SQL>select*fromStudent1;
SQL>DeletefromStudent1wherestud_dept=’CSE’;1row
deleted.
SQL>select*fromStudent1;
Result:
AIM:
To Study and Practice save, commit, commit and rollback Viewing records based
on conditions in RDBMS.
SAVEPOINT:
Syntaxforsavepoint:
SQL>SAVEPOINT<SAVEPOINTNAME>;
SQL>SAVEPOINTS1;
Savepoint created.
SQL>SELECT*FROMEMP;
SQL>INSERTINTOEMPVALUES(105,'PARTHASAR','STUD
ENT',100);1rowcreated.SQL>SELECT*FROMEMP;
EMPNOENAME DESIGNATIN SALARY
Syntaxforsavepoint:
SQL>ROLLBACK<SAVEPOINTNAME>;
SQL>ROLLBACKS1;
Rollbackcomplete.
SQL>SELECT*FROMEMP;
EMPNOENAME DESIGNATIN SALARY
COMMIT
Syntaxforcommit:
SQL>COMMIT;SQL>C
OMMIT;
Commit complete.
Result:
Thus, the given query is executed successfully.
Ex.No:4 TRIGGERS
AIM:
To execute automatically the triggers in RDBMS.
DESCRIPTION:
Database Triggers
Atriggerisastatementthatisexecutedautomaticallybythesystemasasideeffectofamodifi
cationtothedatabase.Thepartsofatriggerare,
• Triggerstatement:SpecifiestheDMLstatementsandfiresthetriggerbody.Italsosp
ecifiesthe tabletowhichthetriggeris associated.
• Triggerbody ortriggeraction: ItisaPL/SQLblockthat isexecuted whenthetrig-
geringstatementis used.
• Triggerrestriction:Restrictionsonthetrigger canbe achieved
Thedifferent usesoftriggersareasfollows,
• Togeneratedataautomatically
• Toenforcecomplexintegrityconstraints
• Tocustomizecomplexsecuringauthorizations
• Tomaintainthereplicatetable
• Toauditdatamodifications
TYPESOFTRIGGERS
Thevarioustypesoftriggersareasfollows,Before: It fires the trigger
before executing the trigger statement.After:It firesthetrigger after
executingthetriggerstatement.
Foreach row:Itspecifiesthatthetriggerfiresonceperrow.
Foreachstatement:This
isthedefaulttriggerthatisinvoked.Itspecifiesthatthetriggerfires onceperstatement.
VARIABLESUSEDINTRIGGERS
• :new
• :old
Thesetwovariablesretainthenewandoldvaluesofthecolumnupdatedinthedatabase.
Thevaluesinthesevariablescanbeusedinthedatabasetriggersfor datamanipulation.
Syntax:
Createorreplacetrigger<Trigger_name>before/afterinsert/delete/updateon
<Table_name>foreachrow/statement
DELCARE
<Declarationstatements>
BEGIN
<ExecutableStatements>
END:
SQL>createtableemply101(eid
varchar(20),enamechar(25),agenumber(10),salarynumber(10));
Tablecreated.
SQL>descemply101;
Name Null?Type
EID VARCHAR2(20)
ENAME CHAR(25)
AGE NUMBER(10)
SALARY NUMBER(10)
SQL>insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’);Enter
valueforeid:e1
Entervalue forename:anu
Entervalueforage:25
Entervalueforsalary:20000
old1:insert intoemply101values(‘&eid’,’&ename’,’&age’,’&salary’)
new1:insertintoemply101values(‘e1’,’anu’,’25’,’20000’)1ro
wcreated.
SQL>/
Enter valuefor eid:
e2Entervalue
forename:abiEntervaluefo
rage: 24
Entervalueforsalary:25700
old1:insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’)new
1:insertintoemply101 values(‘e2’,’abi’,’24’,’25700’)
1rowcreated.
SQL>/
Entervalueforeid:e3Enterval
ueforename:babuEntervalue
forage:30
Entervalueforsalary:34000
old1:insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’)new
1:insertintoemply101 values(‘e3’,’babu’,’30’,’34000’)
1rowcreated.
SQL>/
Enter valuefor eid:
e4Entervalueforename:cibi
Entervalueforage:32
Entervalueforsalary:32000
old1:insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’)new
1:insertintoemply101values(‘e4’,’cibi’,’32’,’32000’)
1rowcreated.
SQL>/
Entervalueforeid:e5
Entervalueforename:brindhaE
ntervalueforage:28
Entervalueforsalary:31000
old1:insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’)new
1:insertintoemply101values(‘e5’,’brindha’,’28’,’31000’)
1rowcreated.
SQL>select*fromemply101;
e1 anu 25 20000
e2 abi 24 25700
e3 babu 30 34000
e4 cibi 32 32000
e5 brindha 23 31000
SQL>createtableemply102(eidvarchar(20),enamechar(25),agenu
mber(10),salarynumber(10));
Tablecreated.
SQL>descemply102;
Name Null?Type
EID VARCHAR2(20)
ENAME CHAR(25)
AGE NUMBER(10)
SALARY NUMBER(10)
SQL>createorreplacetriggertfg1beforeinsert onemply101foreachrow
2 begin
3 insertintoemply102values(:new.eid,:new.ename,:new.age,:new.salary);4
end;
5/
Triggercreated.
SQL>insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’);Enter
valueforeid:e7
Entervalueforename:tharaE
ntervalueforage:28
Entervalueforsalary:30000
old1:insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’)new
1:insertintoemply101 values(‘e7’,’thara’,’28’,’30000’)
1rowcreated.
SQL>select*fromemply102;
EID ENAME AGE SALARY
e7 thara 28 30000
SQL>insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’);Enter
valueforeid:e8
Entervalueforename:sijuE
ntervalueforage: 29
Entervalueforsalary:36000
old1:insertintoemply101values(‘&eid’,’&ename’,’&age’,’&salary’)new
1:insertintoemply101 values(‘e8’,’siju’,’29’,’36000’)
1rowcreated.
SQL>select*fromemply102;
--
e7 thara 28 30000
e8 siju 29 36000
SQL>select*fromemply101;
e1 anu 25 20000
e2 abi 24 25700
e3 babu 30 34000
e4 cibi 32 32000
e5 brindha 23 31000
e7 thara 28 30000
e8 siju 29 s36000
7rowsselected.
SQL>deletefromemply101wher
eename=’babu’;1rowdeleted.
SQL>select*fromemply102;
EID ENAME AGE SALARY
--
e7 thara 28 30000
e8 siju 29 36000
e3 babu 30 34000
SQL>updateemply101setename=’sanju’where
eid=’e5’;1rowupdated.
SQL>select*fromemply102;
e7 thara 28 30000
e8 siju 29 36000
e3 babu 30 34000
e5 brindha 23 31000
RESULT:
AIM
To Create Access Relational Databases Using Python
Installing SQLAlchemy
The installation is very straight forward using Anaconda which we have discussed in the
chapter Data Science Environment. Assuming you have installed Anaconda as described in this
chapter, run the following command in the Anaconda Prompt Window to install the SQLAlchemy
package.
conda install sqlalchemy
Reading Relational Tables
We will use Sqlite3 as our relational database as it is very light weight and easy to use. Though the
SQLAlchemy library can connect to a variety of relational sources including MySql, Oracle and
Postgresql and Mssql. We first create a database engine and then connect to the database engine
using the to_sql function of the SQLAlchemy library.
In the below example we create the relational table by using the to_sql function from a dataframe
already created by reading a csv file. Then we use the read_sql_query function from pandas to
execute and capture the results from various SQL queries.
from sqlalchemy import create_engine
import pandas as pd
data = pd.read_csv('/path/input.csv')
Result 2
dept sum(salary)
0 Finance 1565.75
1 HR 729.00
2 IT 1812.30
3 Operations 1148.00
Inserting Data to Relational Tables
We can also insert data into relational tables using sql.execute function available in pandas. In the
below code we previous csv file as input data set, store it in a relational table and then insert
another record using sql.execute.
from sqlalchemy import create_engine
from pandas.io import sql
import pandas as pd
data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')
import pandas as pd
data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')
data.to_sql('data_table', engine)
date_today = datetime.date.today()
print date_today
print 'This Year :', date_today.year
print 'This Month :', date_today.month
print 'Month Name:',date_today.strftime('%B')
print 'This Week Day :', date_today.day
print 'Week Day Name:',date_today.strftime('%A')
When we execute the above code, it produces the following result.
The Date Today is : 2018-04-22 15:38:35.835000
2018-04-22
This Year : 2018
This Month : 4
Month Name: April
This Week Day : 22
Week Day Name: Sunday
Date Time Arithmetic
For calculations involving dates we store the various dates into variables and apply the relevant
mathematical operator to these variables.
import datetime
date_today = datetime.date.today()
date_today = datetime.date.today()
date1 = datetime.date(2018,4,4)
print 'date1:',date1
if date1 == before_four_days :
print 'Same Dates'
if date_today > date1:
print 'Past Date'
if date1 < after_four_days:
print 'Future Date'
When we execute the above code, it produces the following result.
Today is: 2018-04-22
Before Four Days: 2018-04-18
date1: 2018-04-04
Past Date
Future Date
Result:
Thus, the access relation database is implemented successfully.
EX NO:6 DOCUMENT TYPE DEFINITION AND XML SCHEMA
AIM
To create document type definition and xml schema.
The XML Document Type Declaration, commonly known as DTD, is a way to describe XML language precisely. DTDs
check vocabulary and validity of the structure of XML documents against grammatical rules of appropriate XML
language.
An XML DTD can be either specified inside the document, or it can be kept in a separate document and then liked
separately.
Syntax
Basic syntax of a DTD is as follows −
Syntax
Following is the syntax of internal DTD −
<!DOCTYPE root-element [element-declarations]>
where root-element is the name of root element and element-declarations is where you declare the elements.
Example
Following is a simple example of internal DTD −
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Several elements are declared here that make up the vocabulary of the <name> document. <!ELEMENT name
(#PCDATA)> defines the element name to be of type "#PCDATA". Here #PCDATA means parse-able text data.
End Declaration − Finally, the declaration section of the DTD is closed using a closing bracket and a closing angle
bracket (]>). This effectively ends the definition, and thereafter, the XML document follows immediately.
Rules
The document type declaration must appear at the start of the document (preceded only by the XML header) − it
is not permitted anywhere else within the document.
Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark.
The Name in the document type declaration must match the element type of the root element.
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 −
System Identifiers
A system identifier enables you to specify the location of an external file containing DTD declarations. Syntax is as
follows −
<!DOCTYPE name SYSTEM "address.dtd" [...]>
As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of the document.
Public Identifiers
Public identifiers provide a mechanism to locate DTD resources and is written as follows −
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify
an entry in a catalog. Public identifiers can follow any format, however, a commonly used format is called Formal Public
Identifiers, or FPIs.
Result:
Thus, document type definition and xml schema is executed successfully.
EX NO :7 Extracting XML Documents from Relational Databases
AIM
To implement the extracting XML documents from relational database.
This section discusses the representational issues that arise when converting data from a database system
into XML documents. As we have discussed, 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
types COURSE, SECTION, and STUDENT from Figure 12.8, and the relationships S-S and C-S between
them. In general, most documents extracted from a database will only use a subset of the attributes, entity
types, and relationships in the database. In this example, the subset of the database that is needed is shown in
Figure 12.9.
At least three possible document hierarchies can be extracted from the database subset in Figure 12.9. First,
we can choose COURSE as the root, as illustrated in Figure 12.10. Here, each course entity has the set of its
sections as subelements, and each section has its students as subelements. We can see one consequence of
modeling the information in a hierarchical tree structure. If a student has taken multiple sections, that
student’s information will appear multiple times in the document— once under each section. A possible
simplified XML schema for this view is shown in Figure 12.11. The Grade database attribute in the S-
S relationship is migrated to the STUDENT element. This is because STUDENT becomes a child
of SECTION in this hierarchy, so each STUDENT element under a specific SECTION element can have a
specific grade in that section. In this document hierarchy, a student taking more than one section will have
several replicas, one under each section, and each replica will have the specific grade given in that particular
section.
Figure 12.11
<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>
In the second hierarchical document view, we can choose STUDENT as root (Figure 12.12). In this
hierarchical view, each student has a set of sections as its child elements, and each section is related to one
course as its child, because the relationship between SECTION and COURSE is N:1. Thus, we can merge
the COURSE and SECTION elements in this view, as shown in Figure 12.12. In addition, the GRADE data-
base attribute can be migrated to the SECTION element. In this hierarchy, the
combined COURSE/SECTION information is replicated under each student who completed the section. A
possible simplified XML schema for this view is shown in Figure 12.13.
</xsd:sequence>
</xsd:element>
</xsd:sequence>
</xsd:element>
</xsd:sequence>
</xsd:element>
The third possible way is to choose SECTION as the root, as shown in Figure 12.14. Similar to the second
hierarchical view, the COURSE information can be merged into the SECTION element.
The GRADE database attribute can be migrated to the STUDENT element. As we can see, even in this
simple example, there can be numerous hierarchical document views, each corresponding to a different root
and a different XML document structure.
In the previous examples, the subset of the database of interest had no cycles. It is possible to have a more
complex subset with one or more cycles, indicating multiple relationships among the entities. In this case, it
is more difficult to decide how to create the document hierarchies. Additional duplication of entities may be
needed to represent the multiple relationships. We will illustrate this with an example using the ER schema
in Figure 12.8.
Suppose that we need the information in all the entity types and relationships in Figure 12.8 for a particular
XML document, with STUDENT as the root element. Figure 12.15 illustrates how a possible hierarchical
tree structure can be created for this document. First, we get a lattice with STUDENT as the root, as shown
in Figure 12.15(a). This is not a tree structure because of the cycles. One way to break the cycles is to
replicate the entity types involved in the cycles. First, we replicate INSTRUCTOR as shown in Figure
12.15(b), calling the replica to the right INSTRUCTOR1. The INSTRUCTOR replica on the left represents
the relationship between instructors and the sections they teach, whereas the INSTRUCTOR1 replica on the
right represents the relationship between instructors and the department each works in. After this, we still
have the cycle involving COURSE, so we can replicate COURSE in a similar manner, leading to the
hierarchy shown in Figure 12.15(c). The COURSE1 replica to the left represents the relationship between
courses and their sections, whereas the COURSE replica to the right represents the relationship between
courses and the department that offers each course.
In Figure 12.15(c), we have converted the initial graph to a hierarchy. We can do further merging if desired
(as in our previous example) before creating the final hierarchy and the corresponding XML schema
structure.
In addition to creating the appropriate XML hierarchy and corresponding XML schema document, several
other steps are needed to extract a particular XML document from a database:
It is necessary to create the correct query in SQL to extract the desired information for the XML
document.
Once the query is executed, its result must be restructured from the flat relational form to the XML tree
structure.
The query can be customized to select either a single object or multiple objects into the document. For
example, in the view in Figure 12.13, the query can select a single student entity and create a document
corresponding to that single student, or it may select several—or even all—of the stu-dents and create a
document with multiple students.
Result:
Thus, the XML documents from relational database is executed successfully.
EX NO:8 XML Querying
Aim
To implement the XML querying in RDBMS.
What is XQuery?
XQuery is a language for finding and extracting elements and attributes from XML documents.
"Select all CD records with a price less than $10 from the CD collection stored in cd_catalog.xml"
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 is compatible with several W3C standards, such as XML, Namespaces, XSLT, XPath, and XML
Schema.
XQuery 1.0 became a W3C Recommendation in 2007.
"books.xml":
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
doc("books.xml")
Path Expressions
The following path expression is used to select all the title elements in the "books.xml" file:
doc("books.xml")/bookstore/book/title
(/bookstore selects the bookstore element, /book selects all the book elements under the bookstore element,
and /title selects all the title elements under each book element)
XQuery uses predicates to limit the extracted data from XML documents.
The following predicate is used to select all the book elements under the bookstore element that have a price
element with a value that is less than 30:
doc("books.xml")/bookstore/book[price<30]
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
What is FLWOR?
FLWOR (pronounced "flower") is an acronym for "For, Let, Where, Order by, Return".
We will use the "books.xml" document in the examples below (same XML file as in the previous chapter).
doc("books.xml")/bookstore/book[price>30]/title
The expression above will select all the title elements under the book elements that are under the bookstore
element that have a price element with a value that is higher than 30.
The following FLWOR expression will select exactly the same as the path expression above:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
The for clause selects all book elements under the bookstore element into a variable called $x.
The where clause selects only book elements with a price element with a value greater than 30.
The order by clause defines the sort-order. Will be sort by the title element.
The return clause specifies what should be returned. Here it returns the title elements.
AIM:
To creating database using MongoDB, Installing MongoDB in RDBMS.
If you haven’t installed MongoDB yet, let’s do it first. Download the MongoDB package suitable for your
OS. Download the msi/zip file compatible with your OS and install the application. (I am not going to
describe the installation process in detail, as it is straightforward.)
I assume now you have installed the MongoDB database successfully. Open your CMD and type mongod –
version to verify your installation. If you get an output similar to the result in the picture below, everything
is perfect.
Copy
net start MongoDB
If you get this output, the MongoDB server has successfully started:
Next, we should run the MongoDB shell. To do that, type the command mongo in the CMD.
Now you are in the MongoDB shell, where you can execute commands to:
Create databases
Insert data
Edit and delete data from databases
Issue administrative commands
MongoDB has a keyword called ‘use,’ which is used to switch to a specified database. For example, if you
want to connect with an existing database named Employee, you can use the command ‘use Employee’ to
connect with it. However, if there is no database as Employee, the command ‘use’ will create it and connects
you to it. Let’s use the ‘use’ command to create our database.
Copy
use Company
When you use the command, you will see the following output:
Mongo has created the company database and connected you to it. You can use the db command to confirm,
which will display the currently connected database.
You might want to see all the existing databases before creating a new database. You can do it with
the show dbs command, and it will return the following result:
Installing MongoDB creates three default databases:
Admin
Config
Local
Surprisingly, the database we just created is not listed. This is because MongoDB doesn’t truly create the
database until we save values to it.
One of the critical features in NoSQL databases like MongoDB is that they are schema-less—there’s no
schema. That means you don’t specify a structure for the databases/tables as you do in SQL. Instead of
tables and rows in SQL, MongoDB has collections and documents. So, let’s see how you work with
collections in MongoDB.
In contrast, NoSQL has collections instead of tables. These collections don’t have any structure, and you
insert data, as documents, into the collection. That means that one document can be completely different
from another document. Let’s create a collection called Employee and add a document to it.
Before you could create a collection, remember that you add data to documents in JSON format. So, the
command to insert one document to our database will look like this:
Copy
db.Employee.insert(
{
"Employeename" : "Chris",
"EmployeeDepartment" : "Sales"
}
)
If the insertion is successful it will return WriteResult({ “nInserted” : 1 }):
First, switch to the database to add values using the ‘use’ command. Then use
db.Employee.insert command to add a document to the database:
Copy
db.Employee.find().forEach(printjson)
It will print the following output:
In MongoDB, you cannot set an arbitrary field to the primary key. However, you can change the value of the
default primary key. Let’s add another document while giving value for _id as well.
Copy
db.Employee.insert(
{
"_id" : 1,
"EmployeeName" : "Mark",
"EmployeeDepartment" : "Marketing"
}
)
Great. Now we know how to use the primary key as well. Let’s get back to our main topic. Have we created
our database now? Run the following command again to find it out.
Copy
show dbs
Now you can see the database ‘company’ is listed in the result: it worked!
Removing a database
It’s not good to leave this meaningless database on your server. So, let’s remove it as it is a good chance for
us to learn how to drop a database. To drop any database you want, first, you have to connect with it using
the use keyword.
Copy
use Company
Next, type db.dropDatabase() to remove the database from your server.
That’s why I encourage you to get familiar with a MongoDB Compass tool, a great GUI to work with
MongoDB. Here, I will show you how to create a database in Compass GUI. You can download the
Compass IDE for any operating system. Again, the installation process is very straightforward.
Now open the application and create a connection with the MySQL server that we installed earlier.
Go to ‘Fill in connection fields individually.’ It will take you to the following screen. If you use the default
values when installing MongoDB, all you have to do is click the CONNECT button.
Now you can see a list of databases available on your MongoDB server.
Click the create database button to create a new database. Then, give a database name and a collection name:
Unlike the Mongo shell, Compass will create a database even without adding any data:
1. To access the MongoDB shell, open a terminal window, and run the following command:
mongo
You are now in the MongoDB shell and can start issuing database commands.
2. Start by issuing a use command. The use command is typically used to switch to a specific database.
However, MongoDB creates a new database if one does not exist.
use example_db
You are currently using your newly created database named example_db.
db
Your system should display example_db (or the name you specified).
2. List all the databases on your system with the show dbs command:
show dbs
The newly created database is empty – you’ll need to insert data for it to display in this list.
The following command creates a record and inserts it into a newly created collection. A record is a
document with field names and values. As with a new database, if this record does not exist, MongoDB
creates it:
Let’s take a closer look at the syntax of the command to understand how the record and collection are
created.
db.Sample.insert – This is the insert command. In this example, the name Sample represents the
name of the document you’re inserting data into. If the document does not already exist, MongoDB
automatically creates it.
({ }) – The set of brackets encloses the data you are entering. Note that there’s a set of close-
brackets at the end.
"SampleValue1" : 255, "SampleValue2" : "randomStringOfText" – Represents the format of
the data we are entering into the record.
After you execute the command, you see the following response:
This response confirms that the system automatically created a collection and the record was inserted into
said collection.
If you list the existing databases with the show dbs command, you’ll notice that the example_db database is
now on the list.
Query MongoDB with find Command
You can verify that MongoDB saved the data from the insert command using the find command:
db.Sample.find()
As a result, the system displays the data located within the Sample collection.
Result:
AIM:
To create and implement the relational database management system.
A relational database stores data in relations which are expected to satisfy some simple
often shown as such. The columns of the table are called attributes and the rows are called
tuples. There is no signi cance 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
For example, consider the following relation scheme for the EMPLOYEE relation
Let the domain of the NAME, DEPT, RANK, OFFICE, and SUPERVISOR at-
tributes be character strings, and the domain of the SALARY attribute be integers. A
particular instance of the EMPLOYEE relation, re ecting the employees who are currently
The relation instance of EMPLOYEE will change from moment to moment due toarrival
of new employees, changes to data for existing employees and their departure.
Consider the EMPLOYEE relation discussed earlier. The relation scheme is de ned in SQL
by the following command.
This statement creates a table called EMPLOYEE with six columns. The NAME, DEPT,
RANK, OFFICE and SUPERVISOR columns have character strings (of un- speci ed
length) as values, whereas the SALARY column has integer values. NAME
is the primary key. DEPT is a foreign key which reference the primary key of table
DEPARTMENT. SUPERVISOR is a foreign key which references the primary key (i.e.,
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
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
Retrieval of data is e ected in SQL by the SELECT statement. For example, the NAME,
SALARY and SUPERVISOR data for employees in the Computer Sci de- partment is
extracted as follows.
SELECT NAME, SALARY, SUPERVISOR
FROM EMPLOYEE
WHERE DEPT = `Computer Sci'
This query applied to instance of EMPLOYEE given above returns the data shown below.
NAME SALARY SUPERVISOR
Kaplan 35,000 Brown
Brown 55,000 Black
The WHERE clause in a SELECT statement is optional. SQL also allows the retrieved
functions. For example, the following query gives the average salary for employees in each
department.
Data from two or more relations can be retrieved and linked together in a SELECT
statement. For example, the location of employees can be retrieved by linking the data in
This query will attempt to match every tuple in EMPLOYEE with every tuple in
DEPARTMENT, but will select only those pairs for which the DEPT attribute in the
EMPLOYEE tuple matches the DEPT attribute in the DEPARTMENT tuple. Since DEPT is
with respect to one of the two relations. Queries involving two relations in this manner are
known as joins.
Finally the UPDATE statement allows one or more attributes of existing tuples in a relation
to be modi ed. For example, the following statement gives all employees in the ComputerSci
This statement selects those tuples in EMPLOYEE which have the value of Com- puter Sci
for the DEPT attribute. It then increases the value of the SALARY at- tribute for all these
We now describe the access control facilities included in the SQL standard. The standard is
incomplete and does not address several important issues. Some of these de ciencies are
being addressed in the evolving standard. Di erent vendors have also provided more
SQL Privileges
The creator of a relation in an SQL database becomes its owner. The owner has the
intrinsic ability to grant other users access to that relation. The access priv- ileges or
DELETE and UPDATE SQL statements discussed earlier. There is also a REFERENCES
SQL does not require explicit permission for a user to create a relation, unless the relation is
de ned to have a foreign key to another relation. In the latter case the user must have the
REFERENCES privilege for appropriate columns of the referenced relation. To create a view
a user must have the SELECT privilege on every relation mentioned in de nition of the view.
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.
and WITH clauses denote that these are optional and may not be present in every
GRANT command. Note that it is not possible to grant a user the grant option on a privilege,
INSERT, DELETE and SELECT privileges apply to the entire relation as a unit.
INSERT and DELETE are operations on entire rows so this is appropriate. SELECT,
however, implies the ability to select on all columns. Selection on a subset of the columns
can be achieved by de ning a suitable view, and granting SELECT on the view. This is
somewhat awkward, and there have been proposals to allow SELECT to be granted on a
subset of the columns of a relation. The UPDATE privilege in general applies to a subset of
the columns. For example, a user could be granted the authority to update the OFFICE but
not the SALARY of an EMPLOYEE. SQL'92 extends the INSERT privilege to apply to a
subset of the columns. This can be used, for instance, to allow a clerical user to insert a tuple
DEPARTMENT and RANK data. The OFFICE, SALARY and SUPERVISOR data
SQL'89 has several omissions in its access control facilities. These omissions have been
addressed by di erent vendors in di erent ways. We will identify the major omissions here
and illustrate how they have been addressed in products and in the evolving standard.
Result: