Query Processing and Optimization Algorithms
Query Processing and Optimization Algorithms
Optimization
Chapter Outline
• Heap files
– random order; insert at end-of-file
• Sorted files
– sorted on <age, sal>
• Clustered B+ tree file
– search key <age, sal>
• Heap file with unclustered B+-tree index
– on search key <age, sal>
• Heap file with unclustered hash index
– on search key <age, sal>
Possible Operations
• Scan
– Fetch all records from disk to buffer pool
• Equality search
– Find all employees with age = 23 and sal = 50
– Fetch page from disk, then locate qualifying record in page
• Range selection
– Find all employees with age > 35
• Insert a record
– identify the page, fetch that page from disk, inset record, write back
to disk (possibly other pages as well)
• Delete a record
– similar to insert
Understanding the Workload
• A workload is a mix of queries and updates
SELECT [Link]
• How selective is the condition? FROM Emp E
– everyone > 40, index not of much WHERE [Link]>40
help, scan is as good
– Suppose 10% > 40. Then?
Which attribute(s)?
• Depends on if the index is clustered Clustered/Unclustered?
– otherwise can be more expensive B+ tree/Hash?
than a linear scan
– if clustered, 10% I/O (+ index pages)
Examples of Clustered Indexes
Group-By query What is a good indexing
strategy?
• Use [Link] as search key?
– Bad If many tuples have [Link] > 10 or if not
clustered…. SELECT [Link], COUNT (*)
– …using [Link] index and sorting the retrieved FROM Emp E
tuples by [Link] may be costly
WHERE [Link]>10
GROUP BY [Link]
• Clustered [Link] index may be better
– First group by, then count tuples with age >
10
– good when age > 10 is not too selective Which attribute(s)?
Clustered/Unclustered?
• Note: the first option is good when the B+ tree/Hash?
WHERE condition is highly selective (few
tuples have age > 10), the second is good
when not highly selective
Examples of Clustered Indexes
What is a good indexing
strategy?
Equality queries and duplicates SELECT [Link]
FROM Emp E
• Clustering on [Link] helps WHERE [Link]=‘Stamps’
– hobby not a candidate key, several
tuples possible Which attribute(s)?
Clustered/Unclustered?
B+ tree/Hash?
• Does clustering help now?
– (eid = key) SELECT [Link]
– Not much FROM Emp E
– at most one tuple satisfies the WHERE [Link]=50
condition
Indexes with Composite Search Keys
• Composite Search Keys: Search on a Examples of composite key
combination of fields indexes using lexicographic order.
INPUT 1
OUTPUT
INPUT 2
2N (log 2 N + 1)
2,3
3,4
8-page runs
• Not too practical, but useful to 4,5
learn basic concepts for 6,6
external sorting 7,8
9
General External Merge Sort
• Suppose we have more than 3 buffer pages.
• How can we utilize them?
• To sort a file with N pages using B buffer pages:
– Pass 0: use B buffer pages:
• Produce ⌈N/B⌉ sorted runs of B pages each.
– Pass 1, 2, …, etc.: merge B-1 runs to one output page
• keep writing to disk once the output page is full
INPUT 1
INPUT 2
... ... OUTPUT ...
INPUT B-1
Disk Disk
B Main memory buffers
Cost of External Merge Sort
• Number of passes:1 + ⌈logB-1⌈N/B⌉⌉
• Cost = 2N * (# of passes) – why 2 times?
• E.g., with 5 buffer pages, to sort 108 page file:
• Pass 0: sorting 5 pages at a time
– ⌈108/5⌉ = 22 sorted runs of 5 pages each (last run is only 3
pages)
• Pass 1: 4-way merge
– ⌈22/4⌉ = 6 sorted runs of 20 pages each (last run is only 8 pages)
• Pass 2: 4-way merge
– (but 2-way for the last two runs)
– [6/4⌉ = 2 sorted runs, 80 pages and 28 pages
• Pass 3: 2-way merge (only 2 runs remaining)
– Sorted file of 108 pages
Number of Passes of External Sort
High B is good, although CPU cost increases
INPUT 1
INPUT 1'
INPUT 2
OUTPUT
INPUT 2'
OUTPUT'
b
block size
Disk INPUT k
Disk
INPUT k'
• In algebra: R⨝ S
– Common! Must be carefully optimized
– R X S is large; so, R X S followed by a selection is inefficient
3. Hash Join
4. Index Based Join
Algorithms for Joins
1. NESTED LOOP JOINS
M = 1000 pages in R
pR = 100 tuples per page
Simple Nested Loops Join
N = 500 pages in S
R⨝S pS = 80 tuples per page
foreach tuple r in R do
foreach tuple s in S where ri == sj do
add <r, s> to result
• 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.
...
... ...
Input buffer for S
Output buffer
Block Nested Loops Join
• If R does not fit in memory,
– 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.
Reserves
Sailors
1. Partition Phase
– partition R and S using the same hash function h
2. Probing Phase
– join tuples from the same partition (same h(..)
value) of R and S
– tuples in different partition of h will never join
– use a “different” hash function h2 for joining
these tuples
• (why different – see next slide first)
S R
Hash-Join Original
Relation OUTPUT Partitions
1
Cost of Hash-Join
• In partitioning phase
– read+write both relns; 2(M+N)
– In matching phase, read both relns; M+N I/Os
– remember – we are not counting final write
𝑅 ⋈𝑅.𝐴=𝑆.𝐵 𝑆
• Idea: use a value of 𝑅. 𝐴 to probe the index on 𝑆(𝐵)
• For each block of 𝑅, and for each 𝑟 in the block:
Use the index on 𝑆(𝐵) to retrieve 𝑠 with 𝑠. 𝐵 = 𝑟. 𝐴
Output 𝑟𝑠
• I/O’s: M+ M ⋅ pR ⋅ (index lookup)
• Typically, the cost of an index lookup is 2- 4 I/O’s
• Beats other join methods if |𝑅| is not too big
• Better pick 𝑅 to be the smaller relation
• Memory requirement: 3
Zig-zag joinusing ordered indexes
𝑅 ⋈𝑅.𝐴=𝑆.𝐵 𝑆
• Idea: use the ordering provided by the indexes on 𝑅(𝐴)
and 𝑆(𝐵) to eliminate the sorting step of sort-merge join
• Use the larger key to probe the other index
• Possibly skipping many keys that don’t match
B+-tree on 𝑅 𝐴
(1)
1 (2)
2 3 4 (3)
7 (4)
9 (5)
18
(1)
1 (2)
7 (4)
9 (5)
11 12 17 (6)
19
B+-tree on 𝑆 𝐵
Other operator algorithms
SELECT *
Algorithms FROM Reserves R
WHERE [Link] = ‘Joe’
for Selection
• No index, unsorted data
– Scan entire relation
– May be expensive if not many `Joe’s
• No index, sorted data (on ‘rname’)
– locate the first tuple, scan all matching tuples
– first binary search, then scan depends on matches
• B+-tree index, Hash index
– Discussed earlier
– Cost of accessing data entries + matching data records
– Depends on clustered/unclustered
• More complex condition like day<8/9/94 AND bid=5 AND sid=3
– Either use one index, then filter
– Or use two indexes, then take intersection, then apply third condition
– etc.
SELECT DISTINCT
Algorithms [Link], [Link]
FROM Reserves R
for Projection
• Two parts
– Remove fields: easy
– Remove duplicates (if distinct is specified): expensive
• Sorting-based
– Sort, then scan adjacent tuples to remove duplicates
– Can eliminate unwanted attributes in the first pass of merge sort
• Hash-based
– Exactly like hash join
– Partition only one relation in the first pass
– Remove duplicates in the second pass
• Sort vs Hash
– Sorting handles skew better, returns results sorted
– Hash table may not fit in memory – sorting is more standard
• Index-only scan may work too
– If all required attributes are part of index
Algorithms for Set Operations
• 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
– or, hash on group-by attributes
– can combine sort/hash and aggregate
– can do index-only scan here as well
Algorithms for Aggregate Operations
• SUM, AVG, MIN etc.
– again similar to previous approaches
• 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
– or, hash on group-by attributes
– can combine sort/hash and aggregate
– can do index-only scan here as well
Aggregation example
Compute the sum of numbers for each color ( ),
using partial aggregate values
3,2,4,1,3,5,6,2,2 12,5,11
24,19,27
7,5,3,6,6,6,3,4,2 12,14,16
39,37,49
4,1,1,1,3,5,7,8,3 6,11,16
15,18,22
9,4,0,0,7,1,0,0,1 9,7,6
Beside SUM, the same trick works for COUNT, MIN, MAX
And also AVG, STDEV, with some little twists
Truly “holistic” aggregates?
E.g.,MEDIAN, SUM(DISTINCT …)
• Sort by the input expression (within each group)
• Example:
SELECT SUM(DISTINCT B)
FROM R GROUP BY A;
• Sort R by (A, B)
• But if there are multiple holistic aggregates with
different input expressions, a single global order
won’t work — a group may need to be resorted
Digression: specialized algorithms
• Instead of sorting, specialized algorithms exist for
some aggregates, e.g.: median/quantile
MEDIAN/k-selection
• Pick a pivot 𝑣 to partition data into two runs (those ≤
𝑣 vs. those > 𝑣); recurse on the run with the answer
• E.g.:400-th smallest row among 1000
• Run 1:250 rows ≤ pivot + Run 2:750 rows > pivot
• Answer must be in Run 2
• Recurse on Run 2 to find the 150-th smallest
• Expected I/Ois linear in the number of blocks
• There are tricks for picking pivots (e.g., “median
of medians”) to make worst-case cost linear