Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)

Slides:



Advertisements
Similar presentations
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
Advertisements

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 15-1 Query Processing and.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19 Algorithms for Query Processing and Optimization.
Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2004 Pearson Education, Inc.
1 CSE 480: Database Systems Lecture 22: Query Optimization Reference: Read Chapter 15.6 – 15.8 of the textbook.
Chapter 14 Indexing Structures for Files Copyright © 2004 Ramez Elmasri and Shamkant Navathe.
CS346: Advanced Databases
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19 Algorithms for Query Processing and Optimization.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19 Algorithms for Query Processing and Optimization.
CS263 Lecture 19 Query Optimisation.  Motivation for Query Optimisation  Phases of Query Processing  Query Trees  RA Transformation Rules  Heuristic.
©Silberschatz, Korth and Sudarshan13.1Database System Concepts Chapter 13: Query Processing Overview Measures of Query Cost Selection Operation Sorting.
QUERY OPTIMIZATION AND QUERY PROCESSING.
CSCI 5708: Query Processing I Pusheng Zhang University of Minnesota Feb 3, 2004.
ACS-4902 Ron McFadyen Chapter 15 Algorithms for Query Processing and Optimization.
Introduction to Query Processing and Query Optimization Techniques
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2004 Pearson Education, Inc.
ACS-4902 Ron McFadyen Chapter 15 Algorithms for Query Processing and Optimization See Sections 15.1, 2, 3, 7.
ICS (072)Query Processing and Optimization 1 Chapter 15 Algorithms for Query Processing and Optimization ICS 424 Advanced Database Systems Dr.
CSCI 5708: Query Processing I Pusheng Zhang University of Minnesota Feb 3, 2004.
Algorithms for Query Processing and Optimization
Chapter 19 Query Processing and Optimization
Indexing dww-database System.
Chapter 61 Chapter 6 Index Structures for Files. Chapter 62 Indexes Indexes are additional auxiliary access structures with typically provide either faster.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 File Organizations and Indexing Chapter 5, 6 of Elmasri “ How index-learning turns no student.
Chapter 14-1 Chapter Outline Types of Single-level Ordered Indexes –Primary Indexes –Clustering Indexes –Secondary Indexes Multilevel Indexes Dynamic Multilevel.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 15-1 Query Processing and.
Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)
©Silberschatz, Korth and Sudarshan13.1Database System Concepts Chapter 13: Query Processing Overview Measures of Query Cost Selection Operation Sorting.
Department of Computer Science and Engineering, HKUST Slide Query Processing and Optimization Query Processing and Optimization.
Query Optimization Chap. 19. Evaluation of SQL Conceptual order of evaluation – Cartesian product of all tables in from clause – Rows not satisfying where.
Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2004 Pearson Education, Inc.
1 Index Structures. 2 Chapter : Objectives Types of Single-level Ordered Indexes Primary Indexes Clustering Indexes Secondary Indexes Multilevel Indexes.
Query Processing and Optimization
Algorithms for Query Processing and Optimization
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
METU Department of Computer Eng Ceng 302 Introduction to DBMS Indexing Structures for Files by Pinar Senkul resources: mostly froom Elmasri, Navathe and.
Chapter 9 Disk Storage and Indexing Structures for Files Copyright © 2004 Pearson Education, Inc.
Indexing Structures for Files
1 Chapter 2 Indexing Structures for Files Adapted from the slides of “Fundamentals of Database Systems” (Elmasri et al., 2003)
Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 12: Query Processing.
Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2004 Pearson Education, Inc.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 13 Disk Storage, Basic File Structures, and Hashing.
1 Chapter 18 Query Processing and Optimization Query Processing and Optimization Scanner: identify language components. keywords, attribute,
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
Query Processing – Query Trees. Evaluation of SQL Conceptual order of evaluation – Cartesian product of all tables in from clause – Rows not satisfying.
Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2004 Pearson Education, Inc.
Advance Database Systems Query Optimization Ch 15 Department of Computer Science The University of Lahore.
1 B + -Trees: Search  If there are n search-key values in the file,  the path is no longer than  log  f/2  (n)  (worst case).
Chapter 14 Indexing Structures for Files Copyright © 2004 Ramez Elmasri and Shamkant Navathe.
Query Processing – Implementing Set Operations and Joins Chap. 19.
Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2004 Pearson Education, Inc.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 18 Indexing Structures for Files.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Introduction to Query Processing (1) Query optimization: The process of choosing a suitable execution.
Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2004 Pearson Education, Inc.
Query Processing COMP3017 Advanced Databases Nicholas Gibbins
Copyright © 2011 Ramez Elmasri and Shamkant Navathe CPSC 8620: Database Management System Design Notes 7 Query Processing.
Query optimization Algorithms for execution query elements Execution strategy Query optimization when using indices.
Query Processing and Query Optimization Database System Implementation CSE 507 Slides adapted from Silberschatz, Korth and Sudarshan Database System Concepts.
Algorithms for Query Processing and Optimization
10/3/2017 Chapter 6 Index Structures.
Query Processing and Optimization, and Database Tuning
Systém riadenia bázy dát Database Management System
QUERY OPTIMIZATION.
1/3/2019.
Advance Database Systems
Database Administration
Algorithms for Query Processing and Optimization
Presentation transcript:

Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)

2 Obsah RAID 2-phase multiway sort-merge Fyzická organizácia dát Indexovanie Systémový katalóg Operácie relačnej algebry (krátko) Implementácia operácií relačnej algebry Query plány – optimalizácia dotazov

3 Literatúra [1] Hector Garcia-Molina, Jeffrey D. Ullman, Jennifer D. Widom: Database System Implementation, Prentice Hall, ISBN-10: , pp.653 Database Systems: The Complete Book, 2001

4 Literatúra [2] Elmasri R., Navathe S. B. : Fundamentals of database systems. 4th ed., Pearson Education, th ed. – 2006, pp (ch ; 120 resp. 220 str.)

5 Literatúra [3] Ramakrishnan R., Gehrke J.: Database Management Systems. McGraw-Hill Science/Engineering/Math; 3rd ed., 2002, pp. 906 (ch. 7-14; 220 str.)

6 Literatúra [4] Abraham Silberschatz, Henry Korth, S. Sudarshan: Database System Concepts. McGraw-Hill Science/Engineering/Math; 5th ed., pp.~920 (ch ; 170 resp. 290 str.

RAID Obrázky (väčšina) z [2]

8 RAID Originally - Redundant Arrays of Inexpensive Disks. Currently - Redundant Array of Independent Disks Chen, Lee, Gibson, Katz, and Patterson (1994), ACM Computing Survey, Vol. 26, No.2 (June 1994). (pekne názorne spracované)

9 RAID 0

10 RAID 1, 2

11 RAID 3, 4, 5, 6

12 RAID – ďalšie kombinácie 10, 01 - Kombinácie základných RAIDov Performance: –Block-interleaved distributed-parity disk arrays (RAID 5) have the best small read, large read, and large write performance of any redundant disk array. –Small write requests are somewhat inefficient compared with redundancy schemes such as mirroring.

Two phase, multiway sort-merge Na základe prezentácie Simonas Šaltenis: Advanced Algorithm Design and Analysis

14 Purpose of Algorithm Triedenie veľkých súborov dát (Data>Memory) Klasický algoritmus – Wirthov sort-merge algoritmus (Wirth C.: Algoritmy a dátové štruktúry.)

15 Princíp – 1. fáza 1.Vytvoriť maximálne možné veľké „behy“ (utriedené postupnosti elementov) – najlepšie načítaním do dostupnej pamäte a zotriedením napr. quick-sortom 2.Spájanie behov (mergovanie)

16 Princíp – 2. fáza File Y: File X: Run 1 Run 2 Current page EOF Bf1 p1 Bf2 p2 Bfo po min(Bf1[p1], Bf2[p2], …, Bfk[pk]) Read, when pi = B Write, when Bfo full Run k=n/m Current page Bfk pk

17 Zhodnotenie Fáza 1: O(n), Fáza 2: O(n) Celkom: O(n) I/Os! Dajú sa triediť iba súbory obmedzenej veľkosti –Fáza 2 môže spájať (merge) maximálne m-1 behov (m – počet vyrovnávacích pamätí). –Čo znamená: N/M (počet behov) ≤ m-1

18 Triedenie veľmi veľkých súborov (m-1) 2 M (m-1) 3 M = N Phase 2 Phase 1 … MM (m-1)M MM M M … MM MM M M … MM MM M M … … …...

19 Otázky

SRBD – štruktúry a algoritmy

21 Zdroj [1]

Primárne (fyzické) organizácie

23 Zdroj:Paul Beynon-Davies: DATABASE SYSTEMS.3RD ED. PALGRAVE MACMILLAN,2004

24 O čom budeme hovoriť Podporované dátové typy Formovanie záznamov Organizácia (radenie) záznamov –fyzická –logická „Umiestnenie“ DBMS v rámci OS

25 Podporované dátové typy Tzv. built-in dátové typy Pre účely ukladania dát, je pre nás zaujímavá veľkosť dátového typu (sizeof(typ)) „Sémantika“ typu je podporená implementáciou (HW alebo SW) relevantných operácií (out of scope)

26 Formáty ukladaných záznamov Záznamy s pevnou dĺžkou (A fixed-length record) Záznamy s premenlivou dĺžkou (A record with variable-length fields) Záznamy s premenlivou dĺžkou s oddelľovačmi (A variable-field record with separator characters).

27 Storage Record Formats [2]

28 Fixed length record Veľkosť záznamu je uložená v systémovom katalógu

29 Variable length records Záznamy s premenlivou dĺžkou

30 Reprezentácia NULL hodnôt Prakticky väčšina zdrojov o spôsobe implementácie „mlčí“ Pri záznamoch premenlivej dĺžky sa dá využiť null pointer na prvok záznamu ORACLE v dokumentácii pre ORA7 prezentoval ukladanie NULL hodnoty cez bitmapový prefix záznamu

31 Fyzická organizácia záznamov

32 Fyzická organizácia záznamov 2

33 Umiestňovanie záznamov do fyzických blokov Spanned Unspanned

34 Logické organizácie záznamov Sekvenčná Hašovaná Heap (hromada) Zhodnotenie z pohľadu operácií insert, find a delete

35 Sekvenčná organizácia

36 Zhodnotenie – sekvenčná org. Insert – drahá operácia (potreba posunúť priemerne N/2 záznamov) – oblasti pretečenia (overflow areas) Find – možnosť binárneho vyhľadávania podľa usporiadavajúceho atribútu - O(log 2 N), ináč O(N) = N/2 alebo N Delete – drahá operácia (potreba posunúť priemerne N/2 záznamov) – možnosť označovať záznamy ako zmazané  pack

37 Interné Hašovanie

38 Zhodnotenie – hašovanie Insert – O(1) ak neuvažujeme konflikty; ak uvažujeme - najhorší prípad O(N) Find – O(1) – hashovací atribút, O(N) ostatné atribúty Delete – O(1) Štruktúra musí byť dimenzovaná na maximálny počet záznamov

39 Externé hašovanie

40 Zhodnotenie - externé hašovanie Ako interné hašovanie Konflikty sa riešia blokmi pretečenia (viď ďalší slajd )

41 Ext. hašovanie –bloky pretečenia

42 „Rozšíriteľné“ hašovanie

43 Zhodnotenie – rozšíriteľné hašovanie Ako externé hašovanie Plusom je možnosť dynamického rozširovania „veľkosti hašovacieho poľa“

44 Heap (hromada) Záznamy sú neusporiadané – nie je usporiadavací atrubút Strácame možnosť - binárne vyhľadávanie; primárny index (ale iba pre usporiad. atr.) Veľmi efektívna operácia INSERT

45 Miesto DBMS v rámci OS Cooked files Raw devices NTFS DBMS Služby OS Filesystem Driver DBMS Služby OS - Driver

46 Otázky

Indexovanie Z podstatnej časti podľa [2] Všetky obrázky z [2]

48 Index Alternatívny spôsob prístupu k dátam Lokalizácia záznamu podľa obsahu

49 Kategorizácia indexov Počet úrovní Kategorizácia indexov Indexované záznamy Indexovaný atribút Hustý Riedky Primárne Viacúrovňové Jednoúrovňové Sekundárne Klastrovacie

50 Kategorizácia indexov Podľa počtu úrovní: –Jedno-úrovňové –Viac-úrovňové Podľa indexovaného atribútu: –Primárne –Klastrovacie (clustering) –Sekundárne Podľa počtu indexovaných záznamov: –Hustý (dense) – všetky záznamy v indexe –Riedky (sparse) – len časť záznamov v indexe

51 Jednoúrovňové indexy

52 Primárny index Indexuje „usporiadavajúci“ (ordering) atribút Riedky (sparse) index „Kotviaci“ záznam INSERT problém

53 Clustering index Aj nad „neusporia- davajúcim“ atribú- tom Primárna organizá- cia sa usporiada podľa daného atri- bútu – pri budovaní indexu

54 Clustering index Pri bežnej práci sa primárna organizácia nemodifikuje, ale používajú sa bloky pretečenia (overflow)

55 Sekundárny index Index nad neusporiada- vajúcim atribútom (ale kľúčovým) Hustý (dense) index

56 Sekundárny index Nad nekľúčovým atribútom (opakujúce sa hodnoty)

57 Priebežné zhodnotenie Zatiaľ iba jednoúrovňové indexy Prínos ( N – počet záznamov, r – záznamov v bloku) –Vyhľadávanie nad „ordered“ kľúčom – log 2 N –Vyhľadávanie nad „non-ordered“ kľúčom – N/2 –Vyhľadávanie nad nekľúčovým atribútom – N –Primárny index log 2 (N/r) –Sekundárny index log 2 N (počet čítaných blokov – podstatne menší, kvôli vyššiemu blokovaciemu faktoru)

58 Príklad – sekvenčný súbor (ordering attribute) Ordered file with r = 30,000 records Block size B = 1024 bytes. Records are of fixed size and are unspanned Record length R = 100 bytes. The blocking factor bfr = floor(B/R) = floor(1024/100) = 10 records per block. The number of blocks b = (r/bfr) = r (30,000/1O)l = 3000 blocks. A binary search would need approximately –floor(log 2 b) = floor(log ) = 12 block accesses.

59 Primárny index Na osvieženie pamäti

60 Príklad – primárny index Key field of the file is V = 9 bytes long, a block pointer is P = 6 bytes size of index entry R = (9 + 6) = 15 bytes,  blocking factor bfr i = floor(B/R i ) = floor(1024/15) = 68 entries per block. The total number of index entries r i is equal to the number of blocks in the data file The number of index blocks is hence b i = ceiling(r/bfr i ) = ceiling(3000/68) = 45 blocks. To perform a binary search on the index file would need ceiling (log 2 b i )l = ceiling (log 2 45) = 6 (block accesses). To search for a record using the index, we need one additional block access to the data file - total of = 7 block accesses

61 Príklad – sekundárny index As example 1: r = 30,000,R = 100 bytes, B = 1024 bytes. To do a linear search, we would require b/2 = 3000/2 = 1500 block accesses (on the average, 3000 in the worst case) Supppose V = 9 and P = 6  bfr i = 68 –secondary index is dense  the total number of index entries r i is equal to the number of records = 30,000. –The number of blocks needed for the index is b i = ceiling(r/bfr) = 1(30,000/68) l = 442 blocks. –A binary search on this secondary index needs ceiling(log 2 b i ) = ceiling (log 2 442) = 9 block accesses.

62 Porovnanie (single-level) indexov

63 Viacúrovňové indexy (Multi-Level Indexes)

64 Viacúrovňové indexy Vzhľadom na to, že jednoúrovňový index je „usporiadaným“ súborom (ordered file), môžeme vytvoriť primárny index nad indexom samotným; v tomto prípade originálny indexový súbor sa nazýva indexom prvej úrovne (first-level index) a index nad indexom sa nazýva indexom druhej úrovne (second-level index). Proces môžeme opakovať, vytvárajúc tretiu, štvrtú,..., najvyššiu úroveň dovtedy, kým najvyššia úroveň nezaberá jediný blok na disku Viac úrovňový index môže byť vytvorený pre akýkoľvek typ indexu prvej úrovne (primary, secondary, clustering) za predpokladu, že index prvej úrovne zaberá viac ako jeden diskový blok

65 Viacúrovňové indexy Prvá úroveň - dense alebo sparse Ďalšie úrovne už iba sparse Top level – iba jeden blok Vyhľadávanie vyžaduje pribl. (log bfri b i ) „block accesses“ INSERT problém !!!

66 Dynamické viacúroňové indexy na báze B- Trees a B+-Trees Kvôli problémom so zaraďovaním a vyraďovaním záznamov, vačšina viacúrovňových indexov používa B- tree or B+-tree Tieto štruktúry umožňujú efektívne vykonávanie vkladaní a mazaní nových hodnôt (search values). V B-Tree a B+-Tree, každý uzol stromu zodpovedá diskovému bloku Každý uzol je udržiavaný zaplnený na viac ako polovicu

67 Dynamické viacúroňové indexy na báze B- Trees a B+-Trees (pokr.) Vkladanie do uzla, ktorý nie je úplne zaplnený je veľmi efektívne; ak je uzol plný, operácia vkladanie spôsobí rozdelenie uzla do dvoch uzlov (pôvodný a nový) Rozdeľovanie sa môže šíriť do ďalších úrovní stromu Mazanie je opäť relatívne efektívne, kým uzol „nepodtečie“ pod polovicu Ak dôjde k podtečeniu pri mazaní, uzol musí byť spojený so susednými uzlami (hrozí „kolaps“ úrovne)

68 Rozdiely medzi B-tree a B+-tree V B-tree, odkazy (pointers) na dátové záznamy sú uložené vo všetkých uzloch stromu (na všetkých úrovniach) V B+-tree, odkazy (pointers) na dátové záznamy sú uložené iba v listových uzloch stromu B+-tree môže mať menej úrovní (alebo väčšiu „kapacitu“) než zodpovedajúci B-tree

69 Štruktúra B-tree

70 Štruktúra B+-tree

71 B+-tree príklad

72 B-tree príklad – zopár čísel [2]

73 B+-tree príklad - zopár čísel [2]

74 B-tree – duplicate keys

75 Otázky

Systémový katalóg Na základe prezentácie Ľubomíra Miškoviča

77 Čo je systémový katalóg Systémový katalóg uchováva dáta ktoré popisujú každú databázu (metadata) Obsahuje popis: –Položiek, viet, súborov a vzťahov medzi nimi –Konceptuálnej schémy, externých schém a internú schému. Je tu popísané aj mapovanie medzi schémami na rôznych úrovniach

78 Zjednodušený model prostredia databázového systému

79 Obsah systémového katalógu Katalógy pre relačné SRBD obsahujú –Názvy relácií –Názvy atribútov –Domény atribútov –Primárne kľúče –Sekundárne kľúčové atribúty –Cudzie kľúče –Podmienky

80 Obsah systémového katalógu Ďalej obsahujú popisy –Externých pohľadov –Uloženie štruktúr a indexov pre internú úroveň –Informácie o bezpečnosti a autorizácií, ktoré definujú prístup používateľa k databázovým pohľadom –Prihlasovacie mená tvorcov alebo vlastníkov každej relácie

81 Obsah systémového katalógu Uchovávajú informácie ako –Veľkosť záznamu –Aktuálny počet záznamov –Počet indexov –Meno tvorcu každej relácie

82 Spôsoby implementácie systémového katalógu Systémový katalóg môže byť vytváraný pre každú databázu v systéme, alebo môže byť spoločný pre všetky databázy Systémový katalóg môže byť tvorený tabuľkami, ktorých štruktúra je totožná s tabuľkou databázy alebo špeciálnou štruktúrou

83 Príklad systémových katalógov pre Informix Systables – opisuje každú tabuľku v databáze. Obsahuje jeden riadok pre každú tabuľku v databáze, pohľad alebo synonymum definované v databáze. Zahŕňa všetky tabuľky v databáze aj tabuľku systémového katalógu Syscolumns – definuje každý stĺpec v databáze. Pre každý stĺpec definovaný v tabuľke alebo pohľade existuje jeden riadok Sysindex – popisuje indexy v databáze. Obsahuje jeden riadok pre každý index definovaný v databáze

84 Systables

85 syscolumns

86 Vzťah medzi tabuľkami

87 Oracle

88 Postgres

89 Otázky

Relačná algebra (RA) a implementácia operácií RA Podľa [2]

91 Relačná algebra Relácia - podmnožina karteziánskeho súčinu R  D 1 ...  D n Relačná algebra: –Formálny jazyk pre relačný model –Základný súbor operácií pre vyhľadávacie dotazy

92 Selekcia  Projekcia  Kartéziánsky súčin  Spojenie (join) (theta-, equi-, natural- ) Množinové (union kompatibilné): –Prienik (intersection)  –Zjednotenie (union)  –Rozdiel (difference) \ Operácie relačnej algebry

93 Elementary conditionEC and condition C Definition: Elementary (simple) condition EC is clause of the form: where operator is from the set of relational operators {=,, =,≠}. Definition: Condition C is clause of the form : [NOT] EC1 [{OR | AND } [ [NOT] EC2] …]

94 Examples (O1):  SSN=' ' (EMPLOYEE) (O2):  DNUMBER>5 (DEPARTMENT) (O3):  DNO=5 (EMPLOYEE) (O4):  DNO=5 AND SALARY>30000 AND SEX=' F' (EMPLOYEE) (O5):  ESSN=' ' AND PNO=10 (WORKS_ON)

95 SELECT operation Definition:  c = {  t i  R | c(t i )}(3-value logic) Implementation: –Linear search –Binary search –Using a primary index (or hash key) –Using a primary index to retrieve multiple records –Using a clustering index to retrieve multiple records –Using a secondary (B+-tree) index on an equality comparison –...

96 S1:Linear search (brute force) Retrieve every record in the file, and test whether its attribute values satisfy the selection condition. for every t i if (c(t i ) == TRUE) output(t i )

97 S2:Binary search If the selection condition involves an equality comparison on a key attribute on which the file is ordered.  SSN=' ' (EMPLOYEE)

98 S3: Using a primary index (or hash key) If the selection condition involves an equality comparison on a key attribute with a primary index (or hash key), use the primary index (or hash key) to retrieve the record. Note that this condition retrieves a single record (at most).  SSN=' ' (EMPLOYEE)

99 S4: Using a primary index to retrieve multiple records If the comparison condition is >, >=, <', or <= on a key field with a primary index, use the index to find the record satisfying the corresponding condition  DNUMBER>5 (DEPARTMENT) (selectivity, distribution)  DNO=5 AND SALARY>30000 AND SEX=' F' (EMPLOYEE)

100 S5: Using a clustering index to retrieve multiple records If the selection condition involves an equality comparison on a non key attribute with a clustering index (for example, DNO = 5 in S3) use the index to retrieve all the records satisfying the condition.  DNO=5 (EMPLOYEE) (if clusterred on DNO)

101 S6: Using a secondary (B+-tree) index on an equality comparison This search method can be used to retrieve a single record if the indexing field is a key (has unique values) or to retrieve multiple records if the indexing field is not a key. This can also be used for comparisons involving >, >=, <, or <=.

102 S7: Conjunctive selection using an individual index If an attribute involved in any single simple condition in the conjunctive condition has an access path that permits the use of one of the Methods S2 (binary search) to S6 (B- tree), use that condition to retrieve the records and then check whether each retrieved record satisfies the remaining simple conditions in the conjunctive condition.

103 S8:Conjunctive selection using a composite index If two or more attributes are involved in equality conditions in the conjunctive condition and a composite index (or hash structure) exists on the combined fields-for example, if an index has been created on the composite key (ESSN, PNO) of the WORKS_ON file for O5-we can use the index directly.

104 JOIN operation R ⋈ c S = {t i  R,t j  S| c(t i,t j ) == TRUE } Implementácia –Nested-loop join (brute force) –Single-loop join (using an access structure to retrieve the matching records) –Sort-merge join –Hash-join

105 J1. Nested-loop join (brute force) For each record t in R (outer loop), retrieve every record s from S (inner loop) and test whether the two records satisfy the join condition c (incl. theta-join). for each t i for each s j if( c(t i,s j ) == TRUE ) output(t i.s j ) Improvement - nested-block join

106 J2. Single-loop join (using an access structure to retrieve the matching records) If an index (or hash key) exists for one of the two join attributes-say, B of S, retrieve each record t in R, one at a time (single loop), and then use the access structure to retrieve directly all matching records s from S that satisfy t[B] =t[A] (equi-join).

107 J3. Sort-merge join If the records of R and S are physically sorted (ordered) by value of the join attributes A and B, respectively, we can implement the join in the most efficient way possible. Both files are scanned concurrently in order of the join attributes, matching the records that have the same values for A and B. If the files are not sorted, they may be sorted first by using external sorting.

108 J4. Hash-join The records of files R and S are both hashed to the same hash file, using the same hashing function on the join attributes A of R and B of S as hash keys. First, a single pass through the file with fewer records (say, R) hashes its records to the hash file buckets (partitioning phase - records of R are partitioned into the hash buckets). In the second phase (probing phase), a single pass through the other file (S) then hashes each of its records to probe the appropriate bucket, and that record is combined with all matching records from R in that bucket.

109 PROJECT operation  (R) Implementation: –straightforward to implement if includes a key of relation R – the same number of records. –If does not include a key of R, duplicate tuples must be eliminated (sorting, hashing). –Index can be used in some cases.

110 SET operation CARTESIAN PRODUCT operation R  S is quite expensive, because its result includes a record for each combination of records from R and S. Can be improved by processing at the block level UNION, INTERSECTION, and SET DIFFERENCE apply only to union-compatible relations (that have the same number of attributes and the same attribute domains). Implementation - sort-merge technique or hashing

111 Sort-merge technique (for the SET operation) The two relations are sorted on the same attributes. After sorting, a single scan through each relation is sufficient to produce the result. For example, we can implement the UNION operation, R  S, by scanning and merging both sorted files concurrently, and whenever the same tuple exists in both relations, only one is kept in the merged result. For the INTERSECTION operation, R  S, we keep in the merged result only those tuples that appear in both relations.

112 Hashing (for the SET operation) One table is partitioned and the other is used to probe the appropriate partition. For example, to implement R  S, first hash (partition) the records of R; then, hash (probe) the records of S, but do not insert duplicate records in the buckets. To implement R  S, first partition the records of R to the hash file. Then, while hashing each record of S, probe to check if an identical record from R is found in the bucket, and if so add the record to the result file. To implement R - S, first hash the records of R to the hash file buckets. While hashing (probing) each record of S, if an identical record is found in the bucket, remove that record from the bucket.

113 Implementing Aggregate Operations The aggregate operators (MIN, MAX, COUNT, AVERAGE, SUM), when applied to an entire table, can be computed by a table scan or by using an appropriate index, if available. For example, consider the following SQL query: SELECT MAX(SALARY) FROM EMPLOYEE; If an (ascending) index on SALARY exists for the EMPLOYEE relation, then the optimizer can decide on using the index to search for the largest value by following the rightmost pointer in each index node from the root to the rightmost leaf.

114 Implementing Aggregate Operations The dense index can be used for the COUNT, AVERAGE, and SUM aggregates. The associated computation would be applied to the values in the index.

115 GROUP BY clause When a GROUP BY clause is used in a query, the aggregate operator must be applied separately to each group of tuples. In this case, the computation is more complex - the table must first be partitioned into subsets of tuples, where each partition (group) has the same value for the grouping attributes. Sorting or hashing are used to partition the file into the appropriate groups If a clustering index exists on the grouping attributes, then the records are already partitioned (grouped) into the appropriate subsets.

116 Otázky

Query processing and optimization Based on [2]

118 Query processing

119 Execution (query) plan Logical query plan Physical query plan

120 Logical query plan SQL – deklaratívny jazyk Potrebujeme transformovať dotaz v SQL (SELECT) na (previazanú) postupnosť operácií relačnej algebry Optimalizovať na logickej úrovni

121 Query tree A query tree - tree data structure that corresponds to a relational algebra expression. It represents the input relations of the query as leaf nodes of the tree, and represents the relational algebra operations as internal nodes. An execution of the query tree consists of executing an internal node operation whenever its operands are available and then replacing that internal node by the relation that results from executing the operation. The execution terminates when the root node is executed and produces the result relation for the query.

122 Query tree – example

123 Query tree – example (cont.) Example: For every project located in ‘ Stafford ’, retrieve the project number, the controlling department number and the department manager ’ s last name, address and birthdate. Relation algebra:  PNUMBER, DNUM, LNAME, ADDRESS, BDATE (((  PLOCATION=‘STAFFORD’ (PROJECT)) ⋈ DNUM=DNUMBER (DEPARTMENT)) ⋈ MGRSSN=SSN (EMPLOYEE)) SQL query: Q2: SELECT P.NUMBER,P.DNUM,E.LNAME, E.ADDRESS, E.BDATE FROM PROJECT AS P,DEPARTMENT AS D, EMPLOYEE AS E WHERE P.DNUM=D.DNUMBER AND D.MGRSSN=E.SSN AND P.PLOCATION= ‘ STAFFORD ’ ;

124 Query tree – example

125 Inicial (canonical) query tree

126 Konštrukcia „canonical query tree“ Nad všetkými reláciami vybuduj „veľký“ kartézsky súčin Vyselektuj záznamy podľa úplnej podmienky vo WHERE klauzule Sprav projekciu výsledku podľa atribútov za SELECT klauzulou

127 Konštrukcia „canonical query tree“ SELECT FROM T 1, …, T n WHERE C V relačnej algebre:  (  c (  (T 1, …, T n ) ) ) T1, …, Tn X cc 

128 Heuristic Optimization of Query Trees The same query could correspond to many different relational algebra expressions — and hence many different query trees. The task of heuristic optimization of query trees is to find a final query tree that is efficient to execute. Example: Q: SELECT LNAME FROM EMPLOYEE, WORKS_ON, PROJECT WHERE PNAME = ‘ AQUARIUS ’ AND PNMUBER=PNO AND ESSN=SSN AND BDATE > ‘ ’ ;

129 Canonical query tree

130 Steps in converting QT (1)

131 Steps in converting QT (2)

132 Transformation Rules for query optimization  Cascade of  : A conjunctive selection condition can be broken up into a cascade (sequence) of individual s operations:  c1 AND c2 AND... AND cn (R)   c1 (  c2 (...(  cn (R))...) )  Commutativity of  : The  operation is commutative:  c1 (  c2 (R))   c2 (  c1 (R))  Cascade of  : In a cascade (sequence) of  operations, all but the last one can be ignored:  List1 (  List2 (...(  Listn (R))...) ) =  List1 (R)

133 Transformation Rules for query optimization  Commuting  with  : If the selection condition c involves only the attributes A1,..., An in the projection list, the two operations can be commuted:  A1, A2,..., An (  c (R)) =  c (  A1, A2,..., An (R))  Comutativity of ⋈ ( and x ): The ⋈ operation is commutative as is the x operation: R ⋈ C S = S ⋈ C R; R x S = S x R

134 Transformation Rules for query optimization  Commuting  with ⋈ (or x  ): If all the attributes in the selection condition c involve only the attributes of one of the relations being joined - say, R - the two operations can be commuted as follows :  c ( R ⋈ S )  (  c (R)) ⋈ S Alternatively, if the selection condition c can be written as (c1 and c2), where condition c1 involves only the attributes of R and condition c2 involves only the attributes of S, the operations commute as follows:  c ( R ⋈ S )  (  c1 (R)) ⋈ (  c2 (S))

135 Transformation Rules for query optimization  Commuting  with ⋈ (or x ): Suppose that the projection list is L = {A1,..., An, B1,..., Bm}, where A1,..., An are attributes of R and B1,..., Bm are attributes of S. If the join condition c involves only attributes in L, the two operations can be commuted as follows:  L ( R ⋈ C S )  (  A1,..., An (R)) ⋈ C (  B1,..., Bm (S)) If the join condition c contains additional attributes not in L, these must be added to the projection list, and a final  operation is needed.

136 Transformation Rules for query optimization  Commutativity of set operations: The set operations  and  are commutative but – is not.  Associativity of ⋈, x, , and  : These four operations are individually associative; that is, if  stands for any one of these four operations (throughout the expression), we have ( R  S )  T  R  ( S  T )  Commuting  with set operations: The  operation commutes with  , , and –. If  stands for any one of these three operations, we have  c ( R  S )  (  c (R))  (  c (S))

137 Transformation Rules for query optimization  The  operation commutes with υ.  L ( R  S )  (  L (R))  (  L (S))  Converting a (  x  sequence into ⋈ : If the condition c of a  that  follows a  corresponds to a join condition, convert the (  x  sequence into a ⋈ as follows: (  C (R x S)) = (R ⋈ C S)  Other transformations

138 Outline of a Heuristic Algebraic Optimization Algorithm  Using rule 1, break up any select operations with conjunctive conditions into a cascade of select operations.  Using rules 2, 4, 6, and 10 concerning the commutativity of select with other operations, move each select operation as far down the query tree as is permitted by the attributes involved in the select condition.  Using rule 9 concerning associativity of binary operations, rearrange the leaf nodes of the tree so that the leaf node relations with the most restrictive select operations are executed first in the query tree representation.

139 Outline of a Heuristic Algebraic Optimization Algorithm  Using Rule 12, combine a cartesian product operation with a subsequent select operation in the tree into a join operation.  Using rules 3, 4, 7, and 11 concerning the cascading of project and the commuting of project with other operations, break down and move lists of projection attributes down the tree as far as possible by creating new project operations as needed.  Identify subtrees that represent groups of operations that can be executed by a single algorithm.

140 Summary of Heuristics for Algebraic Optimization  The main heuristic is to apply first the operations that reduce the size of intermediate results.  Perform select operations as early as possible to reduce the number of tuples and perform project operations as early as possible to reduce the number of attributes. (This is done by moving select and project operations as far down the tree as possible.)  The select and join operations that are most restrictive should be executed before other similar operations. (This is done by reordering the leaf nodes of the tree among themselves and adjusting the rest of the tree appropriately.)

141 Physical Query ( Execution ) Plans An physical query plan for a relational algebra query consists of a combination of the relational algebra query tree and information about the access methods to be used for each relation as well as the methods to be used in computing the relational operators stored in the tree.

142 Úloha Ako “obsadiť“ jednotlivé operácie RA konkrétnymi implementáciami? Potreba ohodnotenia jednotlivých implementácií – cost based optimization Mali by sa vybudovať a prepočítať všetky možnosti Ak ich je veľa, preverujú sa len niektoré vetvy

143 Cost Components for Query Execution 1.Access cost to secondary storage 2.Storage cost 3.Computation cost 4.Memory usage cost 5.Communication cost Note: Different database systems may focus on different cost components.

144 Catalog Information Used in Cost Functions –Information about the size of a file number of records (tuples) (r), record size (R), number of blocks (b) blocking factor (bfr) –Information about indexes and indexing attributes of a file Number of levels (x) of each multilevel index Number of first-level index blocks (b I1 ) Number of distinct values (d) of an attribute Selectivity (sl) of an attribute Selection cardinality (s) of an attribute. (s = sl * r)

145 Otázky

Ladenie dotazov

147 Príklad INFORMIX (1) Detailnejsi opis - Sample Query Plan Reports.pdf

148 Príklad INFORMIX (2)

149 Príklad INFORMIX (3)

150 MS-SQL

Späť k DWH

152 Efektívna implementácia Bitmapové indexy Bitmapové join indexy C-store

153 Otázky