Date post: | 29-Mar-2015 |
Category: |
Documents |
Upload: | roy-basford |
View: | 213 times |
Download: | 0 times |
1Handout 5 CIS 550, Fall 2001
Storage, Indexing and Joins
Slides taken fromDatabase Management
Systems, R. Ramakrishnan
CIS 550 Fall 2000Handout 5
2Handout 5 CIS 550, Fall 2001
Disks and Files
DBMS stores information on (“hard”) disks. This has major implications for DBMS design!
– READ: transfer data from disk to main memory (RAM).
– WRITE: transfer data from RAM to disk.– Both are high-cost operations, relative to in-
memory operations, so must be planned carefully!
3Handout 5 CIS 550, Fall 2001
Why Not Store Everything in Main Memory?
Costs too much. $1000 will buy you either 0.5GB of RAM or 50GB of disk today.
Main memory is volatile. We want data to be saved between runs. (Obviously!)
Typical storage hierarchy:– Main memory (RAM) for currently used data.– Disk for the main database (secondary
storage).– Tapes for archiving older versions of the data
(tertiary storage).
4Handout 5 CIS 550, Fall 2001
Disks
Secondary storage device of choice. Main advantage over tapes: random
access vs. sequential. Data is stored and retrieved in units
called disk blocks or pages. Unlike RAM, time to retrieve a disk page
varies depending upon location on disk. – Therefore, relative placement of pages on
disk has major impact on DBMS performance!
5Handout 5 CIS 550, Fall 2001
Components of a Disk
Platters
The platters spin (say, 90rps).
Spindle
The arm assembly is moved in or out to position a head on a desired track. Tracks under heads make a cylinder (imaginary!).
Disk head
Arm movement
Arm assembly
Only one head reads/writes at any one time.
Tracks
Sector
Block size is a multiple of sector size (which is fixed).
6Handout 5 CIS 550, Fall 2001
Accessing a Disk Page
Time to access (read/write) a disk block:– seek time (moving arms to position disk head on track)– rotational delay (waiting for block to rotate under head)– transfer time (actually moving data to/from disk surface)
Seek time and rotational delay dominate.– Seek time varies from about 1 to 20msec– Rotational delay varies from 0 to 10msec– Transfer rate is about 1msec per 4KB page
Key to lower I/O cost: reduce seek/rotation delays! Hardware vs. software solutions?
7Handout 5 CIS 550, Fall 2001
Arranging Pages on Disk
“Next” block concept: – blocks on same track, followed by– blocks on same cylinder, followed by– blocks on adjacent cylinder
Blocks in a file should be arranged sequentially on disk (by “next”), to minimize seek and rotational delay.
For a sequential scan, pre-fetching several pages at a time is a big win!
8Handout 5 CIS 550, Fall 2001
Disk Space Management
Lowest layer of DBMS software manages space on disk.
Higher levels call upon this layer to:– allocate/de-allocate a page– read/write a page
Request for a sequence of pages must be satisfied by allocating the pages sequentially on disk! Higher levels don’t need to know how this is done, or how free space is managed.
9Handout 5 CIS 550, Fall 2001
Buffer Management in a DBMS
Data must be in RAM for DBMS to operate on it! Table of <frame#, pageid> pairs is maintained.
DB
MAIN MEMORY
DISK
disk page
free frame
Page Requests from Higher Levels
BUFFER POOL
choice of frame dictatedby replacement policy
10Handout 5 CIS 550, Fall 2001
When a Page is Requested ...
If requested page is not in pool:– Choose a frame for replacement– If frame is dirty, write it to disk– Read requested page into chosen frame
Pin the page and return its address.
If requests can be predicted (e.g., sequential scans) pages can be pre-fetched several pages at a time!
11Handout 5 CIS 550, Fall 2001
More on Buffer Management
Requestor of page must unpin it, and indicate whether page has been modified: – dirty bit is used for this.
Page in pool may be requested many times, – a pin count is used. A page is a candidate for
replacement iff pin count = 0. CC & recovery may entail additional I/O
when a frame is chosen for replacement.
12Handout 5 CIS 550, Fall 2001
Buffer Replacement Policy
Frame is chosen for replacement by a replacement policy:– Least-recently-used (LRU), Clock, MRU etc.
Policy can have big impact on # of I/O’s; depends on the access pattern.
Sequential flooding: Nasty situation caused by LRU + repeated sequential scans.– # buffer frames < # pages in file means each
page request causes an I/O. MRU much better in this situation (but not in all situations, of course).
13Handout 5 CIS 550, Fall 2001
DBMS vs. OS File System
OS does disk space & buffer management: why not let OS manage these tasks?
Differences in OS support: portability issues Some limitations, e.g., files can’t span disks. Buffer management in DBMS requires ability
to:– pin a page in buffer pool, force a page to disk
(important for implementing CC & recovery),– adjust replacement policy, and pre-fetch pages
based on access patterns in typical DB operations.
14Handout 5 CIS 550, Fall 2001
Files of Records
Page or block is OK when doing I/O, but higher levels of DBMS operate on records, and files of records.
FILE: A collection of pages, each containing a collection of records. Must support:– insert/delete/modify record– read a particular record (specified using record
id)– scan all records (possibly with some conditions
on the records to be retrieved)
15Handout 5 CIS 550, Fall 2001
Record Formats: Fixed Length
Information about field types same for all records in a file; stored in system catalogs.
Finding i’th field requires scan of record.
Base address (B)
L1 L2 L3 L4
F1 F2 F3 F4
Address = B+L1+L2
16Handout 5 CIS 550, Fall 2001
Record Formats: Variable Length Two alternative formats (# fields is fixed):
Second offers direct access to i’th field, efficient storage of nulls (special don’t know value); small directory overhead.
4 $ $ $ $
FieldCount
Fields Delimited by Special Symbols
F1 F2 F3 F4
F1 F2 F3 F4
Array of Field Offsets
17Handout 5 CIS 550, Fall 2001
Page Formats: Fixed Length Records
Record id = <page id, slot #>. In first alternative, moving records for free space management changes rid; may not be acceptable.
Slot 1Slot 2
Slot N
. . . . . .
N M10. . .
M ... 3 2 1PACKED UNPACKED, BITMAP
Slot 1Slot 2
Slot N
FreeSpace
Slot M
11
number of records
numberof slots
18Handout 5 CIS 550, Fall 2001
Page Formats: Variable Length Records
Can move records on page without changing rid; so, attractive for fixed-length records too.
Page iRid = (i,N)
Rid = (i,2)
Rid = (i,1)
Pointerto startof freespace
SLOT DIRECTORY
N . . . 2 120 16 24 N
# slots
19Handout 5 CIS 550, Fall 2001
Alternative File OrganizationsMany alternatives exist, each ideal for some
situation, and not so good in others:– Heap files: Suitable when typical access is a file
scan retrieving all records.– Sorted Files: Best if records must be retrieved in
some order, or only a `range’ of records is needed.
– Hashed Files: Good for equality selections. File is a collection of buckets. Bucket =
primary page plus zero or more overflow pages.
Hashing function h: h(r) = bucket in which record r belongs. h looks at only some of the fields of r, called the search fields.
20Handout 5 CIS 550, Fall 2001
Unordered (Heap) Files
Simplest file structure contains records in no particular order.
As file grows and shrinks, disk pages are allocated and de-allocated.
To support record level operations, we must:– keep track of the pages in a file– keep track of free space on pages– keep track of the records on a page
There are many alternatives for keeping track of this.
21Handout 5 CIS 550, Fall 2001
Heap File Implemented as a List
The header page id and Heap file name must be stored someplace.
Each page contains 2 `pointers’ plus data.
HeaderPage
DataPage
DataPage
DataPage
DataPage
DataPage
DataPage Pages with
Free Space
Full Pages
22Handout 5 CIS 550, Fall 2001
Heap File Using a Page Directory
The entry for a page can include the number of free bytes on the page.
The directory is a collection of pages; linked list implementation is just one alternative.– Much smaller than linked list of all heap file pages!
DataPage 1
DataPage 2
DataPage N
HeaderPage
DIRECTORY
23Handout 5 CIS 550, Fall 2001
Analysis of file organizations
We ignore CPU costs for simplicity, and use the following parameters in our cost model:– B: The number of data pages– R: Number of records per page– D: (Average) time to read or write disk page– Measuring number of page I/O’s ignores gains
of pre-fetching blocks of pages; thus, even I/O cost is only approximated.
– Average-case analysis; based on several simplistic assumptions. Good enough to show the overall trends!
24Handout 5 CIS 550, Fall 2001
Assumptions in Our Analysis
Single record insert and delete. Heap Files:
– Equality selection on key; exactly one match.– Insert always at end of file.
Sorted Files:– Files compacted after deletions.– Selections on sort field(s).
Hashed Files:– No overflow buckets, 80% page occupancy.
25Handout 5 CIS 550, Fall 2001
Cost of Operations
HeapFile
Sorted File
HashedFile
Scan all recs BD BD 1.25 BD
Equality Search 0.5 BD D log2B D
Range Search BD D (log2B + # ofpages withmatches)
1.25 BD
Insert 2D Search + BD 2D
Delete Search + D Search + BD 2D
Several assumptions underlie these (rough) estimates!
26Handout 5 CIS 550, Fall 2001
Indexes A Heap file allows us to retrieve records:
– by specifying the rid, or– by scanning all records sequentially
Sometimes, we want to retrieve records by specifying the values in one or more fields, e.g.,– Find all students in the “CS” department– Find all students with a gpa > 3
Indexes are file structures that enable us to answer such value-based queries efficiently.
This will be topic of our next lecture!
27Handout 5 CIS 550, Fall 2001
Indexing
28Handout 5 CIS 550, Fall 2001
Indexes
An index on a file speeds up selections on the search key fields for the index.– Any subset of the fields of a relation can be the
search key for an index on the relation.– Search key is not the same as key (minimal set
of fields that uniquely identify a record in a relation).
An index contains a collection of data entries, and supports efficient retrieval of all data entries k* with a given key value k.
29Handout 5 CIS 550, Fall 2001
Alternatives for Data Entry k* in Index
Three alternatives: Data record with key value k <k, rid of data record with search key value k> <k, list of rids of data records with search key k>
Choice of alternative for data entries is orthogonal to the indexing technique used to locate data entries with a given key value k.– Examples of indexing techniques: B+ trees, hash-
based structures– Typically, index contains auxiliary information that
directs searches to the desired data entries
30Handout 5 CIS 550, Fall 2001
Index Classification
Primary vs. secondary: If search key contains primary key, then called primary index.– Unique index: Search key contains a candidate key.
Clustered vs. unclustered: If order of data records is the same as, or `close to’, order of data entries, then called clustered index.– Alternative 1 implies clustered, but not vice-versa.– A file can be clustered on at most one search key.– Cost of retrieving data records through index varies
greatly based on whether index is clustered or not!
31Handout 5 CIS 550, Fall 2001
Clustered vs. Unclustered Index
Suppose that Alternative (2) is used for data entries, and that the data records are stored in a Heap file.– To build clustered index, first sort the Heap file
(with some free space on each page for future inserts).
– Overflow pages may be needed for inserts. (Thus, order of data recs is `close to’, but not identical to, the sort order.)
Index entries
Data entries
direct search for
(Index File)
(Data file)
Data Records
data entries
Data entries
Data Records
CLUSTERED UNCLUSTERED
32Handout 5 CIS 550, Fall 2001
Index Classification (Cont.)
Dense vs. Sparse: If there is at least one data entry per search key value (in some data record), then dense.– Alternative 1 always
leads to dense index.– Every sparse index is
clustered!– Sparse indexes are
smaller; however, some useful optimizations are based on dense indexes.
Ashby, 25, 3000
Smith, 44, 3000
Ashby
Cass
Smith
22
25
30
40
44
44
50
Sparse Indexon
Name Data File
Dense Indexon
Age
33
Bristow, 30, 2007
Basu, 33, 4003
Cass, 50, 5004
Tracy, 44, 5004
Daniels, 22, 6003
Jones, 40, 6003
33Handout 5 CIS 550, Fall 2001
Range Searches ``Find all students with gpa > 3.0’’
– If data is in sorted file, do binary search to find first such student, then scan to find others.
– Cost of binary search can be quite high. Simple idea: Create an `index’ file.
Can do binary search on (smaller) index file!
Page 1 Page 2 Page NPage 3 Data File
k2 kNk1 Index File
34Handout 5 CIS 550, Fall 2001
ISAM
Index file may still be quite large. But we can apply the idea repeatedly!
Leaf pages contain data entries.
P0
K1 P
1K 2 P
2K m
P m
index entry
Non-leaf
Pages
Pages
Overflow page
Primary pages
Leaf
35Handout 5 CIS 550, Fall 2001
Comments on ISAM
File creation: Leaf (data) pages allocated sequentially, sorted by search key; then index pages allocated, then space for overflow pages.
Index entries: <search key value, page id>; they `direct’ search for data entries, which are in leaf pages.
Search: Start at root; use key comparisons to go to leaf. Cost log F N ; F = # entries/index pg, N = # leaf pgs
Insert: Find leaf data entry belongs to, and put it there. Delete: Find and remove from leaf; if empty overflow
page, de-allocate.
Static tree structure: inserts/deletes affect only leaf pages.
Data Pages
Index Pages
Overflow pages
36Handout 5 CIS 550, Fall 2001
Example ISAM Tree
Each node can hold 2 entries; no need for `next-leaf-page’ pointers. (Why?)
10* 15* 20* 27* 33* 37* 40* 46* 51* 55* 63* 97*
20 33 51 63
40
Root
37Handout 5 CIS 550, Fall 2001
After Inserting 23*, 48*, 41*, 42* ...
10* 15* 20* 27* 33* 37* 40* 46* 51* 55* 63* 97*
20 33 51 63
40
Root
23* 48* 41*
42*
Overflow
Pages
Leaf
Index
Pages
Pages
Primary
38Handout 5 CIS 550, Fall 2001
... Then Deleting 42*, 51*, 97*
Note that 51* appears in index levels, but not in leaf!
10* 15* 20* 27* 33* 37* 40* 46* 55* 63*
20 33 51 63
40
Root
23* 48* 41*
39Handout 5 CIS 550, Fall 2001
B+ Tree: The Most Widely Used Index
Insert/delete at log F N cost; keep tree height-balanced. (F = fanout, N = # leaf pages)
Minimum 50% occupancy (except for root). Each node contains d <= m <= 2d entries. The parameter d is called the order of the tree.
Supports equality and range-searches efficiently.
Index Entries
Data Entries("Sequence set")
(Direct search)
40Handout 5 CIS 550, Fall 2001
Example B+ Tree
Search begins at root, and key comparisons direct it to a leaf.
Search for 5*, 15*, all data entries >= 24* ...
Based on the search for 15*, we know it is not in the tree!
Root
17 24 30
2* 3* 5* 7* 14* 16* 19* 20* 22* 24* 27* 29* 33* 34* 38* 39*
13
41Handout 5 CIS 550, Fall 2001
Inserting a Data Entry into a B+ Tree Find correct leaf L. Put data entry onto L.
– If L has enough space, done!– Else, must split L (into L and a new node L2)
Redistribute entries evenly, copy up middle key. Insert index entry pointing to L2 into parent of L.
This can happen recursively– To split index node, redistribute entries evenly, but
push up middle key. (Contrast with leaf splits.) Splits “grow” tree; root split increases height.
– Tree growth: gets wider or one level taller at top.
42Handout 5 CIS 550, Fall 2001
Inserting 8* into Example B+ Tree
Observe how minimum occupancy is guaranteed in both leaf and index pg splits.
Note difference between copy-up and push-up; be sure you understand the reasons for this.
2* 3* 5* 7* 8*
5
Entry to be inserted in parent node.(Note that 5 iscontinues to appear in the leaf.)
s copied up and
appears once in the index. Contrast
5 24 30
17
13
Entry to be inserted in parent node.(Note that 17 is pushed up and only
this with a leaf split.)
43Handout 5 CIS 550, Fall 2001
Example B+ Tree After Inserting 8*
Notice that root was split, leading to increase in height.
In this example, we can avoid split by re-distributing entries; however, this is usually not done in practice.
2* 3*
Root
17
24 30
14* 16* 19* 20* 22* 24* 27* 29* 33* 34* 38* 39*
135
7*5* 8*
44Handout 5 CIS 550, Fall 2001
Deleting a Data Entry from a B+ Tree
Start at root, find leaf L where entry belongs. Remove the entry.
– If L is at least half-full, done! – If L has only d-1 entries,
Try to re-distribute, borrowing from sibling (adjacent node with same parent as L).
If re-distribution fails, merge L and sibling. If merge occurred, must delete entry (pointing to L
or sibling) from parent of L. Merge could propagate to root, decreasing height.
45Handout 5 CIS 550, Fall 2001
Example Tree After (Inserting 8*, Then) Deleting 19* and 20* ...
Deleting 19* is easy. Deleting 20* is done with re-distribution.
Notice how middle key is copied up.
2* 3*
Root
17
30
14* 16* 33* 34* 38* 39*
135
7*5* 8* 22* 24*
27
27* 29*
46Handout 5 CIS 550, Fall 2001
... And Then Deleting 24*
Must merge. Observe `toss’ of
index entry (on right), and `pull down’ of index entry (below).
30
22* 27* 29* 33* 34* 38* 39*
2* 3* 7* 14* 16* 22* 27* 29* 33* 34* 38* 39*5* 8*
Root30135 17
47Handout 5 CIS 550, Fall 2001
Example of Non-leaf Re-distribution
Tree is shown below during deletion of 24*. (What could be a possible initial tree?)
In contrast to previous example, can re-distribute entry from left child of root to right child.
Root
135 17 20
22
30
14* 16* 17* 18* 20* 33* 34* 38* 39*22* 27* 29*21*7*5* 8*3*2*
48Handout 5 CIS 550, Fall 2001
After Re-distribution
Intuitively, entries are re-distributed by `pushing through’ the splitting entry in the parent node.
It suffices to re-distribute index entry with key 20; we’ve re-distributed 17 as well for illustration.
14* 16* 33* 34* 38* 39*22* 27* 29*17* 18* 20* 21*7*5* 8*2* 3*
Root
135
17
3020 22
49Handout 5 CIS 550, Fall 2001
B+ Trees in Practice
Typical order: 100. Typical fill-factor: 67%.– average fanout = 133
Typical capacities:– Height 4: 1334 = 312,900,700 records– Height 3: 1333 = 2,352,637 records
Can often hold top levels in buffer pool:– Level 1 = 1 page = 8 Kbytes– Level 2 = 133 pages = 1 Mbyte– Level 3 = 17,689 pages = 133 MBytes
50Handout 5 CIS 550, Fall 2001
Bulk Loading of a B+ Tree If we have a large collection of records,
and we want to create a B+ tree on some field, doing so by repeatedly inserting records is very slow.
Bulk Loading can be done much more efficiently.
Initialization: Sort all data entries, insert pointer to first (leaf) page in a new (root) page.
3* 4* 6* 9* 10* 11* 12* 13* 20* 22* 23* 31* 35* 36* 38* 41* 44*
Sorted pages of data entries; not yet in B+ treeRoot
51Handout 5 CIS 550, Fall 2001
Bulk Loading (Contd.)
Index entries for leaf pages always entered into right-most index page just above leaf level. When this fills up, it splits. (Split may go up right-most path to the root.)
Much faster than repeated inserts, especially when one considers locking!
3* 4* 6* 9* 10*11* 12*13* 20*22* 23* 31* 35*36* 38*41* 44*
Root
Data entry pages
not yet in B+ tree3523126
10 20
3* 4* 6* 9* 10* 11* 12*13* 20*22* 23* 31* 35*36* 38*41* 44*
6
Root
10
12 23
20
35
38
not yet in B+ treeData entry pages
52Handout 5 CIS 550, Fall 2001
Summary of Bulk Loading
Option 1: multiple inserts.– Slow.– Does not give sequential storage of leaves.
Option 2: Bulk Loading – Has advantages for concurrency control.– Fewer I/Os during build.– Leaves will be stored sequentially (and
linked, of course).– Can control “fill factor” on pages.
53Handout 5 CIS 550, Fall 2001
Summary
Many alternative file organizations exist, each appropriate in some situation.
If selection queries are frequent, sorting the file or building an index is important.– Hash-based indexes only good for equality search.– Sorted files and tree-based indexes best for range
search; also good for equality search. (Files rarely kept sorted in practice; B+ tree index is better.)
Index is a collection of data entries plus a way to quickly find entries with given key values.
54Handout 5 CIS 550, Fall 2001
Summary (cont.)
Data entries can be actual data records, <key, rid> pairs, or <key, rid-list> pairs.– Choice orthogonal to indexing technique used to
locate data entries with a given key value. Can have several indexes on a given file of
data records, each with a different search key. Indexes can be classified as clustered vs.
unclustered, primary vs. secondary, and dense vs. sparse. Differences have important consequences for utility/performance.
55Handout 5 CIS 550, Fall 2001
Summary (cont.)
Tree-structured indexes are ideal for range-searches, also good for equality searches.
ISAM is a static structure.– Only leaf pages modified; overflow pages needed.– Overflow chains can degrade performance unless
size of data set and data distribution stay constant. B+ tree is a dynamic structure.
– Inserts/deletes leave tree height-balanced; log F N cost.
– High fanout (F) means depth rarely more than 3 or 4.– Almost always better than maintaining a sorted file.
56Handout 5 CIS 550, Fall 2001
Implementation of Relational Operations
57Handout 5 CIS 550, Fall 2001
Relational Operations
We will consider how to implement:– Selection ( ) Selects a subset of rows from
relation.– Projection ( ) Deletes unwanted columns from
relation.– Join ( ) Allows us to combine two relations.– Set-difference ( ) Tuples in reln. 1, but not in
reln. 2.– Union ( ) Tuples in reln. 1 and in reln. 2.– Aggregation (SUM, MIN, etc.) and GROUP BY
58Handout 5 CIS 550, Fall 2001
Schema for Examples
Reserves:– Each tuple is 40 bytes long, 100 tuples per page,
1000 pages. Sailors:
– Each tuple is 50 bytes long, 80 tuples per page, 500 pages.
Sailors (sid: integer, sname: string, rating: integer, age: real)Reserves (sid: integer, bid: integer, day: dates, rname: string)
59Handout 5 CIS 550, Fall 2001
Equality Joins With One Join Column
In algebra: R S. Common! Must be carefully optimized. R S is large; so, R S followed by a selection is inefficient.
Assume: M pages in R, pR tuples per page, N pages in S, pS tuples per page.– In our examples, R is Reserves and S is Sailors.
We will consider more complex join conditions later. Cost metric: # of I/Os. We will ignore output costs.
SELECT *FROM Reserves R1, Sailors S1WHERE R1.sid=S1.sid
60Handout 5 CIS 550, Fall 2001
Simple Nested Loops Join
For each tuple in the outer relation R, we scan the entire inner relation S. – Cost: M + (pR * M) * N = 1000 + 100*1000*500 I/Os (a lot!)
Page-oriented Nested Loops join: For each page of R, get each page of S, and write out matching pairs of tuples <r, s>, where r is in R-page and S is in S-page.– Cost: M + M*N = 1000 + 1000*500= 501,000– If smaller relation (S) is outer, cost = 500 + 500*1000 =
500,500
foreach tuple r in R doforeach tuple s in S do
if ri == sj then add <r, s> to result
61Handout 5 CIS 550, Fall 2001
Block Nested Loops Join Use one page as an input buffer for scanning the
inner S, one page as the output buffer, and use all remaining pages to hold “block’’ of outer R.– For each matching tuple r in R-block, s in S-page, add
<r, s> to result. Then read next R-block, scan S, etc.
. . .
. . .
R & SHash table for block of R
(k < B-1 pages)
Input buffer for S Output buffer
. . .
Join Result
62Handout 5 CIS 550, Fall 2001
Examples of Block Nested Loops
Cost: Scan of outer + #outer blocks * scan of inner– #outer blocks =
With Reserves (R) as outer, and blocksize=100 :– Cost of scanning R is 1000 I/Os; a total of 10
blocks.– Per block of R, we scan Sailors (S); 10*500 I/Os.– TOTAL: 6,000 I/Os
With 100-page block of Sailors as outer:– Cost of scanning S is 500 I/Os; a total of 5 blocks.– Per block of S, we scan Reserves; 5*1000 I/Os.– TOTAL: 5,500 I/Os
# /of pages of outer blocksize
63Handout 5 CIS 550, Fall 2001
Index Nested Loops Join
If there is an index on the join column of one relation (say S), can make it the inner and exploit the index.– Cost: M + ( (M*pR) * cost of finding matching S tuples)
For each R tuple, cost of probing S index is about 1.2 for hash index, 2-4 for B+ tree. Cost of then finding S tuples depends on clustering.– Clustered index: 1 I/O (typical), unclustered: up to 1
I/O per matching S tuple.
foreach tuple r in R doforeach tuple s in S where ri == sj do
add <r, s> to result
64Handout 5 CIS 550, Fall 2001
Examples of Index Nested Loops
Hash-index on sid of Sailors (as inner):– Scan Reserves: 1000 page I/Os, 100*1000 tuples.– For each Reserves tuple: 1.2 I/Os to get data
entry in index, plus 1 I/O to get (the exactly one) matching Sailors tuple. Total: 221,000 I/Os.
Hash-index on sid of Reserves (as inner):– Scan Sailors: 500 page I/Os, 80*500 tuples.– For each Sailors tuple: 1.2 I/Os to find index page
with data entries, plus cost of retrieving matching Reserves tuples. Assuming uniform distribution, 2.5 reservations per sailor. Cost of retrieving them is 1 or 2.5 I/Os depending on whether the index is clustered. Total: 500 + 40,000(1.2+2.5)= 148,500
65Handout 5 CIS 550, Fall 2001
Sort-Merge Join (R S)
Sort R and S on the join column, then scan them to do a “merge’’ (on join column), and output result tuples.
R is scanned once; each S group is scanned once per matching R tuple. (Multiple scans of an S group are likely to find needed pages in buffer.)
i=j
66Handout 5 CIS 550, Fall 2001
Example of Sort-Merge Join
Cost: M log M + N log N + (M+N)– The cost of scanning, M+N, could be M*N (very unlikely!)
With 35, 100 or 300 buffer pages, both Reserves and Sailors can be sorted in 2 passes; total join cost: 7500.
sid sname rating age22 dustin 7 45.028 yuppy 9 35.031 lubber 8 55.544 guppy 5 35.058 rusty 10 35.0
sid bid day rname
28 103 12/4/96 guppy28 103 11/3/96 yuppy31 101 10/10/96 dustin31 102 10/12/96 lubber31 101 10/11/96 lubber58 103 11/12/96 dustin
(BNL cost: 2500 to 15000 I/Os)
67Handout 5 CIS 550, Fall 2001
Hash-Join Partition both
relations using hash fn h: R tuples in partition i will only match S tuples in partition i.
Read in a partition of R, hash it using h2 (<> h!). Scan matching partition of S, search for matches.
Partitionsof R & S
Input bufferfor Si
Hash table for partitionRi (k < B-1 pages)
B main memory buffersDisk
Output buffer
Disk
Join Result
hashfnh2
h2
B main memory buffers DiskDisk
Original Relation OUTPUT
2INPUT
1
hashfunction
h B-1
Partitions
1
2
B-1
. . .
68Handout 5 CIS 550, Fall 2001
Observations on Hash-Join
#partitions k < B-1 (why?), and B-2 > size of largest partition to be held in memory. Assuming uniformly sized partitions, and maximizing k, we get:– k= B-1, and M/(B-1) < B-2, i.e., B must be >
If we build an in-memory hash table to speed up the matching of tuples, a little more memory is needed.
If the hash function does not partition uniformly, one or more R partitions may not fit in memory. Can apply hash-join technique recursively to do the join of this R-partition with corresponding S-partition.
M
69Handout 5 CIS 550, Fall 2001
Cost of Hash-Join
In partitioning phase, read+write both relns; 2(M+N). In matching phase, read both relns; M+N I/Os.
In our running example, this is a total of 4500 I/Os.
Sort-Merge Join vs. Hash Join:– Given a minimum amount of memory (what is this,
for each?) both have a cost of 3(M+N) I/Os. Hash Join superior on this count if relation sizes differ greatly. Also, Hash Join shown to be highly parallelizable.
– Sort-Merge less sensitive to data skew; result is sorted.
70Handout 5 CIS 550, Fall 2001
General Join Conditions Equalities over several attributes (e.g.,
R.sid=S.sid AND R.rname=S.sname):– For Index NL, build index on <sid, sname> (if S is
inner); or use existing indexes on sid or sname.– For Sort-Merge and Hash Join, sort/partition on
combination of the two join columns. Inequality conditions (e.g., R.rname < S.sname):
– For Index NL, need (clustered!) B+ tree index. Range probes on inner; # matches likely to be much higher
than for equality joins.
– Hash Join, Sort Merge Join not applicable.– Block NL quite likely to be the best join method here.
71Handout 5 CIS 550, Fall 2001
Simple Selections
Of the form Size of result approximated as size of R *
reduction factor. With no index, unsorted: Must essentially
scan the whole relation; cost is M (#pages in R).
With an index on selection attribute: Use index to find qualifying data entries, then retrieve corresponding data records. (Hash index useful only for equality selections.)
SELECT *FROM Reserves RWHERE R.rname < ‘C%’
R attr valueop R. ( )
72Handout 5 CIS 550, Fall 2001
Using an Index for Selections
Cost depends on #qualifying tuples, and clustering.– Cost of finding qualifying data entries (typically small) plus cost
of retrieving records (could be large w/o clustering).– In example, assuming uniform distribution of names, about
10% of tuples qualify (100 pages, 10000 tuples). With a clustered index, cost is little more than 100 I/Os; if unclustered, up to 10000 I/Os!
Important refinement for unclustered indexes: 1. Find qualifying data entries.2. Sort the rid’s of the data records to be retrieved.3. Fetch rids in order. This ensures that each data page is looked
at just once (though # of such pages likely to be higher than with clustering).
73Handout 5 CIS 550, Fall 2001
General Selection Conditions
Such selection conditions are first converted to conjunctive normal form (CNF): (day<8/9/94 OR bid=5 OR sid=3 ) AND (rname=‘Paul’ OR bid=5 OR sid=3)
We only discuss the case with no ORs (a conjunction of terms of the form attr op value).
An index matches (a conjunction of) terms that involve only attributes in a prefix of the search key.– Index on <a, b, c> matches a=5 AND b= 3, but not
b=3.
(day<8/9/94 AND rname=‘Paul’) OR bid=5 OR sid=3
74Handout 5 CIS 550, Fall 2001
Two Approaches to General Selections
First approach: Find the most selective access path, retrieve tuples using it, and apply any remaining terms that don’t match the index:– Most selective access path: An index or file scan that we
estimate will require the fewest page I/Os.– Terms that match this index reduce the number of tuples
retrieved; other terms are used to discard some retrieved tuples, but do not affect number of tuples/pages fetched.
– Consider day<8/9/94 AND bid=5 AND sid=3. A B+ tree index on day can be used; then, bid=5 and sid=3 must be checked for each retrieved tuple. Similarly, a hash index on <bid, sid> could be used; day<8/9/94 must then be checked.
75Handout 5 CIS 550, Fall 2001
Intersection of Rids Second approach (if we have 2 or more matching
indexes that use Alternatives (2) or (3) for data entries):– Get sets of rids of data records using each matching
index.– Then intersect these sets of rids (we’ll discuss
intersection soon!)– Retrieve the records and apply any remaining terms.– Consider day<8/9/94 AND bid=5 AND sid=3. If we have
a B+ tree index on day and an index on sid, both using Alternative (2), we can retrieve rids of records satisfying day<8/9/94 using the first, rids of recs satisfying sid=3 using the second, intersect, retrieve records and check bid=5.
76Handout 5 CIS 550, Fall 2001
The Projection Operation
An approach based on sorting:– Eliminate unwanted fields in first pass of external
sort. Thus, runs of about 2B pages are produced, but tuples in runs are smaller than input tuples. (Size ratio depends on # and size of fields that are dropped.)
– Modify merging passes to eliminate duplicates. Thus, number of result tuples smaller than input. (Difference depends on # of duplicates.)
– Cost: In first pass, read original relation (size M), write out same number of smaller tuples. In merging passes, fewer tuples written out in each pass. Using Reserves example, 1000 input pages reduced to 250 in first pass if size ratio is 0.25
SELECT DISTINCT R.sid, R.bidFROM Reserves R
77Handout 5 CIS 550, Fall 2001
Discussion of Projection Sort-based approach is standard; it is often useful
that the result is sorted. There is also an approach based on hashing (see
book). If an index on the relation contains all wanted
attributes in its search key, can do index-only scan.– Apply projection techniques to data entries (much smaller!)
If an ordered (i.e., tree) index contains all wanted attributes as prefix of search key, can do even better:– Retrieve data entries in order (index-only scan), discard
unwanted fields, compare adjacent tuples to check for duplicates.
78Handout 5 CIS 550, Fall 2001
Set Operations
Intersection and cross-product special cases of join.
Union (Distinct) and Except similar; we’ll do union.
Sorting based approach to union:– Sort both relations (on combination of all attributes).– Scan sorted relations and merge them.
Hash based approach to union:– Partition R and S using hash function h.– For each S-partition, build in-memory hash table (using
h2), scan corresponding R-partition and add tuples to table while discarding duplicates.
79Handout 5 CIS 550, Fall 2001
Aggregate Operations (AVG, MIN, etc.)
Without grouping:– In general, requires scanning the relation.– Given index whose search key includes all attributes in the
SELECT or WHERE clauses, can do index-only scan. With grouping:
– Sort on group-by attributes, then scan relation and compute aggregate for each group. (Can improve upon this by combining sorting and aggregate computation.)
– Similar approach based on hashing on group-by attributes.– Given tree index whose search key includes all attributes in
SELECT, WHERE and GROUP BY clauses, can do index-only scan; if group-by attributes form prefix of search key, can retrieve data entries/tuples in group-by order.
80Handout 5 CIS 550, Fall 2001
Summary A virtue of relational DBMSs: queries are
composed of a few basic operators; the implementation of these operators can be carefully tuned (and it is important to do this!).
Many alternative implementation techniques for each operator; no universally superior technique for most operators.
Must consider available alternatives for each operation in a query and choose best one based on system statistics, etc. This is part of the broader task of optimizing a query composed of several ops.