0% found this document useful (0 votes)
11 views55 pages

Database Lab Manuallllllllllllllllllll

notes

Uploaded by

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

Database Lab Manuallllllllllllllllllll

notes

Uploaded by

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

Ex.

No:1 DDL COMMANDS

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> Alter table Student


add(Stud_addrvarchar2(20));Table
altered.

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;

Name Null? Type

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;

Name Null? Type

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> Drop table


Student;Tabledrop
ped.

SQL>desc Student;
ERROR:ORA-04043:objectStudentdoesnotexist

Result:

Thus, the given DDL query is executed successfully.


Ex.No:2 DMLCOMMANDS

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.

2. Select Command:It is used to retrieve information from the table. It is


generallyreferred to as querying the table. We can either display all columns in a table
or onlyspecifycolumnfromthetable.
Syntax:
Select*fromtablename;E
xample:
SQL>select*fromStudent1;
STUD_NAME STUD_IDSTUD_DEPT STUD_AGE

Ram 101 MECH 14


Vicky 102 EEE 15
Sarath 103 CSE 15
Devi 104 EEE 14
4rowsselected

3. UpdateCommand:Itisusedtoalterthecolumnvalues inatable.Asinglecolumnmaybe
updatedormorethanonecolumncouldbeupdated.
Syntax:
Updatetablenamesetcolumn_name=’value’wherecondition;
Example:

SQL>UpdateStudent1setstud_id=’109’wherestud_name=’Sarath’;1row
updated.

SQL>select*fromStudent1;

STUD_NAME STUD_IDSTUD_DEPT STUD_AGE

Ram 101 MECH 14


Vicky 102 EEE 15
Sarath 109 CSE 15
Devi 104 EEE 14
4rowsselected
4. DeleteCommand:Afterinsertingrowinatablewecanalsodeletethemifrequired.The
delete command consists of a from clause followed by an optional where
clause.Syntax:
Deletefromtablenamewherecondition;Ex
ample:

SQL>DeletefromStudent1wherestud_dept=’CSE’;1row
deleted.

SQL>select*fromStudent1;

STUD_NAME STUD_IDSTUD_DEPT STUD_AGE

Ram 101 MECH 14


Vicky 102 EEE 15
Devi 104 EEE 14
3rowsselected

Result:

Thus, the given DDL query is executed successfully.


Ex.No:3 TCL(TRNSACTIONCONTROLLANGUAGE)

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;

EMPNOENAME DESIGNATIN SALARY


- -
101NAGARAJAN LECTURER 16000
102SARAVANAN ASST. PROF 16000
104 CHINNI HOD,PROF 45000

SQL>INSERTINTOEMPVALUES(105,'PARTHASAR','STUD
ENT',100);1rowcreated.SQL>SELECT*FROMEMP;
EMPNOENAME DESIGNATIN SALARY

105PARTHASAR STUDENT 100


101NAGARAJAN LECTURER 16000
102SARAVANAN ASST. PROF 16000
104 CHINNI HOD,PROF 45000
ROLLBACK

Syntaxforsavepoint:

SQL>ROLLBACK<SAVEPOINTNAME>;

SQL>ROLLBACKS1;
Rollbackcomplete.

SQL>SELECT*FROMEMP;
EMPNOENAME DESIGNATIN SALARY

101 NAGARAJAN LECTURER 16000


102 SARAVANAN ASST.PROF 16000
103 PANNERSELVAMASST.PROF 20000
104 CHINNI HOD,PROF 45000

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;

EID ENAME AGE SALARY

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;

EID ENAME AGESALARY

--
e7 thara 28 30000
e8 siju 29 36000

SQL> createorreplacetriggertrgrr15afterdelete orupdateonemply101foreachrow


2 begin
3 ifdeletingthen
4 insertintoemply102values(:old.eid,:old.ename,:old.age,:old.salary);5
elsifupdatingthen
6 insert into emply102
values(:old.eid,:old.ename,:old.age,:old.salary);7endif;
8end;
9/
Triggercreated.

SQL>select*fromemply101;

EID ENAME AGE SALARY

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;

EID ENAME AGESALARY

e7 thara 28 30000
e8 siju 29 36000
e3 babu 30 34000
e5 brindha 23 31000

RESULT:

Thus, the given triggers in RDBMS is executed successfully.


Ex.No:5 ACCESS RELATIONAL DATABASES USING PYTHON

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')

# Create the db engine


engine = create_engine('sqlite:///:memory:')

# Store the dataframe as a table


data.to_sql('data_table', engine)

# Query 1 on the relational table


res1 = pd.read_sql_query('SELECT * FROM data_table', engine)
print('Result 1')
print(res1)
print('')

# Query 2 on the relational table


res2 = pd.read_sql_query('SELECT dept,sum(salary) FROM data_table group by dept', engine)
print('Result 2')
print(res2)
When we execute the above code, it produces the following result.
Result 1
index id name salary start_date dept
0 0 1 Rick 623.30 2012-01-01 IT
1 1 2 Dan 515.20 2013-09-23 Operations
2 2 3 Tusar 611.00 2014-11-15 IT
3 3 4 Ryan 729.00 2014-05-11 HR
4 4 5 Gary 843.25 2015-03-27 Finance
5 5 6 Rasmi 578.00 2013-05-21 IT
6 6 7 Pranab 632.80 2013-07-30 Operations
7 7 8 Guru 722.50 2014-06-17 Finance

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:')

# Store the Data in a relational table


data.to_sql('data_table', engine)

# Insert another row


sql.execute('INSERT INTO data_table VALUES(?,?,?,?,?,?)', engine,
params=[('id',9,'Ruby',711.20,'2015-03-27','IT')])

# Read from the relational table


res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)
print(res)
When we execute the above code, it produces the following result.
id dept name salary start_date
0 1 IT Rick 623.30 2012-01-01
1 2 Operations Dan 515.20 2013-09-23
2 3 IT Tusar 611.00 2014-11-15
3 4 HR Ryan 729.00 2014-05-11
4 5 Finance Gary 843.25 2015-03-27
5 6 IT Rasmi 578.00 2013-05-21
6 7 Operations Pranab 632.80 2013-07-30
7 8 Finance Guru 722.50 2014-06-17
8 9 IT Ruby 711.20 2015-03-27
Deleting Data from Relational Tables
We can also delete data into relational tables using sql.execute function available in pandas. The
below code deletes a row based on the input condition given.
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:')
data.to_sql('data_table', engine)

sql.execute('Delete from data_table where name = (?) ', engine, params=[('Gary')])

res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)


print(res)
When we execute the above code, it produces the following result.
id dept name salary start_date
0 1 IT Rick 623.3 2012-01-01
1 2 Operations Dan 515.2 2013-09-23
2 3 IT Tusar 611.0 2014-11-15
3 4 HR Ryan 729.0 2014-05-11
4 6 IT Rasmi 578.0 2013-05-21
5 7 Operations Pranab 632.8 2013-07-30
6 8 Finance Guru 722.5 2014-06-17
Date Time Representation
A date and its various parts are represented by using different datetime functions. Also, there are
format specifiers which play a role in displaying the alphabetical parts of a date like name of the
month or week day. The following code shows today's date and various parts of the date.
import datetime

print 'The Date Today is :', datetime.datetime.today()

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

#Capture the First Date


day1 = datetime.date(2018, 2, 12)
print 'day1:', day1.ctime()

# Capture the Second Date


day2 = datetime.date(2017, 8, 18)
print 'day2:', day2.ctime()

# Find the difference between the dates


print 'Number of Days:', day1-day2

date_today = datetime.date.today()

# Create a delta of Four Days


no_of_days = datetime.timedelta(days=4)

# Use Delta for Past Date


before_four_days = date_today - no_of_days
print 'Before Four Days:', before_four_days

# Use Delta for future Date


after_four_days = date_today + no_of_days
print 'After Four Days:', after_four_days
When we execute the above code, it produces the following result.
day1: Mon Feb 12 00:00:00 2018
day2: Fri Aug 18 00:00:00 2017
Number of Days: 178 days, 0:00:00
Before Four Days: 2018-04-18
After Four Days: 2018-04-26
Date Time Comparison
Date and time are compared using logical operators. But we must be careful in comparing the right
parts of the dates with each other. In the below examples we take the future and past dates and
compare them using the python if clause along with logical operators.
import datetime

date_today = datetime.date.today()

print 'Today is: ', date_today


# Create a delta of Four Days
no_of_days = datetime.timedelta(days=4)

# Use Delta for Past Date


before_four_days = date_today - no_of_days
print 'Before Four Days:', before_four_days

after_four_days = date_today + no_of_days

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 −

<!DOCTYPE element DTD identifier


[
declaration1
declaration2
........
]>

In the above syntax,

 The DTD starts with <!DOCTYPE delimiter.


 An element tells the parser to parse the document from the specified root element.
 DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or
URL to a file on the internet. If the DTD is pointing to external path, it is called External Subset.
 The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.
Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To refer it as internal
DTD, standalone attribute in XML declaration must be set to yes. This means, the declaration works independent of an
external source.

Syntax
Following is the syntax of internal DTD −
<!DOCTYPE root-element [element-declarations]>
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 −

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


<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>

<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

Let us go through the above code −


Start Declaration − Begin the XML declaration with the following statement.
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
DTD − Immediately after the XML header, the document type declaration follows, commonly referred to as the
DOCTYPE −
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The DOCTYPE informs the
parser that a DTD is associated with this XML document.
DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare elements, attributes,
entities, and notations.

<!ELEMENT address (name,company,phone)>


<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>

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 −

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


<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

The content of the DTD file address.dtd is as shown −

<!ELEMENT address (name,company,phone)>


<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Types
You can refer to an external DTD by using either system identifiers or public identifiers.

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.

1. Creating Hierarchical XML Views over Flat or Graph-Based Data

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

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>

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:element name=”root”> <xsd:sequence>

<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=”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=”cnumber”
type=”xsd:unsignedInt” /> <xsd:element name=”cname” type=”xsd:string” /> <xsd:element name=”grade”
type=”xsd:string” />

</xsd:sequence>
</xsd:element>

</xsd:sequence>

</xsd:element>

</xsd:sequence>

</xsd:element>

Figure 12.13 XML schema document with student as the root.

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.

2. Breaking Cycles to Convert Graphs into Trees

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.

3. ther Steps for Extracting XML Documents from Databases

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 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 is About Querying XML

XQuery is a language for finding and extracting elements and attributes from XML documents.

Here is an example of what XQuery could solve:

"Select all CD records with a price less than $10 from the CD collection stored in cd_catalog.xml"

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 is a W3C Recommendation

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.

The XML Example Document

We will use the following XML document in the examples below.

"books.xml":

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

<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>

View the "books.xml" file in your browser.

How to Select Nodes From "books.xml"?


Functions

XQuery uses functions to extract data from XML documents.


The doc() function is used to open the "books.xml" file:

doc("books.xml")
Path Expressions

XQuery uses path expressions to navigate through elements in an XML document.

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)

The XQuery above will extract the following:

<title lang="en">Everyday Italian</title>


<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>
Predicates

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]

The XQuery above will extract the following:

<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".

 For - selects a sequence of nodes


 Let - binds a sequence to a variable
 Where - filters the nodes
 Order by - sorts the nodes
 Return - what to return (gets evaluated once for every node)

The XML Example Document

We will use the "books.xml" document in the examples below (same XML file as in the previous chapter).

View the "books.xml" file in your browser.


How to Select Nodes From "books.xml" With FLWOR

Look at the following path expression:

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

The result will be:

<title lang="en">XQuery Kick Start</title>


<title lang="en">Learning XML</title>

With FLWOR you can sort the result:

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.

The result of the XQuery expression above will be:

<title lang="en">Learning XML</title>


<title lang="en">XQuery Kick Start</title>
EX NO:9 Creating Databases using MongoDB, Installing MongoDB

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.

Accessing the Mongo shell


When you install MongoDB, a CLI tool called Mongo shell will be installed along with it. You can use it to
give commands to the MySQL server. In order to get access to the mongo shell, you have to start the server
with the following command:

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

Creating a Mongo database


As I said earlier, there is no ‘create database’ command in MongoDB. It doesn’t mean there is no way to
create a database—of course there is. Let’s see how, by creating a database called Company using the shell.

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.

Using collections in MongoDB


In SQL, you have tables that have a well-defined structure with columns and specified data types. You insert
data into tables as records. Every record you insert should have values (including null values) for every
column defined on the table.

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:

 Db refers to the currently connected database.


 Employee is the newly created collection on the company database.
A significant issue you’ll notice in this query is we haven’t set a primary key. MongoDB automatically
creates a primary key field called _id and sets a default value to it. To see this, let’s view the collection we
just created. Run the following command to access our collection in JSON format.

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.

Run the show dbs command again to verify it.

Using MongoDB Compass


That should be the end of our tutorial—we created and removed a Mongo database. However, I want to talk
about one more thing. Although the Mongo shell is a great tool for working with MongoDB servers, many
people find it difficult, especially in a production environment.

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:

We can verify it with the Mongo shell as well:


Compass has a very intuitive interface way to work with the MongoDB database. It will save a lot of time
when you are developing large applications. However, I still recommend you use the Mongo shell and get a
good grasp of it.

Writing simple queries to access databases created using MongoDB


Create MongoDB Database with the use Command

MongoDB commands are issued within the MongoDB client shell.

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

3. The system immediately responds and switches to your new database.

You are currently using your newly created database named example_db.

Note: If you can’t access the MongoD

How to List Databases in MongoDB

1. Verify the name of the current database by using the db command:

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

You may notice that your new database is not listed.

The newly created database is empty – you’ll need to insert data for it to display in this list.

Add MongoDB Collection with insert() Command

A collection in MongoDB is much like a table in other database applications.

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:

db.Sample.insert({"SampleValue1" : 255, "SampleValue2" : "randomStringOfText"})

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:

WriteResult({ "nInserted" : 1})

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:

Thus, the creating and installing mangoDB is successfully.


EX NO:10 RELATIONAL DATABASES

AIM:
To create and implement the relational database management system.

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

mathematical properties. Roughly speaking, a relation can be thought of as a table, and is

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

the relation at a given instant.

For example, consider the following relation scheme for the EMPLOYEE relation

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

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

employed, is shown below.

NAME DEPT RANK OFFICE SALARY SUPERVISOR


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

The relation instance of EMPLOYEE will change from moment to moment due toarrival

of new employees, changes to data for existing employees and their departure.

The CREATE Statement

Consider the EMPLOYEE relation discussed earlier. The relation scheme is de ned in SQL
by the following command.

CREATE TABLE EMPLOYEE


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

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.,

NAME) of the EMPLOYEE table itself.

INSERT and DELETE Statements

The EMPLOYEE table is initially empty. Tuples are inserted into it by means of the

SQL INSERT statement. For example, the last tuple of the relation instance discussed

above is inserted by the following statement.

INSERT
INTO EMPLOYEE(NAME, DEPT, RANK, OFFICE, SALARY, SUPERVISOR)
VALUES VALUES(`Black, `Administration', `Dean', `ST101', 60000, NULL)
The remaining tuples can be similarly inserted. Insertion of the tuples for Brown and Jones

must respectively precede insertion of the tuples for Kaplan and Rao, so as to maintain

referential integrity. Alternately, these tuples can be inserted in any order with NULL

managers which are later updated to their actual values. There is a DELETE statement to

delete tuples from a relation.

The SELECT Statement

Retrieval of data 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

records to be grouped together for statistical computations by means of built-in statistical

functions. For example, the following query gives the average salary for employees in each

department.

SELECT DEPT, AVG(SALARY)


FROM EMPLOYEE
GROUP BY DEPT

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

EMPLOYEE with that in DEPARTMENT, as follows.

SELECT NAME, LOCATION


FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DEPT = DEPARTMENT.DEPT

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

a common attribute to both relations, every use of it is explicitly identi ed as occurring

with respect to one of the two relations. Queries involving two relations in this manner are

known as joins.

The UPDATE Statement

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

department a raise of $1000.


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

This statement selects those tuples in EMPLOYEE which have the value of Com- puter Sci

for the DEPT attribute. It then increases the value of the SALARY at- tribute for all these

tuples by $1000 each.

2 DISCRETIONARY ACCESS CONTROLS

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

comprehensive facilities than called for by the standard.

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

modes recognized in SQL correspond directly to the CREATE, INSERT, SELECT,

DELETE and UPDATE SQL statements discussed earlier. There is also a REFERENCES

privilege to control the establishment of foreign keys to a relation.

The CREATE Statement

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.

If a user has INSERT, DELETE or UPDATE privileges on these relations, corresponding

privileges will be obtained on the view (if it is updatable).


The GRANT Statement

The owner of a relation can grant one or more access privileges to another user. This can be

done with or without the GRANT OPTION. If the owner grants, say, SELECT with the

GRANT OPTION the user receiving this grant can further grant SELECT to other users.

The latter GRANT can be done in turn with or without the GRANT OPTION at the granting

user's discretion.

The general format of a grant operation in SQL is as follows.


GRANT privileges
[ON relation]
TO users
[WITH GRANT OPTION]
The GRANT command applies to base relations as well as views. The brackets on the ON

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,

without allowing the grant option itself to be further granted.

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

for a new employee with the NAME,


Sa n d hu 2

DEPARTMENT and RANK data. The OFFICE, SALARY and SUPERVISOR data

can then be updated in this tuple by a suitably authorized supervisory user.

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:

Thus, the program is implemented and executed successfully.


Sa n d hu 3
Sa n d hu 4

You might also like