Basis Data
What is a database?
• Database : koleksi terpadu dari data yang
saling berkaitan dari suatu enterprise.
• What databases do you know of?
• “You can look it up.”
–Organizing information properly to find the
desired answers.
Komponen Basis data
• Entity
ialah suatu obyek (orang, tempat atau benda, konsep
atau event) yang akan direpresentasikan dalam database.
• Attributes, or features of the entities.
is a property that describe some aspect of the object that
we wish to record.
• Values of the attributes.
Example
• Entity: Hair
• Attribute: Hair Color.
• Value: a specific attribute for the entity, e.g.
brown.
• Can you name a few more examples?
Alternative Terminology:
Formal Terms Alternatif 1 Alternatif 2
Relation Table File
Tuple Row Record
Attribute Column Field
Hirarki Data
a. Elemen Data
Adalah Unit data terkecil dan tidak dapat dibagi lagi
menjadi unit yang berarti.
b. Catatan atau record
Terdiri dari semua elemen data yang berhubungan dengan
suatu objek atau kegiatan tertentu
c. File
Adalah kumpulan catatan data yang berhubungan dengan
suatu objek tertentu
Manajemen Data
Manajemen data adalah bagian dari manajemen sumber
daya informasi yang mencakup semua kegiatan yang
memastikan bahwa sumber daya data perusahaan akurat,
mutakhir, aman dari gangguan dan tersedia bagi pemakai.
Kegiatan Manajemen data mencakup :
a. Pengumpulan Data e. Keamanan
b. Integritas dan Pengujian f. Organisasi
c. Penyimpanan g. Pengambilan
d. Pemeliharaan
Defining Tables
• Name
– Describes the kinds of things being collected.
• Field Specifier
– Give names to the attributes.
– Essentially column headings.
– Field_name describes the attribute.
– Data_format describes the type of information expected in
the field.
– Optional_comment is an explanatory information about
the attribute.
Mendefinisikan Tabel Matakuliah
• Kode char 15 Kode Matakuliah
• Nama_mk char 30 Nama matakuliah
• SKS number 1 Jumlah Sks
• Primary Key: kode
Character Width and
Number Precision
• Kolom karakter yang lebarnya tidak cukup
untuk menampung data bisa menyebabkan
proses insert gagal
• Kolom number dengan precisi yang salah bisa
mempunyai dua akibat; menolak proses insert
data, atau menghapus beberapa precisi data.
Constraints
• Saat mendefinisikan table, bisa dilakukan
pembatasan-pembatasan (constraints);
primary key, foreign key, check condition.
• Agar basis data terjaga dan terintegrasi.
Defining Tables (continued)
• Primary Key
– Kombinasi dai satu atau lebih kolom, nilai-nilainya adalah unik
sebagai identitas setiap bais tabel
– Dalam satu tabel hanya boleh ada satu primary key
– Kolom primary key tidak boleh kosong
• Foreign Key.
– Kombinasi dari kolom-kolom dimana kolom tersebut bukan
sebagai primary key, tetapi di tabel lain kolom tersebut sebagai
primary key
– Dikenal sebagai referential integrity constraint, menyatakan nilai
dari foreign key berhubungan dengan nilai primary key yang ada
di tabel lain
DB Redundancy
• Never duplicate information. That is very BAD!
• Duplikasi data tidak diinginkan karena:
– Costs time and money utk entry data; storage
space lebih banyak
– Mengakibatkan hilangnya data integrity (data
sulit konsisten) pindah alamat!!!
Desain Database
• Struktur database ditentukan saat database
design (dipengaruhi application needs of
individual departments).
• Paradigm shift: pikirkan datanya dulu, baru
aplikasinya.
Relational Data Model
• Data direpresentasikan sebagai koleksi tabel-tabel
(himpunan entiti) yang saling berkaitan
Mata Kuliah
Mahasiswa
Kode Matakuliah
SKS
RELATIONAL MODEL
Kode Mkul Nama Mkul SKS
SIM105 Sistem Informasi 3
Nrp Nama Mhs Nrp Kode MKul
MMA.101 Budiman MMA.101 SIM105
A Table
Table name
Attribute names
Products:
Name Price Category Manufacturer
gizmo $19.99 gadgets GizmoWorks
Power gizmo $29.99 gadgets GizmoWorks
SingleTouch $149.99 photography Canon
MultiTouch $203.99 household Hitachi
tuples
Operations on Tables
• Table Operations
– Create table
– describe
– alter table
– insert into
– drop table
• Select
– Taking rows from a table to produce a new table.
– Select_from TABLE on Criterion
Create table
create table Course(
Cno char(3) not null,
Cname varchar2(22),
Cdescp varchar2(25),
Clabfee number(5,2),
Cdept char(3)
);
Example
create table Weather(
city varchar2(13),
noon number(3,1),
midnight number(3,1),
precipitation number,
primary key (city,precipitation)
);
create table Zipcodes(
zip number(5) primary key,
city varchar2(30)
);
Example
create table Customer(
cno number(5) primary key,
cname char(30),
street char(30),
zip number(5) references zipcodes(zip),
phone char(12)
);
Describe
• SQL> create table Course(
• Cno char(3) not null,
• Cname varchar2(22),
• Cdescp varchar2(25),
– labfee number(5,2),
• Cdept char(3)
• );
• Table created.
• SQL> describe Course
• Name Null? Type
• ----------------------------------------- -------- ----------------------------
• CNO NOT NULL CHAR(3)
• CNAME VARCHAR2(22)
• CDESCP VARCHAR2(25)
• CLABFEE NUMBER(5,2)
• CDEPT CHAR(3)
Table Modifying
• Alter table Course modify(
Cdept char(6)
);
• drop table Course;
• Menyisipkan row kedalam tabel
insert into Course values
(‘614’, ‘Computer Architecture’, ‘Pipelining and
memory’, 150.00, ‘th’);
Deletion
• menghapus row tertentu dari tabel
delete from Course where Cname = ‘intro to cs’
• Merubah nilai kolom tertentu untuk row tertentu
update Course set Clabfee = clabfee*10 where cdept =
‘phil’
Queries
• A computation to produce a table using the
operations on tables.
• SQL: Standard Query Language
– SELECT (selects fields)
– FROM (a table or database)
– WHERE (such a condition exists)
Query 1: Menampilkan keseluruhan isi tabel
Select *
from Course;
Comparison Operators
• = equal to
• < less than
• > greater than
• <= less than or equal to
• >= greater than or equal to
• !=, ^=,<> not equal
Query
Menampilkan seluruh informasi dari tabel Course yang Labfee zero
Select *
from Course
where Clabfee=0.00
Display all information about courses having course name values which
follows “Database” in alphabetic sequence.
select *
from course
where Cname > ‘Database’;
Sorting the result Table
Display the entire Course table. Sort the output display by the clabfee values
select *
from Course
order by Clabfee;
Display the department id and name of every course. Sort the result by
department id. Within each department, sort by course name.
Select Cdept, Cname
from Course
order by Cdept, Cname;
Display the course name and lab fee of any course with
a lab fee less than $100 or greater than $200.
Select Cname, Clabfee
from Course
where Clabfee not between 100 and 200;
Pattern Matching
When you wish to retrieve information from rows having
similar but not necessarily equal, values in a given
column.
The format is:
where column-name like pattern
Two special wildcard
• “-” : represent exactly one character
• “%” : represent character string of any length (including
zero)
Boolean Connectors: AND - OR - NOT
Display all information about any three credit
philosophy course which has a lab fee which is
strictly between zero and one hundred dollars.
Select *
from Course
where Clabfee > 0 and Clabfee < 1000 and Cdept =
‘phil’ and Cred = 3;
Two Types of SQL Functions
Functions
Single-row Multiple-row
functions functions
Single-Row Functions
Character
General Number
Single-row
functions
Conversion Date
Character Functions
Character
functions
Case conversion Character manipulation
functions functions
LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD
TRIM
Number Functions
•ROUND: Rounds value to specified decimal
Round (45.926, 2) 45.93
•TRUNC: Truncates value to specified decimal
TRUNC (45.926, 2) 45.92
•MOD: Returns remainder of division
MOD (1600, 300) 100
DECODE Function
Facilitates conditional inquiries by doing
the work of a CASE or
IF-THEN-ELSE statement
DECODE (col/expression, search1, result1
[, search2, result2, . . . ,]
[, default])
What are Group Functions?
Group functions operate on sets of rows to give
EMP
one result per group.
DEPTNO SAL
---------------- ---------------
10 2450
10 5000
10 1300
20 800
20 1100 “maximum salary MAX(SAL)
20
20
3000
3000 in the EMP table”
----------------
20 2975
30 1600 5000
30 2850
30 1250
30 950
30 1500
30 1250
Types of Group Functions
• AVG
• COUNT
• MAX
• MIN
• STDDEV
• SUM
• VARIANCE
Using Group Functions
SELECT [column,] group_function(column)
FROM table
[WHERE condition]
[GROUP BY column]
[ORDER BY column];
Using AVG and SUM Functions
You can use AVG and SUM for numeric data.
SQL> SELECT AVG(sal), MAX(sal), MIN(sal), SUM(sal)
3 FROM emp
4 WHERE job LIKE ‘SALES%’;
AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)
-------------- --------------- --------------- --------------
1400 1600 1250 5600
Using MIN and MAX Functions
You can use MIN and MAX for any datatype.
SQL> SELECT MIN(hiredate), MAX(hiredate)
2 FROM emp;
MIN(HIRED MAX(HIRED
---------------- -----------------
17-DEC-80 12-JAN-83
Using the COUNT Function
COUNT (*) returns the number of rows in a table.
SQL> SELECT COUNT(*)
2 FROM emp
3 WHERE deptno = 30;
COUNT(*)
--------------
6
Using the COUNT Function
COUNT(expr) returns the number of non-null rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;
COUNT(COM)
-------------------
4
Group Functions and Null Values
Group functions ignore null values in the column.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------------
550
Using the NVL Function with Group
Functions
The NVL function forces group functions to
include null values.
SQL> SELECT AVG(NVL(comm,0))
2 FROM emp;
AVG(NVL(COMM,0))
----------------------------
157.14286
Creating Groups of Data
DEPTNO SAL
------------ ------------------
10 2450
10 5000
10 1300
20 800 “average salary DEPTNO AVG(SAL)
20 1100 in EMP table for ------------ ---------------
20 3000
each 10 2916.6667
20 3000
20 2975 department” 20 2175
30 1600 30 1566.6667
30 2850
30 1250
30 950
30 1500
30 1250
Creating Groups of Data:
GROUP BY Clause
SELECT [column,] group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];
Divide rows in a table into smaller groups by using the GROUP BY
clause.
Using the GROUP BY Clause
All columns in the SELECT list that are not in group functions must be in the
GROUP BY clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno;
DEPTNO AVG(SAL)
------------ --------------
10 2916.6667
20 2175
30 1566.6667
Using the GROUP BY Clause
The GROUP BY column does not have to be in
the SELECT list.
SQL> SELECT AVG(sal)
2 FROM emp
3 GROUP BY deptno;
AVG(SAL)
--------------
2916.6667
2175
1566.6667
Grouping by More
Than One Column
EMP
DEPTNO JOB SAL
---------- ---------- ---------
10 MANAGER 2450 10
PRESIDENT 5000 DEPTNO JOB SUM(SAL) ---
10 CLERK 1300 --------- ------------ -------------- 10
20 CLERK 800 “sum salaries in CLERK 1300
20 CLERK 1100 the EMP table for 10 MANAGER 2450 10
20 ANALYST 3000 20 each job, PRESIDENT 5000
ANALYST 3000 20 20 ANALYST 6000 20
MANAGER 2850 30 grouped by CLERK 1900
SALESMAN 1250 department.” 20 MANAGER 2975
30 MANAGER 2850 30 30 CLERK 950
SALESMAN 1250 30 MANAGER 2850 30
30 CLERK 950 SALESMAN 5600
30 SALESMAN 1500
30 SALESMAN 1250
... 14
rows selected.
Using the GROUP BY Clause on Multiple
Columns
SQL> SELECT deptno, job, sum(sal)
2 FROM emp
3 GROUP BY deptno, job;
DEPTNO JOB - SUM(SAL)
----------- -------------- --------------
10 CLERK 1300
10 MANAGER
10 PRESIDENT
2450
20 ANALYST 5000
20 CLERK 6000
... 1900
9 rows selected.
Illegal Queries
Using Group Functions
Any column or expression in the SELECT list that is not an aggregate
function must be in the GROUP BY clause.
SQL> SELECT deptno, COUNT(ename)
2 FROM emp;
SELECT deptno, COUNT(ename)
*
ERROR at line 1:
ORA-00937: not a single-group group function
Illegal Queries
Using Group Functions
•You cannot use the WHERE clause to restrict groups.
•You use the HAVING clause to restrict groups.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 WHERE AVG(sal) > 2000
4 GROUP BY deptno;
WHERE AVG (sal) > 2000
*
ERROR at line 3:
ORA-00934: group function is not allowed here
Excluding Group Results
DEPTNO SAL
----------- -------------------
10 2450
10 5000
10 1300
“maximum salary
20 800 DEPTNO MAX(SAL) -
20 1100 per department ----------- --------------
20 3000 greater than
20 3000 10 5000
$2900” 20 3000
20 2975
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
Excluding Group Results: HAVING Clause
Use the HAVING clause to restrict groups
•Rows are grouped.
•The group function is applied.
•Groups matching the HAVING clause are displayed.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Using the HAVING Clause
SQL> SELECT deptno, max(sal)
2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;
DEPTNO MAX(SAL)
------------ --------------
10 5000
20 3000
Using the HAVING Clause
SQL> SELECT job, SUM(sal) PAYROLL
2 FROM emp
3 WHERE job NOT LIKE ‘SALES%’
4 GROUP BY job
5 HAVING SUM(sal) >5000
6 ORDER BY SUM(sal);
DEPTNO PAYROLL
------------ ------------
ANALYST 6000
MANAGER 8275
Nesting Group Functions
Display the maximum average salary.
SQL> SELECT max(avg(sal))
2 FROM emp
3 GROUP BY deptno;
MAX(AVG(SAL) )
------------------------
29916.6667