3. Bahasa Query Relasional
Bahasa Query (Query Languages): Memungkinkan
manipulasi dan pengambilan data dari database.
Model relasional mendukung QL yang sederhana dan
powerful:
Dasar formal yg kuat berdasarkan logika.
Memungkinkan banyak optimasi.
QL != Bahasa Pemrograman.
QL tidak diharapkan untuk menjadi “Turing complete”.
QL tidak ditujukan untuk perhitungan yg kompleks.
QL mendukung kemudahan, dan efisiensi akses untuk data
set yang besar.
3
4. Bahasa Query Relasional Formal
4
Dua matematis QL membentuk dasar untuk bahasa
“real” (contoh: SQL), dan untuk penerapan:
Aljabar Relasional: Lebih operational(procedural),
sangat berguna untuk melambangkan eksekusi.
Kalkulus Relasional: Memungkinkan pengguna untuk
menggambarkan apa yg mereka inginkan, bukan
bagaimana untuk menghitung itu. (Non-operational,
declarative.)
5. Pendahuluan
5
Sebuah query diterapkan untuk hubungan relasi,
dan hasil query juga merupakan hubungan relasi.
Skema relasi input untuk query tertentu adalah tetap
(tetapi query akan dijalankan tanpa instance!).
Skema untuk hasil dari query yg diberikan juga tetap.
Ditentukan oleh definisi dari konstruksi QL.
Positional vs. named-field notation:
Notasi positional lebih mudah untuk definisi formal,
notasi name-field lebih mudah dibaca.
Keduanya digunakan dalam SQL.
7. Contoh Instances
7
Relasi “Sailors” dan
“Reserves” sebagai contoh.
“bid”= boats. “sid”= sailors.
Kita akan menggunakan
positional atau notasi named-
field, diasumsikan nama field
di dalam hasil query
‘diturunkan’ dari nama field
dalam relasi input querynya.
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0
sid sname rating age
28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
sid bid day
22 101 10/10/96
58 103 11/12/96
R1
S1
S2
9. Introduction to Relational Algebra
12/09/2022
9
Queries are composed using a collection of
operators
Consists of :
Basic Operator (selection, projection, union, cross-
product , and difference)
Additional Operator (renaming, join, division)
10. Aljabar Relasional
Operasi-operasi dasar:
Selection ( ) Menyeleksi sekumpulan baris dari relasi.
Projection ( ) Menghapus kolom yg tidak diinginkan dari relasi.
Cross-product ( ) Memungkinkan kita untuk menggabungkan dua
relasi.
Set-difference ( ) Tuples berada di relasi 1, tapi tidak ada di relasi
2.
Union ( ) Tuples ada di relasi 1, dan ada di relasi 2.
Operasi-operasi tambahan:
Intersection, join, division, renaming: Tidak esensial, tetapi (sangat)
berguna.
Karena setiap operasi mengembalikan sebuah relasi, operasi-
operasi dapat dikomposisikan! (Aljabar adalah “tertutup”).
11. Selection and Projection
Selection (σ) : selects a subset of rows from relation
Projection (π) : selects a particular columns from
the relation
12/09/2022
11
13. Selection ( )
rating
S
8
2
( )
sid sname rating age
28 yuppy 9 35.0
58 rusty 10 35.0
sname rating
yuppy 9
rusty 10
sname rating rating
S
,
( ( ))
8
2
Menyeleksi baris-baris
yang memenuhi kondisi
seleksi.
Skema dari hasil identik
dengan skema relasi
input.
Relasi hasil bisa menjadi
input untuk operasi
aljabar relasional yang
lain. (Operator
composition.)
14. Selection condition
12/09/2022
14
The selection operator σ species the tuples to retain
through a selection condition
Selection condition form :
<attribute1> operator <attribute2>
<attribute> operator <constant>
Operator: <, <=, = >=, >, ≠
15. Example of Projection
12/09/2022
15
πsname, rating(S2)
πage(S2)
Three sailors are aged 35.0 but only one tuple appears in the
result
The duplicate elimination is done so the result is always tuples
16. Projection ( )
sname rating
yuppy 9
lubber 8
guppy 5
rusty 10
sname rating
S
,
( )
2
age
35.0
55.5
age S
( )
2
Menghapus atribut-atribut yang tidak
terdapat dalam daftar proyeksi.
Skema dari hasil memuat field-field di
daftar proyeksi, dengan nama yang
sama dengan nama yang ada di relasi
input.
Operator projection menghilangkan
duplikasi! (Mengapa??, dan apa
konsekuensinya?)
Note: sistem yang nyata biasanya tidak
melakukan penghapusan duplikasi
meskipun user secara eksplisit meminta
itu. (Mengapa demikian?)
17. Combine Selection and Projection
12/09/2022
17
πsname, rating(σrating>8(S2))
Computes the names and ratings of highly rated
sailors
18. Union, Intersection, Set-Difference
Operasi-operasi tersebut
memiliki dua relasi input,
dimana keduanya harus
union-compatible:
Memiliki jumlah field yang
sama.
Field yang ‘berelasi’ memiliki
tipe data yang sama.
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0
44 guppy 5 35.0
28 yuppy 9 35.0
sid sname rating age
31 lubber 8 55.5
58 rusty 10 35.0
S S
1 2
S S
1 2
sid sname rating age
22 dustin 7 45.0
S S
1 2
19. Set Operations
12/09/2022
19
Union: R U S returns a relation instance containing
all tuples that occur in either relation instance R or
relation instance S (or both)
Must be union-compatible
Have the same number of the fields
The corresponding fields, taken in order from left to
right, have the same domains
20. Set Operation (cont.)
12/09/2022
20
Intersection: R∩S returns a relation instance
containing all tuples that occur in both R and S
Must be union compatible
The result schema is identical to R schema
21. Set Operation (cont.)
12/09/2022
21
Set-difference: R−S returns a relation instance
containing all tuples that occur in R but not in S.
Must be union compatible
The result schema is identical to R schema
22. Set Operation (cont.)
12/09/2022
22
Cross Product : RxS returns a relation instance
whose schema contains all the fields of R (in the
same order as they appear in R) followed by all the
fields of S (in the same order as they appear in S)
23. Cross-Product
Tiap baris dari S1 dipasangkan dengan tiap baris dari R1.
Skema hasil memiliki satu field per field dari S1 dan R1,
dengan nama field ‘diturunkan’ jika memungkinkan.
Konflik: Kedua S1 dan R1 memiliki field bernama sid.
( ( , ), )
C sid sid S R
1 1 5 2 1 1
(sid) sname rating age (sid) bid day
22 dustin 7 45.0 22 101 10/10/96
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 22 101 10/10/96
31 lubber 8 55.5 58 103 11/12/96
58 rusty 10 35.0 22 101 10/10/96
58 rusty 10 35.0 58 103 11/12/96
Renaming operator:
24. Renaming
12/09/2022
24
To rename several fields in the relation
The expression :
Renaming list F, have form : oldname newname or
position newname
Example :
26. JOIN
+JOIN merupakan penggabungan beberapa table, pemilihan
baris, dan pemilihan kolom
+Join condition terdiri dari dua:
+ Equijoins: join yang menggunakan operator (=)
+ Non-equijoins: join yang menggunakan operator selain operator (=),
misalkan <, >, BETWEEN, dll.
27. NON-EQUIJOIN
+NON-EQUIJOIN :join yang menggunakan operator selain (=),
yaitu <>, <, >, <=, >=, LIKE, IN, BETWEEN
+Contoh :
SELECT e.first_name, e.last_name, e.title,
e.salary, sg.salary_grade_id
FROM employees e, salary_grades sg
WHERE e.salary BETWEEN sg.low_salary AND
sg.high_salary;
28. TIPE-TIPE JOIN
+Inner Join
Mengembalikan row hanya ketika kolom pada join berisi value yang
memenuhi join condition.
+Outer Join
Dapat mengembalikan row bahkan ketika kolom pada join condition
mempunyai nilai null.
+Self Join
Mengembalikan row hasil join tabel itu sendiri.
29. INNER JOIN
+Hampir semua query yang kita lakukan adalah sebuah inner
join.
+Inner join menampilkan semua row yang mempunyai data di
tiap kolomnya.
+Jika ada row yang kolomnya bernilai null, maka tidak akan
ditampilkan pada hasil query
31. LEFT OUTER JOIN
+Left outer join adalah outer join yang menampilkan semua
data pada bagian kiri relasi dan data yang dapat bernilai
null pada bagian kanan relasi.
+Menggunakan operator “(+)” dan diletakkan sebelah kanan
equality operator.
32. LEFT OUTER JOIN
+Contoh :
SELECT p.name, pt.name
FROM products p, product_types pt
WHERE p.product_type_id = pt.product_type_id (+);
33. RIGHT OUTER JOIN
+Right outer join adalah outer join yang menampilkan semua
data pada bagian kanan relasi dan data yang dapat bernilai
null pada bagian kiri relasi.
+Menggunakan operator “(+)” dan diletakkan sebelah kiri
equality operator.
34. RIGHT OUTER JOIN
+Contoh :
SELECT p.name, pt.name
FROM products p, product_types pt
WHERE p.product_type_id (+)= pt.product_type_id;
35. OUTER JOIN
+OUTER JOIN memiliki beberapa keterbatasan yaitu :
+Outer Join hanya dapat terdiri satu sisi join (left atau right),
tidak bisa dua-duanya sekaligus.
+Outer join tidak dapat digunakan pada operator IN
+Outer join tidak dapat digunakan pada operator OR
36. SELF JOIN
+Self join: join yang dihasilkan dengan cara melakukan join
terhadap tabel yang sama.
+Untuk dapat melakukan self join, setiap tabel tersebut harus
mempunyai alias yang berbeda
37. SELF JOIN
+Contoh :
SELECT w.first_name || ' ' || w.last_name || ' works
for '|| m.first_name || ' ' || m.last_name
FROM employees w, employees m
WHERE w.manager_id = m.employee_id;
38. Join
12/09/2022
38
Join combines information from two or more
relations
Join is cross product operation, followed by
selection and projection
Join
Condition join
Equijoin
Natural join
39. Joins
Condition Join:
Skema hasil sama dengan skema cross-product.
Tuple lebih sedikit dari cross-product. Menyaring tuple
yang tidak memenuhi kondisi join.
Terkadang disebut juga theta-join.
R c S c R S
( )
(sid) sname rating age (sid) bid day
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 58 103 11/12/96
S R
S sid R sid
1 1
1 1
. .
40. Condition Join
12/09/2022
40
The join operation that
accept a join condition c and a pair of relation
instances as arguments, and
returns a relation instance
The form :
41. Joins
Equi-Join: Kasus khusus untuk kondisi join dimana
kondisi c hanya memuat persamaan (equalities).
Skema hasil mirip dengan cross-product, tapi hanya satu
salinan field untuk persamaan yang dispesifikasikan.
Natural Join: Equijoin di semua common fields.
sid sname rating age bid day
22 dustin 7 45.0 101 10/10/96
58 rusty 10 35.0 103 11/12/96
)
1
1
(
,..
,
,..,
R
S
sid
bid
age
sid
43. Natural Join
12/09/2022
43
Special case of equijoin in which equalities are
specified on all fields having the same name in R
and S.
If S and R have no attributes in common, then the
join is simply a cross product
can simply be denoted
44. Division
Tidak didukung sebagai operator primitif, tapi berguna
untuk mengekspresikan query seperti:
Find sailors who have reserved all boats.
Persyaratan: dalam A/B, atribut di B harus terdapat dalam
skema yang sama dengan A. Hasil memiliki atribut-atribut
A-B.
SALES(supId, prodId);
PRODUCTS(prodId);
Relasi SALES dan PRODUCTS dapat dibentuk menggunakan
projection.
SALES/PRODUCTS: Menampilkan id dari supplier yang menyuplai
SEMUA product.
45. Division
12/09/2022
45
Consider two relation instances A and B in which A
has (exactly) two fields x and y and B has just one
field y, with the same domain as in A.
We define the division operation A=B as the set of
all x values such that for every y value in B, there is
a tuple <x,y> in A.
50. Implementasi DIVISION dalam SQL
Operator division tidak disediakan secara eksplisit oleh SQL
Contoh:
“mencari nama sailor yang pernah meminjam semua boat”
Strategi untuk mengimplementasikan division dalam SQL:
Cari himpunan, A, untuk semua kapal yang pernah dipinjam
oleh sailor s.
Cari himpunan B, untuk semua kapal
Output s adalah , atau sebaliknya, bila B-A adalah
kosong
B
A
51. Implementasi DIVISION dalam SQL (2)
SELECT R.sid
FROM reserves R
WHERE R.sid menyewa semua kapal di boats
SELECT R.sid
FROM reserves R
WHERE tidak ada kapal yang tidak pernah dipinjam oleh R.sid
SELECT R.sid
FROM reserves R
WHERE NOT EXISTS (kapal di boats yang tidak pernah dipinjam oleh R.sid)
SELECT R.sid
FROM reserves R
WHERE NOT EXISTS (
B: semua kapal di boats
MINUS
A: kapal-kapal yang pernah dipinjam oleh R.sid)
52. 8. Cari sid dari sailor yang pernah menyewa semua boat.
(division)
)
(
))
/(
)
Re
,
(
,
(
Sailors
Tempsids
sname
Boats
bid
serves
bid
sid
Tempsids
SELECT DISTINCT R.sid
FROM reserves R
WHERE NOT EXISTS (
SELECT bid
FROM boats
MINUS
SELECT bid
FROM reserves
WHERE reserves.sid=R.sid
)
53. Case Study (cont.)
12/09/2022
53
1. Find the names of sailors who have reserved boat
103
2. Find the names of sailors who have reserved a red
boat
3. Find the colors of boats reserved by Lubber
4. Find the names of sailors who have reserved at
least one boat
5. Find the names of sailors who have reserved a red
or a green boat
54. Case Study (cont.)
12/09/2022
54
6. Find the names of sailors who have reserved a red
and a green boat
7. Find the names of sailors who have reserved at
least two boats
8. Find the sids of sailors with age over 20 who have
not reserved a red boat
9. Find the names of sailors who have reserved all
boats
10. Find the names of sailors who have reserved all
boats called Interlake
55. Mengekspresikan A/B Mengunakan Operasi
Dasar
Division bukan operasi yang esensial; tetapi sangat
berguna untuk menyederhanakan operasi.
(Bentuk join yang benar, tetapi join tidak begitu umum
digunakan sehingga sistem menerapkan join secara khusus.
Division TIDAK diterapkan dalam SQL).
Ide: Untuk SALES/PRODUCTS, hitung semua products
memiliki setidaknya seorang supplier yang tidak
menyuplainya.
Nilai x didiskualifikasi bila digabungkan dengan nilai y dari B,
didapatkan tuple xy yang tidak ada dalam A.
)
)
Pr
)
(
(( Sales
oducts
Sales
sid
sid
A
The answer is sid(Sales) - A
57. Introduction to Relational Calculus
12/09/2022
57
A nonprocedural (declarative)
It allows us to describe the set of answers without
being explicit about how they should be computed.
It influenced the design of commercial SQL
language
Variant :
Tuple relational calculus (TRC)
Domain relational calculus (DRC)
58. Tuple Relational Calculus
12/09/2022
58
A tuple variable is a variable that takes on tuples of a
particular relation schema as values
The form
{T|p(T)}
Example
Find all sailors with a rating above 7.
{S | S∈ Sailors ^ S.rating > 7}
Find the names and ages of sailors with a rating above 7.
{P| ∈S∈ Sailors(S.rating > 7 ^ P.name = S.sname ^ P.age =
S.age)}
59. Domain Relational Calculus
12/09/2022
59
Similar to TRC, but DRC gives each attribute a
variable name
Example:
Find all sailors with a rating above 7.
{<I,N,T,A>|<I,N,T,A> ∈ Sailors ^T > 7}
60. Assignment 2
12/09/2022
60
The schema :
Suppliers(sid: integer, sname: string, address: string)
Parts(pid: integer, pname: string, color: string)
Catalog(sid: integer, pid: integer, cost: real)
Write the relational algebra and SQL query for :
1. Find the names of suppliers who supply some red part.
2. Find the sids of suppliers who supply some red or green
part
3. Find the sids of suppliers who supply some red part or
are at 221 Packer Street
4. Find the sids of suppliers who supply some red part and
some green part
61. Assignment 2 (cont.)
12/09/2022
61
4. Find the sids of suppliers who supply every part
5. Find the sids of suppliers who supply every red part
6. Find the sids of suppliers who supply every red or green
part
7. Find the sids of suppliers who supply every red part or
supply every green part
8. Find pairs of sids such that the supplier with the first sid
charges more for some part than the supplier with the
second sid
9. Find the pids of parts supplied by at least two different
suppliers
Odd student ID : 1,3,5,7,9
Even student ID : 2,4,6,8,10
Editor's Notes
A Turing Complete system means a system in which a program can be written that will find an answer (although with no guarantees regarding runtime or memory).
So, if somebody says "my new thing is Turing Complete" that means in principle (although often not in practice) it could be used to solve any computation problem.
Sometime's it's a joke... a guy wrote a Turing Machine simulator in vi, so it's possible to say that vi is the only computational engine ever needed in the world.