91797278 Perancangan Basis Data
-
Author
ardianya-artika -
Category
Documents
-
view
504 -
download
61
Embed Size (px)
Transcript of 91797278 Perancangan Basis Data

UBL Fakultas Teknologi Informasi PBD - 1
PERANCANGAN BASIS DATA (3 SKS)
Siklus Pengembangan Sistem
Identifikasi danSeleksi Proyek
Inisiasi danPerencanaan Proyek
Analisa
Perancangan Fisik
Implementasi
Pemeliharaan
Perancangan Logis
Tujuan: Mengembangkan spesifikasi teknologiHasil: Struktur program/data, pembelian teknologi, restrukturisasi organisasi
Aspek Database: Perancangan Fisik Database

UBL Fakultas Teknologi Informasi PBD - 2
PERANCANGAN BASIS DATA (3 SKS)
Pendahuluan
PERANCANGAN DATABASE adalah proses pembuatan (develop) stuktur database sesuai dengan data yang dibutuhkan oleh user.
LANGKAH-LANGKAH DALAM PERANCANGAN DATABASE
1. Mendefinisikan kebutuhan (Requirements definition)Tujuan: untuk mengidentifikasi dan mendeskripsikan data yang dibutuhkan oleh user dalam sebuah organisasi.
2. Rancangan Konseptual (Conceptual design)Tujuan: untuk membuat sebuah model data konseptual (atau arsitektur informasi) yang akan mendukung perbedaan kebutuhan informasi dari beberapa user dalam sebuah organisasi.

UBL Fakultas Teknologi Informasi PBD - 3
PERANCANGAN BASIS DATA (3 SKS)
3. Rancangan Implementasi (Implementation design) Tujuan: untuk memetakan model data logis (logical data model)
kedalam sebuah skema yang dapat diproses oleh DBMS tertentu.
4. Rancangan Fisik (Physical design)Pada tahap terakhir ini, logical database structured ( normalized relation, trees, network dll) dipetakan menjadi physical storage structure seperti file dan tabel.
Langkah Perbaikan (Stepwise refinement)Keseluruhan proses perancangan pada perancangan database harus dipandang sebagai satu langkah perbaikan, dimana perancangan pada setiap tahapan diperbaiki secara progresif melalui perulangan (iteration). Langkah perbaikan harus dilakukan pada bagian akhir setiap tahapan sebelum melangkah ke tahapan berikutnya..

UBL Fakultas Teknologi Informasi PBD - 4
PERANCANGAN BASIS DATA (3 SKS)
• Tujuan: Menterjemahkan deskripsi logis data kedalam spesifikasi teknis penyimpanan dan pengambilan data
• Hasil: Suatu rancangan penyimpanan data yang menghasilkan kinerja pemrosesan yang memadai dan menjamin integritas, keamanan dan ketahanan data

UBL Fakultas Teknologi Informasi PBD - 5
PERANCANGAN BASIS DATA (3 SKS)
Proses Perancangan Fisik
Input• Relasi ter-normalisasi• Perkiraan volume data• Definisi atribut-atribut• Target response time• Kebutuhan
Pengamanan data• Kebutuhan backup/
recovery• Kebijakan integritas
data• Teknologi DBMS yang
digunakan
Menentukan
Pilihan• Tipe data tiap atribut• Deskripsi record fisik• Organisasi file• Indeks dan arsitektur
database• Optimasi kinerja query

UBL Fakultas Teknologi Informasi PBD - 6
PERANCANGAN BASIS DATA (3 SKS)
MAJOR STEPS IN DATABASE DESIGN
Step 1Definisi Kebutuhan
Step 2Disain Konseptual
Step 3Disain Implementasi
Step 4Disain Pisik
Spesifikasi Kebutuhan
Arsitektur Informasi
Logical database structure (DBMS-processible)And application program specifications
Struktur Database pisik
Kebutuhan Informasi Pemakai
Data Perusahaan Model
Memproses Kebutuhan
Karakteristik Sistem Database Management
Hardware / Operating Karakter System

UBL Fakultas Teknologi Informasi PBD - 7
PERANCANGAN BASIS DATA (3 SKS)
Mendefinisikan Kebutuhan (Requirements definition) adalah proses mengidentifikasi & mendokumentasikan data yang dibutuhkan oleh user dalam sebuah database untuk memenuhi kebutuhan informasi saat ini dan masa yang akan datang.
2 jenis informasi yang harus diperhatikan selama tahapan mendefinisikan kebutuhan :1. Informasi yang menjelaskan struktur data, seperti entitas,
atribut, dan relasi. Informasi ini biasanya dinyatakan dalam bentuk grafik seperti entity-relationship diagrams (E-RD).
2. Informasi yang menggambarkan aturan atau batasan yang dapat menjaga integritas data.Biasanya disebut aturan bisnis (business rules), batasan-batasan ini harus di tuangkan dalam data dictionary/directory (atau repository) suatu organisasi.
MENDEFINISIKAN KEBUTUHAN

UBL Fakultas Teknologi Informasi PBD - 8
PERANCANGAN BASIS DATA (3 SKS)
Conceptual data model
Entity Relationship attribute
Candidate key
Class-subclass constraints
Foreign key descriptor
Primary key
simple
composite
domain Referential integrityOther business
constraints
insert
delete
update
Name/Definition
Type
Length
Format
Allowable Value
Information yang dikumpulkan dalam Mendefinisikan Kebutuhan
Komponen data yang konseptual model harus dipahami sebelum mengumpulkan informasi selama definisikan kebutuhan
Komponen dari model ini adalah:

UBL Fakultas Teknologi Informasi PBD - 9
PERANCANGAN BASIS DATA (3 SKS)
Tiga type utama batasan (constraints) :
1. Domain constraintsBatasan ini mendefinisikan type, lebar, format, dan nilai yang diperkenankan untuk setiap data.
2. Referential Integrity constraintsBatasan ini meyakinkan integritas of references antara beberapa baris dari sebuah tabel dan baris-baris pada tabel lainnya (atau beberapa tabel).
3. Other business constraintsBatasan ini meyakinkan integritas dari nilai sebuah data dalam sebuah tabel, memberikan satu atau lebih nilai sebuah data pada tabel yang sama atau pada tabel yang lain.

UBL Fakultas Teknologi Informasi PBD - 10
PERANCANGAN BASIS DATA (3 SKS)
Langkah-langkah dalam Mendefinisikan Kebutuhan
6 Langkah dalam mendefinisikan kebutuhan dilakukan secara berulang
dengan melakukan langkah perbaikan pada setiap langkah.
1. Mendefinisikan Lingkup Database
Team harus meninjau ulang rencana SI pada organisasi sebelum melakukan definisi kebutuhan.
Rencana meliputi tabel bisnis, suatu model informasi perusahaan, dan prioritas database dan implementasi merencanakan.
Rencana ini harus digunakan sebagai suatu keseluruhan kerangka untuk mendisain database.

UBL Fakultas Teknologi Informasi PBD - 11
PERANCANGAN BASIS DATA (3 SKS)
2. Memilih metodologi dalam Mendefinisikan Kebutuhan
Memilih metodologi dan CASE tools yang sesuai adalah hal yang esensial.
Metodologi memberikan prosedur standar dan format pengumpulan data yang dibutuhkan untuk mengelola pengumpulan metadata pada disiplin tertentu.
CASE tools memberikan dukungan berbasis komputer (computer-based support) untuk membangun sebuah repository dari metadata dan membuat tampilan yang terstruktur dari metadata tersebut.
CASE tools yang digunakan selama tahapan Mendefinisikan Kebutuhan harus sesuai dengan CASE tools yang digunakan selama merencanakan database.

UBL Fakultas Teknologi Informasi PBD - 12
PERANCANGAN BASIS DATA (3 SKS)
3. Mengidentifikasi Pandangan User (User Views) Pengumpulan data biasanya fokus pada pandangan user
terhadap data. Pandangan user (User View) adalah sekumpulan data yang
diperlukan oleh user tertentu untuk membuat keputusan atau melakukan tindakan
Kita mengidentifikasi user views dengan meninjau ulang tugas (tasks) yang dilakukan atau keputusan yang dibuat oleh user dan dengan meninjau ulang data yang diperlukan untuk tugas-tugas dan keputusan tersebut.
Laporan, file, form, dokumen, dan tampilan (display) yang ada (baik input maupun output) merupakan sumber informasi yang penting tentang user views, dan analyst harus mengumpulkan contoh salinan dari data yang digunakan untuk mendukung keputusan.
Merupakan hal yang penting untuk mengantisipasi kebutuhan akan data di masa depan jika memungkinkan.

UBL Fakultas Teknologi Informasi PBD - 13
PERANCANGAN BASIS DATA (3 SKS)
4. Model data structure
Tahapan ini membutuhkan struktur yang konsisten pada setiap user views yang telah diidentifikasikan pada tahapan sebelumnya.
Pada sesi sebelumnya, kita menggunakan E-R Diagrams untuk membuatn model data structure. Memodelkan user views dalam bentuk E-R Diagrams memerlukan entitas, relasi (relationship), atribut, candidate keys, Primary Key dan descriptor yang relevan untuk setiap pandangan user yang kita identifikasikan.

UBL Fakultas Teknologi Informasi PBD - 14
PERANCANGAN BASIS DATA (3 SKS)
5. Model database constraints
Selama tahapan mendefinisikan kebutuhan, database analyst juga harus mengidentifikasi basic constraints yang menjaga integritas database.
Batasan-batasan ini : domains, referential integrity dan aturan bisnis lainnya. Batasan ini seharusnya disimpan dalam data dictionary (atau repository), dengan menggunakan CASE tools yang tersedia.

UBL Fakultas Teknologi Informasi PBD - 15
PERANCANGAN BASIS DATA (3 SKS)
6. Mengidentifikasi Kebutuhan Operasional
Seorang analyst juga harus mengumpulkan informasi yang berkenaan dengan kebutuhan operasional user akan data.
Tahapan ini meliputi kebutuhan untuk masing-masing area berikut:1. Keamanan (Security). 2. Waktu Respon (Response times).3. Backup and recovery. 4. Dokumentasi (Archiving). 5. Prediksi Perkembangan (Growth Projections)
Database.

UBL Fakultas Teknologi Informasi PBD - 16
PERANCANGAN BASIS DATA (3 SKS)
Mendefinisikan Lingkup Database
Memilih Metodologi Untuk Mendefinisikan Kebutuhan
Mengidentifikasi User Views
Model Data Structure
Model Data Constraints
Mengidentifikasi kebutuhan operasional
Ke tahapan logical database design
Case Tools
Enterprise data model
report
display
Langkah dalam Mendefinisikan Kebutuhan

UBL Fakultas Teknologi Informasi PBD - 17
PERANCANGAN BASIS DATA (3 SKS)
Perancangan Field
• Field: satuan data terkecil dalam database
• Perancangan field – Memilih tipe data yang sesuai
– Kodifikasi, kompresi, enkripsi
– Penjagaan integritas data

UBL Fakultas Teknologi Informasi PBD - 18
PERANCANGAN BASIS DATA (3 SKS)
Memilih Tipe Data
• CHAR – karakter dengan panjang tetap• VARCHAR2 – karakter dengan panjang
bervariasi (memo)• LONG – bilangan besar• NUMBER – bilangan positif/negatif• DATE – tanggal• BLOB – Binary Large Object, data biner (cocok
untuk grafik, klip suara/video, dsb.)

UBL Fakultas Teknologi Informasi PBD - 19
PERANCANGAN BASIS DATA (3 SKS)
Integritas Data Field
• Nilai otomatis (default): Nilai yang diasumsikan jika tidak disebutkan secara eksplisit
• Penjagaan range: Batasan nilai-nilai yang sah (konstrain atau aturan validasi)
• Penjagaan nilai kosong (nol): Aturan boleh/tidak-boleh field bernilai kosong
• Integritas referensial: Penjagaan range (dan nilai kosong) untuk pasangan key asing dan key primer

UBL Fakultas Teknologi Informasi PBD - 20
PERANCANGAN BASIS DATA (3 SKS)
Penanganan Nilai-nilai Kosong
• Isi dengan nilai perkiraan (misalnya dengan suatu rumus penghitungan/ formula)
• Menulis laporan daftar nilai-nilai kosong• Dalam program, abaikan data bernilai
kosong (kecuali jika nilai tersebut penting)
Trigger dapat digunakan untuk menjalankan operasi-operasi ini

UBL Fakultas Teknologi Informasi PBD - 21
PERANCANGAN BASIS DATA (3 SKS)
Record Fisik
• Record Fisik: Satu set berisi field-field yang disimpan secara berdekatan dalam suatu lokasi memori dan diakses secara bersamaan sebagai satu kesatuan
• Page: Ukuran data yang dibaca atau ditulis DBMS dalam satu operasi Input/Output (I/O)
• Blocking Factor: Jumlah record fisik dalam satu page

UBL Fakultas Teknologi Informasi PBD - 22
PERANCANGAN BASIS DATA (3 SKS)
Denormalisasi• Mengubah relasi-relasi ternormalisasi ke
spesifikasi record fisik yang tak ternormalisasi
• Keuntungan:– Dapat meningkatkan kinerja (kecepatan) proses
dengan mengurangi jumlah tabel yang dilibatkan dalam proses (mengurangi jumlah operasi join)
• Kerugian (karena duplikasi data)– Pemborosan ruang penyimpanan– Resiko pelanggaran integritas/konsistensi data

UBL Fakultas Teknologi Informasi PBD - 23
PERANCANGAN BASIS DATA (3 SKS)
Denormalisasi• Penggunaan denormalisasi yang umum:
– Hubungan satu-ke-satu– Hubungan banyak-ke-banyak dengan atribut– Data referensi (hubungan 1:N dengan satu pihak
memiliki data yang tidak digunakan dalam hubungan-hubungan lain)

UBL Fakultas Teknologi Informasi PBD - 24
PERANCANGAN BASIS DATA (3 SKS)
• Model Conceptual.
• Analisa Entity Relationship.
• Membangun Entity Relationship Models
• Entity Relationship and Data Flow Diagrams
• Subsets and Dependent Entity Sets
Deskripsi Data

UBL Fakultas Teknologi Informasi PBD - 25
PERANCANGAN BASIS DATA (3 SKS)
4 Komponen pertama (Entitas, Relasi, Atribut dan class-subclass) berhubungan dengan struktur data.
1. Entitas (Entity)Adalah orang, tempat, peristiwa, objek atau konsep yang datanya akan dikelola.– Contoh:– Orang MAHASISWA, KARYAWAN, PASIEN – Tempat TOKO, GUDANG, KOTA– Peristiwa PENJUALAN, PEMINJAMAN– Objek MOBIL, BARANG, BUKU– Konsep MATAKULIAH, REKENING, ACCOUNT
Komponen Model Data Konseptual

UBL Fakultas Teknologi Informasi PBD - 26
PERANCANGAN BASIS DATA (3 SKS)
• Merupakan objek yang memiliki lebih dari satu entity instances (contoh) dalam database
– Entity Instance untuk Entitas MAHASISWA adalah Rika, Andi, Della, dll
• Merupakan objek yang memiliki beberapa atribut.
• BUKAN seorang user dari sistem.
• BUKAN sebuah output dari sistem (contoh: laporan)
Syarat sebuah Entitas

UBL Fakultas Teknologi Informasi PBD - 27
PERANCANGAN BASIS DATA (3 SKS)
Inappropriate entities
System userSystem user System outputSystem output
Appropriate entities

UBL Fakultas Teknologi Informasi PBD - 28
PERANCANGAN BASIS DATA (3 SKS)
Gambar -- Notasi dasar E-R
Simbol Entitas
Simbol Relasi
Simbol Atribut
Entitas yang juga merupakan Relasi

UBL Fakultas Teknologi Informasi PBD - 29
PERANCANGAN BASIS DATA (3 SKS)
2. Atribut (Attribute)Adalah properti atau karakteristik dari sebuah entitas atau relationship. Berhubungan dengan field pada tabel.
Contoh:
Entitas MAHASISWA
Atribut NIM, Nama, Alamat, TTL, dst
Klasifikasi Atributa. Simple Attribute
Adalah atribut yang tidak dapat di breakdown menjadi beberapa komponen.
Komponen Model Data Konseptual

UBL Fakultas Teknologi Informasi PBD - 30
PERANCANGAN BASIS DATA (3 SKS)
Klasifikasi Atribut (lanjutan)
b. Composite Attribute
Adalah atribut yang dapat di breakdown menjadi beberapa komponen.
c. Multivalued Attribute
Adalah atribut yang memiliki lebih dari satu entity instance.
d. Derived Attribute
Adalah atribut yang merupakan nilai hasil perhitungan dari nilai atribut yang lain.

UBL Fakultas Teknologi Informasi PBD - 31
PERANCANGAN BASIS DATA (3 SKS)
Composite attribute
Sebuah atribut yang di breakdown menjadi beberapa komponen

UBL Fakultas Teknologi Informasi PBD - 32
PERANCANGAN BASIS DATA (3 SKS)
Simple key attribute
Sebuah key digaris bawahi

UBL Fakultas Teknologi Informasi PBD - 33
PERANCANGAN BASIS DATA (3 SKS)
Entitas dengan multivalued attribute (Skill) dan derived attribute (Years_Employed)
Derived from date employed and current date
What’s wrong with this?
Multivalued: an employee can have more than one skill

UBL Fakultas Teknologi Informasi PBD - 34
PERANCANGAN BASIS DATA (3 SKS)
• Beberapa jenis Atribut (lanjutan)
Candidate Key Adalah atribut yang dapat di dijadikan sebagai identifikasi dari EntitasPrimary Key Adalah atribut yang mempunyai sifat unik.
• Simple Primary Key yang terdiri dari saru atribut
• CompositePrimary Key yang terdiri dari dua atau lebih atribut.
Foreign Key Adalah suatu atribut yang dimiliki oleh suatu entitas, tetapi atribut tersebut merupakan Primary Key dari entitas lain.
Descriptor Adalah atribut biasa.

UBL Fakultas Teknologi Informasi PBD - 35
PERANCANGAN BASIS DATA (3 SKS)
Memilih Nama Attribute
• Nama harus unik di dalam sistem
• Semua atribut yang menguraikan Entity atau Relationship tertentu harus diberi nama.
• Masing-Masing Relationship harus meliputi atribut yang menguraikan Entity tersebut dalam membentuk Raltionship.
• Nama penuh arti harus diterpilih sehingga E-R diagram adalah self-explanatory (menjelaskan isi dari dirinya)

UBL Fakultas Teknologi Informasi PBD - 36
PERANCANGAN BASIS DATA (3 SKS)
• Sebuah Relationship Set direpresentasikan dengan sebuah diamond pada E-R diagram
• Diamond ini menghubungkan Entity Sets dari entitas yang berinteraksi dalam sebuah relasi (relationship)
• Relatlationship dapat mempunyai attributsAttributs ini mengambarkan ciri dari Entity dan Relationship.
• Dua Entity dapat mempunyai lebih dari satu jenis Relasi (multiple relationships)
• Associative Entity = Kombinasi dari Relationship and Entity
3. Relationship SetsUntuk Memodelkan Interaksi Antara Entitas Dalam Entity Sets
PERSONS VEHICLESDRIVE

UBL Fakultas Teknologi Informasi PBD - 37
PERANCANGAN BASIS DATA (3 SKS)
Degree of Relationships
• Jenis-Jenis dari Degree of Relationship– Unary Relationship– Binary Relationship– Ternary Relationship

UBL Fakultas Teknologi Informasi PBD - 38
PERANCANGAN BASIS DATA (3 SKS)
Contoh :

UBL Fakultas Teknologi Informasi PBD - 39
PERANCANGAN BASIS DATA (3 SKS)
Unary Relationship

UBL Fakultas Teknologi Informasi PBD - 40
PERANCANGAN BASIS DATA (3 SKS)
Binary Relationship

UBL Fakultas Teknologi Informasi PBD - 41
PERANCANGAN BASIS DATA (3 SKS)
Ternary Relationship

UBL Fakultas Teknologi Informasi PBD - 42
PERANCANGAN BASIS DATA (3 SKS)
v1
v2
v3
p1
p2
p3
p4
persons
E-R DIAGRAM
Dimana,Person p1 Drive Vehicle v1Person p2 Drive Vehicles v1 dan v2Person p3 Drive Vehicle v2Person p4 Drive Vehicles v2 dan v3
vehicles RelasiDrive
P4 Drive v3
OCCURENCE DIAGRAM
d1
d2
d3
d4
d6
d5
PERSONS VEHICLESDRIVE

UBL Fakultas Teknologi Informasi PBD - 43
PERANCANGAN BASIS DATA (3 SKS)
• Sebuah Perusahaan memiliki beberapa kendaraan(vehicles) dan menyewa beberapa kendaraan
COMPANIES VEHICLES
PUNYA
SEWA
E-R DIAGRAM
c1
c2
c3
v1
v2v3v4
v5
COMPANIESVEHICLESPUNYA
SEWA
Lebih Dari Satu Relationship Set Antara Dua Entity Sets

UBL Fakultas Teknologi Informasi PBD - 44
PERANCANGAN BASIS DATA (3 SKS)
E-R diagram berinama yang menarik dan sesuai dengan kondisi.
ENTITY SETS Berinama Dengan Kata BENDA
RELATIONSHIP SETSBerinama Dengan Kata KERJA
Tapi Terkadang RELATIONSHIP SETSdiberinama dengan Kata Penghubung
OFFORIN
TOABOUTBY
Penamaan Entity Set
ADAUNTUKDALAMKEdst

UBL Fakultas Teknologi Informasi PBD - 45
PERANCANGAN BASIS DATA (3 SKS)
Note that relationship naming is “uni-directional”
Proyek
Material
Pakai
Manajer Orang
Perjalanan
Buat
Kepulauan
Pimpin
Ke
Examples/Contoh

UBL Fakultas Teknologi Informasi PBD - 46
PERANCANGAN BASIS DATA (3 SKS)
ExamplesMenggunakan kata depan untuk nama Relationship Set
Ownership
Vehicles
Of
PersonsBy
PriceChanges
Items
Of
SuppliersFrom

UBL Fakultas Teknologi Informasi PBD - 47
PERANCANGAN BASIS DATA (3 SKS)
Cardinality of Relationships
• One – to – One– Each entity in the relationship will have exactly
one related entity
• One – to – Many– An entity on one side of the relationship can have
many related entities, but an entity on the other side will have a maximum of one related entity
• Many – to – Many– Entities on both sides of the relationship can have
many related entities on the other side

UBL Fakultas Teknologi Informasi PBD - 48
PERANCANGAN BASIS DATA (3 SKS)
Cardinality Constraints
• Cardinality Constraints – Jummlah dari instances pada satu Entity dapat atau harus dihubungkan dengan masing-masing instance pada entity lain.
• Minimum Cardinality– Jika Kosong, merupakan optional– Jika Satu atau Lebih, merupakan mandatory
• Maximum Cardinality– Jumlah maximum

UBL Fakultas Teknologi Informasi PBD - 49
PERANCANGAN BASIS DATA (3 SKS)
1 : 1 Relationship
Masing-Masing PERSON Mengendarai Satu VEHICLE dan
Masing-Masing VEHICLE dikendarai hanya satu PERSON.
P1
P2
P3
V1
V2
V3
PERSONS VEHICLESDRIVE1 1

UBL Fakultas Teknologi Informasi PBD - 50
PERANCANGAN BASIS DATA (3 SKS)
N :1 and 1 : N Relationships
PERSONS VEHICLESDRIVE1 N
P1
P2
P3
V1
V2
V3
PERSONS VEHICLESDRIVEN 1
P1
P2
P3
V1
V2
V4

UBL Fakultas Teknologi Informasi PBD - 51
PERANCANGAN BASIS DATA (3 SKS)
p4p1 p2 p3
v1 v2 v3 v4 v5
N : M Relationship
PERSONS VEHICLESDRIVEM N

UBL Fakultas Teknologi Informasi PBD - 52
PERANCANGAN BASIS DATA (3 SKS)
Cardinality dapat juga digambar

UBL Fakultas Teknologi Informasi PBD - 53
PERANCANGAN BASIS DATA (3 SKS)
Menulis Atribut Dan Identifiers Pada Suatu E-R Diagram
Mahasiswa Punya KTP1 1
NIM
Nama
Alamat
No_KTP
Masa Berlaku
No_KTP
NIMJika Atribut Merupakan Atribut Unik, Beri garis bawah
Identifiers of participating entities

UBL Fakultas Teknologi Informasi PBD - 54
PERANCANGAN BASIS DATA (3 SKS)
Strong vs. Weak Entities, and Identifiying Relationships
• Strong entities – Keberadaanya berdiri sendiri.– Mempunyai Primary Key (unique identifier)– Digambarkan dengan Persegi Empat dengan Garis Tunggal.
• Weak entity– Tergantung pada strong entity…Tidak Dapat berdiri sendiri.– Tidak Mempunyai Primary Key (unique identifier)– Digambar dengan dengan Persegi Empat dengan Garis
double.• Identifying relationship
– Penghubung strong entities ke weak entities– Digambar dengan Belah Ketupat dengan garis double.

UBL Fakultas Teknologi Informasi PBD - 55
PERANCANGAN BASIS DATA (3 SKS)
Contoh Weak Entity

UBL Fakultas Teknologi Informasi PBD - 56
PERANCANGAN BASIS DATA (3 SKS)
Associative Entities• Merupakan entity yang mempunyai attributes• Dan merupakan relationship merupakan pengubung
entities bersama.• Kapan sebaiknya relationship dengan attributes menjadi
sebuah associative entity? – Semua Relationships pada associative entity harus
many– The associative entity bisa mempunya arti tidak terikat
pada Entity lain– The associative entity Lebih disukai mempunyai
unique identifier, dan juga harus mempunyai attributes lain.
– Ternary relationships harus dikonversi ke associative entities

UBL Fakultas Teknologi Informasi PBD - 57
PERANCANGAN BASIS DATA (3 SKS)
Associative entity (CERTIFICATE)
Associative entity melibatkan Persegi Empat dengan dengan belah ketupat.Catat bahwa many-to-many cardinalas gambar untuk ke arah Associative Entity dan bukan ke arah Entity lain

UBL Fakultas Teknologi Informasi PBD - 58
PERANCANGAN BASIS DATA (3 SKS)
A Good E-R Diagram
Semua Attributes should be simple
Mereka dapat dimasukkan awal akan tetapi yang dikurangi langkah-langkah kemudiannya
Identifiers harus unik.
The E-R diagram tidak harus suatu flowchart.

UBL Fakultas Teknologi Informasi PBD - 59
PERANCANGAN BASIS DATA (3 SKS)
PERSON-IDDATE-OF-BIRTH QUALIFICATION* ADDRESS NUMBER
STREET SUBURB POSTCODE
DEPENDENTS* DEPENDENT-NAME DEPENDENT BIRTH-DATE
PERSONS
Starting With Structured Attributes

UBL Fakultas Teknologi Informasi PBD - 60
PERANCANGAN BASIS DATA (3 SKS)
QUALIFICATION DEPENDENT-NAME
PERSON-IDDATE-OF-BIRTH
PERSON-ID QUALIFICATION
DEPENDENT- BIRTH-DATE
PERSONS
NUMBER STREET SUBURB POSTCODE
QUALIFICATIONS DEPENDENTS ADDRESSES
HAS LIVES-ATOBTAINED
N
M
1
N
1
1PERSON-ID DEPENDENT -NAME
PERSON-ID NUMBER STREET SUBURB POSTODE
PERSON-IDDATE-OF-BIRTH QUALIFICATION* ADDRESS NUMBER
STREET SUBURB POSTCODE
DEPENDENTS* DEPENDENT-NAME DEPENDENT BIRTH-DATE
PERSONS
Reducing to Simple Attributes

UBL Fakultas Teknologi Informasi PBD - 61
PERANCANGAN BASIS DATA (3 SKS)
Do not Include Derived Relationships
Do not Include Ternary Relationships
Pastikan Masing-masing Relationship Mengambarkan Satu konsep.
Pastikan Bahwa Tidak Ada Informasi Yang Hilang.
Good Relationships

UBL Fakultas Teknologi Informasi PBD - 62
PERANCANGAN BASIS DATA (3 SKS)
OBJECT-ORIENTED REPRESENTATION
Object-oriented representation is an emerging tool that helps overcome some of these limitations of E-R models.
The advantage of object-oriented techniques is that they allow us to incorporate integrity rules ( as well as other database operations) directly in the database model or description, in the form of methods or procedures.

UBL Fakultas Teknologi Informasi PBD - 63
PERANCANGAN BASIS DATA (3 SKS)
OBJECT
an object is a named representation of real-word entity. for example, the following are objects : customers, products, accounts, students, and courses
Two type of characteristics that are associated with objects :
Attributes Operations ( also called Methods)
Attributes properties of objects that are of interest to the
organizations. for example, some attributes associated with the object
Bicycle are Make, Model, Serial Number, frame size, and color.

UBL Fakultas Teknologi Informasi PBD - 64
PERANCANGAN BASIS DATA (3 SKS)
Operations (Methods)
Operations are actions that may be performed on objects and that may change the values of attributes of the object.
for example, some operations that are performed on the bicycle objects are lock bicycle, unlock bicycle, ride bicycle, and paint bicycle.
The combination of all the values of the attributes of a given object represent the state of that object. For example, the values of make, model, serial number, frame size, and color determine the state of bicycle object at a given point in time.
Some operations may change the state of the object.
In a larger sense, a database represents the state of an organization; the state changes constantly through time as operations (such as transactions) occur

UBL Fakultas Teknologi Informasi PBD - 65
PERANCANGAN BASIS DATA (3 SKS)
CLASSES AND INSTANCES
A class is a logical grouping of objects that share the same attributes and operations.
An instance is one member (or materialization) of that class
For example, bicycle is a class of object; mary’s bicycle is an instance of that class. All of the attributes and operations for the class are described in one place (the class object).
Object instances may contain attributes or operations that are peculiar to that instance but are not shared by other instances of the class.

UBL Fakultas Teknologi Informasi PBD - 66
PERANCANGAN BASIS DATA (3 SKS)
INHERITANCE
An object class is really a subclass of a more general class (called a super class).for example, bicycle, motorcycles, and auto-mobiles are subclasses of a super class called vehicles
vehicles
motorcyclebicycle automobile

UBL Fakultas Teknologi Informasi PBD - 67
PERANCANGAN BASIS DATA (3 SKS)
Inheritance mean that each subclass inherits the attributes and operations of the super class to which it belongs.
for example, the attributes make, model, serial number, and color would apply to the super class vehicle
These attributes would be defined once for vehicle and would automatically be inherited by the bicycle, motorcycle, and automobile sub-classes.
However, each subclass often possesses additional attributes and operation that do not apply to the super class.
for example, the attribute frame size would apply to the bicycle subclass only, while the attribute engine displacement would apply to motorcycle and automobile ( but not to bicycle)

UBL Fakultas Teknologi Informasi PBD - 68
PERANCANGAN BASIS DATA (3 SKS)
Object Oriented Database Management Systems
Object Oriented Database Management Systems Motivation Examples of Existing Systems and Prototypes Object Oriented Concepts Examples of Type Declarations Examples of Class Definitions Operations on Objects Type and Class Hierarchy Advantages and Disadvantages of OODBMS
Hierarchical Data Model Networked Data Model

UBL Fakultas Teknologi Informasi PBD - 69
PERANCANGAN BASIS DATA (3 SKS)
Object Oriented Database Management Systems
MotivationRecord-oriented data models are effective when applied to traditional transaction processing applications. However, for advanced database applications such as the following, traditional model are not suitable:
CAD/CAM CIM Imaging and Graphics Geographic Information Systems Scientific databases Multimedia databases
Such applications have complex requirements: Complex data structures (beyond simple character, number, date) New data types for large, unstructured objects (Video, audio,
multimedia documents) Reactive/Active transactions Long duration activities and transactions Collaborative activities (multiple authors)
Object Oriented Data Models and OODBMS are designed to address these requirements

UBL Fakultas Teknologi Informasi PBD - 70
PERANCANGAN BASIS DATA (3 SKS) Object Oriented ConceptsOODBMS are based on Object Oriented models They add Persistence to objects Some basics: An Object:
is an Instance of a Class Contains both data and the methods (functions) to operate on data Hides its internal data structure (data hiding) May only be accessed using the methods provided (encapsulation)
Objects in an OO program are transient Objects in an OO DBMS are persistent An OODBMS provides interfaces to one or more OO programming languages (Smalltalk, C++,
Java) Both transient and persistent objects are treated uniformly - the programmer need not be
concerned with the difference. Every Object has a unique Object Identifier (OID) - remains for the life of the object An object may be arbitrarily complex - capable of expressing and storing all related data in a
single object (unlike relational model) Consider an Object as a triple: O( i, c, v ) where
i is the object identifierc is a set of constructorsv is a set of instance variables
Instance variables are the object's internal structure that hold its state. Constructor is basic data type used to make up instance variables - tuple, bag, set, list, etc. Relationships are captured through OID references

UBL Fakultas Teknologi Informasi PBD - 71
PERANCANGAN BASIS DATA (3 SKS)
Examples of Type Declarationsdefine type Employee: tuple ( name: string, ssn: string, birthdate: Date, dept: Department);
define type Department: tuple ( dname: string, dnumber: integer, manager: tuple (manager: Employee, startdate: Date), locations: set(string), employees: set(Employees), projects: set(Projects) );
define type Date: tuple ( year: integer, month: integer, day: integer );

UBL Fakultas Teknologi Informasi PBD - 72
PERANCANGAN BASIS DATA (3 SKS)
Examples of Class Definitions class Person { type tuple ( name: string, ssn: string, birthdate: Date, address: tuple ( street: string, city: string, state: string) ) method age: integer }
class Employee inherit Person { type tuple ( hiredate: Date, dept: Department )
method number_of_employees: integer}

UBL Fakultas Teknologi Informasi PBD - 73
PERANCANGAN BASIS DATA (3 SKS)
Operations on Objects
• Encapsulation: Only a specific set of predefined operations or functions may be applied to a given object - Objects are assumed to independent
• Each Operation has two components:
1. Interface (or signature): The name of the operation and the arguments or parameters it expects.
2. This is visible to other objects.
• Method (body): The actual implementation of the operation. This is not visible to other objects.
• Operations are invoked by passing messages from one objects to the next.
• message (oid, method, arguments)
• Thus the implementation of a particular method can be changed without affecting the objects that invoke the method
• This gives us object-program independence.

UBL Fakultas Teknologi Informasi PBD - 74
PERANCANGAN BASIS DATA (3 SKS)
Type and Class Hierarchy• Object Type: Set of allowable values • Object Class: Collection of objects meaningful in an application • New types and classes can be defined based on existing ones • Inheritance: New types and classes that the structure and
operations from which they are derived (see Person and Employee
example above). • Fosters incremental design and reuse.

UBL Fakultas Teknologi Informasi PBD - 75
PERANCANGAN BASIS DATA (3 SKS)
Advantages and Disadvantages of OODBMS
Advantages Disadvantages
Integrated with Programming Language (C++, Java, Smalltalk)
Requires OO Programming (in general)
Automatic Method Storage (some OODBMS)
Not much data is presently in Object form - huge investment in relational
User-defined Types Poor query and reporting tools
Easy to process Complex data Limited concurrency control and transaction management
Persistent Object Identifiers Unproven performance
Single-level memory Steep learning curve

UBL Fakultas Teknologi Informasi PBD - 76
PERANCANGAN BASIS DATA (3 SKS)
Hierarchical Data Model• For the Hierarchical model, we focus on IBM's Information
Management System or IMS developed in the 1960's. • IMS/DB is the data management part of the IMS product and is based
on the DL/I language. • All data is held in hierarchical structures (trees). • A Field is some item of data. Like an attribute in relational. • Fields are grouped into Segments. • A segment is a node in a tree (hierarchy). Segments also have a
sequence field used for sorting. • A particular tree structure is called a Data Base Record. • A Data Base Record is a collection of segments organized as a
hierarchy. • Physical Data Base Record (PDBR) - Describes data as they exist on
a storage device. • Logical Data Base Record (LDBR) - Describes data as they appear
to applications programs. • An LDBR may represent multiple PDBR's.

UBL Fakultas Teknologi Informasi PBD - 77
PERANCANGAN BASIS DATA (3 SKS)
•DL/I has a data manipulation language that operates on LDBR's. •Commands such as:GET UNIQUE - Reads a segmentGET NEXT - Reads the next segment in orderGET HOLD UNIQUE and GET HOLD NEXT - Perform the get operation but hold the pointer on the segment pending a replace or delete. REPLACE - Modify data in a segment.DELETE - Deletes a segment and all child segments in the data base record.INSERT - Creates a new segment.

UBL Fakultas Teknologi Informasi PBD - 78
PERANCANGAN BASIS DATA (3 SKS)
Inheritance mean that each subclass inherits the attributes and operations of the super class to which it belongs.
for example, the attributes make, model, serial number, and color would apply to the super class vehicle
These attributes would be defined once for vehicle and would automatically be inherited by the bicycle, motorcycle, and automobile sub-classes.
However, each subclass often possesses additional attributes and operation that do not apply to the super class.
for example, the attribute frame size would apply to the bicycle subclass only, while the attribute engine displacement would apply to motorcycle and automobile ( but not to bicycle)

UBL Fakultas Teknologi Informasi PBD - 79
PERANCANGAN BASIS DATA (3 SKS)
CONCEPTUAL DATABASE DESIGN
INTRODUCTION
Conceptual database design is the process of constructing a detailed architecture for a database that is independent of implementation details such as the target database management system, application programs or programming language, or any other physical consideration.
The primary inputs to conceptual database design are the structured requirement defined during requirement definition.

UBL Fakultas Teknologi Informasi PBD - 80
PERANCANGAN BASIS DATA (3 SKS)
The conceptual data model should have the criteria :1. Structural validity : consistency with the way the business
defines and organizes data
2. Simplicity : ease of understanding by both IS professional and non-technical users.
3. Non redundancy : each piece of information represented exactly once in the model
4. Share ability : all qualified users sharing the data in the conceptual model
5. Extensibility : ability to evolve to support new requirements with minimal impact on existing users
6. Integrity : consistency with the way the business uses and manages data

UBL Fakultas Teknologi Informasi PBD - 81
PERANCANGAN BASIS DATA (3 SKS)
STEPS IN CONCEPTUAL DATABASE DESIGN
A five steps process for conceptual database design :1. Develop conceptual data model
During this steps, the E-R diagrams that were developed for each user view during requirement definition are combined to form a single, integrated conceptual data model.
Database analyst must perform this step carefully to ensure that the resulting model (called the conceptual schema) is non redundant and logically consistent.
2. Transform data model to relations During this steps, E-R diagrams (or other logical data
model) are converted to relations. This steps might also be considered part to
implementation design (rather than conceptual design) But, this steps is preliminary to normalization ( we
consider part of conceptual design)

UBL Fakultas Teknologi Informasi PBD - 82
PERANCANGAN BASIS DATA (3 SKS)
3. Normalize the relationsDuring this step, the relation that were derived in the previous step are normalized
4. Integrate the relation. View integration is the process of merging individual user (in the form of E-R diagrams or 3NF relations) into an integrated data structure (or conceptual schema)
5. Develop action diagrams. action diagrams are high level-level definitions of data
operations that maintain a database in a current and consistent state.
Typical database operations add and delete records, modify records, and produce output in the form of reports and displays.

UBL Fakultas Teknologi Informasi PBD - 83
PERANCANGAN BASIS DATA (3 SKS)
Data structures
and constraints
Develop conceptual data model
Transforms data model to relations
Normalize the relations
Perform view integration
Develop action diagrams
To physicalDatabase
design
(from requirements definition)
Step 1
Step 2
Step 3
Step 4
Step 5

UBL Fakultas Teknologi Informasi PBD - 84
PERANCANGAN BASIS DATA (3 SKS)
DEVELOPING THE CONCEPTUAL DATA MODEL
During requirements definition, an E-R diagrams is developed for each user view within the scope of the analysis.
In developing the conceptual data model, we need to combine all of these individual E-R diagrams to form a single, integrated data model.
In combining these views, we include all of the relevant components (entities, relationships, attributes) but eliminate redundant components.
As a result, the conceptual data model is a non redundant superset of the individual E-R diagrams

UBL Fakultas Teknologi Informasi PBD - 85
PERANCANGAN BASIS DATA (3 SKS)
TRANSFORMING E-R DIAGRAMS TO RELATIONS
Each entity in an E-R diagram is transformed to a relation.
The primary key (or identifier) of the entity becomes the primary key of the corresponding relation, and descriptors (non-key attributes) of the entity become non-key attributes of the relation
For example the customer entity. Customer-no is the primary key for the entity, as well as for the customer relation

UBL Fakultas Teknologi Informasi PBD - 86
PERANCANGAN BASIS DATA (3 SKS)
CUSTOMER
CUST_NO
NAME ADDRES CITY-STATE-ZIP
DISCOUNT
1273 CONTEMPORARY DESIGN
123 OAK ST AUSTIN, TX 38405
5%
6390 CASUAL CORNER 18 HOOSIER DR.
BLOOMINGTON, IN 45821
3%
……
CUSTOMER
CUST_NO ADDRES
DISCOUNTCITY-STATE-ZIPNAME

UBL Fakultas Teknologi Informasi PBD - 87
PERANCANGAN BASIS DATA (3 SKS)
RELATIONSHIP
1 : N relationship a one-to-many (1:N) relationship in an E-R diagram is
represented by placing a foreign key in the relation that represents the entity on the many-side of the relationship.
This foreign key is the primary key of the entity on the one-side of the relationship.
CUSTOMER ORDERPLACED BY
1 N
CUST_NO ADDRES
DISCOUNTCITY-STATE-ZIPNAME
ORDER_NO
ORDER_DATE PROMISED_DATE

UBL Fakultas Teknologi Informasi PBD - 88
PERANCANGAN BASIS DATA (3 SKS)
CUSTOMER
CUST_NO
NAME ADDRES CITY-STATE-ZIP
DISCOUNT
1273 CONTEMPORARY DESIGN
123 OAK ST AUSTIN, TX 38405
5%
6390 CASUAL CORNER 18 HOOSIER DR.
BLOOMINGTON, IN 45821
3%
……
ORDER
ORDER_NO
ORDER_DATE PROMISED_DATE
CUST_NO
57194 3/15/2003 3/28/2003 6390
63725 3/17/2003 4/01/2003 1273
80149 3/14/2003 3/24/2003 6390

UBL Fakultas Teknologi Informasi PBD - 89
PERANCANGAN BASIS DATA (3 SKS)
M : N relationship For this relationship, we create new relation (thus, there
are three relations: one for each of the two entities and one for the relationship).
The key of this relation is a composite key consisting of the primary key for each of the two entities in the relationship.
ORDER PRODUCTREQUESTED ON
M N
DESCRIPTION (OTHER ATTRIBUTES)
QUANTITY ORDERED PRODUCT_NOROOM
ORDER_NO
ORDER_DATE PROMISED_DATE

UBL Fakultas Teknologi Informasi PBD - 90
PERANCANGAN BASIS DATA (3 SKS)
ORDERORDER_N
OORDER_DATE PROMISED_DATE
61384 2/17/2003 3/01/2003
62009 2/13/2003 3/27/2003
62807 2/15/2003 3/01/2003
ORDERPRODUCT_
NODESCRIPTION OTHER
ATTRIBUTES
M128 BOOKCASE ….
A261 WALL UNIT …
R149 CABINET ….
ORDER_LINEORDER_N
OPRODUCT_NO QUANTITY_ORDE
R
61384 M128 2
61384 A261 1

UBL Fakultas Teknologi Informasi PBD - 91
PERANCANGAN BASIS DATA (3 SKS)
ISA relationship (class-subclass)strategy that database designer can use to represent ISA relationship using relation. The strategy is :
1. Create a separate relation for the class and for each of the subclasses
2. The table (relation) for the class consists only of the column that are common to all of the subclasses, plus a suntype identification column
3. The table for each subclass contains only its primary key and the columns unique to that subclass
4. The primary key of the class and each of the subclasses are from the same domain

UBL Fakultas Teknologi Informasi PBD - 92
PERANCANGAN BASIS DATA (3 SKS)
BEACH_PROPERTY MOUNTAIN_PROPERTY
STREET_ADDR
TYPICAL-RENT
SKIING
BLOKSTO BEACH
STREET_ADDR CITY-STATE-ZIP
PROPERTY
NO-ROOMSCITY-STATE-ZIP
ISA ISA
STREET_ADDR CITY-STATE-ZIP

UBL Fakultas Teknologi Informasi PBD - 93
PERANCANGAN BASIS DATA (3 SKS)
PEOPERTY
STREET_ADDR CITY-STATE-ZIP NO-ROOMS
TYPICAL-RENT
SUBTYPE
120 SURF DR. HONOLULU, HI 99987
3 500 BEACH
100 MOGUL DR.
JACKSON, WY 89204
3 250 MOUNTAIN
BEACH
STREET_ADDR CITY-TATE-ZIP BLOCKS-TO-BEACH
120 SURF DR. HONOLULU, HI 99987
2
MOUNTAIN
STREET_ADDR CITY-STATE-ZIP SKIING
100 MOGUL DR. JACKSON, WY 89204 4

UBL Fakultas Teknologi Informasi PBD - 94
PERANCANGAN BASIS DATA (3 SKS)
Normalization
First Normal Form
Second Normal Form
Third Normal Form
Boyce-Codd Normal Form
Fourth Normal Form
Fifth Normal Form
Domain/Key Normal Form
De-Normalization
All-In-One Example of normalization.
NormalizationWhat you’ll learn :

UBL Fakultas Teknologi Informasi PBD - 95
PERANCANGAN BASIS DATA (3 SKS)
Normalization
Relations can fall into one or more categories (or classes) called Normal Forms
Normal Form: A class of relations free from a certain set of modification anomalies.
Normal forms are given name such as:
First normal form (1NF)
Second normal form (2NF)
Third normal form (3NF)
Boyce-Codd normal form (BCNF)
Fourth normal form (4NF)
Fifth normal form (5NF)
Domain-Key normal form (DK/NF)
•These forms are cumulative. A relation in Third normal form is also in 2NF and 1NF.

UBL Fakultas Teknologi Informasi PBD - 96
PERANCANGAN BASIS DATA (3 SKS)
First Normal Form (1NF)•A relation is in first normal form if it meets the definition of a relation: 1.Each column (attribute) value must be a single value only.
2.All values for a given column (attribute) must be of the same type. 3.Each column (attribute) name must be unique. 4.The order of columns is insignificant. 5.No two rows (tuples) in a relation can be identical. 6.The order of the rows (tuples) is insignificant.
•If you have a key defined for the relation, then you can meet the unique row requirement. •Example relation in 1NF:STOCKS (Company, Symbol, Date, Close_Price)
Company Symbol Date Close Price
IBM IBM 01/05/94 101.00
IBM IBM 01/06/94 100.50
IBM IBM 01/07/94 102.00
Netscape NETS 01/05/94 33.00
Netscape NETS 01/06/94 112.00

UBL Fakultas Teknologi Informasi PBD - 97
PERANCANGAN BASIS DATA (3 SKS)
Second Normal Form (2NF)•A relation is in second normal form (2NF) if all of its non-key attributes are
dependent on all of the key. •Relations that have a single attribute for a key are automatically in 2NF. •This is one reason why we often use artificial identifiers as keys. •In the example below, Close Price is dependent on Company, Date and
Symbol, Date •The following example relation is not in 2NF:STOCKS (Company, Symbol, Headquarters, Date, Close_Price)
Company Symbol Headquarters Date Close Price
IBM IBM Armonk, NY 01/05/94 101.00
IBM IBM Armonk, NY 01/06/94 100.50
IBM IBM Armonk, NY 01/07/94 102.00
Netscape NETS Sunyvale, CA 01/05/94 33.00
Netscape NETS Sunyvale, CA 01/06/94 112.00
Company, Date -> Close Price Symbol, Date -> Close Price Company -> Symbol, Headquarters Symbol -> Company, Headquarters

UBL Fakultas Teknologi Informasi PBD - 98
PERANCANGAN BASIS DATA (3 SKS)
Consider that Company, Date -> Close Price.
So we might use Company, Date as our key.
However: Company -> Headquarters
This violates the rule for 2NF. Also, consider the insertion and deletion
anomalies.
•One Solution: Split this up into two relations:
COMPANY (Company, Symbol, Headquarters)
STOCKS (Symbol, Date, Close_Price)
Company Symbol Headquarters
IBM IBM Armonk, NY
Netscape NETS Sunnyvale, CA
Company -> Symbol, Headquarters Symbol -> Company, Headquarters
Symbol Date Close Price
IBM 01/05/94 101.00
IBM 01/06/94 100.50
IBM 01/07/94 102.00
NETS 01/05/94 33.00
NETS 01/06/94 112.00
Symbol, Date -> Close Price

UBL Fakultas Teknologi Informasi PBD - 99
PERANCANGAN BASIS DATA (3 SKS)
Third Normal Form (3NF)•A relation is in third normal form (3NF) if it is in second normal form and
it contains no transitive dependencies. •Consider relation R containing attributes A, B and C.
If A -> B and B -> C then A -> C •Transitive Dependency: Three attributes with the above dependencies. •Example: At CUNY:
Course_Code -> Course_Num, Section
Course_Num, Section -> Classroom, Professor •Example: At Rutgers: Course_
Index_Num -> Course_Num, Section
Course_Num, Section -> Classroom, Professor

UBL Fakultas Teknologi Informasi PBD - 100
PERANCANGAN BASIS DATA (3 SKS)
Company County Tax Rate
IBM Putnam 28%
AT&T Bergen 26%
Company -> County and
County -> Tax Rate thus
Company -> Tax Rate
•What happens if we remove AT&T ?
We loose information about 2 different themes. •Split this up into two relations:
Company County
IBM Putnam
AT&T Bergen
Company -> County
County Tax Rate
Putnam 28%
Bergen 26%
County -> Tax Rate
Example:

UBL Fakultas Teknologi Informasi PBD - 101
PERANCANGAN BASIS DATA (3 SKS)
Boyce-Codd Normal Form (BCNF)•A relation is in BCNF if every determinant is a candidate key. •Recall that not all determinants are keys. •Those determinants that are keys we initially call candidate keys. •Eventually, we select a single candidate key to be the primary key for the relation.
Consider the following example:
Funds consist of one or more Investment Types.
Funds are managed by one or more Managers
Investment Types can have one more Managers
Managers only manage one type of investment.
FundID InvestmentType Manager
99 Common Stock Smith
99 Municipal Bonds Jones
33 Common Stock Green
22 Growth Stocks Brown
11 Common Stock Smith
FundID, InvestmentType -> Manager FundID, Manager -> InvestmentType Manager -> InvestmentType

UBL Fakultas Teknologi Informasi PBD - 102
PERANCANGAN BASIS DATA (3 SKS)
. In this case, the combination FundID and InvestmentType form a candidate key
because we can use FundID,InvestmentType to uniquely identify a tuple in the
relation. • Similarly, the combination FundID and Manager also form a candidate key because
we can use FundID, Manager to uniquely identify a tuple. • Manager by itself is not a candidate key because we cannot use Manager alone to
uniquely identify a tuple in the relation. • Is this relation R(FundID, InvestmentType, Manager) in 1NF, 2NF or 3NF ?
Given we pick FundID, InvestmentType as the Primary Key: 1NF for sure.
2NF because all of the non-key attributes (Manager) is dependant on all of the key.
3NF because there are no transitive dependencies. • Consider what happens if we delete the tuple with FundID 22. We loose the fact
that Brown manages the InvestmentType "Common Stocks."
FundID InvestmentType Manager
99 Common Stock Smith
99 Municipal Bonds Jones
33 Common Stock Green
22 Growth Stocks Brown
11 Common Stock Smith
FundID, InvestmentType -> Manager FundID, Manager -> InvestmentType Manager -> InvestmentType

UBL Fakultas Teknologi Informasi PBD - 103
PERANCANGAN BASIS DATA (3 SKS)
• The following are steps to normalize a relation into BCNF: 1. List all of the determinants. 2. See if each determinant can act as a key (candidate keys). 3. For any determinant that is not a candidate key, create a new relation from the
functional dependency. Retain the determinant in the original relation. For our example:
Rorig(FundID, InvestmentType, Manager) 1. The determinants are:
FundID, InvestmentTypeFundID, ManagerManager
2. Which determinants can act as keys ?FundID, InvestmentType YESFundID, Manager YESManager NO
3. Create a new relation from the functional dependency:Rnew(Manager, InvestmentType)Rorig(FundID, Manager)
In this last step, we have retained the determinant "Manager" in the original relation Rorig.

UBL Fakultas Teknologi Informasi PBD - 104
PERANCANGAN BASIS DATA (3 SKS)
Fourth Normal Form (4NF)• A relation is in fourth normal form if it is in BCNF and it contains no
multivalued dependencies. • Multivalued Dependency: A type of functional dependency where
the determinant can determine more than one value. • More formally, there are 3 criteria:
1. There must be at least 3 attributes in the relation. call them A, B, and
C, for example.
2. Given A, one can determine multiple values of B.
Given A, one can determine multiple values of C.
3. B and C are independent of one another.
example:
Student has one or more majors.
Student participates in one or more activities.

UBL Fakultas Teknologi Informasi PBD - 105
PERANCANGAN BASIS DATA (3 SKS)
StudentID Major Activities
100 CIS Baseball
100 CIS Volleyball
100 Accounting Baseball
100 Accounting Volleyball
200 Marketing Swimming
StudentID ->-> Major StudentID ->-> Activities
Portfolio ID Stock Fund Bond Fund
999 Janus Fund Municipal Bonds
999 Janus Fund Dreyfus Short-Intermediate Municipal Bond Fund
999 Scudder Global Fund Municipal Bonds
999 Scudder Global Fund Dreyfus Short-Intermediate Municipal Bond Fund
888 Kaufmann Fund T. Rowe Price Emerging Markets Bond Fund

UBL Fakultas Teknologi Informasi PBD - 106
PERANCANGAN BASIS DATA (3 SKS)
• A few characteristics:
1. No regular functional dependencies
2. All three attributes taken together form the key.
3. Latter two attributes are independent of one another.
4. Insertion anomaly: Cannot add a stock fund without adding a
bond fund (NULL Value). Must always maintain the combinations
to preserve the meaning.
• Stock Fund and Bond Fund form a multivalued dependency on
Portfolio ID. PortfolioID ->-> Stock Fund PortfolioID ->-> Bond
Fund

UBL Fakultas Teknologi Informasi PBD - 107
PERANCANGAN BASIS DATA (3 SKS)
Resolution: Split into two tables with the common key:
Portfolio ID
Stock Fund
999 Janus Fund
999 Scudder Global Fund
888 Kaufmann Fund
Portfolio ID
Bond Fund
999 Municipal Bonds
999 Dreyfus Short-Intermediate Municipal Bond Fund
888 T. Rowe Price Emerging Markets Bond Fund
Portfolio ID Stock Fund Bond Fund
999 Janus Fund Municipal Bonds
999 Janus Fund Dreyfus Short-Intermediate Municipal Bond Fund
999 Scudder Global Fund Municipal Bonds
999 Scudder Global Fund Dreyfus Short-Intermediate Municipal Bond Fund
888 Kaufmann Fund T. Rowe Price Emerging Markets Bond Fund

UBL Fakultas Teknologi Informasi PBD - 108
PERANCANGAN BASIS DATA (3 SKS)
Fifth Normal Form (5NF)There are certain conditions under which after decomposing a relation, it cannot be reassembled back into its original form.

UBL Fakultas Teknologi Informasi PBD - 109
PERANCANGAN BASIS DATA (3 SKS)
Domain Key Normal Form (DK/NF)• A relation is in DK/NF if every constraint on the relation is a logical consequence of the definition of keys and domains. • Constraint: An rule governing static values of an attribute such that we can determine if this constraint is True or False. Examples:
1. Functional Dependencies 2. Multivalued Dependencies 3. Inter-relation rules 4. Intra-relation rules
However: Does Not include time dependent constraints.
• Key: Unique identifier of a tuple.
• Domain: The physical (data type, size, NULL values) and semantic (logical) description of what values an attribute can hold. •T here is no known algorithm for converting a relation directly into DK/NF.

UBL Fakultas Teknologi Informasi PBD - 110
PERANCANGAN BASIS DATA (3 SKS)
De-Normalization
• Consider the following relation:
CUSTOMER (CustomerID, Name, Address, City, State, Zip) • This relation is not in DK/NF because it contains a functional dependency
not implied by the key.
Zip -> City, State • We can normalize this into DK/NF by splitting the CUSTOMER relation
into two:
CUSTOMER (CustomerID, Name, Address, Zip)
CODES (Zip, City, State) • We may pay a performance penalty - each customer address lookup
requires we look in two relations (tables). • In such cases, we may de-normalize the relations to achieve a
performance improvement.

UBL Fakultas Teknologi Informasi PBD - 111
PERANCANGAN BASIS DATA (3 SKS)
All-in-One Example
• Many of you asked for a "complete" example that would run through all of the normal forms from beginning to end using the same tables. This is tough to do, but here is an attempt: • Example relation:EMPLOYEE ( Name, Project, Task, Office, Phone )
Note: Keys are underlined. • Example Data:
Name Project Task Office Floor Phone
Bill 100X T1 400 4 1400
Bill 100X T2 400 4 1400
Bill 200Y T1 400 4 1400
Bill 200Y T2 400 4 1400
Sue 100X T33 442 4 1442
Sue 200Y T33 442 4 1442
Sue 300Z T33 442 4 1442
Ed 100X T2 588 5 1588

UBL Fakultas Teknologi Informasi PBD - 112
PERANCANGAN BASIS DATA (3 SKS)
• Name is the employee's name • Project is the project they are working on. Bill is working on two different
projects, Sue is working on 3. • Task is the current task being worked on. Bill is now working on Tasks T1
and T2. Note that Tasks are independent of the project. Examples of a
task might be faxing a memo or holding a meeting. • Office is the office number for the employee. Bill works in office number
400. • Floor is the floor on which the office is located. • Phone is the phone extension. Note this is associated with the phone in
the given office.
Question :
First Normal Form
Assume the key is Name, Project, Task.
Is EMPLOYEE in 1NF ?

UBL Fakultas Teknologi Informasi PBD - 113
PERANCANGAN BASIS DATA (3 SKS) Second Normal Form•List all of the functional dependencies for EMPLOYEE. •Are all of the non-key attributes dependant on all of the key ? •Split into two relations EMPLOYEE_PROJECT_TASK and
EMPLOYEE_OFFICE_PHONE. EMPLOYEE_PROJECT_TASK (Name, Project,
Task) Name Project Task
Bill 100X T1
Bill 100X T2
Bill 200Y T1
Bill 200Y T2
Sue 100X T33
Sue 200Y T33
Sue 300Z T33
Ed 100X T2
EMPLOYEE_OFFICE_PHONE (Name, Office, Floor, Phone)
Name Project Task Office Floor Phone
Bill 100X T1 400 4 1400
Bill 100X T2 400 4 1400
Bill 200Y T1 400 4 1400
Bill 200Y T2 400 4 1400
Sue 100X T33 442 4 1442
Sue 200Y T33 442 4 1442
Sue 300Z T33 442 4 1442
Ed 100X T2 588 5 1588 Name Office Floor Phone
Bill 400 4 1400
Sue 442 4 1442
Ed 588 5 1588

UBL Fakultas Teknologi Informasi PBD - 114
PERANCANGAN BASIS DATA (3 SKS) Third Normal Form
•Assume each office has exactly one phone number. •Are there any transitive dependencies ? •Where are the modification anomalies in EMPLOYEE_OFFICE_PHONE ? •Split EMPLOYEE_OFFICE_PHONE. •EMPLOYEE_PROJECT_TASK (Name, Project, Task)
Name Project Task Bill 100X T1 Bill 100X T2 Bill 200Y T1 Bill 200Y T2 Sue 100X T33 Sue 200Y T33 Sue 300Z T33 Ed 100X T2
EMPLOYEE_OFFICE (Name, Office, Floor)Name Office Floor Bill 400 4 Sue 442 4 Ed 588 5
EMPLOYEE_PHONE (Office, Phone)Office Phone 400 1400 442 1442 588 1588

UBL Fakultas Teknologi Informasi PBD - 115
PERANCANGAN BASIS DATA (3 SKS)
Boyce-Codd Normal Form•List all of the functional dependencies for
EMPLOYEE_PROJECT_TASK, EMPLOYEE_OFFICE and
EMPLOYEE_PHONE. Look at the determinants. •Are all determinants candidate keys ?

UBL Fakultas Teknologi Informasi PBD - 116
PERANCANGAN BASIS DATA (3 SKS)
Forth Normal Form•Are there any multivalued dependencies ? •What are the modification anomalies ? •Split EMPLOYEE_PROJECT_TASK. •EMPLOYEE_PROJECT (Name, Project )
Name Project Bill 100X Bill 200Y Sue 100X Sue 200Y Sue 300Z Ed 100X
Name Project Task Bill 100X T1 Bill 100X T2 Bill 200Y T1 Bill 200Y T2 Sue 100X T33 Sue 200Y T33 Sue 300Z T33 Ed 100X T2
Name Task Bill T1 Bill T2 Sue T33 Ed T2
EMPLOYEE_TASK (Name, Task )

UBL Fakultas Teknologi Informasi PBD - 117
PERANCANGAN BASIS DATA (3 SKS)
•EMPLOYEE_OFFICE (Name, Office, Floor)
Name Office Floor
Bill 400 4
Sue 442 4
Ed 588 5
•R4 (Office, Phone)
Office Phone
400 1400
442 1442
588 1588

UBL Fakultas Teknologi Informasi PBD - 118
PERANCANGAN BASIS DATA (3 SKS)
At each step of the process, we did the following:
1.Write out the relation
2.(optionally) Write out some example data.
3.Write out all of the functional dependencies
4.Starting with 1NF, go through each normal form and state why the
relation is in the given normal form.

UBL Fakultas Teknologi Informasi PBD - 119
PERANCANGAN BASIS DATA (3 SKS)
Another short example
Consider the following example of normalization for a CUSTOMER relation.
Relation Name
CUSTOMER (CustomerID, Name, Street, City, State, Zip, Phone)
Example Data
CustomerID Name Street City State Zip Phone
C101 Bill Smith 123 First St. New Brunswick NJ 07101 732-555-1212
C102 Mary Green 11 Birch St. Old Bridge NJ 07066 908-555-1212
Functional Dependencies CustomerID -> Name, Street, City, State, Zip, Phone Zip -> City, State

UBL Fakultas Teknologi Informasi PBD - 120
PERANCANGAN BASIS DATA (3 SKS)
•1NF Meets the definition of a relation. •2NF All non key attributes are dependent on all of the key. •3NF There are no transitive dependencies. •BCNF Relation CUSTOMER is not in BCNF because one of the
determinants Zip can not act as a key for the entire relation. Solution:
Split CUSTOMER into two relations:
CUSTOMER (CustomerID, Name, Street, Zip, Phone)
ZIPCODES (Zip, City, State)
•Check both CUSTOMER and ZIPCODE to ensure they are both in 1NF
up to BCNF. •4NF There are no multi-valued dependencies in either CUSTOMER or
ZIPCODES.
As a final step, consider de-normalization.
Normalization

UBL Fakultas Teknologi Informasi PBD - 121
PERANCANGAN BASIS DATA (3 SKS)
Structured Query Language -1
You'll Learn :Structured Query Language (SQL)
•SQL Data Types •Data Definition Language (DDL)
•Creating Domains •Creating a Schema •Specifying Constraints on Columns and Tables •Removing Schema Components with DROP •Changing Schema Components with ALTER

UBL Fakultas Teknologi Informasi PBD - 122
PERANCANGAN BASIS DATA (3 SKS)
Structured Query Language
Structured Query Language•SQL pertama diterapkan oleh System R IBM, pada
tahun1970 an. •SQL adalah standard query language untuk membuat
dan memanipulasipada Relational Databases. •Beberapa perbedaan kecil pada syntax, tetapi
mayoritas SQL adalah standar misal pada MS Access,
Oracle, Sybase, Informix, etc. •SQL adalah suatu alat Perintah Baris atau dapat juga
ditempelkan pada bahasa pemrograman seperti: Cobol,
"C", Pascal, etc.

UBL Fakultas Teknologi Informasi PBD - 123
PERANCANGAN BASIS DATA (3 SKS)
•SQL adalah Bahasa distandarisasi yang dimonitor oleh American
National Standards Institute (ANSI) sama halnya oleh National
Institute of Standards (NIST). •ANSI 1990 - SQL 1 standard •ANSI 1992 - SQL 2 Standard (sometimes called SQL-92) •SQL 3 is in the works - adds some Object oriented concepts
•SQL mempunyai 2 bagian utama:
1.Data Definition Language (DDL) yang digunakan untuk
menciptakan struktur data seperti tables, indexes, clusters
2.Data Manipulation Language (DML) yang digunakan untuk
menyimpan, mendapatkan dan update data dari tables.
Structured Query Language

UBL Fakultas Teknologi Informasi PBD - 124
PERANCANGAN BASIS DATA (3 SKS)
SQL Data Types
SQL Data Types•Masing-Masing Implementasi SQL menggunakan nama sedikit berbeda untuk jenis data.
Numeric Data Types•Integers: INTEGER, INT or SMALLINT •Real Numbers: FLOAT, REAL, DOUBLE, PRECISION •Formatted Numbers: DECIMAL(i,j), NUMERIC(i,j)
Character Strings•Two main types: Fixed length and variable length. •Fixed length of n characters: CHAR(n) or CHARACTER(n) •Variable length up to size n: VARCHAR(n)

UBL Fakultas Teknologi Informasi PBD - 125
PERANCANGAN BASIS DATA (3 SKS)
•Date and Time•DATEmempunyai 10 digit untuk format: YYYY-MM-DD •TIME mempunyai 8 digit untuk format: HH:MM:SS •TIME(i)Gambarkan TIME Data Type dengan menambahkan i memposisikan untuk pecahan suatu detik/second. For example:HH:MM:SS:dd
SQL Data Type

UBL Fakultas Teknologi Informasi PBD - 126
PERANCANGAN BASIS DATA (3 SKS)
Examples of Data Types Pada RDBMS
Data Type Storage Size Range of Values
Byte 1 byte 0 to 255
Boolean 2 bytes True or False.
Integer 2 bytes -32,768 to 32,767.
Long (long integer) 4 bytes -2,147,483,648 to 2,147,483,647.
Single (single-precision floating-point)
4 bytes -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double (double-precision floating-point)
8 bytes -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency (scaled integer) 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Date 8 bytes January 1, 100 to December 31, 9999.
Object 4 bytes Any Object reference.
String (variable-length) 10 bytes + string length
0 to approx. 2 billion (approx. 65,400 for MS Windows version 3.1).
String (fixed-length) Length of string 1 to approximately 65,400.
Variant (with numbers) 16 bytes Any numeric value up to the range of a Double.
Variant (with characters) 22 bytes + string length
Same range as for variable-length String.

UBL Fakultas Teknologi Informasi PBD - 127
PERANCANGAN BASIS DATA (3 SKS)
•Oracle mendukung jenis data yang berikut:
•Numeric: BINARY_INTEGER, DEC, DECIMAL, DOUBLE
PRECISION, FLOAT, INT, INTEGER, NATURAL, NATURALN,
NUMBER, NUMERIC, PLS_INTEGER, POSITIVE, POSITIVEN,
REAL, SMALLINT •Date: DATE
Note: Also stores time. •Character: CHAR, CHARACTER, STRING, VARCHAR, VARCHAR2 •Others: BOOLEAN, LONG, LONG RAW, RAW
•Note: Dalam hal ini tidak perlu dihawal, kondisi ini hanya untuk bahan
acuan.
SQL Data Types

UBL Fakultas Teknologi Informasi PBD - 128
PERANCANGAN BASIS DATA (3 SKS)
Data Definition Language•DDL is used to define the schema of the database. •Create a database schema •Create a domain •Create, Drop or Alter a table •Create or Drop an Index •Define Integrity constraints •Define access privileges to users •Define access privileges on objects •SQL2 specification supports the creation of multiple schemas per database each with a distinct owner and authorized users.

UBL Fakultas Teknologi Informasi PBD - 129
PERANCANGAN BASIS DATA (3 SKS)
Creating Domains•Yang diharapkan adalah untuk menciptakan suatu bentuk standar untuk jenis data, ukuran dan memberi suatu nama. •Yang Baik Untuk standardisasi untuk semua tabel. •CREATE DOMAIN d_last_name AS VARCHAR(30) •CREATE DOMAIN d_gender AS VARCHAR(1) •CREATE DOMAIN d_salary AS NUMBER(12,2) •CREATE DOMAIN d_soc_sec AS VARCHAR(11)

UBL Fakultas Teknologi Informasi PBD - 130
PERANCANGAN BASIS DATA (3 SKS)
Creating a SchemaCreating a Table:
CREATE TABLE employee ( Last_Name d_last_name NOT NULL, First_name VARCHAR(18) NOT NULL, Soc_Sec d_soc_sec NOT NULL, Date_of_Birth DATE, Salary d_salary
) ; CREATE TABLE dependant ( Last_Name d_last_name NOT NULL, First_name VARCHAR(18) NOT NULL, Soc_Sec d_soc_sec NOT NULL, Date_of_Birth DATE, Employee_Soc_Sec d_soc_sec NOT NULL
);
Creating Domains

UBL Fakultas Teknologi Informasi PBD - 131
PERANCANGAN BASIS DATA (3 SKS)
CREATE TABLE order_header ( order_number NUMBER(10,0) NOT NULL, order_date DATE, sales_person VARCHAR(25), bill_to VARCHAR(35), bill_to_address VARCHAR(45), bill_to_city VARCHAR(20), bill_to_state VARCHAR(2), bill_to_zip VARCHAR(10), PRIMARY KEY (order_number));CREATE TABLE order_items ( order_number NUMBER(10,0) NOT NULL, line_item NUMBER(4,0) NOT NULL, part_number VARCHAR(12) NOT NULL, quantity NUMBER(4,0), PRIMARY KEY (order_number, line_item), FORIEGN KEY (order_number) REFERENCES order_header (order_number), FOREIGN KEY (part_number) REFERENCES parts (part_number));
Specifying Primary and Foreign keys:

UBL Fakultas Teknologi Informasi PBD - 132
PERANCANGAN BASIS DATA (3 SKS)
CREATE INDEX order_index ON order_header (order_number) ASC ;
CREATE INDEX items_index ON order_items (order_number, line_item) ASC ;
Example from MS Access:CREATE TABLE employee ( FirstName TEXT, LastName TEXT, ssn INTEGER CONSTRAINT ssnConstraint PRIMARY KEY);
CREATE INDEX employee_index ON employee (ssn) ;
Index File

UBL Fakultas Teknologi Informasi PBD - 133
PERANCANGAN BASIS DATA (3 SKS)
•Batasan pada atribut:NOT NULL - Attribute tidak boleh punya nilai null DEFAULT - Nilai yang akan disimpan telah ditentukan dari awal.PRIMARY KEY – Tandai pada Primary KeyFOREIGN KEY – Tandai pada foreign key. Ini akan menguatkan dalam integritas data.UNIQUE – Tandai attribute mempunyai nilai-nilai unik.Batasan Integritas Yang mempunyai petunjuk: Menetapkan perilaku untuk anak tuples ketika suatu orangtua tuple dimodifikasi.
Menetapkan Batasan pada Kolom Dan Tabel

UBL Fakultas Teknologi Informasi PBD - 134
PERANCANGAN BASIS DATA (3 SKS)
Examples of ON DELETE and ON UPDATE
CREATE TABLE order_items (
order_number NUMBER(10,0) NOT NULL,
line_item NUMBER(4,0) NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER(4,0),
PRIMARY KEY (order_number, line_item),
FORIEGN KEY (order_number)
REFERENCES order_header (order_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE,
FOREIGN KEY (part_number)
REFERENCES parts (part_number)
);

UBL Fakultas Teknologi Informasi PBD - 135
PERANCANGAN BASIS DATA (3 SKS)
CREATE TABLE order_header ( order_number NUMBER(10,0) NOT NULL, order_date DATE, sales_person VARCHAR(25), bill_to VARCHAR(35), bill_to_address VARCHAR(45), bill_to_city VARCHAR(20), bill_to_state VARCHAR(2), bill_to_zip VARCHAR(10), CONSTRAINT order_header_pk PRIMARY KEY (order_number));
CREATE TABLE order_items ( order_number NUMBER(10,0) NOT NULL, line_item NUMBER(4,0) NOT NULL, part_number VARCHAR(12) NOT NULL, quantity NUMBER(4,0),

UBL Fakultas Teknologi Informasi PBD - 136
PERANCANGAN BASIS DATA (3 SKS)
CONSTRAINT order_items_pk PRIMARY KEY (order_number, line_item),
CONSTRAINT order_items_fk1 FORIEGN KEY (order_number) REFERENCES order_header (order_number) ON DELETE SET DEFAULT ON UPDATE CASCADE,
CONSTRAINT order_items_fk2 FOREIGN KEY (part_number) REFERENCES parts (part_number) ON DELETE SET DEFAULT ON UPDATE CASCADE);

UBL Fakultas Teknologi Informasi PBD - 137
PERANCANGAN BASIS DATA (3 SKS)
DROP SCHEMA schema_name CASCADE•Drop the entire schema including all tables. CASCADE option deletes all data, all tables, indexes, domains, etc. •DROP SCHEMA schema_name RESTRICT•Removes the schema only if it is empty.
•DROP TABLE table_name•Remove the table and all of its data. •DROP TABLE table_name CASCADE•Remove the table and all related tables as specified by FOREIGN KEY constraints. •DROP TABLE table_name RESTRICT•Remove the table only if it is not referenced (via a FORIEGN KEY constraint) by other tables.
•DROP INDEX index_name•Removes an index.
•DROP CONSTRAINT table_name.constraint_name•Removes a constraint from a table.
Removing Schema Components with DROP

UBL Fakultas Teknologi Informasi PBD - 138
PERANCANGAN BASIS DATA (3 SKS)
Merubah Attributes:ALTER TABLE student ALTER last_name VARCHAR(35);ALTER TABLE student ALTER gpa DROP DEFAULTALTER TABLE student ALTER gpa SET DEFAULT 0.00;
Menambah Attributes:ALTER TABLE student ADD admission DATE;
membuang Attributes (not widely implemented):ALTER TABLE student DROP home_phone;
Changing Schema Components with ALTER

UBL Fakultas Teknologi Informasi PBD - 139
PERANCANGAN BASIS DATA (3 SKS)
You'll Learn :
Structured Query Language (SQL)
Data Manipulation Language (DML)
Inserting Data into Tables with INSERT
Retrieving Data from Tables with SELECT
Relational Operators and SQL
SQL Built-in Functions
Selecting from 2 or More Tables
Recursive Queries and Aliases
WHERE Clause expressions: IN, EXISTS
Deleting Tuples with DELETE
Change Values using UPDATE
Defining Views
Structured Query Language -2

UBL Fakultas Teknologi Informasi PBD - 140
PERANCANGAN BASIS DATA (3 SKS)
Data Manipulation LanguageDML adalah digunaan untuk memanipulasi (select, insert, update, delete) data.
Inserting Data into TablesGeneral syntax:INSERT INTO tablename (column1, column2, ... columnX)
VALUES (val1, val2, ... valX);Examples: INSERT INTO employee (first_name, last_name, street, city, state) VALUES ("Buddy", "Rich", "123 Sticks Ln.", "Fillville", "TN");
INSERT INTO stocks (symbol, close_date, close_price) VALUES ("IBM", "03-JUN-94", 104.25);
INSERT INTO student_grades (student_id, test_name, score, grade) VALUES (101, "Quiz 1", 88, "B+");

UBL Fakultas Teknologi Informasi PBD - 141
PERANCANGAN BASIS DATA (3 SKS)
Tanda kutip ditempatkan di antara data yang tergantung pada Jenis Data dan pada spesifik RDBMS digunakan:
•RDBMS •Text Data Type •Dates
•MS Access •TEXT: Either " or ' •DATETIME: Either " or '
•Oracle •VARCHAR: ' •DATE: '
•IBM DB2 •VARCHAR: ' •DATE: '
•Sybase •CHAR and VARCHAR: " •DATE: "

UBL Fakultas Teknologi Informasi PBD - 142
PERANCANGAN BASIS DATA (3 SKS)
Mendapat Selectkan data dengan Select
SELECT column1, column2, ... columnNFROM tableA, tableB, ... tableZWHERE condition1, condition2, ...conditionMGROUP BY column1, ...HAVING conditionORDER BY column1, column2, ... columnN

UBL Fakultas Teknologi Informasi PBD - 143
PERANCANGAN BASIS DATA (3 SKS)
Some example queries:
SELECT employee_id, last_name, first_nameFROM employeesWHERE last_name = "Smith"ORDER BY first_name DESC
SELECT employee_id, last_name, first_nameFROM employeesWHERE salary > 40000ORDER BY last_name, first_name DESC
SELECT *FROM employeesORDER BY 2;

UBL Fakultas Teknologi Informasi PBD - 144
PERANCANGAN BASIS DATA (3 SKS)
Relational operators each have implementations in SQL.
SELECT employee_id, last_name, first_name FROM employee WHERE salary > 40000
SELECT AVG(salary) FROM employee WHERE state = 'NJ'
SELECT * FROM employee WHERE last_name = 'Smith' AND state = 'NY'

UBL Fakultas Teknologi Informasi PBD - 145
PERANCANGAN BASIS DATA (3 SKS)
Example Table students:
Name Major GradeBill CIS 95Mary CIS 98Sue Marketing 88Tom Finance 92Alex CIS 79Sam Marketing 89Jane Finance 83...
Average grade in the class:
SELECT AVG(grade) FROM students;
Results:AVG(GRADE)----------89.1428571
SQL Built-in Functions

UBL Fakultas Teknologi Informasi PBD - 146
PERANCANGAN BASIS DATA (3 SKS)
Mencari nama siswa dengan nilai yang paling tinggi, contoh suatu subquery
SELECT name, grade FROM studentsWHERE grade = ( SELECT MAX(grade) FROM students );
Results:
NAME GRADE-------------- -----Mary 98

UBL Fakultas Teknologi Informasi PBD - 147
PERANCANGAN BASIS DATA (3 SKS)
Mendapatkan siswa yang nilainya paling tinggi:
SELECT name, major, gradeFROM students s1WHERE grade = ( SELECT max(grade) FROM students s2 WHERE s1.major = s2.major )ORDER BY grade DESC;
Results:
NAME MAJOR GRADE------------- -------------------- -----Mary CIS 98Tom Finance 92Sam Marketing 89

UBL Fakultas Teknologi Informasi PBD - 148
PERANCANGAN BASIS DATA (3 SKS)
Selecting from 2 or More TablesDi dalam FROM , list semua table yang dipisahkan koma. Disebut Join. WHERE menjadi bagian dari Join Condition
Example table EMPLOYEE:
Name Department SalaryJoe Finance 50000Alice Finance 52000Jill MIS 48000Jack MIS 32000Fred Accounting 33000
Example table DEPARTMENTS:Department LocationFinance NJMIS CAAccounting CAMarketing NY

UBL Fakultas Teknologi Informasi PBD - 149
PERANCANGAN BASIS DATA (3 SKS)
List all of the employees working in California:
SELECT employee.nameFROM employee, departmentWHERE employee.department = department.departmentAND department.location = 'CA';
Results:NAME--------------------------------JillJackFred

UBL Fakultas Teknologi Informasi PBD - 150
PERANCANGAN BASIS DATA (3 SKS)
Mecari dartar nama karyawan dan dibagian mana nama-nama tersebut bekerja:
SELECT employee.name, department.locationFROM employee, departmentWHERE employee.department = department.departmentORDER BY department.location, employee.name;
Results:NAME LOCATION--------------- -------------Fred CAJack CAJill CAAlice NJJoe NJ
•Serupa dengan LEFT JOIN

UBL Fakultas Teknologi Informasi PBD - 151
PERANCANGAN BASIS DATA (3 SKS)
Mencari department dan semua karyawan yang bekerja disana..
SELECT department.department, department.location, employee.nameFROM employee RIGHT JOIN departmentON employee.department = department.departmentORDER BY department.location, employee.name;
Results:DEPARTMENT LOCATION NAME------------- ---------------- ----------------Accounting CA FredMIS CA JackMIS CA JillFinance NJ Alice Finance NJ JoeMarketing NY NULL

UBL Fakultas Teknologi Informasi PBD - 152
PERANCANGAN BASIS DATA (3 SKS)
What is the highest paid salary in California ?
SELECT MAX(employee.salary) FROM employee, departmentWHERE employee.department = department.departmentAND department.location = 'CA';
Results: MAX(SALARY) ------------ 48000

UBL Fakultas Teknologi Informasi PBD - 153
PERANCANGAN BASIS DATA (3 SKS)
Cartesian Product of the two tables:
SELECT *FROM employee, department;
Results:Name employee.Departmen Salary Department.Dep Location Joe Finance 50000 Finance NJ Joe Finance 50000 MIS CA Joe Finance 50000 Accounting CA Joe Finance 50000 Marketing NY Alice Finance 52000 Finance NJ Alice Finance 52000 MIS CA Alice Finance 52000 Accounting CA Alice Finance 52000 Marketing NY Jill MIS 48000 Finance NJ Jill MIS 48000 MIS CA Jill MIS 48000 Accounting CA Jill MIS 48000 Marketing NY Jack MIS 32000 Finance NJ Jack MIS 32000 MIS CA Jack MIS 32000 Accounting CA Jack MIS 32000 Marketing NY Fred Accounting 33000 Finance NJ Fred Accounting 33000 MIS CA Fred Accounting 33000 Accounting CA Fred Accounting 33000 Marketing NY

UBL Fakultas Teknologi Informasi PBD - 154
PERANCANGAN BASIS DATA (3 SKS)
In which states do our employees work ?
SELECT DISTINCT location
FROM department;
From our Bank Accounts example.List the Customer name and their total account holdings:
SELECT customers.LastName, Sum(Balance)
FROM customers, accountsWHERE customers.CustomerID = accounts.customeridGROUP BY customers.LastName
Results:
LASTNAME SUM(BALANCE)--------- ------------Axe $15,000.00 Builder $1,300.00 Jones $1,000.00 Smith $6,000.00

UBL Fakultas Teknologi Informasi PBD - 155
PERANCANGAN BASIS DATA (3 SKS)
Kita juga dapat menggunakan Kolom Alias untuk merubah Judul pada kolom.
SELECT customers.LastName, Sum(Balance) AS TotalBalanceFROM customers, accountsWHERE customers.CustomerID = accounts.customeridGROUP BY customers.LastName
Results:
LASTNAME TotalBalance--------- ------------Axe $15,000.00 Builder $1,300.00 Jones $1,000.00 Smith $6,000.00

UBL Fakultas Teknologi Informasi PBD - 156
PERANCANGAN BASIS DATA (3 SKS)
Kombinasi Fungsi dan Kolom Alias:
SELECT name, department, salary AS CurrentSalary, (salary * 1.03) AS ProposedRaise (Usulan Gaji)FROM employee;
Results:
name department CurrentSalary ProposedRaise-------- ------------ ------------- -------------Alice Finance 52000 53560 Fred Accounting 33000 33990 Jack MIS 32000 32960 Jill MIS 48000 49440 Joe Finance 50000 51500

UBL Fakultas Teknologi Informasi PBD - 157
PERANCANGAN BASIS DATA (3 SKS)
Recursive Queries and Aliases
• Recall some of the E-R diagrams and relations we dealt with had a recursive relationship. • For example: A student can tutor one or more other students. A student has only one tutor.STUDENTS (StudentID, Name, Student_TutorID)
•StudentID •Name •Student_TutorID
•S101 •Bill •NULL
•S102 •Alex •S101
•S103 •Mary •S101
•S104 •Liz •S103
•S105 •Ed •S103
•S106 •Sue •S101
•S107 •Petra •S106

UBL Fakultas Teknologi Informasi PBD - 158
PERANCANGAN BASIS DATA (3 SKS)
Menyediakan Daftar siswa sama tutornya:
SELECT s1.name AS Student, tutors.name AS TutorFROM students s1, students tutorsWHERE s1.student_tutorid = tutors.studentid;
Results:
Student Tutor ---------- ----------Alex Bill Mary Bill Sue Bill Liz Mary Ed Mary Petra Sue

UBL Fakultas Teknologi Informasi PBD - 159
PERANCANGAN BASIS DATA (3 SKS)
Dari table ada sesuatu yang hilang: Kita tidak melihat Siapa yang menjadi tutornya Bill Smith. Gunakan LEFT JOIN:
SELECT s1.name AS Student, tutors.name AS TutorFROM students s1 LEFT JOIN students tutorsON s1.student_tutorid = tutors.studentid;
Results:
Student Tutor ---------- ----------Bill Alex BillMary BillSue BillLiz MaryEd MaryPetra Sue

UBL Fakultas Teknologi Informasi PBD - 160
PERANCANGAN BASIS DATA (3 SKS)
Mengetahui jumlah siswa yang ditutor? Gunakan RIGHT JOIN
How many students does each tutor work with ?
SELECT s1.name AS TutorName, COUNT(tutors.student_tutorid) AS NumberTutoredFROM students s1, students tutorsWHERE s1.studentid = tutors.student_tutoridGROUP BY s1.name;
Results:
TutorName NumberTutored---------- -------------Bill 3Mary 2Sue 1

UBL Fakultas Teknologi Informasi PBD - 161
PERANCANGAN BASIS DATA (3 SKS)
WHERE Clause ExpressionsThere are a number of expressions one can use in a WHERE clause. Typical Logic expressions:COLUMN = valueAlso:
= != <= = Also consider BETWEEN
SELECT name, grade, "You Got an A"FROM studentsWHERE grade between 91 and 100
Subqueries using = (equals): SELECT name, grade FROM studentsWHERE grade = ( SELECT MAX(grade) FROM students );
This assumes the subquery returns only one tuple as a result. Typically used for aggregate functions.

UBL Fakultas Teknologi Informasi PBD - 162
PERANCANGAN BASIS DATA (3 SKS)
Subqueries using IN:
SELECT nameFROM employee WHERE department IN ('Finance', 'MIS');
SELECT nameFROM employee WHERE department IN (SELECT department FROM departments WHERE location = 'CA');
In the above case, the subquery returns a set of tuples. The IN clause returns true when a tuple matches a member of the set.

UBL Fakultas Teknologi Informasi PBD - 163
PERANCANGAN BASIS DATA (3 SKS)
Subqueries using EXISTS: SELECT name, salaryFROM employeeWHERE EXISTS (SELECT name FROM EMPLOYEE e2 WHERE e2.salary > employee.salary) AND EXISTS (SELECT name FROM EMPLOYEE e3 WHERE e3.salary < employee.salary)
Results:name salary----------- ---------- Joe 50000 Jill 48000 Fred 33000
The above query shows all employees names and salaries where there is at least one person who makes more money (the first exists) and at least one person who makes less money (second exists).

UBL Fakultas Teknologi Informasi PBD - 164
PERANCANGAN BASIS DATA (3 SKS)
NOT EXISTS:
SELECT name, salaryFROM employeeWHERE NOT EXISTS (SELECT name FROM EMPLOYEE e2 WHERE e2.salary > employee.salary)
Results:name salary --------- ----------Alice 52000
Above query shows all employees for whom there does not exist an employee who is paid less.

UBL Fakultas Teknologi Informasi PBD - 165
PERANCANGAN BASIS DATA (3 SKS)
Deleting Tuples with DELETE DELETE digunakan untuk menghilangkan tuples dari table. With no WHERE clause, DELETE akan menghilangkan semua tuples dari table. Remove all employees: DELETE employee;
Remove only employees making more than $50,000 DELETE employee WHERE salary > 50000; Remove all employees working in California: DELETE employee WHERE department IN (SELECT department FROM department WHERE location = 'CA');

UBL Fakultas Teknologi Informasi PBD - 166
PERANCANGAN BASIS DATA (3 SKS)
Merubah Values dengan UPDATEPerintah UPDATE digunakan untuk merubah nilai atribut pada tabel.. UPDATE dengan SET clause untuk menuliskan ulang nilai.
Change the last name of an Employee:
UPDATE employee
SET last_name = 'Smith'WHERE employee_id = 'E1001';
Give an Employee a raise:
UPDATE employeeSET salary = salary * 1.05WHERE employee_id = 'E1001';

UBL Fakultas Teknologi Informasi PBD - 167
PERANCANGAN BASIS DATA (3 SKS)
Defining ViewsDigunakan untuk menggambarkan pandangan terhadap table. Example, Jika kita biasanya mengakses 2 atau 3 kolom dalam suatu table , Kita dapat mendefinisikan View pada table dan menggunakan view name untuk queries yang spesifik.
CREATE VIEW emp_address AS SELECT first_name, last_name, street, city, state, zip FROM employee;
CREATE VIEW emp_salary AS SELECT first_name, last_name, salary FROM employee;
CREATE VIEW avg_sal_dept AS SELECT department, AVG(salary) FROM employee GROUP BY department;

UBL Fakultas Teknologi Informasi PBD - 168
PERANCANGAN BASIS DATA (3 SKS)
One can then query these views as if they were tabes
SELECT * FROM emp_addressORDER BY last_name;
SELECT *FROM avg_sal_deptWHERE department = 'Finance';

UBL Fakultas Teknologi Informasi PBD - 169
PERANCANGAN BASIS DATA (3 SKS)
Structured Query Language -3
Database Security and Authorization
Subject-Based Security
Authorization Subsystem
Object-Based Security
The SQL GRANT and REVOKE Statements
System Administration
Database Administration
Data Administration

UBL Fakultas Teknologi Informasi PBD - 170
PERANCANGAN BASIS DATA (3 SKS)
Database Security and Authorization 3 Isu besar dalam Data Base Security:
1. Legal and Ethical considerations– Siapa yang mempunyai hak dalam membaca informasi ?
2. Policy issues – Siapa yang menyelenggaran keamanan (government, corporations) ?
3. System-Level issues –dimana keamanan diletakan pada sistem dan bagai mana ?

UBL Fakultas Teknologi Informasi PBD - 171
PERANCANGAN BASIS DATA (3 SKS)
Jika sebagai Database Admin, Kita harus menyediakan cara mencegah penggunaan data yang tidak syah di dalam suatu database. 3 Kondisi yang harus dipertimbangkan:
1. Access Control: Siapa yang harus diijinkan akses ke database yang mana . Ini adalah suatu cara yang digunakan untuk pertanggung-jawaban tingkatan pengguna sistem dengan kata sandi.
2. Authorization: Untuk Kepentingan:Reading Data – Seperti untuk mengetahui gaji karyawan (gunakan SELECT statement for example).Writing Data – untuk merubah nilai pada database (using UPDATE or DELETE).
3. Statistical Information: Keharusan Siapa yang harus mengakses ke informasi dari databases (Census example).

UBL Fakultas Teknologi Informasi PBD - 172
PERANCANGAN BASIS DATA (3 SKS)
• Secara khusus keamanan untuk tujuan otorisasi database
diterapkan suatu subsistem otorisasi yang memonitor tiap-tiap
transaksi di dalam database. Ini bagian dari DBMS,
• Aturan Otorisasi mempertimbangkan beberapa hal: 1. Subjects: Siapa saja yang melakukan beberapa aktifitas di Database.
Mungkin melibatkan orang-orang khusus atau group pada user.
2. Objects: Unit Database yang memerlukan otorisasi dalam rangka manipulasi
data. Database unit mungkin termasuk entri table, specific columns in a
table, specific rows in a table, etc.
3. Actions: Tindakan apapung yang mungkin dilakukan pada object.
example: Read, Modify, Insert, Write, Delete, Grant (the ability to grant
authorizations to others)
1. Constraint: Suatu aturan yang lebih spesifik mengenai suatu pengarahan
terhadap obyek dan tindakan.
Authorization Subsystem

UBL Fakultas Teknologi Informasi PBD - 173
PERANCANGAN BASIS DATA (3 SKS)
•Subject •Object •Action •Constraint
•Rich •Employee •Read •None
•Rich •Employee •Insert •None
•Rich •Employee •Modify •None
•Rich •Employee •Grant •None
•Bill •Employee •Read •Salary < 50,000
•Sally •PurchaseOrder •Insert •Total < 1,000
•Sally •PurchaseOrder •Modify •Total < 1,000
•PayrollClerks •Employee •Read •None
•These elements are commonly combined into an authorization table
•What happens as the number of subjects and objects grows ? •Presently, no commercial DBMS support this level of
authorization flexibility. •Typically, a DBMS supports some basic authorization models.
Application developers must provide more complex constraint
enforcement.

UBL Fakultas Teknologi Informasi PBD - 174
PERANCANGAN BASIS DATA (3 SKS)
•Subjects are individually defined in the DBMS and each object and
action is specified. •For example, user SMITH (a Subject) has the following
authorizations:
•Objects
•Actions •EMPLOYEES •ORDERS •PRODUCTS •...
•Read •Y •Y •Y •...
•Insert •N •Y •N •...
•Modify •N •Y •Y •...
•Delete •N •N •N •...
•Grant •N •N •N •...
Subject-Based Security

UBL Fakultas Teknologi Informasi PBD - 175
PERANCANGAN BASIS DATA (3 SKS)
•Objects are individually defined in the DBMS and each subject and action is specified. •For example, the EMPLOYEES table (an Object) has the following authorizations:
•Subjects
•Actions •SMITH •JONES •GREEN •DBA •...
•Read •Y •Y •N •Y •...
•Insert •N •N •N •Y •...
•Modify •N •N •N •Y •...
•Delete •N •N •N •Y •...
•Grant •N •N •N •Y •...
Object-Based Security

UBL Fakultas Teknologi Informasi PBD - 176
PERANCANGAN BASIS DATA (3 SKS)
The SQL GRANT and REVOKE Statements
SQL provides two main statements for setting up authorization.
GRANT is used to grant an action on an object to a subject.
GRANT action1, action2 ... ON object1, object2, ... TO subject1, subject2 ...
Another option of the GRANT statement is WITH GRANT OPTION. This allows the grantee to propagate the authorization to another subject.

UBL Fakultas Teknologi Informasi PBD - 177
PERANCANGAN BASIS DATA (3 SKS)
For example, assume we have a database withTables: employees, departments, orders, productsUsers: smith, jones, green, dba
GRANT INSERT, DELETE, UPDATE, SELECTON employees, departmentsTO smith ;
GRANT INSERT, SELECT ON orders TO smith ;
GRANT SELECT ON products TO smith ;
GRANT SELECT ON employees, departmentsTO jones ;
GRANT INSERT, DELETE, UPDATE, SELECTON employees, departments, orders, productsTO dbaWITH GRANT OPTION ;

UBL Fakultas Teknologi Informasi PBD - 178
PERANCANGAN BASIS DATA (3 SKS)
Grants can also be done on specific columns in a table:
GRANT SELECT ON products TO jones ;GRANT UPDATE ON products (price) TO jones ;
If no GRANT statement is issued, it is assumed that no authorization is given (e.g., user GREEN above).
REVOKE is used to revoke authorizations from subjects.
REVOKE action1, action2, ...ON object1, object2, ...FROM subject1, subject2, ...

UBL Fakultas Teknologi Informasi PBD - 179
PERANCANGAN BASIS DATA (3 SKS)
If Ms. Smith leaves the company, then we should:
REVOKE INSERT, DELETE, UPDATE, SELECTON employees, departmentsFROM smith ;
REVOKE INSERT, SELECT ON orders FROM smith ;
REVOKE SELECT ON products FROM smith ;
Many RDBMS have an ALL PRIVILEGES option that will revoke all of the privileges on an object from a subject:
REVOKE ALL PRIVILEGESON employees, departments, orders, productsFROM smith ;

UBL Fakultas Teknologi Informasi PBD - 180
PERANCANGAN BASIS DATA (3 SKS)
System AdministrationDatabase AdministrationTransaction Processing Concurrency Control and Locking
Characteristics of Locks Two Phase Locking Deadlock
Database Recovery and Backup Reprocessing Rollback / Rollforward Database Backup

UBL Fakultas Teknologi Informasi PBD - 181
PERANCANGAN BASIS DATA (3 SKS)
•Any reasonably sized organization that relies on a database for its
business processes will probably have a Database Administrator or DBA. •The DBA is responsible for:
1.Installing and configuring the DBMS
2.Assisting in the implementation of information systems
3.Monitoring the performance of the database and tuning the DBMS for
optimal performance
4.Maintaining documentation including recording all changes to the
database and DBMS.
5.Ensuring data integrity is maintained and appropriate backups are
made. •Thus a DBA is mainly concerned with the day to day operational aspects
of database systems.
Database Administration

UBL Fakultas Teknologi Informasi PBD - 182
PERANCANGAN BASIS DATA (3 SKS)
Data Administration
Data Administration•Many organizations, in addition to DBAs, will also have a Data
Administrator. •DAs are concerned with the data needs and data flows throughout the
entire organization. •Thus DAs are responsible for:
1.Specifying data standards across databases
2.Establishing policies: data usage, security and authorization, data
flows into and out of the organization
3.Assisting the application development process by identifying data
resources in the organization
4.Arbitrating the sharing of data across departments
5.Increasing the return on an organization's data investment

UBL Fakultas Teknologi Informasi PBD - 183
PERANCANGAN BASIS DATA (3 SKS)
MultiUser Databases•Multiuser database - more than one user processes the database at the
same time •Several issues arise:
1.How can we prevent users from interfering with each other's work ?
2.How can we safely process transactions on the database without
corrupting or losing data ?
3.If there is a problem (e.g., power failure or system crash), how can we
recover without loosing all of our data ?
Transaction Processing•A transaction is a set of read and write operations that must either commit or
abort. •Consider the following transaction that reserves a seat on an airplane flight and
changes the customer:
1. Read customer information
2. Write reservation information
3. Write charges •We need the ability to control how transactions are run in a multiuser database.

UBL Fakultas Teknologi Informasi PBD - 184
PERANCANGAN BASIS DATA (3 SKS)
•Suppose that after the second step, the database crashes. Or for some
reason, changes can not be written...
•Transactions can either reach a commit point, where all actions are
permanently saved in the database or they can abort in which case none
of the actions are saved.
•Another way to say this is transactions are Atomic. All operations in a
transaction must be executed as a single unit - Logical Unit of Work. • Consider two users, each executing similar transactions:
Example #1:
User A User B
Read Salary for emp 101 Read Salary for emp 101
Multiply salary by 1.03 Multiply salary by 1.04
Write Salary for emp 101 Write Salary for emp 101

UBL Fakultas Teknologi Informasi PBD - 185
PERANCANGAN BASIS DATA (3 SKS)
Example #2:
User A User B
Read inventory for Prod 200 Read inventory for Prod 200
Decrement inventory by 5 Decrement inventory by 7
Write inventory for Prod 200 Write inventory for Prod 200
• First, what should the values for salary (in the first example) really be ?
• The DBMS must find a way to execute these two transactions concurrently and ensure the result is what the users (and designers) intended.
• These two are examples of the Lost Update or Concurrent Update problem. Some changes to the database can be overwritten.

UBL Fakultas Teknologi Informasi PBD - 186
PERANCANGAN BASIS DATA (3 SKS)
Consider how the operations for user's A and B might be interleaved as in example #2. Assume there are 10 units in inventory for Prod 200:
Read inventory for Prod 200 for user ARead inventory for Prod 200 for user BDecrement inventory by 5 for user ADecrement inventory by 7 for user BWrite inventory for Prod 200 for user AWrite inventory for Prod 200 for user B
Or something similar like: Read inventory for Prod 200 for user ADecrement inventory by 5 for user AWrite inventory for Prod 200 for user ARead inventory for Prod 200 for user BDecrement inventory by 7 for user BWrite inventory for Prod 200 for user B

UBL Fakultas Teknologi Informasi PBD - 187
PERANCANGAN BASIS DATA (3 SKS)
• In the first case, the incorrect amount (3) is written to the database. This is called the Lost Update problem because we lost the update from User A - it was overwritten by user B. The second example works because we let user A write the new value of Prod 200 before user B can read it. Thus User B's decrement operation will fail.
Here is another example. User's A and B share a bank account. Assume an initial balance of $200.
User A reads the balanceUser A deducts $100 from the balanceUser B reads the balanceUser A writes the new balance of $100User B deducts $100 from the balanceUser B writes the new balance of $100
• The reason we get the wrong final result (remaining balance of $100) is because transaction B was allowed to read stale data. This is called the inconsistent read problem.
• Suppose, instead of interleaving (mixing) the operations of the two transactions, we execute one after the other (note it makes no difference which order: A then B, or B then A)
User A reads the balanceUser A deducts $100 from the balanceUser A writes the new balance of $100User B reads the balance (which is now $100)User B deducts $100 from the balanceUser B writes the new balance of $0

UBL Fakultas Teknologi Informasi PBD - 188
PERANCANGAN BASIS DATA (3 SKS)
• If we insist only one transaction can execute at a time, in serial order, then performance will be quite poor.
• Concurrency Control is a method for controlling or scheduling the operations in such a way that concurrent transactions can be executed.
• If we do concurrency control properly, then we can maximize transaction throughput while avoiding any chance.
• Transaction throughput: The number of transactions we can perform in a given time period. Often reported as Transactions per second or TPS.
• A group of two or more concurrent transactions are serializable if we can order their operations so that the final result is the same as if we had run them in serial order (one after another).
• Consider transaction A, B, C and D. Each has 3 operations. If executing:A1, B1, A2, C1, C2, B2, A3, B3, C3has the same result as executing:A1, A2, A3, B1, B2, B3, C1, C2, C3Then the above schedule of transactions and operations is serialized.

UBL Fakultas Teknologi Informasi PBD - 189
PERANCANGAN BASIS DATA (3 SKS)
Concurrency Control and Locking We need a way to guarantee that our concurrent transactions can be serialized.
Locking is one such means. Locking is done to data items in order to reserve them for future operations. A lock is a logical flag set by a transaction to alert other transactions the data item
is in use.
Characteristics of Locks Locks may be applied to data items in two ways:
Implicit Locks are applied by the DBMSExplicit Locks are applied by application programs.
Locks may be applied to: 1. a single data item (value) 2. an entire row of a table 3. a page (memory segment) (many rows worth) 4. an entire table 5. an entire database
This is referred to as the Lock granularity •Locks may be of type types depending on the requirements of the transaction:
1.An Exclusive Lock prevents any other transaction from reading or modifying the locked item.
2.A Shared Lock allows another transaction to read an item but prevents another transaction from writing the item.

UBL Fakultas Teknologi Informasi PBD - 190
PERANCANGAN BASIS DATA (3 SKS)
Two Phase Locking
The most commonly implemented locking mechanism is called Two Phased Locking or 2PL. 2PL is a concurrency control mechanism that ensure serializability.
2PL has two phases: Growing and shrinking. A transaction acquires locks on data items it will need to complete the transaction. This is called the growing phase.
Once one lock is released, all no other lock may be acquired. This is called the shrinking phase.
Consider our prior example, this time using locks: User A places an exclusive lock on the balanceUser A reads the balanceUser A deducts $100 from the balance
User B attempts to place a lock on the balance but fails because A already has an exclusive lock User B is placed into a wait stateUser A writes the new balance of $100User A releases the exclusive lock on the balance
User B places an exclusive lock on the balanceUser B reads the balanceUser B deducts $100 from the balanceUser B writes the new balance of $100

UBL Fakultas Teknologi Informasi PBD - 191
PERANCANGAN BASIS DATA (3 SKS)
Here is a more involved example: User A places a shared lock on item raise_rateUser A reads raise_rateUser A places an exclusive lock on item Amy_salaryUser A reads Amy_salary
User B places a shared lock on item raise_rateUser B reads raise_rate
User A calculates a new salary as Amy_salary * (1+raise_rate)
User B places an exclusive lock on item Bill_salaryUser B reads Bill_salaryUser B calculates a new salary as Bill_salary * (1+raise_rate)User B writes Bill_salary
User A writes Amy_salaryUser A releases exclusive lock on Amy_salary
User B releases exclusive lock on Bill_SalaryUser B releases shared lock on raise_rate
User A releases shared lock on raise_rate

UBL Fakultas Teknologi Informasi PBD - 192
PERANCANGAN BASIS DATA (3 SKS)
Here is another example: User A places a shared lock on raise_rate
User B attempts to place an exclusive lock on raise_rate Placed into a wait state
User A places an exclusive lock on item Amy_salaryUser A reads raise_rateUser A releases shared lock on raise_rate
User B places an exclusive lock on raise_rate
User A reads Amy_salary
User B reads raise_rate
User A calculates a new salary as Amy_salary * (1+raise_rate)
User B writes a new raise_rateUser B releases exclusive lock on raise_rate
User A writes Amy_salaryUser A releases exclusive lock on Amy_salary

UBL Fakultas Teknologi Informasi PBD - 193
PERANCANGAN BASIS DATA (3 SKS)
Deadlock
Locking can cause problems, however. Consider:
User A places an exclusive lock on item 1001User B places an exclusive lock on item 2002User A attempts to place an exclusive lock on item 2002 User A placed into a wait stateUser B attempts to place an exclusive lock on item 1001 User B placed into a wait state...
This is called a deadlock. One transaction has locked some of the resources and is waiting for locks so it can complete. A second transaction has locked those needed items but is awaiting the release of locks the first transaction is holding so it can continue.
Two main ways to deal with deadlock. Prevent it in the first place by giving each transaction exclusive rights to
acquire all locks needed before proceeding. • Allow the deadlock to occur, then break it by aborting one of the
transactions.

UBL Fakultas Teknologi Informasi PBD - 194
PERANCANGAN BASIS DATA (3 SKS)
Database Recovery and Backup
There are many situations in which a transaction may not reach a commit or abort point.
An operating system crash can terminate the DBMS processes
The DBMS can crash
The system might lose power
A disk may fail or other hardware may fail.
Human error can result in deletion of critical data. In any of these situations, data in the database may become inconsistent or lost. Database Recovery is the process of restoring the database and the data to a consistent state. This may include restoring lost data up to the point of the event (e.g. system crash). Two approaches are discussed here: Reprocessing and Rollback/Rollforward

UBL Fakultas Teknologi Informasi PBD - 195
PERANCANGAN BASIS DATA (3 SKS)
Reprocessing
Reprocessing
In a Reprocessing approach, the database is periodically backed up (a database save) and all transactions applied since the last save are recorded
If the system crashes, the latest database save is restored and all of the transactions are re-applied (by users) to bring the database back up to the point just before the crash.
Several shortcomings:
Time required to re-apply transactions
Transactions might have other (physical) consequences
Re-applying concurrent transactions is not straight forward.

UBL Fakultas Teknologi Informasi PBD - 196
PERANCANGAN BASIS DATA (3 SKS)
Rollback / RollforwardWe apply a similar technique: Make periodic saves of the database (time consuming operation). However, maintain a more intelligent log of the transactions that have been applied. This transaction log Includes before images and after images Before Image: A copy of the table record (or page) of data before it was changed by the transaction. After Image: A copy of the table record (or page) of data after it was changed by the transaction. Rollback: Undo any partially completed transactions (ones in progress when the crash occurred) by applying the before images to the database. Rollforward: Redo the transactions by applying the after images to the database. This is done for transactions that were committed before the crash. Recovery process uses both rollback and rollforward to restore the database. In the worst case, we would need to rollback to the last database save and then rollforward to the point just before the crash. The DBMS flushes all pending transactions and writes all data to disk and transaction log. Checkpoints can also be taken (less time consuming) in between database saves. Database can be recovered from the last checkpoint in much less time.

UBL Fakultas Teknologi Informasi PBD - 197
PERANCANGAN BASIS DATA (3 SKS)
When secondary media (disk) fails, data may become unreadable. We typically rely on backing up the database to cheaper magnetic tape or other
backup medium for a copy that can be restored. However, when an DBMS is running, it is not possible to backup its files as the
resulting backup copy on tape may be inconsistent. One solution: Shut down the DBMS (and thus all applications), do a full backup -
copy everything on to tape. Then start up again.May be infeasible to do often.
Most modern DBMS allow for incremental backups. An Incremental backup will backup only those data changed or added since the
last full backup. Sometimes called a delta backup. Follows something like: Weekend: Do a shutdown of the DBMS, and full backup of the database onto a
fresh tape(s). Nightly: Do an incremental backup onto different tapes for each night of the week.
Database Backup