0% found this document useful (0 votes)
11 views

Dbms

Question related to DBMS and practical file related to dbms

Uploaded by

Arti Saroya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Dbms

Question related to DBMS and practical file related to dbms

Uploaded by

Arti Saroya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

MODERNGROUPOFCOLLEGES

Practical No:- 1
UsedofCreate,Alert,RenameandDropstatementinthedatabasetables(relations).

Create

Acopyofanexisting table canalsobe createdusingCREATETABLE.

Thefollowing SQLcreatesanewtablecalled"TestTables"(which isacopyofthe"Customers"table)

Alert

MySQLprovidesthe
ALTERfunctionthathelpsusincorporatethechangestothealreadyexistingdatabasedesign.

Thebasicsyntaxused toaddacolumnto
analreadyexisAsthe sayinggoesChangeisthe
onlyconstant

Withtimebusinessrequirementschangeaswell.Asbusinessrequirementschange,Databasedesignsneed
changingas well.

tingtableisshownbelow

ALTERTABLE`table_name`ADDCOLUMN`column_name``data_type

Roll no. -2226650 Page1


MODERNGROUPOFCOLLEGES

Rename
RENAME
TABLErenamesoneormoretables.YoumusthaveALTERandDROPprivilegesfortheoriginaltable,a
ndCREATEandINSERTprivilegesforthe new table.

Roll no. -2226650 Page2


MODERNGROUPOFCOLLEGES

Dropstatement

TheDROPDATABASEstatementisusedtodropanexistingSQLdatabase.Syntax
DROPDATABASEdatabasename;

Roll no. -2226650 Page3


MODERNGROUPOFCOLLEGES

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.

Roll no. -2226650 Page4


MODERNGROUPOFCOLLEGES

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

Roll no. -2226650 Page5


MODERNGROUPOFCOLLEGES

Roll no. -2226650 Page6


MODERNGROUPOFCOLLEGES

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.

3. Next,you addfields.You canadd upto 255fieldsfromasmanyas32 tablesorqueries.

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.

Roll no. -2226650 Page7


MODERNGROUPOFCOLLEGES

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.

Roll no. -2226650 Page8


MODERNGROUPOFCOLLEGES

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

Aone-to-manyrelationshipisthemostcommonkindofrelationship. Inthiskindofrelationship,a row


in table A can have many matching rows in table B. But a row in table B can have onlyone
matching row in table A. For example, the "Publishers" and "Titles" tables have a one-to-many
relationship. That is, each publisher produces many titles. But each title comes from onlyone
publisher.

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.

Roll no. -2226650 Page9


MODERNGROUPOFCOLLEGES

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

Roll no. -2226650 Page10


MODERNGROUPOFCOLLEGES

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.

Createanewquery(Query4)andadd Query1toit(thesamewayyou wouldadd atable).

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.

Roll no. -2226650 Page11


MODERNGROUPOFCOLLEGES

Click onthe Totalpropertyofthe Profitfield andchangethevaluefromGroupByto Sum.

Runthequeryto viewtheresult.Thequeryaddsup allofthevaluesintheprofitcolumn


andreturnstheresult.

Roll no. -2226650 Page12


MODERNGROUPOFCOLLEGES

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.

SUBCODE: -UGCA1925 Page13


MODERNGROUPOFCOLLEGES

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

Field List Thenameofthefieldorfieldstoberetrievedalongwith


any field-name aliases, SQL aggregatefunctions,
selectionpredicates(ALL,DISTINCT,
DISTINCTROW,orTOP),or
otherSELECTstatementoptions.

Table The name ofthetablefromwhichrecords


areretrieved.Formoreinformation,see
theFROMclause.
Select Selectioncriteria. Ifthestatementincludes
Criteria aWHEREclause,theMicrosoftAccessdatabaseeng
ine orders values after applying the
WHEREconditionstotherecords.

Field1,Field2 Thenamesofthefieldsonwhichto sortrecords.

Remarks

ORDERBYisoptional.However,ifyouwantyourdatadisplayedinsortedorder,thenyoumustuseOR
DER BY.
Thedefaultsortorder
isascending(AtoZ,0to9).Bothofthefollowingexamplessortemployeenamesinlastname order:
SQLCopy
SELECTLastName,FirstName
FROMEmployees
ORDER BY
LastName;SELECTLastName,
FirstNameFROMEmployees
ORDERBYLastNameASC;

Roll no. -2125920 Page14


MODERNGROUPOFCOLLEGES

To sortindescending order(Zto A,9to 0),addtheDESCreserved wordtotheend ofeach fieldyou want


to sort in descending order. The following example selects salaries and sorts them
indescendingorder:
SQLCopy
SELECTLastName,Salary
FROMEmployees
ORDERBYSalaryDESC,LastName;
IfyouspecifyafieldcontainingMemoor OLEObjectdataintheORDERBYclause,
anerroroccurs.The MicrosoftJetdatabase engine doesnotsortonfieldsofthese types.
ORDERBYisusuallythelastiteminanSQLstatement.
YoucanincludeadditionalfieldsintheORDERBYclause.
Recordsaresortedfirstbythefirstfieldlistedafter
ORDERBY.Recordsthathaveequalvaluesinthatfieldarethensortedbythevalueinthe
secondfieldlisted,andsoon.

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

'Selectthe lastnameand firstname valuesfrom


'theEmployeestable,andsortthemindescending'orde
r.
Setrst
=dbs.OpenRecordset("SELECTLastName,"_&"Firs
tName FROMEmployees" _
&"ORDERBYLastNameDESC;")

'PopulatetheRecordset.rs
t.MoveLast

'CallEnumFieldstoprintrecordsetcontents.
EnumFieldsrst,12d

bs.Close

End Sub

Roll no. -2125920 Page15


MODERNGROUPOFCOLLEGES

Roll no. -2125920 Page16


MODERNGROUPOFCOLLEGES

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.

Indeclarepart,wedeclarevariablesandbetween beginand endpart,weperformtheoperations.

Here, first,wetakethreevariables x,y, andzandassignthevalueinxandyandafter


additionofboththenumbers,weassignthe resultantvalue tozandprintz.

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;

Assigning sum of x and y into


zz:=x+y;
Printthe
Resultdbms_output.put_line('Sum
is '||z);end;
/
Program

EndOutput

Roll no. -2125920 Page17


MODERNGROUPOFCOLLEGES
:Sumis 30

Roll no. -2125920 Page18


MODERNGROUPOFCOLLEGES

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

Roll no. -2125920 Page20


MODERNGROUPOFCOLLEGES

||
x);E
ND;
endofProgram

Output:
Sum: 20
Timecomplexity=O(n)

Anefficientsolutionistousedirectformula n(n+1)(n+2)/6

Mathematically,weneed tofind,Σ((i* (i+1))/2),where1 <=i<=nSo,lets


solvethissummation,
Sum=Σ((i*(i+1))/2),where1<=i<=n
=(1/2) *Σ(i*(i+1))
=(1/2)*Σ(i2+i)
=(1/2)* (Σi2 +Σi)
Weknow Σ i2= n*(n+ 1)*(2*n+ 1)/6andΣ
i=n*(n+1)/2.
Substitutingthevalue, weget,
Sum=(1/2)*((n*(n+1) *(2*n+1)/6)+(n*(n+1)/2))
=n*(n+1)/2[(2n+1)/6+1/2]
=n*(n+1)*(n+2)/6
Belowistherequiredimplementation:D
eclarationsection
DECLARE
x
NUMBER;n
NUMBER;
Utilityfunction
FUNCTIONFindmax(nINNUMBER)R
ETURN NUMBER
IS
z
NUMBER;B
EGIN
Formulaforfindingsum
z
:=(n*(n+1)*(n+2))/6;RETUR
N z;
END;B
EGINn
:=4;
x :=
findmax(n);dbms_output.Put_
line('Sum:'
||
Roll no. -2125920 Page21
MODERNGROUPOFCOLLEGES
x);E
ND;
Endofprogram

Output:sum20

Roll no. -2125920 Page22


MODERNGROUPOFCOLLEGES

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

iv. BOOKCOPIES(Bookid,Branchid, NoofCopies)


create table
book_copiesbook_idintn
otnull,branch_idintnotnul
l,no_of_copiesintnotnull,
primarykey(book_id)
);

v. BOOK_LENDING(Book_id,Branch_id,Card_No,Date_Out,Due_Date)

Roll no. -2125920 Page23


MODERNGROUPOFCOLLEGES
createtablebook_lending(

Roll no. -2125920 Page24


MODERNGROUPOFCOLLEGES

book_id int not


null,branch_id int not
null,card_nointnotnull
,date_out date not
null,due_datedatenotn
ull,primarykey(book_i
d)
);
vi. LIBRARY_BRANCH(Branch_id,Branch_Name,Address)

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

Roll no. -2125920 Page26


MODERNGROUPOFCOLLEGES

insert into book_copies(book_id, branch_id, no_of_copies)values(4444, 33,


10);insert into book_copies(book_id, branch_id, no_of_copies)values(2222, 11,
12);insertintobook_copies(book_id,branch_id,no_of_copies)values(4444,55,3);

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

Roll no. -2125920 Page27

You might also like