Dbms
Dbms
Practical No:- 1
UsedofCreate,Alert,RenameandDropstatementinthedatabasetables(relations).
Create
Alert
MySQLprovidesthe
ALTERfunctionthathelpsusincorporatethechangestothealreadyexistingdatabasedesign.
Thebasicsyntaxused toaddacolumnto
analreadyexisAsthe sayinggoesChangeisthe
onlyconstant
Withtimebusinessrequirementschangeaswell.Asbusinessrequirementschange,Databasedesignsneed
changingas well.
tingtableisshownbelow
ALTERTABLE`table_name`ADDCOLUMN`column_name``data_type
Rename
RENAME
TABLErenamesoneormoretables.YoumusthaveALTERandDROPprivilegesfortheoriginaltable,a
ndCREATEandINSERTprivilegesforthe new table.
Dropstatement
TheDROPDATABASEstatementisusedtodropanexistingSQLdatabase.Syntax
DROPDATABASEdatabasename;
Practical No:2
Usedtoinsert,Delete,andUpdatestatementinthedatabasetables(relations).Insert
Insert statement is a DML (Data modification language) statement which is used to insert data
intheMySQLtable. UsingtheInsertquery,wecanaddoneormorerowsinthetable.Followingisthe
basicsyntaxoftheMySQLINSERTStatement.
Delete
TheDeletequeryinMySQLcandeletemorethanonerowfromatableinasinglequery.Thisprovestobe
advantageswhenremovinglargenumbersofrowsfroma database table.
Update StatementinRelation
UPDATE MySQL command is used to modify rows in a table. The update command can
beusedtoupdateasinglefieldormultiplefieldsatthesametime.ItcanalsobeusedtoupdateaMySQLtabl
ewithvaluesfromanothertable.
Openthedatabasethatcontainstherecordsyouwant
toupdate.OntheCreatetab,intheQueriesgroup,clickQueryDesign.Clickthe Tables
tab.Selectthetable ortables
thatcontaintherecordsthatyouwanttoupdate,clickAdd,andthenclickClose.
MySQLUpdateCommandSyntax
ThebasicsyntaxoftheUpdatequeryinMySQLisasshownbelow.
UPDATE`table_name`SET`column_name`=`new_value'[WHEREcondition];
Practical No:3
Useofsimpleselectstatement
When you want to select specific data from one or more sources, you can use a select query.
Aselect query helps you retrieve only the data that you want, and also helps you combine
datafromseveraldatasources.Youcanusetablesandotherselectqueriesasdatasourcesforaselectquery
1. OntheCreatetab,intheQueriesgroup,clickQueryWizard.
2. IntheNewQuerydialogbox,click SimpleQueryWizard,andthenclickOK.
Foreachfield,performthesetwosteps:
a) UnderTables/Queries, clickthetableorquerythatcontainsthefield.
b) UnderAvailableFields,double-clickthe fieldtoaddittotheSelectedFieldslist.Ifyouwantto
addallfieldstoyour query,clickthebuttonwiththedoublerightarrows(>>).
c) Whenyouhaveaddedallthefieldsthatyouwant,clicknext.
4. Ifyoudidnotaddanynumberfields(fieldsthatcontainnumericdata), skipaheadtostep
9.Ifyouaddedanynumberfields, thewizardasks
whetheryouwantthequerytoreturndetailsorsummarydata.
Dooneofthefollowing:
a) If you want to see individual records, click Detail, and then click Next. Skip ahead to
step9.
b) Ifyouwanttoseesummarizednumericdata, suchasaverages, clickSummary,
andthenclickSummaryOptions.
5. On the last page of the wizard, give the query a title, specify whether you want to open
ormodifythequery,andthenclickFinish.
Practical No:4
Useof selectqueryontworelations
A relationship works by matching data in key columns, usually columns (or fields) that have
thesame name in both tables. In most cases, the relationship connects the primary key, or the
uniqueidentifiercolumnforeachrow,fromonetabletoafieldinanothertable.
Thecolumnintheothertable is known as the "foreign key." For example, if you want to track sales
of each book title,you create a relationship between the primary key column (let's call it
title_ID) in the "Titles"tableand a column inthe"Sales"tablethatisnamedtitle_ID.The
title_IDcolumnin the"Sales"tableis theforeignkey.
Table1
Table2
One-to-manyrelationships
A one-to-many relationship is created if only one of the related columns is a primary key or has
aunique constraint.
In the relationship window in Access, the primary key side of a one-to-many relationship
isdenoted bya number1.The foreignkeyside ofa relationshipisdenotedbyaninfinitysymbol.
Many-to-manyrelationships
In a many-to-many relationship, a row in table A can have many matching rows in table B,
andvice versa. You create such a relationship by defining a third table that is called a junction
table.Theprimarykeyofthejunctiontable consistsofthe foreignkeysfrombothtable Aandtable
B.For example, the "Authors" table and the "Titles" table have a many-to-many relationship that
isdefined by a one-to-many relationship from each of these tables to the "TitleAuthors" table.
Theprimary key of the "TitleAuthors" table is the combination of the au_IDcolumn (the
"Authors"table'sprimarykey)andthetitle_IDcolumn(the "Titles"table's primarykey).
Practical No: 5
UseofAggregatefunctions
Aggregate functions are used when you need to perform a calculation on the data in one
ofyour columns. For instance, the sum aggregate function can be used to add up all of
theprofitsfromthebooks.
Addtheprofitfield tothequery
Now press the Totals button in the Show/Hide group. When this button is pressed, we
areable to use aggregate functions. Notice that once you press the Totals button, a new
rownamedTotalappearsinthequerydesign.
Practical No:13
Useofnestingofqueries
InAccess,weareabletonestonequeryinsideofanothertousethefirstquery'sresultsinplaceof a table. In
other words, a query can provide the data source from which another query canselect data, filter,
sort, aggregate, et cetera. This allows us to answer questions like,
"Whichscientistworkedonmorethanoneproject?"
Let's start by determining how many different projects each scientist has worked on. We
canbegin by finding the distinct list of projects each scientist worked on using unique values.
Wewant to count how many projects are listed here for each scientist. Since counting is
anaggregation,weneed to
usetheresultsofthisqueryasinputforaseparatequerythatdoestheaggregation.
To nest this query as the source for a larger query, we start by saving this query as". Then
wecreate a second query. When we start the query, instead of adding an existing table, we click
onthe queries tab and add the query. We can now use this query just like a table and aggregate
thevalues by clicking on "totals", grouping by login ID, and counting "project". Now, if we want
toseealistofonlythescientiststhathaveworkedonmorethanoneproject,wecanfilterthiscounttobe
greaterthanone,andchoose nottoshowtheprojectcolumn.
Nesting queries like this is really useful if the data you want to write a query on isn't present
inexactly the right form in the database. You can use one query to get the data in the form
youneeditin, andthenwhennesting,youareabletousetheseresultsastheinputforalargerquery.
There are also other things that we can do with nested queries, such as use the results of
onequery to filter the results of another query. This allows us to do things like determine
whichscientists have not been experimenting with time travel. But these types of nested queries
orsubqueries can't be generated using Access's graphical interface. They require us to
useStructuredQueryLanguage,aprogramminglanguagetypicallyreferred toas"SQL"or"sequel".If
you're interested in how to do this, check out the Software Carpentry lectures on
databasesusingSQL.
Inthisscreencast,we'veintroducedtheideaofnestingqueries.We'veseenthatyoucanuseanested
query in place of a table to answer more complicated questions than you could using asingle
queryonits own.
Practical No:7
Useoforderbystatement
The ORDER BY clause in Access sorts a query's resulting records on a specified field or
fieldsinascendingordescendingorder
Syntax
SELECT field list FROM table WHERE select criteria [ORDER BY field1 [ASC | DESC]
[,field2[ASC |DESC]][,…]]]
ASELECT statementcontaininganORDERBYclausehastheseparts:
Part Description
Remarks
ORDERBYisoptional.However,ifyouwantyourdatadisplayedinsortedorder,thenyoumustuseOR
DER BY.
Thedefaultsortorder
isascending(AtoZ,0to9).Bothofthefollowingexamplessortemployeenamesinlastname order:
SQLCopy
SELECTLastName,FirstName
FROMEmployees
ORDER BY
LastName;SELECTLastName,
FirstNameFROMEmployees
ORDERBYLastNameASC;
Example
The SQL statement shown in the following example uses the ORDER BY clause to sort
recordsbylastnameindescendingorder(Z-A).Itcallsthe
EnumFieldsprocedure,whichyoucanfindinthe SELECTstatementexample.
VBCopy
SubOrderByX()
DimdbsAsDatabase,rst AsRecordset
'Modifythis
linetoincludethepathtoNorthwind'onyourcomputer
.
Setdbs=OpenDatabase("Northwind.mdb")
'PopulatetheRecordset.rs
t.MoveLast
'CallEnumFieldstoprintrecordsetcontents.
EnumFieldsrst,12d
bs.Close
End Sub
Practical No:8
WriteaPL/SQLcodetoaddtwonumbersanddisplaytheresult.
Readthenumbersduringrun time.
Prerequisite–PL/SQLintroduction
In PL/SQL code groups of commands are arranged within a block. A block group
relateddeclarationsorstatements.
Examples:
Input:15 25
Output:40
Input:250400
Output:650
Belowistherequiredimplementation:de
clare
declarevariablex,y
andzofdatatypenumberx
number(5);
y
number(5);z
number(7);b
egin
Here we Assigning 10 into
xx:=10;
Assigning 20 into
xy:=20;
EndOutput
Practical No:9
WriteaPL/SQLcodetofindsumoffirst10naturalnumbersusingwhileandforloop.
In PL/SQL code groups of commands are arranged within a block. A block group
relateddeclarationsorstatements.Indeclarepart,wedeclarevariablesandbetweenbeginandendpart,w
eperformtheoperations.
Givenapositiveintegernand thetask isto
findthesumoffirstnnaturalnumber.Examples:
Input: n =
3Output:10
Input: n =
2Output:4
Approachisto takedigitsform1 andto nandsumminglikedonebelow-
Sumoffirstnaturalnumber:1
Sumoffirstandsecondnaturalnumber:1 + 2=3
Sumoffirst,secondandthird naturalnumber= 1+ 2 + 3=
6Belowisthe requiredimplementation:
declaration
sectionDECLARE
x
NUMBER;n
NUMBER;i
NUMBER;
functionforfindingsum
FUNCTIONFindmax(nINNUMBER)R
ETURN NUMBER
IS
sumsNUMBER:=0;B
EGIN
forloopforntimesiterationF
ORiIN1..n
LOOP
sums:=sums+i*(i+1)/
2;ENDLOOP;
RETURN
sums;END;
BEGIN
drivercode
n:=4;
x :=
findmax(n);dbms_output.Put
_line('Sum:'
Roll no. -2125920 Page19
MODERNGROUPOFCOLLEGES
||
x);E
ND;
endofProgram
Output:
Sum: 20
Timecomplexity=O(n)
Anefficientsolutionistousedirectformula n(n+1)(n+2)/6
Output:sum20
Practical No:10
ConsiderthefollowingschemaforaLibraryDatabase:
i. Creationoftableswiththeirattributes:
BOOK(Book_id,Title,Publisher_Name,Pub_Year)cr
eatetablebook
(book_idintnotnull,titlev
archar(25)notnull,
publisher_namevarchar(20)notnull,p
ub_yearintnot null,
primarykey(book_id)
);
ii. BOOK_AUTHORS(Book_id,Author_Name)
create table
book_authors(book_idintn
otnull,
author_namevarchar(20)notnull,p
rimarykey(book_id)
);
iii. PUBLISHER(Name,Address,Phone)
create table
publisher(namevarchar(20
)notnull,address char(25)
not
null,phoneintnotnull,prim
arykey(phone));
v. BOOK_LENDING(Book_id,Branch_id,Card_No,Date_Out,Due_Date)
create table
library_branch(branch_idintnotnul
l,branch_namevarchar(25)notnull,
addresschar(25)notnull,
primarykey(branch_id)
);
Insertionofrecords:
i. BOOK(Book_id,Title,Publisher_Name,Pub_Year)
insertintobook(book_id,title,publisher_name,pub_year)values(1111,'SE','PEARSON',2005);insert
into book(book_id, title, publisher_name, pub_year)values(2222, 'DBMS', 'MCGRAW',2004);
insertintobook(book_id,title,publisher_name,pub_year)values(3333,'ANOTOMY'
ii. BOOK_AUTHORS(Book_id,Author_Name)
insertintobook_authors(book_id,author_name)values(1111,'SOMMERVILLE');in
sertintobook_authors(book_id,author_name)values(2222,'NAVATHE');insert into
book_authors(book_id, author_name)values(3333, 'HENRY
GRAY');insertintobook_authors(book_id,author_name)values(4444,'THOMAS');
iii. PUBLISHER(NAME,ADDRESS,PHONE)
insertintopublisher(name,address,phone)values('PEARSON','BANGALORE',9875462530);inser
t into publisher(name, address, phone)values('MCGRAW', 'NEWDELHI',
7845691234);insertinto
publisher(name,address,phone)values('SAPNA','BANGALORE',7845963210);
iv. BOOK_COPIES(BOOK_ID,BRANCH_ID,NO_OF_COPIES)
altertablebook_copiesd
ropprimarykey;
(herewedropprimarykey becauseourbook_idisrepeated
whichcreatesanerror“uniqueconstraints violates”. And if we don’t mention a primary key
while creating a table itshowsanerrorof“invalididentifier”.)
insert into book_copies(book_id, branch_id, no_of_copies)values(1111, 11,
5);insertintobook_copies(book_id,branch_id,no_of_copies)values(3333,22,6);
Roll no. -2125920 Page25
MODERNGROUPOFCOLLEGES
v. BOOK_LENDING(BOOK_ID,BRANCH_ID,CARD_NO,DATE_OUT,
DUE_DATE)
altertablebook_lendingd
ropprimarykey;
(herewedropprimarykey becauseourbook_idisrepeated
whichcreatesanerror“uniqueconstraints violates”. And if we don’t mention a primary key
while creating a table itshowsanerrorof“invalididentifier”.)
insert into book_lending(book_id, branch_id, card_no, date_out, due_date)values(2222,
11,1, TO_DATE('10-JAN-17','DD-MM-YY'),TO_DATE('20-AUG-17','DD-MM-YY'));
insertintobook_lending(book_id,branch_id,card_no,date_out,due_date)values(3333,22,2,
TO_DATE('09-JUL-17','DD-MM-YY'),TO_DATE('12-AUG-17','DD-MM-YY'));
insertintobook_lending(book_id,branch_id,card_no,date_out,due_date)values(4444,55,1,
TO_DATE('11-APR-17','DD-MM-YY'),TO_DATE('09-AUG-17','DD-MM-YY'));
insertintobook_lending(book_id,branch_id,card_no,date_out,due_date)values(2222,11,5,
TO_DATE('09-AUG-17','DD-MM-YY'),TO_DATE('19-AUG-17','DD-MM-YY'));
insertintobook_lending(book_id,branch_id,card_no,date_out,due_date)values(4444,33,1,
TO_DATE('10-JUL-17','DD-MM-YY'),TO_DATE('15-AUG-17','DD-MM-YY'));
insertintobook_lending(book_id,branch_id,card_no,date_out,due_date)values(1111,11,1,
TO_DATE('12-MAY-17','DD-MM-YY'),TO_DATE('10-JUN-17','DD-MM-YY'));
insertintobook_lending(book_id,branch_id,card_no,date_out,due_date)values(3333,22,1,T
O_DATE('10-JUL-17','DD-MM-YY'),TO_DATE('15-JUL-17','DD-MM-YY'));
vi. LIBRARY_BRANCH(BRANCH_ID,BRANCH_NAME,ADDRESS)
insertintolibrary_branch(branch_id,branch_name,address)values(11,'CENTRALTECHNICAL','
MGROAD');
insertintolibrary_branch(branch_id,branch_name,address)values(22,'MEDICAL','BHROAD');
insertintolibrary_branch(branch_id,branch_name,address)values(33,'CHILDREN','SSPURAM');
insertintolibrary_branch(branch_id,branch_name,address)values(44,'SECRETARIAT','SIRAGAT
E');
insertintolibrary_branch(branch_id,branch_name,address)values(55,'GENERAL','JAYANAGAR')
;