Вы находитесь на странице: 1из 2

DataModification

MySQL:
INSERTINTO__VALUES__
DISTINCT(toremoveduplicates)
DELETEFROMRWHERE__
%=anystring
UPDATERSET__WHERE
_=onecharacter
ExpressivepowerofSQL
Setoperators:
limitedexpressivepower
INTERSECT,UNION,EXCEPT
doesnotsupportrecursionandcannot
sameschemaforoperands
computetransitiveclosure
basedonsetsemantics
keepduplicateswithALL
Subqueries:
DatabaseIntegrity
canrewritethemaslongaswedonthave Datavalidityenforcement
negation
Domain:GPAisreal
withnegation,weneedEXCEPT
Constraints:giveerror,abortstate.
Setmembership(IN,NOTIN)
key,referentialintegrity,CHECK
aINRisTRUEisaisinR
constraint,SQLassertions
Setcomparision(>ALL,<SOME,)
trigger:EventConditionAction
KeyConstraints
ALLis ,SOMEis
<>ALL NOTIN,=SOME INoneprimarykeypertable
ReferentialIntegrity
EXISTSandCorrelatedsubqueries
correlatedouterquerylooks1tupleatatimemeansreferencedvalalwaysexists
referencingattributeorforeignkey
andbindsthetupletoS
foreachS,weexecutetheinnerqueryand referencedattribute
foreignkeycanbeNULL,whenitis,no
checkcondition
constraintchecking
thisisjustinterpretation
referencedmustbePRIMARYor
SubqueriesinFROMclause
UNIQUE
consideredasaregularrelation
maybeomittediftheyarethesamename
mustberenamedinside
withreferencingattri.
Aggregates
RIviolationbyinsertingintoreferencing
SUM,AVG,COUNT,MIN,MAX
tableisnotallowed
COUNT(*)countstuples(NULLs)
systemrejectsthestatement
GROUPBYduplicatesareremoved
ONDELETE[SETNULL,CASCADE,
HAVINGusedwithaggregates
SETDEFAULT]
ORDERBY[ASC/DESC]
ONUPDATE[^same]
Set:noduplicatetuples(eliminated)
defaultASC,usedforlooks
Bag:allowedduplicates
Order(bycomputer):FROM>WHERE> CHECK
GROUPBY>HAVING>ORDERBY> constraintcheckedwhentupleisupdated
(orinserted)
SELECT
SELECT (columns)
inSQL92,canbecomplex
NULL
PROJECT (rows)
aggregatesarecomputedignoringNULL, SQLAssertion
CROSSPRODUCT
entiresetofrelationsordatabase
exceptCOUNT(*)
NATURALJOIN (eqofshared ifinputtoanaggregateisempty,COUNT CREATEASSERTION<name>
CHECK(<condition>)
attr)
returns0,allothersreturnNULL
Trigger
THETAJOIN C =>
Setoperators( , ,
EventConditionAction
NULListreatedlikeothervalueshere
R C T = C (R T )
CREATETRIGGER<name>
checkNULL:ISNULL,ISNOTNULL
event[AFTERINSERT]
RENAME S (R)
Arithmeticopsandcomps
<referencingclause>//optional
=renameRtoS
forNULLs,UNKNOWN,onlytruevalues
WHEN(<condition>)//optional
'
returned
<action>
Threevaluedlogic:
<event>
A 1' , A 2
Truthtable:

forR(A1,A2)
*BEFORE|AFTERINSERT/DELETE/

AND:U&T=U,U&F=F,U&U=U
UPDATE[OFA1]ONR
S
OR:U|T=T,U|F=U,U|U=U
<action>

SQLandbagsemantics
*Mutiplestatements:BEGIN/END
renameR(A1,A2)toS(A1,A2)
everythingusesbagexceptsetopers
<referencingclause>
rulesforbag:
UNION schemasofR&S
*REFERENCINGOLD|NEWTABLE|
underbag, R S=S R (for ROWAS<var>,

same(userenametobethesame),no
duplicatesinresult
too)
*FOREACHROW:rowleveltrigger
DIFFERENCE :schemas
R (S T ) (R S )(R T ) *FOREACHSTATEMENT(default)
mustmatchexactly
OUTERJoin
INTERSECT :
preservesdanglingtuples
RLEFT/RIGHT/FULLOUTERJOINSON
R S=R( RS )
R.A=S.A
DIVISION
keepdanglingfrom:(RbypaddingSw/
*assumeR(A,B)andS(B)
NULL/SbypaddingRw/NULL/bothRand
*setofalla R.Asuchthat
S)
a ,b R forevery b S
*R/S=

RelationalModel:
relations=tables
attributes=columns
tuples=rows
domain=type
SQLTypes:
char(n)fixedlength
varchar(n)varlenght
integer32bit
decimal(5,2)999.99
real,double32bit,64bit
date20020115
time13:50:00
timestamp2002011513:50:00
Tables:
oneprimarykeypertable
UNIQUEforotherkeys
SQL92:noNULLinprimary
DEFAULTfordefault
LoadingData:
LOADDATAINFILE<datafile>
INTOTABLE<table>
Terms:
Datamodel=graph/treemodel
Schema=tabledesign/structure
Instance=data
Databaseconstructionsteps:
1.domainanalysis
2.databasedesign:E/Rmodel,
databasedesigntheory
3.tablecreation:DDL
4.load
5.queryandupdate:DML
RelationalAlgebra:

ViewsandAuthorization
Views
CREATEVIEW<name>AS<query>
canbecreatedontopofotherviewsb
*tuplescreatedontheflyusingrealtables
usedtosavecomplicatedtables
*virtualdatabase:views
*conceptualdatabase:tables
*physicaldatabase:pagesondisk
ModifyingViews:
possible,butmustmakesense
*SQL2:attr.OfTnotprojectedinview
allowedtobeNULLordefault,subqueriesin
WHEREmustnotrefertoT,noaggregation
*SELECTstatementcannothave:
ajoinof2ormoretables
anaggregatefunctionorGROUPBYclause
theDISTINCTkeyword(orUNIQUE)
theUNIONkeyword
*WHEREclausemustbeintheSELECT
CHECKOPTION:
*CREATEVIEWASWITHCHECK
OPTION
*checkINSERT/DELETEtoensurenew
tupleisstillinview
*rejectifstatementisnot
DROP[CASCADE|RESTRICT]
(droppingaviewinbetween2tables)
*CASCADEdefault(destroysabove)
*RESTRICT:dropstatementfailsifobjectis
referenced
MaterializedViews
tobemoreefficient
updatesmeanwehavetocreateanew1
refreshiscostly
Authorization
GRANT<privileges>ON<R>TO<users>
[WITHGRANTOPTION]
<privileges>:SELECT,INSERT(separated
bycommas,orALLpriv.)
<R>:table,view
<users>:listofusers/groups,orPUBLIC
Managingprivileges:
DBA(ownsall)
WITHGRANTOPTION
userscangrantthesameorlesspriv.
Authorizationgraph
*nodes:users
*edges:1grantsperm.to2
REVOKE<privileges>on<R>FROM
<users>[CASCADE|RESTRICT]
restrictisdefault
Viewsandprivileges
tocreateaview,userneedsmin.SELECT
privilegeontheunderlyingbasetablesofthe
view
tograntaprivilegeonaview,userhasto
haveGRANTOPTIONprivilegeonthebase
tablesoftheview
whenprivilegesneededforthebasetables
arerevoked,theaffectedviewsare
automaticallydropped

DisksandFiles
Terms:Boom,Head,Sector,Spindle,Track,
Platter,Cylinder
Eachplatterhas:track,cylinder,sector(=block,
page)
Adisk:
Q:2platters,2surfaces/platter,500
tracks/surface,200sect/track,1KB/sector
AccessTime:
=seektime+rotationaldelay+transfer
SeekTime
timetomovediskheadbetweentracks
e.g.timetotrack~1ms,average10ms,full~
20ms,1000sectors:20/1000ms
RotationalDelay
typical:100015kRPM
Q:for6kRPM,averagerotationaldelay
1x60sec/min/(6kRPM)=1/100=>.01sec/2=
5ms
TransferRate
howlongtoreadoneblock
e.g.6KRPM,200sec/track,512B/sec
10ms/rotx1/200=10/200=.05ms
transferrate(bytes/sec)
accesstime:10ms+5ms+.05ms
BurstTransferRate
=(RPM/60)*(sec/track)*(bytes/sect)
SequentialvsRandomI/O
read3seqblocks=3*.05ms=.15ms
3rand.blocks=.05ms(1st),
2*(10ms+5ms+.05ms)=30.15ms
DataModification
bytelevelnotallowed(byblocks)
AbstractionbyOS
seq.blocks:dontneedtoworryabouthead,
cylinder,sector
accesstononadjablocksrand.IO
accesstoadjacentblocks=seqI/O
Buffers,Bufferpool
cachefordiskblocks
Files:MainProblem
howtostorefilesindisk?
SpannedvsUnspanned:
unspannedextraspacewasted
spannedfilllater
unspannedguaranteesfulltupleinside,worst
caseiswaste50%eachblock
VariableLengthTuples
ReservedSpace
reservemaxspaceforeachtuple(problem:
wasteofspace)
VariableLengthSpace
packtuplestightly
endofarecordbyEOR(markatend)
orreadlengthatthebeginning
SlottedPagearrayofpointers
LongTuplesspanningorsplittingtuple
SequentialFiletuplesorderedbycertain
attribute
SequencingTuples2options
rearrange,linkedlist
insertwhenfull?Overflowpage

Index
Dense,PrimaryIndex
dense:1indexentryforeverytuple(key,pointer)pair
foreveryrecord
primary:orderofunderlyingtableissameasindex
(indexonthesearchkey)
e.g.10mrecords(900B/rec),4Bsearchkey,4Bptr,
4KBblock,unspanned
Howmanyblocksfortable(howbig)?
4096/900=4,10Mtuples/(4tuples/blk)=2.5mblocks/
(2.5blk*4KB/blocks)=10GB
e.g.howmanyblocksforindex(howbig)?
8bytes/entry,4096/8=512entr/block,10M/512=
19531.25=19532,19532*4KB=78MB(forindex
alone)
Sparse,PrimaryIndex
sparse:(key,ptr)pairforeveryblock
pointstofirstrecordinblock
MultilevelIndex
sparse(2ndlvl)>1stlvl>sequential
Secondary(nonclustering)Index
whentuplesintablearenotorderedbytheindex
searchkey
firstlevelisalwaysdense,sparsefromthesecond
level
Terms:
searchkey primarykey
Insertion
overflow(anewbucket)
redistribute
TraditionalIndex
advantage:simple,sequentialblocks
disadvantage:badforupdates,uglyovertime
B+Tree
advantage:suitableforupdates,balanced,minspace
usageguarantee
disadvantage:nonsequentialindexblocks
LeafNode:
leftof#pointstotuples,rightptstonextleaf
NonleafNode
leftof#pointstolowerlevel(rightsideis )(at
leasthalfpointersused)
Insertion:simple,leafoverflow,nonleafoverflow,
newroot
nonleafoverflow:split,withnewleafnode,pushit
uptotheroot
Deletion:simple,leaf(coalesce/redistributewith
neighbor),nonleaf,(coalesce/redistributewithneigh.)
redistribute(updatetheparentw/lowestvalue)
n?ndeterminedbysizeofnode/searchkey/indexptr
Q:1024Bnode,10Bkey,8Bptr=>8n+10n10
1024 ,18n 1034,n 57.44,n=57
Remember:
forleavenodemerging,wedeletethemidkeyfrom
theparent
fornonleafnodemerging/redistributing,wepull
downthemidkeyfromparent
NumberofPtrs/Keys:
MaxPtrs

MinKey
s

MinPtrs

MinKeys

nonleaf
nonroot

n1

leaf,non
root
root

n1

n
1
2
(n+1)/2 (n1)/2

n1

n/ 2

Вам также может понравиться