1 of 46

Overview of Implementing Relational Operators�Query Evaluation

Chapter 12

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

1

2 of 46

Motivation: Evaluating Queries

  • The same query can be evaluated in different ways.
  • The evaluation strategy (plan) can make orders of magnitude of difference.
  • Query efficiency is one of the main areas where DBMS systems compete with each other.
  • Person-decades of development, secret details.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

2

3 of 46

Overview of Query Evaluation

  • Plan: Tree of R.A. ops, with choice of alg for each op.
    • Each operator typically implemented using a `pull’ interface: when an operator is `pulled’ for the next output tuples, it `pulls’ on its inputs and computes them.
    • Much like cursor/iterator.
  • Two main issues in query optimization:
    • For a given query, what plans are considered?
    • Algorithm to search for cheapest (estimated) plan.
    • How is the cost of a plan estimated?
  • Ideally: Want to find best plan. Practically: Avoid worst plans!
  • We will study the System R approach (IBM).

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

3

4 of 46

Some Common Techniques

  • Algorithms for evaluating relational operators use some simple ideas extensively:
    • Indexing: Can use WHERE conditions and indexes to retrieve small set of tuples (selections, joins)
    • Iteration: Sometimes, faster to scan all tuples even if there is an index.
    • Partitioning: By using sorting or hashing on a sort key, we can partition the input tuples and replace an expensive operation by similar operations on smaller inputs.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

4

5 of 46

Examples

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

5

6 of 46

Example Relations

Sailors

Reservations

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

6

7 of 46

Query Plan Example

  • RA Tree: expression tree.
  • Each leaf is a schema table.
  • Internal nodes: relational algebra operator applied to children.
  • Full plan labels each internal node with implementation strategy.

SELECT S.sname

FROM Reserves R, Sailors S

WHERE R.sid=S.sid AND

R.bid=100 AND S.rating>5

Reserves

Sailors

sid=sid

bid=100

rating > 5

sname

RA Tree:

Reserves

Sailors

sid=sid

bid=100

rating > 5

sname

(Simple Nested Loops)

(On-the-fly)

(On-the-fly)

Plan:

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

7

8 of 46

Alternative Plan

  • Goal of optimization: To find efficient plans that compute the same answer.

Reserves

Sailors

sid=sid

bid=100

sname

(On-the-fly)

rating > 5

(Scan;

write to

temp T1)

(Scan;

write to

temp T2)

(Sort-Merge Join)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

8

9 of 46

Indexes and Query Plans

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

9

10 of 46

Access Paths

  • An access path is a method of retrieving tuples:
    • File scan, or index that matches a selection (in the query)
  • A tree index matches (a conjunction of) terms that involve only attributes in a prefix of the search key.
    • E.g., Tree index on <a, b, c> matches the selection a=5 AND b=3, and a=5 AND b>6, but not b=3.
  • A hash index matches (a conjunction of) terms that has a term attribute = value for every attribute in the search key of the index.
    • E.g., Hash index on <a, b, c> matches a=5 AND b=3 AND c=5; but it does not match b=3, or a=5 AND b=3, or a>5 AND b=3 AND c=5.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

10

11 of 46

Exercise 12.4

Consider the following schema with the Sailors relation:

Sailors(sid: integer, sname: string, rating: integer, age: real) 

  • For each of the following indexes, list whether the index matches the given selection conditions.
    1. A hash index on the search key <Sailors.sid> 
      1. σsid<50,000 (Sailors)
      2. σsid=50,000 (Sailors)
    2. A B+-tree on the search key <Sailors.sid>
      • σsid<50,000 (Sailors)
      • σsid=50,000 (Sailors)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

11

12 of 46

Selecting Indexes

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

12

13 of 46

Create Indexes in SQL-Server

  • A DBMS supports many options for creating indices (more than we can cover).
  • Sample Syntax:

use aworks;

create index IX_Product_Color

on SalesLT.Product (Color);

  • More Examples

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

13

14 of 46

Understanding the Workload

  • For each query in the workload:
    • Which relations does it access?
    • Which attributes are retrieved?
    • Which attributes are involved in selection/join conditions? How selective are these conditions likely to be?
  • For each update in the workload:
    • Which attributes are involved in selection/join conditions? How selective are these conditions likely to be?
    • The type of update (INSERT/DELETE/UPDATE), and the attributes that are affected.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

14

15 of 46

Statistics and Catalogs

  • Need information about the relations and indexes involved. Catalogs typically contain at least:
    • # tuples (NTuples) and # pages (NPages) for each relation.
    • # distinct key values (NKeys) and NPages for each index.
    • Index height, low/high key values (Low/High) for each tree index.
  • Catalogs updated only periodically.
  • More detailed information (e.g., histograms of the values in some field) are sometimes stored.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

15

16 of 46

Choice of Indexes

  • What indexes should we create?
    • Which relations should have indexes?
    • What field(s) should be the search key?
    • Should we build several indexes?
  • For each index, what kind of an index should it be?
    • Clustered? Hash/tree?
  • Trade-off: Indexes can make queries go faster, updates slower. Require disk space, too.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

16

17 of 46

Choice of Index, One Approach

  1. Consider the most important queries in turn.
  2. Consider the best query plan using the current indexes.
  3. If a better plan is possible with an additional index, create it.
    • Obviously, this implies that we must understand how a DBMS evaluates queries and creates query evaluation plans!
  4. For now, we discuss simple 1-table queries.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

17

18 of 46

Examples of Clustered Indexes

  • B+ tree index on E.age can be used to get qualifying tuples.
    • How selective is the condition?
    • Is the index clustered?
  • Consider the GROUP BY query.
    • If many tuples have E.age > 10, using E.age index and sorting the retrieved tuples may be costly.
    • Clustered E.dno index may be better!
  • Equality queries and duplicates:
    • Clustering on E.hobby helps!

SELECT E.dno

FROM Emp E

WHERE E.age>40

SELECT E.dno, COUNT (*)

FROM Emp E

WHERE E.age>10

GROUP BY E.dno

SELECT E.dno

FROM Emp E

WHERE E.hobby=Stamps

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

18

19 of 46

Index-Only Plans

  • A number of queries can be answered without retrieving any tuples from one or more of the relations involved if a suitable index is available.

SELECT D.mgr

FROM Dept D, Emp E

WHERE D.dno=E.dno

SELECT D.mgr, E.eid

FROM Dept D, Emp E

WHERE D.dno=E.dno

SELECT E.dno, COUNT(*)

FROM Emp E

GROUP BY E.dno

SELECT E.dno, MIN(E.sal)

FROM Emp E

GROUP BY E.dno

SELECT AVG(E.sal)

FROM Emp E

WHERE E.age=25 AND

E.sal BETWEEN 3000 AND 5000

<E.dno>

<E.dno,E.eid>

Tree index!

<E.dno>

<E.dno,E.sal>

Tree index!

<E. age,E.sal>

or

<E.sal, E.age>

Tree!

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

19

20 of 46

Index Selection Guidelines

  • Attributes in WHERE clause are candidates for index keys.
    • Exact match condition suggests hash index.
    • Range query suggests tree index.
    • Clustering is especially useful for range queries.
  • Multi-attribute search keys should be considered when a WHERE clause contains several conditions.
    • Order of attributes is important for range queries.
    • Such indexes can sometimes enable index-only strategies for important queries.
    • For index-only strategies, clustering is not important!
  • Try to choose indexes that benefit as many queries as possible. MS Index Tuning Wizard

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

20

21 of 46

Computing Relational Operators

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

21

22 of 46

Selection and Projection

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

22

23 of 46

One Approach to Selections

  • Estimate 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 requires the fewest page I/Os.
    • Terms that match this index reduce the number of tuples retrieved.
    • Other terms affect the query result, but not the number of tuples/pages fetched.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

23

24 of 46

Selectivity Example

    • 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.
    • A hash index on <bid, sid> could be used; day<8/9/94 must then be checked.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

24

25 of 46

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, assume that 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 10,000 I/Os!

SELECT *

FROM Reserves R

WHERE R.rname < ‘C%’

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

25

26 of 46

Projection

  • The expensive part is removing duplicates.
    • SQL systems don’t remove duplicates unless the keyword DISTINCT is specified in a query.
  • Sorting Approach: Sort on <sid, bid> and remove duplicates.
  • Hashing Approach:
    • Hash on <sid, bid> to create partitions.
    • Load partitions into memory one at a time.
    • Build in-memory hash structure, and eliminate duplicates.
  • If there is an index with both R.sid and R.bid in the search key, may be cheaper to sort data entries!

SELECT DISTINCT

R.sid, R.bid

FROM Reserves R

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

26

27 of 46

The Biggie: Join

Nested Loops: Scan and Match

Sort and Merge

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

27

28 of 46

Join: Sort-Merge (R S)

  • Sort R and S on the join column, then scan them to do a ``merge’’ (on join col.), and output result tuples.
    • Advance scan of R until current R-tuple >= current S tuple.
    • Advance scan of S until current S-tuple >= current R tuple.
    • Repeat until match: current R tuple = current S tuple.
    • At this point, all R tuples with same value in Ri (current R group) and all S tuples with same value in Sj (current S group) match; output <r, s> for all pairs of such tuples.
    • Then resume scanning R and S.
  • R is scanned once; each S group is scanned once per matching R tuple.

i=j

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

28

29 of 46

Example of Sort-Merge Join

  • Cost: sort + scan =
  • sort cost + (M+N) [sid is key]
    • The cost of scanning, M+N, could be M*N (very unlikely!)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

29

30 of 46

Sorting

  • Sorting is strongly optimized in DBMS.
  • Common method: merge-sort.
  • I/O Cost for merge sort using B buffer pages�is O(N * logB-1 N/B)
  • See Ch.13.
  • Example: With enough buffer pages, both Reserves and Sailors can be sorted in 2 passes. total join cost: 7500.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

30

31 of 46

Example of Sort-Merge Join

  • Cost: sort + scan =�4* (500+1000) + (500+1000) =�7,500 I/Os

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

31

32 of 46

Exercise 14.4.3

  • Consider the join R.A with S.b given the following information. The cost measure is the number of page i/Os, ignoring the cost of writing out the result.
    • Relation R contains 10,000 tuples and has 10 tuples per page.
    • Relation S contains 2000 tuples, also 10 tuples per page.
    • Attribute b is the primary key for S.
    • Both relations are stored as heap files. No indexes are available.
  • What is the cost of joining R and S using a sort-merge join? Assume that the number of I/Os for sorting a table T is 4 *pages_in_T .

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

32

33 of 46

Nested Loops: Flowchart

From http://www.dbsophic.com/physical-join-operators-in-sql-server-nested-loops/.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

33

34 of 46

Join: Index Nested Loops

  • If there is an index on the join column of one relation (say S), can make it the inner and exploit the index.
    • Cost: Pages_in_r * �( 1 + tup_per_page* 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 (assuming alt. (2) or (3) for data entries) depends on clustering.
    • Clustered index on S: 1 I/O (typical) for each R tuple, �unclustered: up to 1 I/O per matching S tuple.

foreach tuple r in R do

foreach tuple s in S where ri == sj do

add <r, s> to result

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

34

35 of 46

Examples: Scan and Match

  • Hash-index (Alt. 2) 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.
      • 1 I/O to get (the exactly one) matching Sailors tuple.
    • Total: 220,000 I/Os for finding matches.
  • Hash-index (Alt. 2) on sid of Reserves (as inner):
    • Scan Sailors: 500 page I/Os, 80*500 tuples.
    • For each Sailors tuple:
      • 1.2 I/Os to get data entry in index.
      • plus cost of retrieving matching Reserves tuples. Assuming uniform distribution, 2.5 reservations per sailor (100,000 R/ 40,000 S). Cost of retrieving them is 1 or 2.5 I/Os depending on whether the index is clustered.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

35

36 of 46

Exercise 14.4.1

  • Consider the join R.A with S.b given the following information. The cost measure is the number of page I/Os, ignoring the cost of writing out the result.
    • Relation R contains 10,000 tuples and has 10 tuples per page.
    • Relation S contains 2000 tuples, also 10 tuples per page.
    • Attribute b is the primary key for S.
    • Both relations are stored as heap files. No indexes are available.
  • What is the cost of joining R and S using nested loop join? R is the outer relation.
  • How many tuples does the join of R and S produce, at most, and how many pages are required to store the result of the join back on disk?

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

36

37 of 46

Query Planning

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

37

38 of 46

Highlights of System R Optimizer

  • Impact:
    • Most widely used currently; works well for < 10 joins.
  • Cost estimation: NP-hard, approximate art at best.
    • Statistics, maintained in system catalogs, used to estimate cost of operations and result sizes.
    • Considers combination of CPU and I/O costs.
  • Plan Space: Too large, must be pruned.
    • Only the space of left-deep plans is considered. (see text)
    • Cartesian products avoided.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

38

39 of 46

Cost Estimation

  • For each plan considered, must estimate cost:
    • Must estimate cost of each operation in plan tree.
      • Depends on input cardinalities.
      • We’ve already discussed how to estimate the cost of operations (sequential scan, index scan, joins, etc.)
    • Must also estimate size of result for each operation in tree!
      • Use information about the input relations.
      • For selections and joins, assume independence of predicates.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

39

40 of 46

Size Estimation and Reduction Factors

  • Consider a query block:
  • Maximum # tuples in result is the product of the cardinalities of relations in the FROM clause.
  • Reduction factor (RF) associated with each term reflects the impact of the term in reducing result size. Result cardinality = Max # tuples * product of all RF’s.
    • Implicit assumption that terms are independent!
    • Term col=value has RF 1/NKeys(I), given index I on col
    • Term col1=col2 has RF 1/MAX(NKeys(I1), NKeys(I2))
    • Term col>value has RF (High(I)-value)/(High(I)-Low(I))

SELECT attribute list

FROM relation list

WHERE term1 AND ... AND termk

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

40

41 of 46

Schema for Examples

  • Similar to old schema; rname added for variations.
  • 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)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

41

42 of 46

Motivating Example

  • Cost: 1000+1000*500 I/Os
  • By no means the worst plan!
  • Misses several opportunities: selections could have been `pushed’ earlier, no use is made of any available indexes, etc.
  • Goal of optimization: To find more efficient plans that compute the same answer.

SELECT S.sname

FROM Reserves R, Sailors S

WHERE R.sid=S.sid AND

R.bid=100 AND S.rating>5

Reserves

Sailors

sid=sid

bid=100

rating > 5

sname

Reserves

Sailors

sid=sid

bid=100

rating > 5

sname

(Simple Nested Loops)

(On-the-fly)

(On-the-fly)

RA Tree:

Plan:

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

42

43 of 46

Alternative Plans 1 �(No Indexes)

  • Main difference: push selects.
  • With 5 buffers, cost of plan:
    • Scan Reserves (1000) + write temp T1 (10 pages, if we have 100 boats, uniform distribution).
    • Scan Sailors (500) + write temp T2 (250 pages, if we have 10 ratings).
    • Sort T1 (2*2*10), sort T2 (2*3*250), merge (10+250)
    • Total: 3560 page I/Os.

Reserves

Sailors

sid=sid

bid=100

sname

(On-the-fly)

rating > 5

(Scan;

write to

temp T1)

(Scan;

write to

temp T2)

(Sort-Merge Join)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

43

44 of 46

Alternative Plan 2�With Indexes

  • With clustered index on bid of Reserves, we get 100,000/100 = 1000 tuples on 1000/100 = 10 pages for selection.
  • INL with pipelining (outer is not materialized).
  • Join column sid is a key for Sailors.
    • At most one matching tuple, unclustered index on sid OK.
  • Decision not to push rating>5 before the join:
    • there is an index on sid of Sailors, don’t want to compute selection
  • Cost: Selection of Reserves tuples (10 I/Os).
    • For each, must get matching Sailors tuple (1000*(1.2+1)).
    • Total 2210 page I/Os.

Reserves

Sailors

sid=sid

bid=100

sname

(On-the-fly)

rating > 5

(Use hash

index; do

not write

result to

temp)

(Index Nested Loops,

with pipelining )

(On-the-fly)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

44

45 of 46

Summary

  • There are several alternative evaluation algorithms for each relational operator.
  • A query is evaluated by converting it to a tree of operators and evaluating the operators in the tree.
  • Must understand query optimization in order to fully understand the performance impact of a given database design (relations, indexes) on a workload (set of queries).
  • Two parts to optimizing a query:
    • Consider a set of alternative plans.
      • Must prune search space; typically, left-deep plans only.
    • Must estimate cost of each plan that is considered.
      • Must estimate size of result and cost for each plan node.
      • Key issues: Statistics, indexes, operator implementations.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

45

46 of 46

Choosing Indexes

  • Understanding the nature of the workload for the application, and the performance goals, is essential to developing a good design.
    • What are the important queries and updates? What attributes/relations are involved?
  • Indexes must be chosen to speed up important queries (and perhaps some updates!).
    • Index maintenance overhead on updates to key fields.
    • Choose indexes that can help many queries, if possible.
    • Build indexes to support index-only strategies.
    • Clustering is an important decision, demanding on DBMS but potentially high payoff.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke

46