Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Handout 5CIS 550, Fall 2001 Storage, Indexing and Joins Slides taken from Database Management Systems, R. Ramakrishnan CIS 550 Fall 2000 Handout 5.

Similar presentations

Presentation on theme: "1 Handout 5CIS 550, Fall 2001 Storage, Indexing and Joins Slides taken from Database Management Systems, R. Ramakrishnan CIS 550 Fall 2000 Handout 5."— Presentation transcript:

1 1 Handout 5CIS 550, Fall 2001 Storage, Indexing and Joins Slides taken from Database Management Systems, R. Ramakrishnan CIS 550 Fall 2000 Handout 5

2 2 CIS 550, Fall 2001 Disks and Files v DBMS stores information on (hard) disks. v 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!

3 3 Handout 5CIS 550, Fall 2001 Why Not Store Everything in Main Memory? v Costs too much. $1000 will buy you either 0.5GB of RAM or 50GB of disk today. v Main memory is volatile. We want data to be saved between runs. (Obviously!) v 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).

4 4 Handout 5CIS 550, Fall 2001 Disks v Secondary storage device of choice. v Main advantage over tapes: random access vs. sequential. v Data is stored and retrieved in units called disk blocks or pages. v 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!

5 5 Handout 5CIS 550, Fall 2001 Components of a Disk Platters v The platters spin (say, 90rps). Spindle v 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 v Only one head reads/writes at any one time. Tracks Sector v Block size is a multiple of sector size (which is fixed).

6 6 Handout 5CIS 550, Fall 2001 Accessing a Disk Page v 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 ) v 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 v Key to lower I/O cost: reduce seek/rotation delays! Hardware vs. software solutions?

7 7 Handout 5CIS 550, Fall 2001 Arranging Pages on Disk v Next block concept: –blocks on same track, followed by –blocks on same cylinder, followed by –blocks on adjacent cylinder v Blocks in a file should be arranged sequentially on disk (by next), to minimize seek and rotational delay. v For a sequential scan, pre-fetching several pages at a time is a big win!

8 8 Handout 5CIS 550, Fall 2001 Disk Space Management v Lowest layer of DBMS software manages space on disk. v Higher levels call upon this layer to: –allocate/de-allocate a page –read/write a page v Request for a sequence of pages must be satisfied by allocating the pages sequentially on disk! Higher levels dont need to know how this is done, or how free space is managed.

9 9 Handout 5CIS 550, Fall 2001 Buffer Management in a DBMS v Data must be in RAM for DBMS to operate on it! v Table of pairs is maintained. DB MAIN MEMORY DISK disk page free frame Page Requests from Higher Levels BUFFER POOL choice of frame dictated by replacement policy

10 10 Handout 5CIS 550, Fall 2001 When a Page is Requested... v 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 v 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!

11 11 Handout 5CIS 550, Fall 2001 More on Buffer Management v Requestor of page must unpin it, and indicate whether page has been modified: – dirty bit is used for this. v Page in pool may be requested many times, –a pin count is used. A page is a candidate for replacement iff pin count = 0. v CC & recovery may entail additional I/O when a frame is chosen for replacement.

12 12 Handout 5CIS 550, Fall 2001 Buffer Replacement Policy v Frame is chosen for replacement by a replacement policy: –Least-recently-used (LRU), Clock, MRU etc. v Policy can have big impact on # of I/Os; depends on the access pattern. v 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).

13 13 Handout 5CIS 550, Fall 2001 DBMS vs. OS File System OS does disk space & buffer management: why not let OS manage these tasks? v Differences in OS support: portability issues v Some limitations, e.g., files cant span disks. v 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.

14 14 Handout 5CIS 550, Fall 2001 Files of Records v Page or block is OK when doing I/O, but higher levels of DBMS operate on records, and files of records. v 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)

15 15 Handout 5CIS 550, Fall 2001 Record Formats: Fixed Length v Information about field types same for all records in a file; stored in system catalogs. v Finding ith field requires scan of record. Base address (B) L1L2L3L4 F1F2F3F4 Address = B+L1+L2

16 16 Handout 5CIS 550, Fall 2001 Record Formats: Variable Length v Two alternative formats (# fields is fixed): * Second offers direct access to ith field, efficient storage of nulls (special dont know value); small directory overhead. 4$$$$ Field Count Fields Delimited by Special Symbols F1 F2 F3 F4 Array of Field Offsets

17 17 Handout 5CIS 550, Fall 2001 Page Formats: Fixed Length Records * Record id =. In first alternative, moving records for free space management changes rid; may not be acceptable. Slot 1 Slot 2 Slot N... N M1 0 M... 3 2 1 PACKED UNPACKED, BITMAP Slot 1 Slot 2 Slot N Free Space Slot M 11 number of records number of slots

18 18 Handout 5CIS 550, Fall 2001 Page Formats: Variable Length Records * Can move records on page without changing rid; so, attractive for fixed-length records too. Page i Rid = (i,N) Rid = (i,2) Rid = (i,1) Pointer to start of free space SLOT DIRECTORY N... 2 1 201624 N # slots

19 19 Handout 5CIS 550, Fall 2001 Alternative File Organizations Many 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. u File is a collection of buckets. Bucket = primary page plus zero or more overflow pages. u 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.

20 20 Handout 5CIS 550, Fall 2001 Unordered (Heap) Files v Simplest file structure contains records in no particular order. v As file grows and shrinks, disk pages are allocated and de-allocated. v 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 v There are many alternatives for keeping track of this.

21 21 Handout 5CIS 550, Fall 2001 Heap File Implemented as a List v The header page id and Heap file name must be stored someplace. v Each page contains 2 `pointers plus data. Header Page Data Page Data Page Data Page Data Page Data Page Data Page Pages with Free Space Full Pages

22 22 Handout 5CIS 550, Fall 2001 Heap File Using a Page Directory v The entry for a page can include the number of free bytes on the page. v The directory is a collection of pages; linked list implementation is just one alternative. – Much smaller than linked list of all heap file pages ! Data Page 1 Data Page 2 Data Page N Header Page DIRECTORY

23 23 Handout 5CIS 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/Os 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!

24 24 Handout 5CIS 550, Fall 2001 Assumptions in Our Analysis v Single record insert and delete. v Heap Files: –Equality selection on key; exactly one match. –Insert always at end of file. v Sorted Files: –Files compacted after deletions. –Selections on sort field(s). v Hashed Files: –No overflow buckets, 80% page occupancy.

25 25 Handout 5CIS 550, Fall 2001 Cost of Operations * Several assumptions underlie these (rough) estimates!

26 26 Handout 5CIS 550, Fall 2001 Indexes v A Heap file allows us to retrieve records: –by specifying the rid, or –by scanning all records sequentially v 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 v Indexes are file structures that enable us to answer such value-based queries efficiently. v This will be topic of our next lecture!

27 27 Handout 5CIS 550, Fall 2001 Indexing

28 28 Handout 5CIS 550, Fall 2001 Indexes v 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). v An index contains a collection of data entries, and supports efficient retrieval of all data entries k* with a given key value k.

29 29 Handout 5CIS 550, Fall 2001 Alternatives for Data Entry k* in Index v Three alternatives: À Data record with key value k Á Â v 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

30 30 Handout 5CIS 550, Fall 2001 Index Classification v Primary vs. secondary : If search key contains primary key, then called primary index. – Unique index: Search key contains a candidate key. v 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!

31 31 Handout 5CIS 550, Fall 2001 Clustered vs. Unclustered Index v 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

32 32 Handout 5CIS 550, Fall 2001 Index Classification (Cont.) v 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 50 Sparse Index on Name Data File Dense Index on Age 33 Bristow, 30, 2007 Basu, 33, 4003 Cass, 50, 5004 Tracy, 44, 5004 Daniels, 22, 6003 Jones, 40, 6003

33 33 Handout 5CIS 550, Fall 2001 Range Searches v `` 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. v Simple idea: Create an `index file. * Can do binary search on (smaller) index file! Page 1 Page 2 Page N Page 3 Data File k2 kN k1 Index File

34 34 Handout 5CIS 550, Fall 2001 ISAM v Index file may still be quite large. But we can apply the idea repeatedly! * Leaf pages contain data entries. P 0 K 1 P 1 K 2 P 2 K m P m index entry Non-leaf Pages Overflow page Primary pages Leaf

35 35 Handout 5CIS 550, Fall 2001 Comments on ISAM v File creation : Leaf (data) pages allocated sequentially, sorted by search key; then index pages allocated, then space for overflow pages. v Index entries : ; they `direct search for data entries, which are in leaf pages. v Search : Start at root; use key comparisons to go to leaf. Cost log F N ; F = # entries/index pg, N = # leaf pgs v Insert : Find leaf data entry belongs to, and put it there. v 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

36 36 Handout 5CIS 550, Fall 2001 Example ISAM Tree v 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* 20335163 40 Root

37 37 Handout 5CIS 550, Fall 2001 After Inserting 23*, 48*, 41*, 42*... 10*15*20*27*33*37*40* 46* 51* 55* 63* 97* 20335163 40 Root 23* 48* 41* 42* Overflow Pages Leaf Index Pages Primary

38 38 Handout 5CIS 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* 20335163 40 Root 23* 48* 41*

39 39 Handout 5CIS 550, Fall 2001 B+ Tree: The Most Widely Used Index v Insert/delete at log F N cost; keep tree height- balanced. (F = fanout, N = # leaf pages) v Minimum 50% occupancy (except for root). Each node contains d <= m <= 2 d entries. The parameter d is called the order of the tree. v Supports equality and range-searches efficiently. Index Entries Data Entries ("Sequence set") (Direct search)

40 40 Handout 5CIS 550, Fall 2001 Example B+ Tree v Search begins at root, and key comparisons direct it to a leaf. v Search for 5*, 15*, all data entries >= 24*... * Based on the search for 15*, we know it is not in the tree! Root 1724 30 2* 3*5* 7*14*16* 19*20*22*24*27* 29*33*34* 38* 39* 13

41 41 Handout 5CIS 550, Fall 2001 Inserting a Data Entry into a B+ Tree v Find correct leaf L. v Put data entry onto L. –If L has enough space, done ! –Else, must split L (into L and a new node L2) u Redistribute entries evenly, copy up middle key. u Insert index entry pointing to L2 into parent of L. v This can happen recursively –To split index node, redistribute entries evenly, but push up middle key. (Contrast with leaf splits.) v Splits grow tree; root split increases height. –Tree growth: gets wider or one level taller at top.

42 42 Handout 5CIS 550, Fall 2001 Inserting 8* into Example B+ Tree v Observe how minimum occupancy is guaranteed in both leaf and index pg splits. v 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 is continues to appear in the leaf.) s copied up and appears once in the index. Contrast 52430 17 13 Entry to be inserted in parent node. (Note that 17 is pushed up and only this with a leaf split.)

43 43 Handout 5CIS 550, Fall 2001 Example B+ Tree After Inserting 8* v Notice that root was split, leading to increase in height. v 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*

44 44 Handout 5CIS 550, Fall 2001 Deleting a Data Entry from a B+ Tree v Start at root, find leaf L where entry belongs. v Remove the entry. –If L is at least half-full, done! –If L has only d-1 entries, u Try to re-distribute, borrowing from sibling (adjacent node with same parent as L). u If re-distribution fails, merge L and sibling. v If merge occurred, must delete entry (pointing to L or sibling) from parent of L. v Merge could propagate to root, decreasing height.

45 45 Handout 5CIS 550, Fall 2001 Example Tree After (Inserting 8*, Then) Deleting 19* and 20*... v Deleting 19* is easy. v 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*

46 46 Handout 5CIS 550, Fall 2001... And Then Deleting 24* v Must merge. v 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* Root 30 135 17

47 47 Handout 5CIS 550, Fall 2001 Example of Non-leaf Re-distribution v Tree is shown below during deletion of 24*. (What could be a possible initial tree?) v In contrast to previous example, can re-distribute entry from left child of root to right child. Root 135 1720 22 30 14*16* 17*18* 20*33*34* 38* 39* 22*27*29*21* 7*5*8* 3*2*

48 48 Handout 5CIS 550, Fall 2001 After Re-distribution v Intuitively, entries are re-distributed by ` pushing through the splitting entry in the parent node. v It suffices to re-distribute index entry with key 20; weve 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 30 20 22

49 49 Handout 5CIS 550, Fall 2001 B+ Trees in Practice v Typical order: 100. Typical fill-factor: 67%. –average fanout = 133 v Typical capacities: –Height 4: 133 4 = 312,900,700 records –Height 3: 133 3 = 2,352,637 records v 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

50 50 Handout 5CIS 550, Fall 2001 Bulk Loading of a B+ Tree v 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. v Bulk Loading can be done much more efficiently. v 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+ tree Root

51 51 Handout 5CIS 550, Fall 2001 Bulk Loading (Contd.) v 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.) v 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+ tree 3523126 1020 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+ tree Data entry pages

52 52 Handout 5CIS 550, Fall 2001 Summary of Bulk Loading v Option 1: multiple inserts. –Slow. –Does not give sequential storage of leaves. v 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.

53 53 Handout 5CIS 550, Fall 2001 Summary v Many alternative file organizations exist, each appropriate in some situation. v 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.) v Index is a collection of data entries plus a way to quickly find entries with given key values.

54 54 Handout 5CIS 550, Fall 2001 Summary (cont.) v Data entries can be actual data records, pairs, or pairs. –Choice orthogonal to indexing technique used to locate data entries with a given key value. v Can have several indexes on a given file of data records, each with a different search key. v Indexes can be classified as clustered vs. unclustered, primary vs. secondary, and dense vs. sparse. Differences have important consequences for utility/performance.

55 55 Handout 5CIS 550, Fall 2001 Summary (cont.) v Tree-structured indexes are ideal for range- searches, also good for equality searches. v 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. v 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.

56 56 Handout 5CIS 550, Fall 2001 Implementation of Relational Operations

57 57 Handout 5CIS 550, Fall 2001 Relational Operations v 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

58 58 Handout 5CIS 550, Fall 2001 Schema for Examples v Reserves: –Each tuple is 40 bytes long, 100 tuples per page, 1000 pages. v 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)

59 59 Handout 5CIS 550, Fall 2001 Equality Joins With One Join Column v In algebra: R S. Common! Must be carefully optimized. R S is large; so, R S followed by a selection is inefficient. v Assume: M pages in R, p R tuples per page, N pages in S, p S tuples per page. –In our examples, R is Reserves and S is Sailors. v We will consider more complex join conditions later. v Cost metric : # of I/Os. We will ignore output costs. SELECT * FROM Reserves R1, Sailors S1 WHERE R1.sid=S1.sid

60 60 Handout 5CIS 550, Fall 2001 Simple Nested Loops Join v For each tuple in the outer relation R, we scan the entire inner relation S. –Cost: M + (p R * M) * N = 1000 + 100*1000*500 I/Os (a lot!) v Page-oriented Nested Loops join: For each page of R, get each page of S, and write out matching pairs of tuples, 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 do foreach tuple s in S do if r i == s j then add to result

61 61 Handout 5CIS 550, Fall 2001 Block Nested Loops Join v 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 to result. Then read next R-block, scan S, etc.... R & S Hash table for block of R (k < B-1 pages) Input buffer for S Output buffer... Join Result

62 62 Handout 5CIS 550, Fall 2001 Examples of Block Nested Loops v Cost: Scan of outer + #outer blocks * scan of inner –#outer blocks = v 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 v 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

63 63 Handout 5CIS 550, Fall 2001 Index Nested Loops Join v 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*p R ) * cost of finding matching S tuples) v 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 do foreach tuple s in S where r i == s j do add to result

64 64 Handout 5CIS 550, Fall 2001 Examples of Index Nested Loops v 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. v 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

65 65 Handout 5CIS 550, Fall 2001 Sort-Merge Join (R S) v Sort R and S on the join column, then scan them to do a merge (on join column), and output result tuples. v 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

66 66 Handout 5CIS 550, Fall 2001 Example of Sort-Merge Join v Cost: M log M + N log N + (M+N) –The cost of scanning, M+N, could be M*N (very unlikely!) v With 35, 100 or 300 buffer pages, both Reserves and Sailors can be sorted in 2 passes; total join cost: 7500. ( BNL cost: 2500 to 15000 I/Os )

67 67 Handout 5CIS 550, Fall 2001 Hash-Join v Partition both relations using hash fn h : R tuples in partition i will only match S tuples in partition i. v Read in a partition of R, hash it using h2 (<> h!). Scan matching partition of S, search for matches. Partitions of R & S Input buffer for Si Hash table for partition Ri (k < B-1 pages) B main memory buffers Disk Output buffer Disk Join Result hash fn h2 B main memory buffers Disk Original Relation OUTPUT 2 INPUT 1 hash function h B-1 Partitions 1 2 B-1...

68 68 Handout 5CIS 550, Fall 2001 Observations on Hash-Join v #partitions k 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) v If we build an in-memory hash table to speed up the matching of tuples, a little more memory is needed. v 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.

69 69 Handout 5CIS 550, Fall 2001 Cost of Hash-Join v In partitioning phase, read+write both relns; 2(M+N). In matching phase, read both relns; M+N I/Os. v In our running example, this is a total of 4500 I/Os. v 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.

70 70 Handout 5CIS 550, Fall 2001 General Join Conditions v Equalities over several attributes (e.g., R.sid=S.sid AND R.rname=S.sname ): –For Index NL, build index on (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. v Inequality conditions (e.g., R.rname < S.sname ): –For Index NL, need (clustered!) B+ tree index. u 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.

71 71 Handout 5CIS 550, Fall 2001 Simple Selections v Of the form v Size of result approximated as size of R * reduction factor. v With no index, unsorted: Must essentially scan the whole relation; cost is M (#pages in R). v 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 R WHERE R.rname < C%

72 72 Handout 5CIS 550, Fall 2001 Using an Index for Selections v 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! v Important refinement for unclustered indexes : 1. Find qualifying data entries. 2. Sort the rids 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).

73 73 Handout 5CIS 550, Fall 2001 General Selection Conditions v 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) v We only discuss the case with no OR s (a conjunction of terms of the form attr op value ). v An index matches (a conjunction of) terms that involve only attributes in a prefix of the search key. –Index on matches a=5 AND b= 3, but not b=3. * (day<8/9/94 AND rname=Paul) OR bid=5 OR sid=3

74 74 Handout 5CIS 550, Fall 2001 Two Approaches to General Selections v First approach: Find the most selective access path, retrieve tuples using it, and apply any remaining terms that dont 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 could be used; day<8/9/94 must then be checked.

75 75 Handout 5CIS 550, Fall 2001 Intersection of Rids v 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 (well 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.

76 76 Handout 5CIS 550, Fall 2001 The Projection Operation v 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, FROM Reserves R

77 77 Handout 5CIS 550, Fall 2001 Discussion of Projection v Sort-based approach is standard; it is often useful that the result is sorted. v There is also an approach based on hashing (see book). v 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!) v 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.

78 78 Handout 5CIS 550, Fall 2001 Set Operations v Intersection and cross-product special cases of join. v Union (Distinct) and Except similar; well do union. v Sorting based approach to union: –Sort both relations (on combination of all attributes). –Scan sorted relations and merge them. v 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.

79 79 Handout 5CIS 550, Fall 2001 Aggregate Operations ( AVG, MIN, etc.) v 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. v 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.

80 80 Handout 5CIS 550, Fall 2001 Summary v 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!). v Many alternative implementation techniques for each operator; no universally superior technique for most operators. v 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.

Download ppt "1 Handout 5CIS 550, Fall 2001 Storage, Indexing and Joins Slides taken from Database Management Systems, R. Ramakrishnan CIS 550 Fall 2000 Handout 5."

Similar presentations

Ads by Google