0% found this document useful (0 votes)
4 views78 pages

4 DBMS

The document discusses various types of physical storage media used in databases, including cache, main memory, flash memory, magnetic disks, optical storage, and tape storage, highlighting their characteristics such as speed, cost, and reliability. It also covers file organization methods, including fixed-length and variable-length records, and different organizational structures like heap, sequential, and hashing. Additionally, it explains the role of buffer management and indexing in optimizing data access and retrieval within database systems.

Uploaded by

sandip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views78 pages

4 DBMS

The document discusses various types of physical storage media used in databases, including cache, main memory, flash memory, magnetic disks, optical storage, and tape storage, highlighting their characteristics such as speed, cost, and reliability. It also covers file organization methods, including fixed-length and variable-length records, and different organizational structures like heap, sequential, and hashing. Additionally, it explains the role of buffer management and indexing in optimizing data access and retrieval within database systems.

Uploaded by

sandip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

File structure Classification of Physical Storage Media

• Speed with which data can be


SRS accessed
• Cost per unit of data
ER-Diagram • Reliability
data loss on power failure or system
crash
Relational Model physical failure of the storage device
• Can differentiate storage into:
Normalization • volatile storage: loses contents
when power is switched off
• non-volatile storage:
File Structure Contents persist even when power is
switched off.
Includes secondary and tertiary storage, as
well as batter- backed up main-memory.
Indexing and Physical Structures
Physical Storage Media
• Cache – fastest and most costly form of storage; volatile; managed by the
computer system hardware.
• Main memory:
• fast access
• generally too small (or too expensive) to store the entire database
• capacities of up to a few Gigabytes widely used currently
• Capacities have gone up and per-byte costs have decreased steadily and rapidly (roughly factor of 2
every 2 to 3 years)
• Volatile — contents of main memory are usually lost if a power failure or system crash
occurs.
• Flash memory
• Data survives power failure
• Data can be written at a location only once, but location can be erased and written to again
• Can support only a limited number (10K – 1M) of write/erase cycles.
• Erasing of memory has to be done to an entire bank of memory
• Reads are roughly as fast as main memory
• But writes are slow (few microseconds), erase is slower
• Widely used in embedded devices such as digital cameras, phones, and USB keys
Physical Storage Media (Cont.)
• Magnetic-disk
• Data is stored on spinning disk, and read/written magnetically
• Primary medium for the long-term storage of data; typically stores entire database.
• Data must be moved from disk to main memory for access, and written back for storage
• Much slower access than main memory (more on this later)
• direct-access – possible to read data on disk in any order, unlike magnetic tape
• Capacities range up to roughly 6 TB
• Much larger capacity and cost/byte than main memory/flash memory
• Growing constantly and rapidly with technology improvements (factor of 2 to 3 every 2 years)
• Survives power failures and system crashes : disk failure can destroy data, but is rare
• Optical storage
• non-volatile, data is read optically from a spinning disk using a laser
• CD-ROM (640 MB) and DVD (4.7 to 17 GB) most popular forms, Blu-ray disks: 27 GB to 54 GB
• Write-one, read-many (WORM) optical disks used for archival storage (CD-R, DVD-R, DVD+R)
• Multiple write versions also available (CD-RW, DVD-RW, DVD+RW, and DVD-RAM)
• Reads and writes are slower than with magnetic disk
• Juke-box systems, with large numbers of removable disks, a few drives, and a mechanism for
automatic loading/unloading of disks available for storing large volumes of data
Physical Storage Media (Cont.)
• Tape storage
• non-volatile, used primarily for backup (to recover from disk failure), and for
archival data
• sequential-access – much slower than disk
• very high capacity (40 to 300 GB tapes available)
• tape can be removed from drive  storage costs much cheaper than disk,
but drives are expensive
• Tape jukeboxes available for storing massive amounts of data
• hundreds of terabytes (1 terabyte = 109 bytes) to even multiple petabytes (1 petabyte =
1012 bytes)
Storage Hierarchy • primary storage:
• Fastest media but volatile (cache,
main memory).
• secondary storage:
• next level in hierarchy, non-volatile,
moderately fast access time
• also called on-line storage
• E.g. flash memory, magnetic disks
• tertiary storage:
• lowest level in hierarchy, non-
volatile, slow access time
• also called off-line storage
• E.g. magnetic tape, optical storage
File Organization
• Files resides permanently on disks
• The database is stored as a collection of files.
• Each file is a logically organized sequence of records.
• Records are mapped onto disk blocks
• A record is a sequence of fields.
• File organization is a logical relationships among various records
• Each file is also logically partitioned into fixed-length storage units called
blocks( unit of storage allocation and data transfer method)
• usually 4-8 KB,
• can be set while DB instance is created
• A block can contains several records
File Organization
• In a Relational DB System tuples of distinct relations are generally of
different sizes.
• One approach:
•assume record size is fixed
•each file has records of one particular type only
•different files are used for different relations
•mapping the database to files is to use several files, and to store records of
only one fixed length in any given file.
• An alternative
• is to structure our files so that we can accommodate multiple lengths for
records;
• however, files of fixed-length records are easier to implement than are
files of variable-length records.
• Many of the techniques used for the above can be applied to the
variable-length case.
Fixed-Length Records
• Simple approach:
• Store record i starting from byte n  (i – 1), where n is the size of
each record.
• Record access is simple but records may cross blocks
• Modification: do not allow records to cross block boundaries

• Deletion of record i:
alternatives:
• move records i + 1, . . ., n
to i, . . . , n – 1
• move record n to i
• do not move records, but
link all free records on a
free list
Example :
Type instructor =record
ID varchar(5);
name varchar(20);
dept_name varchar(20);
salary numeric (8,2);
END
Assume : 1 byte for each character , 8 byte for numeric type
Total Size of instructor Record : 53 Bytes long .
Simple approach is to use the first 53 bytes for the first record , 53 bytes for second
record and so on .

There are two problems with this simple approach


• Unless the block size happens to be a multiple of 53 some records will cross block
boundaries
• It is difficult to delete record from this structure
Deleting record 3 and compacting Deleting record 3 and moving last record
Free Lists
• Store the address of the first deleted record in the file header.
• Use this first record to store the address of the second deleted record,
and so on
• Can think of these stored addresses as pointers since they “point” to the
location of a record.
• More space efficient representation: reuse space for normal attributes of
free records to store pointers. (No pointers stored in in-use records.)

free list, after records 1, 4, and 6 have been deleted


Fixed-length records
• On insertion of a new record, we use the record pointed to by the header.
• We change the header pointer to point to the next available record. If no
space is available, we add the new record to the end of the file
• Insertion and deletion for files of fixed-length records are simple to
implement, because the space made available by a deleted record is exactly
the space needed to insert a record
• If we allow records of variable length in a file, this match no longer holds. An
inserted record may not fit in the space left free by a deleted record, or it may
fill only part of that space.
Variable-Length Records
• Variable-length records arise in database systems in several ways:
• Storage of multiple record types in a file.
• Record types that allow variable lengths for one or more fields such as strings
(varchar)
• Record types that allow repeating fields such as arrays or multisets(used in
some older data models).
• Attributes are stored in order
• Different techniques for implementing variable-length records exist.
• Two different problems must be solved by any such technique:
• How to represent a single record in such a way that individual attributes can
be extracted easily.
• How to store variable-length records within a block, such that records in a
block can be extracted easily.
Variable-Length Records
• The representation of a record with variable-length attributes typically has
two parts:
• an initial part with fixed length attributes
• numeric values, dates, or fixed,length character strings are allocated as many
bytes as required to store their value
• Second part data for variable length attributes
• Variable length attributes represented by fixed size (offset, length), with actual data
stored after all fixed length attributes
• where offset denotes where the data for that attribute begins within the record, and
length is the length in bytes of the variable-sized attribute
• Null values represented by null-value bitmap
attributes ID, name, and dept
name are variable-length
strings, and whose fourth
attribute salary is a fixed-sized
number
Variable-Length Records: Slotted Page Structure

• Slotted page header contains:


• number of record entries
• end of free space in the block
• location and size of each record
• Records can be moved around within a page to keep them contiguous
with no empty space between them; entry in the header must be
updated.
• Pointers should not point directly to record — instead they should
point to the entry for the record in header.
Organization of Records in Files
• Heap
• a record can be placed anywhere in the file where there is space, no ordering of records,
there is a single file for each relation
• Sequential
• store records in sequential order, based on the value of the search key of each record
• Hashing
• a hash function computed on some attribute of each record; the result specifies in which
block of the file the record should be placed

• Generally Records of each relation may be stored in a separate file.


• multitable clustering file organization
• records of several different relations can be stored in the same file known as clusters
• Motivation: store related records on the same block to minimize I/O
• Lowers the cost of searching and retrieving various records in diff. files

• B+ File Organization
Sequential File Organization
• Suitable for applications that require sequential processing of the entire file / Frequent
joining of table is required
• The records in the file are ordered by a search-key/Clustered Key
• A search key is any attribute or set of attributes; it need not be the primary key, or even a
superkey
• To permit fast retrieval of records in search-key order, we chain together records by pointers.

In that example, the records are stored in search-key


order, using ID as the search key.
Sequential File Organization (Cont.)
• Deletion – use pointer chains
• Insertion –locate the position where the record is to be inserted
• if there is free space insert there
• if no free space, insert the record in an overflow block
• In either case, pointer chain must be updated
• Need to reorganize the file
from time to time to restore
sequential order
Multitable Clustering File Organization
Store several relations in one file using a multitable clustering file
organization

department

instructor

multitable clustering
of department and
instructor
Multitable Clustering File Organization (cont.)
• good for queries involving department instructor, and for
queries involving one single department and its instructors
• bad for queries involving only department
• results in variable size records
• Can add pointer chains to link records of a particular relation
B+ File Organization
• The primary disadvantage of the index-sequential file organization is that performance degrades as the file
grows. To overcome this deficiency, we can use a B+-tree index.
• B+ tree file organization is the advanced method of an indexed sequential access method. It uses
a tree-like structure to store records in File.
• It uses the same concept of key-index where the primary key is used to sort the records. For each
primary key, the value of the index is generated and mapped with the record.
• The B+ tree is similar to a binary search tree (BST), but it can have more than two children. In this
method, all the records are stored only at the leaf node. Intermediate nodes act as a pointer to
the leaf nodes. They do not contain any records.

Data Dictionary Storage
The Data dictionary (also called system catalog) stores metadata; that is,
data about data, such as
• Information about relations
• names of relations, names, types and lengths of attributes of each relation, names and
definitions of views
• integrity constraints
• User and accounting information
• name of authorized users , authorization and accounting information's about users and
Passwords or other information used to authenticate users
• Statistical and descriptive data
• number of tuples in each relation, Methods of storage for each relations (Clustered , non
clustered )
• Physical file organization information
• How relation is stored (sequential/hash/…), Physical location of relation
• Information about indices
• Name of the index, Name of the relation being indexed , Attributes on which the index is
defined , Type of index formed.
Relational Representation of System Metadata

• Relational
representatio
n on disk
• Specialized
data
structures
designed for
efficient
access, in
memory
Storage Access
• A database file is partitioned into fixed-length storage units called
blocks.
• Blocks are units of both storage allocation and data transfer.
• Database system seeks to minimize the number of block transfers
between the disk and memory.
• We can reduce the number of disk accesses by keeping as many blocks
as possible in main memory.
• Buffer – portion of main memory available to store copies of disk
blocks.
• Buffer manager – subsystem responsible for allocating buffer space in
main memory.
Buffer Manager
• Programs call on the buffer manager when they need a
block from disk.
1.If the block is already in the buffer, buffer manager
returns the address of the block in main memory
2.If the block is not in the buffer, the buffer manager
1. Allocates space in the buffer for the block
1. Replacing (throwing out) some other block, if required, to make
space for the new block.
2. Replaced block written back to disk only if it was modified since the
most recent time that it was written to/fetched from the disk.
2. Reads the block from the disk to the buffer, and returns the
address of the block in main memory to requester.
Buffer-Replacement Policies
• Most operating systems replace the block least recently used (LRU strategy)
• Idea behind LRU – use past pattern of block references as a predictor of
future references
• Queries have well-defined access patterns (such as sequential scans), and a
database system can use the information in a user’s query to predict future
references
• LRU can be a bad strategy for certain access patterns involving repeated scans of data
• For example: when computing the join of 2 relations r and s by a nested loops
for each tuple tr of r do
for each tuple ts of s do
if the tuples tr and ts match …
• Mixed strategy with hints on replacement strategy provided
by the query optimizer is preferable
Buffer-Replacement Policies (Cont.)
• Pinned block – memory block that is not allowed to be written back to disk.
• Toss-immediate strategy – frees the space occupied by a block as soon as
the final tuple of that block has been processed
• Most recently used (MRU) strategy – system must pin the block currently
being processed. After the final tuple of that block has been processed, the
block is unpinned, and it becomes the most recently used block.
• Buffer manager can use statistical information regarding the probability that
a request will reference a particular relation
• E.g., the data dictionary is frequently accessed. Heuristic: keep data-dictionary blocks
in main memory buffer
• Buffer managers also support forced output of blocks for the purpose of
recovery
Indexing and Hashing
• Many queries reference only a small proportion of the records in a file. To reduce the
overhead in searching for these records, we can construct indices for the files that store the
database.
• Case
• “Find all instructors in the Physics department” or
• “Find the total number of credits earned by the student with ID 22201”
references only a fraction of the student records.
• It is inefficient for the system to read every tuple in the instructor relation to check if the dept
name value is “Physics”.
• Likewise, it is inefficient to read the entire student relation just to find the one tuple for the ID
“32556,”.
• Ideally, the system should be able to locate these records directly.
• To allow these forms of access, additional structures that we associate with files which is
index structure.
• to retrieve a student record given an ID,
• the database system would look up an index to find on which disk block the corresponding record
resides, and then fetch the disk block, to get the appropriate student record.
Basic Concepts
• Indexing mechanisms used to speed up access to desired data.
• To gain fast random access to records in a file, we can use an index
structure
• E.g., author catalog in library
• Search Key - attribute to set of attributes used to look up records in
a file.
search-key pointer

• An index file consists of records (called index entries) of the form

• Index files are typically much smaller than the original file

• Two basic kinds of indices:


• Ordered indices: search keys are stored in sorted order
• Hash indices: search keys are distributed uniformly across “buckets” using a
“hash function”.
Index Evaluation Metrics
• Access types supported efficiently. E.g.,
• records with a specified value in the attribute
• or records with an attribute value falling in a specified range of values.
• Access time
• Insertion time
• Deletion time
• Space overhead
Ordered Indices
• In an ordered index, index entries are stored sorted on the search key
value. E.g., author catalog in library.
• Primary index: in a sequentially ordered file, the index whose search
key specifies the sequential order of the file.
• Also called clustering index
• The search key of a primary index is usually but not necessarily the primary
key.
• Secondary index: an index whose search key specifies an order
different from the sequential order of the file.
• Also called
non-clustering index.
• Index-sequential file: ordered sequential file with a primary index.
Dense Index Files
• Dense index — Index record appears for every search-key value in the file.
• E.g. index on ID attribute of instructor relation
Dense Index Files (Cont.)
• Dense index on dept_name, with instructor file
sorted on dept_name
Sparse Index Files
• Sparse Index: contains index records for only some search-key values.
• Applicable when records are sequentially ordered on search-key
• To locate a record with search-key value K we:
• Find index record with largest search-key value < K
• Search file sequentially starting at the record to which the index record points
Sparse Index Files (Cont.)
• Compared to dense indices:
• Less space and less maintenance overhead for insertions and deletions.
• Generally slower than dense index for locating records.
• Good tradeoff: sparse index with an index entry for every block in file,
corresponding to least search-key value in the block.
Ordered Indices
• If the sort order of a search key matches the sort order of a relation,
an index on the search key is called a clustering index(sparse always).
• The other indices are called nonclustering or secondary indices.
• Secondary indices improve the performance of queries that use
search keys other than the search key of the clustering index.
However, they impose an overhead on modification of the database.

Note:
Ordered File/data Primary Index(Sparse) Clustered Index
We cant create
(Always Sparse) More than one primary
Unordered File/data Secondary Secondary Or clustered index
Index Index
Key Non Key
Primary Index
• Ordered Data
• Key Data
• No . Of Entries in Index Table=NO. of Blocks in HD
• Time Required : log2N+1
• N is the No. of Blocks in index table
Clustered Indices
• DepNo EName Phone Here DepNo is Nonkey
Key Pointer Attribute and indexing is
1 A
1 On this
B1 1 B
2
2 A
3
2 D
4
3 E
5
3 F
3 A
B2
Index table 4 B
Search Time
4 C
log2N+1+1
4 D
Block Hanker N is block in index table
4
4
B3
5
Secondary Indices Example

Secondary index on salary field of instructor

• Index record points to a bucket that contains pointers to all the actual records
with that particular search-key value. Non Key Secondary Index :
• Secondary indices have to be dense log2N+1+1
Key Based
log2N+1
Non Key Pointer
Secondary Indices
• Frequently, one wants to find all the records whose values
in a certain field (which is not the search-key of the primary
index) satisfy some condition.
• Example 1: In the instructor relation stored sequentially
by ID, we may want to find all instructors in a particular
department
• Example 2: as above, but where we want to find all
instructors with a specified salary or with salary in a
specified range of values
• We can have a secondary index with an index record for
each search-key value
Primary and Secondary Indices
• Indices offer substantial benefits when searching for records.
• BUT: Updating indices imposes overhead on database modification --when a file is modified,
every index on the file must be updated,
• Sequential scan using primary index is efficient, but a sequential scan using a secondary index is
expensive
• Each record access may fetch a new block from disk
• Block fetch requires about 5 to 10 milliseconds, versus about 100 nanoseconds for memory
access
Multilevel Index
• If primary index does not fit in memory, access becomes expensive.
• Solution: treat primary index kept on disk as a sequential file and
construct a sparse index on it.
• outer index – a sparse index of primary index
• inner index – the primary index file
• If even outer index is too large to fit in main memory, yet another
level of index can be created, and so on.
• Indices at all levels must be updated on insertion or deletion from
the file.
Multilevel Index (Cont.)
Index Definition in SQL
• Create an index
create index <index-name> on <relation-name>
(<attribute-list>)
E.g.: create index b-index on branch(branch_name)
• Use create unique index to indirectly specify and enforce the
condition that the search key is a candidate key is a candidate key.
• Not really required if SQL unique integrity constraint is supported
• To drop an index
drop index <index-name>
• Most database systems allow specification of type of index, and
clustering.
B+-Tree Index Files(Dynamic Multilevel Index)
• balanced tree- in which every path from the root of the tree to a leaf of the tree is of the same
length
• B+-tree indices are an alternative to indexed-sequential files

• Disadvantage of indexed-sequential files


• performance degrades as file grows, since many overflow blocks get created.
• Periodic reorganization of entire file is required.
• Advantage of B+-tree index files:
• automatically reorganizes itself with small, local, changes, in the face of insertions
and deletions.
• Reorganization of entire file is not required to maintain performance.
• (Minor) disadvantage of B+-trees:
• extra insertion and deletion overhead, space overhead.
• Advantages of B+-trees outweigh disadvantages
• B+-trees are used extensively
Example of B+-Tree
B+-Tree Index Files (Cont.)
A B+-tree is a rooted tree satisfying the following properties:

• All paths from root to leaf are of the same length(Balanced Tree)
• Each node that is not a root or a leaf has between n/2 and n children.
• A leaf node has between (n–1)/2 and n–1 values
• Special cases:
• If the root is not a leaf, it has at least 2 children.
• If the root is a leaf (that is, there are no other nodes in the tree), it can have
between 0 and (n–1) values.
+
B -Tree Node Structure
• Typical node

• Ki are the search-key values


• Pi are pointers to children (for non-leaf nodes) or pointers to records or buckets of records
(for leaf nodes).
• The search-keys in a node are ordered
K1 < K2 < K3 < . . . < Kn–1
(Initially assume no duplicate keys, address duplicates later)
Leaf Nodes in B+-Trees
Properties of a leaf node:
• For i = 1, 2, . . ., n–1, pointer Pi points to a file record with search-key value Ki,
• If Li, Lj are leaf nodes and i < j, Li’s search-key values are less than or equal to Lj’s
search-key values
• Pn points to next leaf node in search-key order
Non-Leaf Nodes in +
B -Trees
• Non leaf nodes form a multi-level sparse index on the leaf nodes. For a non-leaf node with m
pointers:
• All the search-keys in the subtree to which P1 points are less than K1
• For 2  i  n – 1, all the search-keys in the subtree to which Pi points have values greater than
or equal to Ki–1 and less than Ki
• All the search-keys in the subtree to which Pn points have values greater than or equal to Kn–1
Example of B+-tree

B+-tree for instructor file (n = 6)

• Leaf nodes must have between 3 and 5 values


((n–1)/2 and n –1, with n = 6).
• Non-leaf nodes other than root must have between 3 and 6
children ((n/2 and n with n =6).
• Root must have at least 2 children.
Multiple-Key Access
• Use multiple indices for certain types of queries.
• Example:
select ID
from instructor
where dept_name = “Finance” and salary = 80000
• Possible strategies for processing query using indices on single attributes:
1. Use index on dept_name to find instructors with department name Finance;
test salary = 80000
2. Use index on salary to find instructors with a salary of $80000; test
dept_name = “Finance”.
3. Use dept_name index to find pointers to all records pertaining to the
“Finance” department. Similarly use index on salary. Take intersection of
both sets of pointers obtained.
Indices on Multiple Attributes
Suppose we have an index on combined search-key
(dept_name, salary).
• With the where clause
where dept_name = “Finance” and salary = 80000
the index on (dept_name, salary) can be used to fetch only
records that satisfy both conditions.
• Using separate indices in less efficient — we may fetch many records
(or pointers) that satisfy only one of the conditions.
• Can also efficiently handle
where dept_name = “Finance” and salary < 80000
• But cannot efficiently handle
where dept_name < “Finance” and balance = 80000
• May fetch many records that satisfy the first but not the second
condition
Hashing
Hashing
• A data bucket is a unit of storage containing one or more records
(a bucket is typically a disk block).
• In a hash file organization we obtain the bucket of a record directly
from its search-key value using a hash function.
• Hash function h is a mapping function from the set of all search-
key values K to the set of all bucket addresses B(actual record
location).
• Hash function is used to locate records for access, insertion as
well as deletion.
• Records with different search-key values may be mapped to the
same bucket; thus entire bucket has to be searched sequentially to
locate a record.
Hashing
• To insert a record with search key Ki,
• we compute h(Ki ), which gives the address of the bucket for that record.
• Assume for now that there is space in the bucket to store the record. Then, the
record is stored in that bucket
• To perform a lookup on a search-key value Ki ,
• simply compute h(Ki ),
• then search the bucket with that address.
• Suppose that two search keys, K5 and K7, have the same hash value;
• that is, h(K5) = h(K7).
• If we perform a lookup on K5, the bucket h(K5) contains records with search-key
values K5 and records with search-key values K7.
• we have to check the search-key value of every record in the bucket to verify that
the record is one that we want.
• Deletion.
• If the search-key value of the record to be deleted is Ki, we compute h(Ki ), then
search the corresponding bucket for that record, and delete the record from the
bucket.
Hashing
• Hashing can be used for two different purposes.
• In a hash file organization, we obtain the address of the disk block
containing a desired record directly by computing a function on
the search-key value of the record.
• In a hash index organization we organize the search keys, with
their associated pointers, into a hash file structure.
Data Buckets
Example of Hash File Organization
Hash file organization of instructor file, using dept_name as key
(See figure in next slide.)

• There are 10 buckets,


• The binary representation of the ith character is assumed to be the
integer i.
• The hash function returns the sum of the binary representations of the
characters modulo 10

• E.g. h(Music) = 1 h(History) = 2


h(Physics) = 3 h(Elec. Eng.) = 3
Example of Hash File Organization

Hash file organization of instructor file, using dept_name as key


(see previous slide for details).
Hash Functions
• Worst hash function maps all search-key values to the same bucket; this
makes access time proportional to the number of search-key values in
the file.
• An ideal hash function is uniform, i.e., each bucket is assigned the same
number of search-key values from the set of all possible values.
• Ideal hash function is random, so each bucket will have the same
number of records assigned to it irrespective of the actual distribution of
search-key values in the file.
• Typical hash functions perform computation on the internal binary
representation of the search-key.
• For example, for a string search-key, the binary representations of all the
characters in the string could be added and the sum modulo the number of
buckets could be returned. .
Hash Functions
• bad hash function may result in lookup taking time
proportional to the number of search keys in the file

• A well designed function gives an average-case lookup time that is a


(small) constant, independent of the number of search keys in the file
Handling of Bucket Overflows
• Bucket overflow can occur because of
• Insufficient buckets
• The number of buckets, which we denote nB, must be chosen such
that nB > nr / fr, where nr denotes the total number of records that
will be stored and fr denotes the number of records that will fit in a
bucket.

• Skew in distribution of records.


• Some buckets are assigned more records than are others, so a
bucket may overflow even when other buckets still have space.
• This can occur due to two reasons:
• multiple records have same search-key value
• chosen hash function produces non-uniform distribution of key values

• Although the probability of bucket overflow can be reduced, it cannot be


eliminated; it is handled by using overflow buckets.
Handling of Bucket Overflows (Cont.)
• Overflow chaining – the overflow buckets of a given bucket are chained
together in a linked list.
• Above scheme is called closed hashing.
• An alternative, called open hashing, which does not use overflow buckets, is not
suitable for database applications.
Hash Indices
• Hashing can be used not only for file organization, but also for index-
structure creation.
• A hash index organizes the search keys, with their associated record
pointers, into a hash file structure.
• Strictly speaking, hash indices are always secondary indices
• if the file itself is organized using hashing, a separate primary hash index on it
using the same search-key is unnecessary.
• However, we use the term hash index to refer to both secondary index
structures and hash organized files.
Example of Hash Index

hash index on instructor, on attribute ID


Deficiencies of Static Hashing
• In static hashing, function h maps search-key values to a fixed set
of B of bucket addresses. Databases grow or shrink with time.
• If initial number of buckets is too small, and file grows, performance will
degrade due to too much overflows.
• If space is allocated for anticipated growth, a significant amount of space
will be wasted initially (and buckets will be underfull).
• If database shrinks, again space will be wasted.
• One solution: periodic re-organization of the file with a new hash
function
• Expensive, disrupts normal operations
• Better solution: allow the number of buckets to be modified
dynamically.
Dynamic Hashing
• Good for database that grows and shrinks in size
• Allows the hash function to be modified dynamically
• Extendable hashing – one form of dynamic hashing
• Hash function generates values over a large range — typically b-bit
integers, with b = 32.
• At any time use only a prefix of the hash function to index into a table of
bucket addresses.
• Let the length of the prefix be i bits, 0  i  32.
• Bucket address table size = 2i. Initially i = 0
• Value of i grows and shrinks as the size of the database grows and shrinks.
• Multiple entries in the bucket address table may point to a bucket (why?)
• Thus, actual number of buckets is < 2i
• The number of buckets also changes dynamically due to coalescing and splitting of
buckets.
General Extendable Hash Structure

In this structure, i2 = i3 = i, whereas i1 = i – 1


Use of Extendable Hash Structure
• Each bucket j stores a value ij
• All the entries that point to the same bucket have the same values on the first ij
bits.
• To locate the bucket containing search-key Kj:
1.Compute h(Kj) = X
2.Use the first i high order bits of X as a displacement into bucket address table, and
follow the pointer to appropriate bucket
• To insert a record with search-key value Kj
• follow same procedure as look-up and locate the bucket, say j.
• If there is room in the bucket j insert record in the bucket.
• Else the bucket must be split and insertion re-attempted (next slide.)
• Overflow buckets used instead in some cases (will see shortly)
Insertion in Extendable Hash Structure (Cont)
To split a bucket j when inserting record with search-key value Kj:

• If i > ij (more than one pointer to bucket j)


• allocate a new bucket z, and set ij = iz = (ij + 1)
• Update the second half of the bucket address table entries originally pointing to j, to
point to z
• remove each record in bucket j and reinsert (in j or z)
• recompute new bucket for Kj and insert record in the bucket (further splitting is
required if the bucket is still full)
• If i = ij (only one pointer to bucket j)
• If i reaches some limit b, or too many splits have happened in this insertion, create an
overflow bucket
• Else
• increment i and double the size of the bucket address table.
• replace each entry in the table by two entries that point to the same bucket.
• recompute new bucket address table entry for Kj
Now i > ij so use the first case above.
Deletion in Extendable Hash Structure
• To delete a key value,
• locate it in its bucket and remove it.
• The bucket itself can be removed if it becomes empty (with appropriate updates
to the bucket address table).
• Coalescing of buckets can be done (can coalesce only with a “buddy” bucket
having same value of ij and same ij –1 prefix, if it is present)
• Decreasing bucket address table size is also possible
• Note: decreasing bucket address table size is an expensive operation and should be done only
if number of buckets becomes much smaller than the size of the table
Extendable Hashing vs. Other Schemes
• Benefits of extendable hashing:
• Hash performance does not degrade with growth of file
• Minimal space overhead
• Disadvantages of extendable hashing
• Extra level of indirection to find desired record
• Bucket address table may itself become very big (larger than memory)
• Cannot allocate very large contiguous areas on disk either
• Solution: B+-tree structure to locate desired record in bucket
address table
• Changing size of bucket address table is an expensive operation
• Linear hashing is an alternative mechanism
• Allows incremental growth of its directory (equivalent to bucket
address table)
Comparison of Ordered Indexing and Hashing

• Comparison Basis :
• Cost of periodic re-organization
• Relative frequency of insertions and deletions
• Is it desirable to optimize average access time at the expense of worst-case access time?

• Expected type of queries:


• Hashing is generally better at retrieving records having a specified value of
the key.
• If range queries are common, ordered indices are to be preferred
• In practice:
• PostgreSQL supports hash indices, but discourages use due to poor
performance
• Oracle supports static hash organization, but not hash indices
• SQLServer supports only B+-trees
Bitmap Indices
• Bitmap indices are a special type of index designed for efficient
querying on multiple keys
• Records in a relation are assumed to be numbered sequentially from,
say, 0
• Given a number n it must be easy to retrieve record n
• Particularly easy if records are of fixed size
• Applicable on attributes that take on a relatively small number of
distinct values
• E.g. gender, country, state, …
• E.g. income-level (income broken up into a small number of levels
such as 0-9999, 10000-19999, 20000-50000, 50000- infinity)
• A bitmap is simply an array of bits
Bitmap Indices (Cont.)
• In its simplest form a bitmap index on an attribute has a bitmap for
each value of the attribute
• Bitmap has as many bits as records
• In a bitmap for value v, the bit for a record is 1 if the record has the value v for
the attribute, and is 0 otherwise
Bitmap Indices (Cont.)
• Bitmap indices are useful for queries on multiple attributes
• not particularly useful for single attribute queries
• Queries are answered using bitmap operations
• Intersection (and)
• Union (or)
• Complementation (not)
• Each operation takes two bitmaps of the same size and applies the
operation on corresponding bits to get the result bitmap
• E.g. 100110 AND 110011 = 100010
100110 OR 110011 = 110111
NOT 100110 = 011001
• Males with income level L1: 10010 AND 10100 = 10000
• Can then retrieve required tuples.
• Counting number of matching tuples is even faster
Bitmap Indices (Cont.)
• Bitmap indices generally very small compared with relation size
• E.g. if record is 100 bytes, space for a single bitmap is 1/800 of space
used by relation.
• If number of distinct attribute values is 8, bitmap is only 1% of relation size
• Deletion needs to be handled properly
• Existence bitmap to note if there is a valid record at a record location
• Needed for complementation
• not(A=v): (NOT bitmap-A-v) AND ExistenceBitmap
• Should keep bitmaps for all values, even null value
• To correctly handle SQL null semantics for NOT(A=v):
• intersect above result with (NOT bitmap-A-Null)

You might also like