Aljabar Relasional dan Pemrosesan Query IF 6323903 Sistem
Aljabar Relasional dan Pemrosesan Query IF 6323903 - Sistem Basis Data andika. amalia@ittelkom-pwt. ac. id
Capaian Pembelajaran • Mahasiswa mampu menjelaskan tahapan proses dalam pemrosesan query
Sub Chapters • Aljabar Relasional • Pemrosesan Query
Bahasa Query Formal Dua bentuk bahasa query formal yang merupakan dasar dari bahasa “nyata” (contoh : SQL), dan dasar dari implementasi: • Aljabar Relasional: prosedural, fokus pada langkah untuk menghitung jawaban yang diinginkan berdasarkan urutan operator di dalam query • Relational Calculus: deklaratif, memungkinkan pengguna menggambarkan himpunan jawaban tanpa menyatakan secara eksplisit bagaimana jawaban itu dihitung Query language is NOT a programming language!
Konsep Relasional • Relasi direpresentasikan sebagai sebuah tabel • Element t of r adalah tuple, direpresentasikan sebagai baris pada attribut sebuah tabel (kolom) customer_name customer_street Jones Smith Curry Lindsay Main North Park customer_city Harrison Rye Pittsfield tuples (baris)
Operator Dasar Aljabar Relasional • Select ( ) : Seleksi sejumlah baris dari relasi • Project ( ) : menghapus kolom yang tidak diinginkan dari relasi • Union ( ) : tupleyangadapadarelasi 1 dan relasi 2 • set difference (–) : tuple yang ada pada relasi 1 tetapi tidak ada di relasi 2 • Cartesian product (x) : kombinasi 2 relasi • Rename ( ) : mengubah nama relasi
Operasi Select (1) • Notasi: p(r) • Digunakan untuk menyeleksi sekumulan tuple dari sebuah relasi yang memenuhi kondisi seleksi • Dijabarkan : p(r) = {t | t r and p(t)} • Penggabungan formula (and), (or), (not) • Operator : =, , >, , <, • Contoh : branch_name=“Perryridge”(account)
Operasi Select (2) Contoh : n Relasi r ¡ A=B ^ D > 5 (r) A B C D 1 7 5 7 12 3 23 10 A B C D 1 7 23 10
Operasi Select (3)
Operasi Projection (1) • Notasi: dimana A 1, A 2 adalah nama atribut dan r adalah nama relasi • Hasilnya adalah sebuah relasi dari beberapa yang didefinisikan pada query • Hasil yang duplikat akan diambil salah satu • Example: Untuk mengambil kolom selain atribut branch_name dari relasi account_number, balance (account)
Operasi Projection (2) • Relation r: A, C (r) A B C 10 1 20 1 30 1 40 2 A C 1 1 1 2 2 =
Operasi Projection (3)
Operasi Union (1) • Notasi: r s • Dijabarkan : r s = {t | t r or t s} • Syarat r s valid : 1. r, s harus memiliki jumlah atribut yang sama 2. Domain atribut harus kompatibel (contoh: kolom kedua r tipe nilai yang dikeluarkan sama dengan kolom kedua s) union-compatible • Contoh : carilah nama customer yang memiliki deposito dan pinjaman customer_name (depositor) customer_name (borrower)
Operasi Union (2) • Relasi r, s: A B 1 2 2 3 1 s r n r s: A B 1 2 1 3
Operasi Union (3) Student FN Student Instructor Student LN Instructor FN LN John Smith Susan Yao Picardo Brown Susan Yao Zanu Zahwa Joni Kohir Barbara Jones Amy Ford Jimmy Wang Ernest Nirina John Smith Picardo Brown Francis John Susan Yao Zanu Zahwa Joni Kohir Francis John Barbara Jones Zanu Zahwa Amy Ford Jimmy Wang Ernest Nirina
Type Compatibility • Dua relasi dikatakan union-compatible jika memiliki derajat yang sama(jumlah atribut yang sama ) dan urutan atribut memiliki domain yang sama • Asumsi ada 2 tabel : • Checking-Account (c-num, c-owner, c-balance) • Saving-Account (s-num, s-owner, s-balance) – Kedua tabel tersebut union-compatible • Union, intersection dan set difference membutuhkan tabel-tabel yang union-compatible
Operasi Intersection (1) • Hasil dari operasi ini, dinotasikan dengan R ∩ S, adalah sebuah relasi yang mengandung semua tuple yang muncul pada R dan S. Harus"type compatible" • Contoh : Hasil operasi intersection Student FN LN Susan Yao Zanu Student Instructor FN LN Zahwa John Smith Joni Kohir Susan Yao Picardo Brown Barbara Jones Susan Yao Zanu Zahwa Amy Ford Francis John Jimmy Wang Zanu Zahwa Ernest Nirina
Operasi Intersection (2) C-num C-owner C-balance s-num s-owner s-balance 101 J. Smith 1000 103 J. Smith 5000 102 Warto 2000 104 Jenny 1000 105 Seno 10. 000 Saving-Account Checking-Account • Checking-Account Saving-Account ? ? ? – Kosong. Tidak ada tuple yang sama • ( c-owner. Checking-Account) ( s-owner. Saving-Account) ? – J. Smith
Operasi Set Difference (1) • Notasi r – s • Dijabarkan : r – s = {t | t r and t s} • Set difference harus diambil dari relasi yang union compatible – r dan s memiliki jumlah atribut sama – Domain atribut dari r and s harus compatible
Operasi Set Difference (1) • Relasi r, s: A B 1 2 2 3 1 s r n r – s: A B 1 1
Operasi Cartesian Product (1) • Notasi r x s • Dijabarkan : r x s = {t q | t r and q s} • Anggap atribut dari r(R) and s(S) disjoint. (Yaitu, R S = ). • Jika atribut r(R) and s(S) tidak disjoint, maka operasi renaming harus dilakukan
Operasi Cartesian Product (2) • Union and intersection adalah operasi komutatif; yaitu R ∪ S = S ∪ R, and R ∩ S = S ∩ R • Union and intersection dapat ditangani dalam bentuk operasi n-ary yang menangani banyak relasi dan merupakan operasi asosiasi ; yaitu R ∪ (S ∪ T) = (R ∪ S) ∪ T, and (R ∩ S) ∩ T = R ∩ (S ∩ T) • Operasi minus bukan merupakan operasi komutatif R-S≠S–R
Operasi Cartesian Product (3) n Relations r, s: A B C D E 1 2 10 10 20 10 a a b b r s n r x s: Cartesian Product : kombinasi informasi dari kedua tabel, menghasilkan semua kombinasi yang mungkin A B C D E 1 1 2 2 10 10 20 10 a a b b
Operasi Composite • Penggunaan lebih dari 1 operasi dalam sebuah query • Contoh : A=C(r x s) rxs A=C(r x s) A B C D E 1 1 2 2 10 10 20 10 a a b b A B C D E 1 2 2 10 20 a a b
Operasi Rename • Mengubah nama , dari hasil aljar relasional • Contoh : x (E) menghasilkan E dengan nama X • Jika aljabar relasional E memiliki aari 1 tribut lebih , maka menghasilkan E dengan nama X, dan dengan nama atribut A 1 , A 2 , …. , An. • Menghasilkan relasi baru dengan skema yang sama dan konten sama, Hanya berbeda nama baik nama relasi maupun nama atribut • Relasi aslinya tidak berubah!
Contoh Mhs(nim, nama_mhs, tgl_lahir, alamat, kota) Kuliah(kode_kul, nama_kul, sks, semester) Nilai(nim, kode_kul, indeks_nilai) select kode_kul, sks from kuliah where semester<3 a. δ semester<3 (π kode_kul, sks(kuliah) b. π kode_kul, sks (δ semester<3(kuliah)
Studi Kasus (1) branch (branch_name, branch_city, assets) customer (customer_name, customer_street, customer_city) account (account_number, branch_name, balance) loan (loan_number, branch_name, amount) depositor (customer_name, account_number) borrower (customer_name, loan_number)
Studi Kasus (1) • Cari semua pinjaman dengan jumlah lebih dari $1200 amount > 1200 (loan) • Cari loan number pada masing-masing loan yang jumlahnya lebih besar dari $1200 loan_number ( amount > 1200 (loan)) • Cari nama semua nama customer yang memiliki loan, account, atau keduanya customer_name (borrower) customer_name (depositor)
Studi Kasus (2) • Cari semua nama customer yang memiliki loan di cabang Perryridge. customer_name ( borrower. loan_number = loan_number ^ branch_name=“Perryridge” (borrower x loan)) • Cari semua nama customer yang memiliki loan di cabang Perryridge tapi tidak memiliki account di semua cabang customer_name ( borrower. loan_number = loan_number ^ branch_name = “Perryridge” (borrower x loan)) – customer_name(depositor)
Studi Kasus (3) • Cari semua customer yang memiliki loan di cabang Perryridge. l Query 1 customer_name ( branch_name = “Perryridge” ( borrower. loan_number = loan_number (borrower x loan))) l Query 2 customer_name( loan_number = borrower. loan_number ( ( branch_name = “Perryridge” (loan)) x borrower))
Tahapan Pemrosesan Query [1] 1. Parsing and translation 2. Optimization 3. Evaluation
Tahapan Pemrosesan Query [2] • Parsing and translation - Parser mengecek sintaks, memverifikasi relasi/tabel - Menerjemahkan query ke dalam bentuk internal (digunakan Aljabar Relasional) • Evaluation : mengeksekusi query evaluation plan dan memberikan jawaban dari query tersebut
Basic Steps in Query Processing : Optimization • A relational algebra expression may have many equivalent expressions – E. g. , salary 75000( salary(instructor)) is equivalent to salary( salary 75000(instructor)) • Each relational algebra operation can be evaluated using one of several different algorithms – Correspondingly, a relational-algebra expression can be evaluated in many ways. • Annotated expression specifying detailed evaluation strategy is called an evaluation-plan. – E. g. , can use an index on salary to find instructors with salary < 75000, – or can perform complete relation scan and discard instructors with salary 75000
Basic Steps: Optimization (Cont. ) • Query Optimization: Amongst all equivalent evaluation plans choose the one with lowest cost. – Cost is estimated using statistical information from the database catalog • e. g. number of tuples in each relation, size of tuples, etc.
Measures of Query Cost • Cost is generally measured as total elapsed time for answering query – Many factors contribute to time cost • disk accesses, CPU, or even network communication • Typically disk access is the predominant cost, and is also relatively easy to estimate. Measured by taking into account – Number of seeks * average-seek-cost – Number of blocks read * average-block-read-cost – Number of blocks written * average-block-write-cost • Cost to write a block is greater than cost to read a block – data is read back after being written to ensure that the write was successful
Measures of Query Cost (Cont. ) • For simplicity we just use the number of block transfers from disk and the number of seeks as the cost measures – t. T – time to transfer one block – t. S – time for one seek – Cost for b block transfers plus S seeks b * t. T + S * t. S • We ignore CPU costs for simplicity – Real systems do take CPU cost into account • We do not include cost to writing output to disk in our cost formulae
Measures of Query Cost (Cont. ) • Several algorithms can reduce disk IO by using extra buffer space – Amount of real memory available to buffer depends on other concurrent queries and OS processes, known only during execution • We often use worst case estimates, assuming only the minimum amount of memory needed for the operation is available • Required data may be buffer resident already, avoiding disk I/O – But hard to take into account for cost estimation
Selection Operation • File scan • Algorithm A 1 (linear search). Scan each file block and test all records to see whether they satisfy the selection condition. – Cost estimate = br block transfers + 1 seek • br denotes number of blocks containing records from relation r – If selection is on a key attribute, can stop on finding record • cost = (br /2) block transfers + 1 seek – Linear search can be applied regardless of • selection condition or • ordering of records in the file, or • availability of indices • Note: binary search generally does not make sense since data is not stored consecutively – except when there is an index available, – and binary search requires more seeks than index search
Selections Using Indices • Index scan – search algorithms that use an index – selection condition must be on search-key of index. • A 2 (primary index, equality on key). Retrieve a single record that satisfies the corresponding equality condition – Cost = (hi + 1) * (t. T + t. S) • A 3 (primary index, equality on nonkey) Retrieve multiple records. – Records will be on consecutive blocks • Let b = number of blocks containing matching records – Cost = hi * (t. T + t. S) + t. S + t. T * b
Selections Using Indices • A 4 (secondary index, equality on nonkey). – Retrieve a single record if the search-key is a candidate key • Cost = (hi + 1) * (t. T + t. S) – Retrieve multiple records if search-key is not a candidate key • each of n matching records may be on a different block • Cost = (hi + n) * (t. T + t. S) – Can be very expensive!
Selections Involving Comparisons • Can implement selections of the form A V (r) or A V(r) by using – a linear file scan, – or by using indices in the following ways: • A 5 (primary index, comparison). (Relation is sorted on A) • For A V(r) use index to find first tuple v and scan relation sequentially from there • For A V (r) just scan relation sequentially till first tuple > v; do not use index • A 6 (secondary index, comparison). • For A V(r) use index to find first index entry v and scan index sequentially from there, to find pointers to records. • For A V (r) just scan leaf pages of index finding pointers to records, till first entry > v • In either case, retrieve records that are pointed to – requires an I/O for each record – Linear file scan may be cheaper
Implementation of Complex Selections • Conjunction: 1 2. . . n(r) • A 7 (conjunctive selection using one index). – Select a combination of i and algorithms A 1 through A 7 that results in the least cost for i (r). – Test other conditions on tuple after fetching it into memory buffer. • A 8 (conjunctive selection using composite index). – Use appropriate composite (multiple-key) index if available. • A 9 (conjunctive selection by intersection of identifiers). – Requires indices with record pointers. – Use corresponding index for each condition, and take intersection of all the obtained sets of record pointers. – Then fetch records from file – If some conditions do not have appropriate indices, apply test in memory.
Algorithms for Complex Selections • Disjunction: 1 2 . . . n (r). • A 10 (disjunctive selection by union of identifiers). – Applicable if all conditions have available indices. • Otherwise use linear scan. – Use corresponding index for each condition, and take union of all the obtained sets of record pointers. – Then fetch records from file • Negation: (r) – Use linear scan on file – If very few records satisfy , and an index is applicable to • Find satisfying records using index and fetch from file
Join Operation • Several different algorithms to implement joins – Nested-loop join – Block nested-loop join – Indexed nested-loop join – Merge-join – Hash-join • Choice based on cost estimate • Examples use the following information – Number of records of student: 5, 000 takes: 10, 000 – Number of blocks of student: 100 takes: 400
Nested-Loop Join • To compute theta join r s for each tuple tr in r do begin for each tuple ts in s do begin test pair (tr, ts) to see if they satisfy the join condition if they do, add tr • ts to the result. end • r is called the outer relation and s the inner relation of the join. • Requires no indices and can be used with any kind of join condition. • Expensive since it examines every pair of tuples in the two relations.
Nested-Loop Join (Cont. ) • In the worst case, if there is enough memory only to hold one block of each relation, the estimated cost is nr bs + br block transfers, plus nr + b r seeks • If the smaller relation fits entirely in memory, use that as the inner relation. – Reduces cost to br + bs block transfers and 2 seeks • Assuming worst case memory availability cost estimate is – with student as outer relation: • 5000 400 + 100 = 2, 000, 100 block transfers, • 5000 + 100 = 5100 seeks – with takes as the outer relation • 10000 100 + 400 = 1, 000, 400 block transfers and 10, 400 seeks • If smaller relation (student) fits entirely in memory, the cost estimate will be 500 block transfers. • Block nested-loops algorithm (next slide) is preferable.
Block Nested-Loop Join • Variant of nested-loop join in which every block of inner relation is paired with every block of outer relation. for each block Br of r do begin for each block Bs of s do begin for each tuple tr in Br do begin for each tuple ts in Bs do begin Check if (tr, ts) satisfy the join condition if they do, add tr • ts to the result. end end
Block Nested-Loop Join (Cont. ) • Worst case estimate: br bs + br block transfers + 2 * br seeks – Each block in the inner relation s is read once for each block in the outer relation • Best case: br + bs block transfers + 2 seeks. • Improvements to nested loop and block nested loop algorithms: – In block nested-loop, use M — 2 disk blocks as blocking unit for outer relations, where M = memory size in blocks; use remaining two blocks to buffer inner relation and output • Cost = br / (M-2) bs + br block transfers + 2 br / (M-2) seeks – If equi-join attribute forms a key or inner relation, stop inner loop on first match – Scan inner loop forward and backward alternately, to make use of the blocks remaining in buffer (with LRU replacement) – Use index on inner relation if available (next slide)
• Indexed Nested-Loop Join Index lookups can replace file scans if – join is an equi-join or natural join and – an index is available on the inner relation’s join attribute • • • Can construct an index just to compute a join. For each tuple tr in the outer relation r, use the index to look up tuples in s that satisfy the join condition with tuple tr. Worst case: buffer has space for only one page of r, and, for each tuple in r, we perform an index lookup on s. Cost of the join: br (t. T + t. S) + nr c – Where c is the cost of traversing index and fetching all matching s tuples for one tuple or r – c can be estimated as cost of a single selection on s using the join condition. If indices are available on join attributes of both r and s, use the relation with fewer tuples as the outer relation.
Example of Nested-Loop Join Costs • Compute student takes, with student as the outer relation. • Let takes have a primary B+-tree index on the attribute ID, which contains 20 entries in each index node. • Since takes has 10, 000 tuples, the height of the tree is 4, and one more access is needed to find the actual data • student has 5000 tuples • Cost of block nested loops join – 400*100 + 100 = 40, 100 block transfers + 2 * 100 = 200 seeks • assuming worst case memory • may be significantly less with more memory • Cost of indexed nested loops join – 100 + 5000 * 5 = 25, 100 block transfers and seeks. – CPU cost likely to be less than that for block nested loops join
- Slides: 50