Anda di halaman 1dari 48

SQL Query:

Aggregate Function, Set Operation & Join


operation

INF2033 Basis Data 1


Pertemuan 12

R. Kristoforus JB
Fakultas Sains & Teknologi
Universitas Katolik Musi Charitas
Sub Capaian Mata Kuliah
• Mahasiswa dapat menggunakan fungsi agregat dalam
sebuah query
• Mahasiswa dapat menggunakan klausa group by dan
kalusa having dalam sebuah query
• Mahasiswa dapat menggunakan operator-operator
himpunan dalam sebuah query

2
Outline
• SQL
– Review: Aggregate functions:
• Avg
• Min
• Max
• Sum
• count
– Review: Set operations
• Union
• Intersect
• Except
– Join operation
• Natural join
• Outer join

3
Yang perlu dipersiapkan
• aplikasi DB4S
• Schema diagram for university database
• File latihan:
– university.db
– university_ddl.sql
– university_dml.sql
• Kunjungi laman:
– https://www.sqlitetutorial.net/
– https://www.w3resource.com/sqlite/index.php

4
Schema Diagram for University Database

5
Aggregate functions
• Aggregate functions bekerja dengan banyak himpunan nilai
dari sebuah kolom atau atribut relasi dan mengembalikan
sebuah nilai.
• Fungsi agregat:
– avg: average value
– min: minimum value
– max: maximum value
– sum: sum of values
– count: number of values

6
Aggregate functions examples
• Contoh 1: Berapa rerata salary instructor di departemen Computer
Science?
select avg (salary)
from instructor
where dept_name= 'Comp. Sci.';
• Contoh 2: Berapa jumlah instructor yang mengajar di semester Spring
2010
select count (distinct ID)
from teaches
where semester = 'Spring' and year = 2010;
• Contoh 3: Berapa jumlah tuple pada tabel course?
select count (*)
from course;

7
Avg() function
• avg() function : mengembalikan nilai rerata dari sebuah ekpresi yang diberikan.
• Jika fungsi tidak menemukan nilai yang cocok, hasilnya: NULL.
• Tipe String dan BLOB diinterpretasikan sebagai 0.
• Hasil fungsi avg() selalu bertipe floating point value.

• Sintaks:
avg([DISTINCT] expr)

• Contoh 4: Tampilkan rerata salary dari instructor di departemen Comp. Sci.


select avg (salary)
from instructor
where dept_name= 'Comp. Sci.';

8
Avg() function
• Fungsi avg() dapat dikombinasikan dengan klausa group by.
• Hasilnya: rerata nilai setiap group.
• Contoh 5: Berapa rerata salary setiap departemen?
– select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name;

9
Avg() function
• Fungsi avg() dapat dikombinasikan dengan keyword distinct.
• Hasilnya nilai rerata yang unik. Jika ada dua nilai rerata yang sama,
maka hanya satu yang ditampilkan.
• Perhatikan perbedaan contoh 6 dan contoh 7

• Contoh 6: Berapa rerata kredit dari setiap departemen?


select dept_name, avg(tot_cred) as avg_tot_cred
from student
group by dept_name;

• Contoh 7: Berapa rerata kredit dari setiap departemen?


select dept_name, avg(distinct(tot_cred)) as avg_tot_cred
from student
group by dept_name;

10
Avg() function
• Untuk mengatur nilai desimal dari hasil fungsi avg() dapat digunakan
keyword round().
• Contoh 8: Berapa rerata kredit dari setiap departemen?
select dept_name, round(avg(tot_cred),2) as avg_tot_cred
from student
group by dept_name;

11
Avg() function
• Fungsi avg() dapat juga dipakai bersama dengan klausa having.
• Klausa having hanya dapat digunakan bersama dengan klausa group
by.
• Dengan klausa having, fungsi avg() yang dihasilkan adlah yang
memenuhi syarat yang diekpresikan pada klausa having.
• Contoh 9: Tampilkan nama dan rerata salary yang lebih besar dari
42000 dari seluruh departemen.

select dept_name, avg (salary) as avg_salary


from instructor
group by dept_name
having avg (salary) > 42000;

12
Count() function
• Fungsi count() mengembalikan nilai banyaknya data dalam sebuah
atribut.

• Sintaks:
count(column)

• Contoh 10: Berapa banyak jumlah instructor?


select count(ID)
from instructor;

13
count() function
• Fungsi count dapat digunakan bersama keyword distinct
• Contoh 11: berapa banyak nama departemen pada tabel instructor?
select count(dept_name)
from instructor;
• Hasil dari contoh 11 akan menampilkan 50 (banyaknya data dept)name
pada tabel instructor)
• Contoh 12: berapa banyak nama departemen pada tabel instructor?
select count(distinct(dept_name))
from instructor;
• Hasil dari contoh 12 akan menampilkan 17
• Fungsi count() dapat digunakan bersama dengan klausa group by
• Contoh 13: Berapa banyak jumlah isntructor di setiap departemen?
select count(ID)
from instructor
group by dept_name;

14
count() function
• Perhatikan contoh berikut dan lihat • Contoh 16:
perbedaannya select building, student.dept_name,
count(*)
• Contoh 14
from student, department
select building, student.dept_name,
where student.dept_name=
count(*)
department.dept_name
from student, department
group by building, student.dept_name;
where student.dept_name=
department.dept_name
group by student.dept_name; • Contoh 17:
select building, student.dept_name,
count(*)
• Contoh 15:
from student, department
select building, student.dept_name,
where student.dept_name=
count(*)
department.dept_name
from student, department
group by student.dept_name, building;
where student.dept_name=
department.dept_name
group by building;

15
Count() function
• Fungsi count dapat digunakan bersama klausa having.
• Perhatikan contoh berikut:
• Contoh 18: berapa banyak berapa banyak instructor di setiap
departemen, tampilkan yang banyaknya lebih dari 3 instructor
select count(ID)
from instructor
group by dept_name
having count(ID)>3;
• Contoh 19: berapa banyak berapa banyak mahasiswa di setiap
departemen, tampilkan yang banyaknya lebih dari 100 mahasiswa
select building, student.dept_name, count(*)
from student, department
where student.dept_name=department.dept_name
group by student.dept_name
having count(*) > 100;

16
Max() function
• Fungsi max() mengembalikan nilai maksimum dari semua nilai dalam
kelompok.
• Sintaks:
max(expr);

• Contoh 20: Siapa dan berapa salary tertinggi dari seluruh instructor?
select name, max(salary)
from instructor;

• Contoh 21: Siapa dan berapa salary tertinggi dari seluruh instructor di
departemen Accounting?
select name, max(salary)
from instructor
where dept_name='Accounting';

17
Max() function
• Fungsi max() dapat digunakan bersama dengan klausa group by.
• Perhatikan contoh berikut.
• Contoh 22: Tampilkan nama dan salary dari instruktur yang memiliki
salary tertinggi di setiap departemen
select name, dept_name, max(salary)
from instructor
group by dept_name;
• Contoh 23: Tampilkan nama dan salary dari instruktur yang memiliki
salary tertinggi di setiap building
select building, max(salary)
from instructor, department
where department.dept_name=instructor.dept_name
group by building;

18
Max() function
• Contoh 24: Tampilkan nama dan salary dari instruktur yang memiliki
salary tertinggi di setiap departemen
select building, department.dept_name, max(salary)
from instructor, department
where department.dept_name=instructor.dept_name
group by building, department.dept_name;

19
Min() function
• Fungsi min() mengembalikan nilai terkecil dari sekelompok nilai.
• Sintaks:
min(expr)

• Contoh 25: Berapa salary terkecil dari seluruh instructor?


Select min(salary)
from instructor;
• Fungsi min dapat digunakan bersama klausa group by.
• Contoh 26: berapa salary terkecil di setiap departemen?
Select dept_name, min(salary)
from instructor
group by dept_name;

20
Sum() function
• Fungsi sum mengembalikan nilai jumlah dari seluruh nilai dalam
kelompok
• Sintaks:
Sum(expr)

• Contoh 27: berapa jumlah total sks?


select sum(credits)
from course;
• Fungsi sum() dapat digunakan bersama klausa group by
• Contoh 28: berapa jumlah total sks di setiap departemen?
select dept_name, sum(credits)
from course
group by dept_name;

21
Set operations
• SQL menyediakan operator yang berkorespondensi dengan
teori himpunan
• Union

• Intersect

• Except

22
Set Operations
• Contoh 29: Find courses that ran in Fall 2002 or in Spring 2010
select course_id from section where semester = 'Fall' and year = 2002
union
select course_id from section where semester = 'Spring' and year = 2010;

• Contoh 30: Find courses that ran in Fall 2002 and in Spring 2010
select course_id from section where semester = 'Fall' and year = 2002
intersect
select course_id from section where semester = 'Spring' and year = 2007;

• Contoh 31: Find courses that ran in Fall 2002 but not in Spring 2010
select course_id from section where semester = 'Fall' and year = 2002
except
select course_id from section where semester = 'Spring' and year = 2010;

23
Latihan 12.1
1. Berapakah rerata sks mata kuliah di setiap departemen?
2. Berapakah rerata sks mata kuliah di setiap building?
3. Departemen manakah yang memiliki budget tertinggi?
4. Mahasiswa manakah yang memiliki total sks (tot_cred) tertinggi?
5. Dari semua mahasiswa bimbingan Luo, siapakah yang memiliki total sks
terkecil?
6. Berapa jumlah salary dari seluruh dosen yang berkantor di Taylor building?
7. Berapa banyak mahasiswa yang dibimbing oleh Mahmoud?
8. Berapa banyak mahasiswa yang mengambil mata kuliah Game programming?
9. Siapa saja yang berkantor di Taylor bulding dan yang berkantor di Lamberton
building?
10. Siapakah mahasiswa yang pernah mengambil mata kuliah Corporate Law dan
Game Design?
11. Siapakah mahasiswa yang pernah mengambil Corporate Law namun belum
pernah mengambil Game Design

24
Latihan 12.1
12. Berapakah rerata total sks mahasiswa yang dibimbing oleh Luo
13. Mata kuliah apakah yang paling banyak ditawarkan
14. Berapa banyak mata kuliah yang ada di tiap departemen?
15. Berapa banyak mahasiswa di tiap departemen?
16. Berapa banyak mahasiswa yang mendapat nilai A pada mata kuliah Mobile
Computing?
17. Berapa banyak nilai A yang diperoleh mahasiswa bernama Rumat?
18. Mata kuliah apa yang pernah ditawarkan pada semester spring tahun 2002
dan spring tahun 2010?
19. Mata kuliah apa yang pernah ditawarkan pada spring 2002 namun tidak
ditawarkan pada spring 2010?

25
Join Operation
• Join operations take two relations and return as a result another relation.
• A join operation is a Cartesian product which requires that tuples in the two
relations match (under some condition). It also specifies the attributes that are
present in the result of the join
• The join operations are typically used as subquery expressions in the from clause
• Three types of joins:
– Natural join
– Inner join
– Outer join

26
Natural Join
• Natural join matches tuples with the same values for all common attributes, and
retains only one copy of each common column.
• List the names of instructors along with the course ID of the courses that they
taught
– select name, course_id
from students, takes
where student.ID = takes.ID;
• Same query in SQL with “natural join” construct
– select name, course_id
from student natural join takes;
• The from clause can have multiple relations combined using natural join:
select A1, A2, … An
from r1 natural join r2 natural join .. natural join rn
where P ;

27
Natural Join
student takes

28
Natural Join
• Contoh:
Select *
From student natural join
takes

29
Dangerous in Natural Join
• Beware of unrelated attributes with same name which get equated incorrectly
• Example -- List the names of students instructors along with the titles of
courses that they have taken
– Correct version
select name, title
from student natural join takes, course
where takes.course_id = course.course_id;
– Incorrect version
select name, title
from student natural join takes natural join course;
• This query omits all (student name, course title) pairs where the student
takes a course in a department other than the student's own
department.
• The correct version (above), correctly outputs such pairs.

30
Natural Join with Using Clause
• To avoid the danger of equating attributes erroneously, we can use the
“using” construct that allows us to specify exactly which columns
should be equated.
• Query example
select name, title
from (student natural join takes) join course using (course_id)

31
Join Condition
• The on condition allows a general predicate over the relations being joined
• This predicate is written like a where clause predicate except for the use of the
keyword on
• Query example
select *
from student join takes on student_ID = takes_ID
– The on condition above specifies that a tuple from student matches a tuple
from takes if their ID values are equal.
• Equivalent to:
select *
from student , takes
where student_ID = takes_ID

32
Join Condition
• The on condition allows a general predicate over the relations being joined.
• This predicate is written like a where clause predicate except for the use of the
keyword on.
• Query example
select *
from student join takes on student_ID = takes_ID
– The on condition above specifies that a tuple from student matches a tuple
from takes if their ID values are equal.
• Equivalent to:
select *
from student , takes
where student_ID = takes_ID

33
Outer Join
• An extension of the join operation that avoids loss of information.
• Computes the join and then adds tuples form one relation that does not match
tuples in the other relation to the result of the join.
• Uses null values.
• Three forms of outer join:
– left outer join
– right outer join
– full outer join

34
Outer Join Examples
• Relation course

• Relation prereq

• Observe that
course information is missing CS-347
prereq information is missing CS-315

• x

35
Left Outer Join
• course natural left outer join prereq

 In relational algebra: course ⟕ prereq

36
Right Outer Join
• course natural right outer join prereq

 In relational algebra: course ⟖ prereq

37
Full Outer Join
• course natural full outer join prereq

• In relational algebra: course ⟗ prereq

38
Joined Types and Conditions
• Join operations take two relations and return as a result another
relation.
• These additional operations are typically used as subquery expressions
in the from clause
• Join condition – defines which tuples in the two relations match.
• Join type – defines how tuples in each relation that do not match any
tuple in the other relation (based on the join condition) are treated

39
Joined Relations – Examples
• course natural right outer join prereq

• course full outer join prereq using (course_id)

40
Joined Relations – Examples
• course inner join prereq on
course.course_id = prereq.course_id

• What is the difference between the above, and a natural join?


• course left outer join prereq on
course.course_id = prereq.course_id

41
Joined Relations – Examples
• course natural right outer join prereq

• course full outer join prereq using (course_id)

42
Latihan 12.2
1. Berapakah rerata sks mata kuliah di setiap departemen?
2. Berapakah rerata sks mata kuliah di setiap building?
3. Departemen manakah yang memiliki budget tertinggi?
4. Mahasiswa manakah yang memiliki total sks (tot_cred) tertinggi?
5. Dari semua mahasiswa bimbingan Luo, siapakah yang memiliki total sks
terkecil?
6. Berapa jumlah salary dari seluruh dosen yang berkantor di Taylor building?
7. Berapa banyak mahasiswa yang dibimbing oleh Mahmoud?
8. Berapa banyak mahasiswa yang mengambil mata kuliah Game programming?
9. Siapa saja yang berkantor di Taylor bulding dan yang berkantor di Lamberton
building?
10. Siapakah mahasiswa yang pernah mengambil mata kuliah Corporate Law dan
Game Design?
11. Siapakah mahasiswa yang pernah mengambil Corporate Law namun belum
pernah mengambil Game Design

43
Latihan 12.2
12. Berapakah rerata total sks mahasiswa yang dibimbing oleh Luo
13. Mata kuliah apakah yang paling banyak ditawarkan
14. Berapa banyak mata kuliah yang ada di tiap departemen?
15. Berapa banyak mahasiswa di tiap departemen?
16. Berapa banyak mahasiswa yang mendapat nilai A pada mata kuliah Mobile
Computing?
17. Berapa banyak nilai A yang diperoleh mahasiswa bernama Rumat?
18. Mata kuliah apa yang pernah ditawarkan pada semester spring tahun 2002
dan spring tahun 2010?
19. Mata kuliah apa yang pernah ditawarkan pada spring 2002 namun tidak
ditawarkan pada spring 2010?

44
Jadwal
Prt Tgl T P
1 05/09 Pengantar Kuliah Basis Data 1 V
2 05/09 Intro to Database System, DB System Environment V
3 12/09 Into to Relational Model V
4 12/09 Intro to SQLite & DB4S V
5 19/09 Query Language: Overview, Data Definition V
6 19/09 SQLite: Data Definition V
7 26/09 Query Language: Basic Structure V
8 26/09 SQLite: Basic Structure V

45
Jadwal
Prt Tgl Teori T P
9 03/10 Relational Database: Relational Algebra V
10 03/10 Relational Database: Relational Algebra V
11 10/10 Relational Database: Relational Algebra V
12 10/10 SQLite: Aggregate Function, Set Operation, Join V
Operation
13 24/10 Project 1: Presentasi V
14 24/10 SQLite: Subquery V
15 26/10 UTS V
16

46
Jadwal
Prt Tgl Teori T P
17 31/10 Data Modeling: ER Model V
18 31/10 Data Modeling: ER Model V
19 07/11 Query language: Sub query V
20 07/11 SQLite: Sub query V
21 14/11 Data Modeling: ER Model V
22 14/11 Data Modeling: ER Model V
23 21/11 Query language: Views V
24 21/11 SQLite: views V

47
Jadwal
Prt Tgl Teori T P
25 28/11 Data Modeling Integrity Rules & Normalization V
26 28/11 Data Modeling Integrity Rules & Normalization V
27 05/12 Query Language: Integrity Constraints V
28 05/12 SQLite V
29 12/12 Data Modeling Integrity Rules & Normalization V
30 12/12 Data Modeling Integrity Rules & Normalization V
31 UAS V
32 Project 2 V

48

Anda mungkin juga menyukai

  • Inf0733 06P
    Inf0733 06P
    Dokumen30 halaman
    Inf0733 06P
    Renaldi Fernando
    Belum ada peringkat
  • Inf0733 01P
    Inf0733 01P
    Dokumen19 halaman
    Inf0733 01P
    Renaldi Fernando
    Belum ada peringkat
  • Inf0733 11
    Inf0733 11
    Dokumen37 halaman
    Inf0733 11
    Renaldi Fernando
    Belum ada peringkat
  • Inf0733 06
    Inf0733 06
    Dokumen18 halaman
    Inf0733 06
    Renaldi Fernando
    Belum ada peringkat
  • Inf0733 05
    Inf0733 05
    Dokumen50 halaman
    Inf0733 05
    Renaldi Fernando
    Belum ada peringkat
  • Inf0733 04
    Inf0733 04
    Dokumen20 halaman
    Inf0733 04
    Renaldi Fernando
    Belum ada peringkat
  • Inf0733 02
    Inf0733 02
    Dokumen59 halaman
    Inf0733 02
    Renaldi Fernando
    Belum ada peringkat
  • Inf0733 03
    Inf0733 03
    Dokumen43 halaman
    Inf0733 03
    Renaldi Fernando
    Belum ada peringkat
  • Inf2033 23
    Inf2033 23
    Dokumen71 halaman
    Inf2033 23
    Renaldi Fernando
    Belum ada peringkat