Anda di halaman 1dari 82

SQL Query:

Modification database

INF2033 Basis Data 1


Pertemuan 19, 20

R. Kristoforus JB
Fakultas Sains & Teknologi
Universitas Katolik Musi Charitas
Outline
1. Review table modification
1. Create table
2. Alter table
3. Drop table
2. Data modification
1. Insert
2. Update
3. Delete
3. Constraint
1. Not null
2. Primary key
3. Foreign key
4. Check
5. Unique
6. On delete On update

3
Yang perlu dipersiapkan
• aplikasi DB4S
• Schema diagram universitas1
• File latihan:
– universitas1.db
• Kunjungi laman:
– https://www.sqlitetutorial.net/
– https://www.w3resource.com/sqlite/index.php

4
Schema Diagram: Universitas1

5
Review: table modification
Table modification
• Lihat kembali materi pertemuan 5 dan 6
• Modifikasi tabel:
– Membuat tabel baru
– Mengubah atribut
• Menambah atribut
• Menghapus atribut
– Mengubah constraint

7
Table modification
• Membuat table baru
– Sintaks:
create table r
(A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
• r adalah nama tabel
• Setiap Ai adalah atribut dalam tabel r
• Di adalah tipe data dalam domain atribut Ai
• Menghapus table
– Sintaks:
drop table r
• r adalah nama tabel

8
Table modification
• Menambahkan atribut
– Sintaks:
alter table r add A D
• A adalah nama atribut yang ditambahkan ke tabel r
• D adalah tipe data dari domain A.
• Semua nilai record pada atribut baru akan diisi dengan nilai null.

• Menghapus atribut
– Sintaks:
alter table r drop A
• A adalah nama atribut yang dihapus dari tabel r

• Catatan: SQLite tidak mendukung penghapusan atribut

9
Latihan 27. 1
1. Buatlah sebuah tabel baru dengan nama: program. Dengan atributnya:
nama atribut tipe primary key autoincrement keterangan
kdpr integer v v kode program
namapr text nama program
jmlsks integer jumlah sks
masastudi integer masa studi

2. Buatlah sebuah tabel baru dengan nama: fakultas


nama atribut tipe primary key autoincrement keterangan
kdf integer v v kode fakultas
namaf text nama fakultas

3. Tambahkan atribut kdpr bertipe text pada tabel prodi


4. Tambahkan atribut baru kdf bertipe text pada tabel prodi

10
Latihan 27.1
5. Buatlah sebuah tabel dengan nama backupmhs
nama atribut tipe primary key autoincrement keterangan
nim text v
nama text
kdp text
nidn text
6. Buatlah sebuah tabel dengan nama backupmhsif
nama atribut tipe primary key autoincrement keterangan
nim text v
nama text
kdp text
nidn text

11
Data modification
Data modification
• Data dalam tabel dapat dimodifikasi.
• Data modification:
– Insert
– Update
– Delete

14
Insert
• Sintaks umum:
INSERT
INTO table_name [(column_list)]
VALUES (values_list)

• Bentuk:
– Full inserting
• Insert values with mention column
• Insert values without mention column
– Partial inserting
• Insert values without primary key
• Insert values for specific column
– Multi row insert
– Insert using replace
– Insert using select statement

15
Insert
• Contoh 1: full inserting with mention column
insert into program (kdpr, namapr, jmlsks, masastudi) values (1, 'Diploma 1',40,2);

16
Insert
• Contoh 2: full inserting without mention column
insert into program values (2, 'Diploma 2',80,4);

• Contoh 3: insert values without primary key


insert into program (namapr, jmlsks, masastudi) values ('Diploma 3',120,6);

17
Insert
• Contoh 4: insert values with specific column
insert into program (kdpr, namapr) values (4, 'Diploma 4');

18
Insert
• Contoh 5: multi row insert
insert
into program (kdpr, namapr, jmlsks, masastudi)
values
(5, 'Sarjana',144,8),
(6, ‘Profesi',40,2),
(7, ‘Magister',40,6);

19
Insert
• Contoh 6: insert using replace
replace
into program (kdpr, namapr, jmlsks, masastudi)
values(4,'Diploma 4',144,8);

20
Insert
• Contoh 7: insert values with select statement
insert
into backupmhs (nim, nama, kdp, nidn)
select * from mahasiswa;

21
Insert
• Contoh 8: insert values with select statement
insert into tempuh
select nim, kdmk,'A' from (select nim from mahasiswa where nama='Andi'),(select kdmk
from matakuliah where namamk='Agama');

22
Latihan 27.2
1. Tambahkan atribut singkatan (bertipe text) dan atribut lokasi (bertipe
text) pada tabel fakultas
2. Tambahkan data berikut ke tabel fakultas
kdf nama fakultas singkatan lokasi
1 Fakultas Sains dan Teknologi fst Kampus Bangau
2 Fakultas Bisnis dan Akuntansi fba Kampus Bangau
3 Fakultas Ilmu Kesehatan fik Kampus Bangau
4 Fakultas Humaniora dan ilmu Pendidikan fhip Kampus Bangau

3. Tambahkan data mahasiswa prodi informatika dari tabel mahasiswa


ke tabel backupmhsif
4. Prodi informatika memiliki mata kuliah baru: Strategi Algoritma
dengan kode mata kuliah: M031, 2 sks. Tambhkan data tersebut ke
tabel mata kuliah.

23
Latihan 27.2
5. Mahasiswa bernama Wati mendapat nilai A untuk mata kuliah
Statistik 2. Tambahkan data tersebut pada tabel tempuh
6. Dosen bernama Natalia Regina mengajar mata kuliah Statistik 2 di
semester Genap 2019. Tambahkan data tersebut ke tabel mengajar.

25
Update
• Sintaks umum:
UPDATE table
SET column_1 = new_value_1,
column_2 = new_value_2
WHERE
search_condition
ORDER column_or_expression
LIMIT row_count OFFSET offset;
• Bentuk:
– Update column
– Update cell (update data)
– Update row

28
Update
• Contoh 9:
update prodi set kdpr=1;

29
Update
• Contoh 10:
update prodi
set kdpr=5
where prodi.program='Sarjana';

30
Update
• Contoh 11:
update prodi
set kdf = (select kdf from fakultas where singkatan='fst')
where namap='Arsitektur';

31
Latihan 27.3
1. Lakukan update pada tabel program berdasarkan data berikut
namap diupdate menjadi
Diploma 1 Diploma Satu
Diploma 2 Diploma Dua
Diploma 3 Diploma Tiga
Diploma 4 Sarjana Terapan

2. semua dosen mendapat kenaikan gaji sebesar 10%. Lakukan update


gaji dosen
3. semua dosen informatika mendapat tambahan gaji sebesar 100000.
Lakukan update gaji dosen
4. Dosen yang memiliki jenjang jabatan akademik Lektor Kepala
mendapat gaji tambahan sebesar 250000. lakukan update gaji dosen
5. Mahasiswa bernama Andi berganti pembimbing akademik dari
Kaludius Jevanda ke Gunadi Emanuel. Lakukan update.

32
Latihan 27.3
6. Mahasiswa bernama Andi seharusnya mendapatkan nilai A untuk
mata kuliah Perancangan Arsitektur 1. Data yang tersimpan
mahasiswa tersebut mendapat nilai C. Lakukan perubahan data.

33
Delete
• Bentuk umum:
DELETE FROM table
WHERE search_condition
ORDER BY criteria
LIMIT row_count OFFSET offset;
• Bentuk:
– Delete row

37
Delete
• Contoh 12:
– delete from backupmhsif where nama='Wati';
• Contoh 13:
– delete from backupmhsif where nama like '%Ma%';
• Contoh 14:
– delete from backupmhsif;
• Contoh 15:
– delete from matakuliah where kdp in (select kdp from prodi where
namap='Manajemen');

38
Latihan 27.4
1. Hapuslah seluruh data pada tabel backupmhs
2. Hapuslah semua mata kuliah yang dikelola oleh prodi Akuntansi
3. Hapuslah semua mahasiswa yang pembimbing akademiknya Gunadi
Emanuel
4. Hapuslah data dosen arsitektur yang masih berjenjang tenaga pengajar

39
40
constraint
Outline
3. Constraint
1. Not null
2. Primary key
3. Foreign key
4. Check
5. Unique
6. On delete & On update
1. No action
2. Cascade
3. Restrict

42
What is Constraint ?
• The CONSTRAINTS are an integrity which defines some conditions
that restrict the column to contain the true data while inserting or
updating or deleting.
• We can use two types of constraints, that is column level or table level
constraint.
• The column level constraints can be applied only on a specific column
where as table level constraints can be applied to the whole table.
• The following column constraints that should be enforced when data is
inserted:
– NOT NULL
– PRIMARY KEY
– UNIQUE
– CHECK
– FOREIGN KEY

43
Not Null
• A NOT NULL constraint may only be attached to a column definition,
not specified as a table constraint.
• Not surprisingly, a NOT NULL constraint dictates that the associated
column may not contain a NULL value.
• Attempting to set the column value to NULL when inserting a new row
or updating an existing one causes a constraint violation.

44
Not Null
• Example 1:
create table company(
com_id text(4) NOT NULL,
com_name text(15) NOT NULL);

• Now look at the usage of the NOT NULL with CREATE TABLE
statement. See the list of commands below:
• Example 2:
INSERT INTO company VALUES("COM1","T S LTD.");

• Example 3:
SELECT * FROM company;
com_id com_name
COM1 T S LTD.

• No problem arise at the time of insertion.

45
Not Null
• Example 4:
INSERT INTO company VALUES("COM1",""); com_id com_name
SELECT * FROM company; COM1 T S LTD.
COM1

• Here also no problem arise at the time of insertion, though the value of
the second column is blank.

• Example 5:
INSERT INTO company VALUES("COM1",NULL);
Result: NOT NULL constraint failed: company.com_name
At line 18:
/*Example 5*/
INSERT INTO company VALUES("COM1",NULL);

• But, here in the above we forcefully tried to enter the value of second
column NULL a violation of constraint occurred.
• Example 6:
DROP TABLE company;

46
Primary Key
• If the keywords PRIMARY KEY are added to a column definition, then
the primary key for the table consists of that single column.
• If a PRIMARY KEY clause is specified as a table-constraint, then the
primary key of the table consists of the list of columns specified as part
of the PRIMARY KEY clause.
• Each row in a table with a primary key must have a unique combination
of values in its primary key columns.
• For the purposes of determining the uniqueness of primary key values,
NULL values are considered distinct from all other values, including
other NULLs.
• More than one PRIMARY KEY clause is not possible in a CREATE
TABLE statement.
• The PRIMARY KEY is optional for ordinary tables. According to the
SQL standard, PRIMARY KEY should always imply NOT NULL.

47
Primary Key
• Example 7:
create table company(
com_id text(4) PRIMARY KEY,
com_name text(15) NOT NULL);

• Here in the above example com_id is the single column PRIMARY KEY
• The PRAGMA command can be used to see the structure of the table.

• Example 8:
PRAGMA table_info(company);

cid name type notnull dflt_value pk


0 com_id text(4) 0 1
1 com_name text(15) 1 0

48
Primary Key
• Now see the usage of PRIMARY KEY.
• Example 9:
– INSERT INTO company VALUES(NULL,"T S LTD.");

• Here we insert a row and value against column com_id is NULL, and it
has been accepted though the com_id is a PRIMARY KEY because
SQLite allows NULL values in a PRIMARY KEY column.
• Example 10:
– SELECT * FROM company;
com_id com_name
T S LTD.

49
Primary Key
• Now,
• Example 11:
INSERT INTO company VALUES("COM1","T S LTD.");
INSERT INTO company VALUES("COM2","K M P CORP.");
INSERT INTO company VALUES("COM1","T S LTD.");
• Result:
Result: query executed successfully. Took 2ms, 1 rows affected
At line 42:
INSERT INTO company VALUES("COM2","K M P CORP.");

• Here in the above, the first two rows have been inserted, but in the 3rd
line, we forcefully tried to enter the value of com_id COM1, which
already exists and this is violating the uniqueness of the PRIMARY KEY
and the above error message appeared.

50
Primary Key
• It is good practice to use NOT NULL along with the PRIMARY KEY at
the time of creation of column level PRIMARY KEY to making a table
more secure and stronger.
• Now we are going to enforce two PRIMARY KEY in column level
PRIMARY KEY constraint, look the result -
• Example 12:
DROP TABLE company;

• Example 13:
create table company(
com_id text(4) NOT NULL PRIMARY KEY ,
com_name text(15) NOT NULL PRIMARY KEY);

– Error: table "company" has more than one primary key

51
Composite Primary key
• Composite PRIMARY KEY is the combination of more than one
columns PRIMARY KEY.
• Here is the example below –
• Example 14:
CREATE TABLE orders(
ord_id text(4) NOT NULL,
item_id text(4) NOT NULL,
ord_date date,
ord_qty integer,
cost integer,
PRIMARY KEY (item_id,ord_date) );

52
Composite Primary key
• To see the structure of the table, use the following commands.
• Example 15:
sqlite> PRAGMA table_info(orders);
cid name type notnull dflt_value pk
0 ord_id text(4) 1 0
1 item_id text(4) 1 1
2 ord_date date 0 2
3 ord_qty integer 0 0
4 cost integer 0 0

• From the above structure of the table shows that item_id and ord_date
columns are combinedly treated as a primary key, and this is composite
primary key.

53
Composite Primary key
• Now,
• Example 16:
INSERT INTO orders VALUES("ORD1","ITM1","9/13/2014",10,300);
INSERT INTO orders VALUES("ORD2","ITM2","8/22/2014",12,300);
INSERT INTO orders VALUES("ORD3","ITM1","9/13/2014",25,300);

– Error: UNIQUE constraint failed: orders.item_id, orders.ord_date

• Here in the above the first two rows have been inserted, but in 3rd line,
we forcefully tried to enter the value of item_id is "ITM1" and ord_date
is "9/13/2014", which combination is already exists and this is violating
the uniqueness of the PRIMARY KEY and the above error message
appeared.

54
Unique
• A UNIQUE constraint is similar to a PRIMARY KEY constraint, except
that a single table may have any number of UNIQUE constraints.
• For each UNIQUE constraint on the table, each row must contain a
unique combination of values in the columns identified by the UNIQUE
constraint.
• For the purposes of UNIQUE constraints, NULL values are considered
distinct from all other values, including other NULLs.

55
Unique
• Example 17:
create table company(
com_id text(4) PRIMARY KEY NOT NULL UNIQUE,
com_name text(15) NOT NULL UNIQUE);

• Here in the above example, UNIQUE constraint has added in each


column, but can not do in the case of PRIMARY KEY we have seen
before.

56
Check
• A CHECK constraint may be attached to a column definition to define
what is a valid value for a column.
• At the time of inserting a new row or updating row, check the value for
the specific column whether it is violating the condition, and if the
condition evaluates false no new row will be inserted or no row will be
updated due to the violation of the constraint.
• Example 18:
CREATE TABLE item(
item_id text(4) NOT NULL UNIQUE PRIMARY KEY,
item_desc text(20) NOT NULL,
rate integer CHECK (rate>0 AND rate<100));
• Here in the above example CHECK constraint have with rate column,
mention that rate must be a positive value and rate should not exceed
100 or more .

57
Check
• Now, Example 19:
INSERT INTO item VALUES("ITM1","Pea-n-Nut",15);
SELECT * FROM item;
• Example 20:
INSERT INTO item VALUES("ITM2","Cool Pesta",0);
– Error: CHECK constraint failed: item
• Example 21:
INSERT INTO item VALUES("ITM3","Crack-Munch",110);
– Error: CHECK constraint failed: item

• Here in the first insertion in item table on problem arise but in the second and
the third insertion error been occur, because in the second insertion, the value of
rate define 0 which is violating the CHECK constraint and in the third insertion,
the value of rate is 110 which is also violating the CHECK constraint

58
Foreign key
• A FOREIGN KEY CONSTRAINT is used to ensure the referential
integrity of the data in one table to match values in another table.
• It may be one column or list of columns which points to the PRIMARY
KEY of another table.
• The only and useful purpose of FOREIGN KEY is, those values will
only appear which present in the primary key table.
• For each row in the referencing table( the table contains the FOREIGN
KEY), the foreign key must match an existing primary key in the
referenced table(the table contains the PRIMARY KEY).

59
Foreign key
• Example 22:
DROP TABLE IF EXISTS company;
DROP TABLE IF EXISTS item;

• Example 23:
create table company(
com_id text(4) PRIMARY KEY NOT NULL UNIQUE,
com_name text(15) NOT NULL);
• Example 24:
CREATE TABLE item(
item_id text(4) NOT NULL UNIQUE PRIMARY KEY,
item_desc text(20) NOT NULL,
rate integer NOT NULL,
com_id text(4) NOT NULL,
FOREIGN KEY (com_id) REFERENCES company(com_id));

60
Foreign key
• Here in the above example, the com_id is the PRIMARY KEY in
company table, i.e. each com_id comes once in the table; and com_id in
item table is FOREIGN KEY, and this is reference to the PRIMARY KEY
of the company table, that means, which value against com_id column
exists in the company table, only those values are eligible to come in the
com_id column in item table.

61
Foreign key
• Example 25: Now, insert the records into two tables, and see- :
INSERT INTO company VALUES("COM1","T S LTD.");
INSERT INTO company VALUES("COM2","K M P CORP.");
INSERT INTO company VALUES("COM3","M B D INC.");
INSERT INTO company VALUES("COM4","T S LTD.");

• Example 26: After insertion here is the table below.


SELECT * FROM company;
com_id com_name
COM1 T S LTD.
COM2 K M P CORP.
COM3 M B D INC.
COM4 T S LTD.

62
Foreign key
• Example 27:
INSERT INTO item VALUES("ITM1","Pea-n-Nut",15,"COM1");
INSERT INTO item VALUES("ITM2","Cool Pesta",25,"COM3");
INSERT INTO item VALUES("ITM3","Crack-Munch",12,"COM1");
INSERT INTO item VALUES("ITM4","Pepsi",16,"COM2");
INSERT INTO item VALUES("ITM6","Pea-n-Nut",14,"COM2");
INSERT INTO item VALUES("ITM5","Charlie Gold",700,"COM4");

• Here we insert 6 rows. Now I am going to insert 7th rows. Look the
results –
• Example 28:
INSERT INTO item VALUES("ITM7","Charlie Gold",710,"COM6");
– Error: FOREIGN KEY constraint failed

63
Foreign key
• No problem arise though "COM6" does not exist in company table.
Because foreign key support has not been enabled for the database
session, so if you enabled the support by -
• Example 28a:
PRAGMA foreign_keys = ON;
• foreign key support will be enabled.
• Example 28b: Now we delete the last row from item table by-
DELETE FROM item WHERE com_id='COM6';
• The last inserted have been deleted. Now we execute the following
command, and see the result-
• Example 28c:
INSERT INTO item VALUES("ITM7","Charlie Gold",710,"COM6");
– Error: FOREIGN KEY constraint failed

64
Foreign key
• Here at the time of insertion of 7th rows, a FOREIGN KEY constraint
failed error have appeared because of the value "COM6" in the
reference column com_id not exists in company table. Here is the table-
• Example 29:
– SELECT * FROM item;

item_id item_desc rate com_id


ITM1 Pea-n-Nut 15 COM1
ITM2 Cool Pesta 25 COM3
ITM3 Crack-Munch 12 COM1
ITM4 Pepsi 16 COM2
ITM6 Pea-n-Nut 14 COM2
ITM5 Charlie Gold 700 COM4

65
Composite foreign key
• A COMPOSITE FOREIGN KEY constraint is one where the child and
parent keys are both composite keys, that is, two or more columns are
combined in both the parent and child table as a primary key and
foreign key respectively.

• Example 30:
create table comp_mast(
com_id text(4) ,
com_name text(15),
prod_id text(4),
PRIMARY KEY (com_id,prod_id));

66
Composite foreign key
• Example 31:
create table itm_mast(
item_id text(4) ,
item_name text(15),
factory text(4),
pro_type text(4),
pro_cost integer,
FOREIGN KEY(factory,pro_type) REFERENCES comp_mast(com_id,prod_id));

67
On delete & On update
• ON DELETE and ON UPDATE clauses along with FOREIGN KEY are
used to configure actions that take place when deleting rows from the
parent table (ON DELETE), or modifying the parent key values of
existing rows (ON UPDATE). The ON DELETE and ON UPDATE
action associated with each foreign key in a database, execute one of
such action i.e. "NO ACTION", "RESTRICT", "SET NULL", "SET
DEFAULT" or "CASCADE".
– NO ACTION: - Configuring "NO ACTION" means just that: when a parent key is
modified or deleted from the database, no special action is taken.
– RESTRICT: The "RESTRICT" action means that the application is prohibited from
deleting (for ON DELETE RESTRICT) or modifying (for ON UPDATE RESTRICT) a
parent key when there exist one or more child keys mapped to it.

68
On delete & On update
– SET NULL: If the configured action is "SET NULL", then when a parent key is
deleted (for ON DELETE SET NULL) or modified (for ON UPDATE SET NULL), the
child key columns of all rows in the child table that mapped to the parent key are set
to contain SQL NULL values.
– SET DEFAULT: The "SET DEFAULT" actions are similar to "SET NULL", except that
each of the child key columns is set to contain the columns default value instead of
NULL.
– CASCADE: A "CASCADE" action propagates the delete or update operation on the
parent key to each dependent child key. For an "ON DELETE CASCADE" action, this
means that each row in the child table that was associated with the deleted parent
row is also deleted. For an "ON UPDATE CASCADE" action, it means that the values
stored in each dependent child key are modified to match the new parent key values.

69
No Action
• Now if we update and delete the record from company table, no effect
to seem in child table item, because no action have been set for DELETE
and UPDATE records.
• If an action is not explicitly specified, it defaults to "NO ACTION". Here
is the example-
• Example 32:
DROP TABLE IF EXISTS company;
CREATE TABLE company(
com_id text(4) NOT NULL UNIQUE PRIMARY KEY,
com_name text(15) NOT NULL);
• Example 33:
INSERT INTO company VALUES("COM1","TS LTD.");
INSERT INTO company VALUES("COM2","KMP CORP.");
INSERT INTO company VALUES("COM3","MBD INC.");
INSERT INTO company VALUES("COM4","TS LTD.");

70
No Action
• Example 34:
DROP TABLE IF EXISTS item;
CREATE TABLE item(
item_id text(4) NOT NULL UNIQUE PRIMARY KEY,
item_desc text(20) NOT NULL,
rate integer NOT NULL,
icom_id TEXT(4) NOT NULL,
FOREIGN KEY (icom_id) REFERENCES company(com_id));
• Example 35:
INSERT INTO item VALUES("ITM1","Pea-n-Nut",15,"COM1");
INSERT INTO item VALUES("ITM2","Cool Pesta",25,"COM3");
INSERT INTO item VALUES("ITM3","Crack-Munch",12,"COM1");
INSERT INTO item VALUES("ITM4","Pepsi",16,"COM2");
INSERT INTO item VALUES("ITM6","Pea-n-Nut",14,"COM2");
INSERT INTO item VALUES("ITM5","Charlie Gold",700,"COM4");

71
No Action
• Example 36:
– SELECT * FROM company;
com_id com_name
COM1 TS LTD.
COM2 KMP CORP.
COM3 MBD INC.
COM4 TS LTD.

• Example 37:
– SELECT * FROM item;
item_id item_desc rate com_id
ITM1 Pea-n-Nut 15 COM1
ITM2 Cool Pesta 25 COM3
ITM3 Crack-Munch 12 COM1
ITM4 Pepsi 16 COM2
ITM6 Pea-n-Nut 14 COM2
ITM5 Charlie Gold 700 COM4

72
No Action
• Example 38:
UPDATE company SET com_id='COM5' WHERE com_id='COM4';

• Example 38a:
SELECT * FROM company; com_id com_name
COM1 TS LTD.
COM2 KMP CORP.
COM3 MBD INC.
COM4 TS LTD.

• Example 38b:
SELECT * FROM item;
item_id item_desc rate com_id
ITM1 Pea-n-Nut 15 COM1
ITM2 Cool Pesta 25 COM3
ITM3 Crack-Munch 12 COM1
ITM4 Pepsi 16 COM2
ITM6 Pea-n-Nut 14 COM2
ITM5 Charlie Gold 700 COM4

73
No Action
• Example 38c:
DELETE FROM company WHERE com_id='COM2';

• Example 38d:
SELECT * FROM company;

• Example 38e:
– SELECT * FROM item;

74
Cascade
• But, if defines the ON UPDATE CASCADE and ON DELETE
CASCADE along with the FOREIGN KEY, then look what happen in
the following examples -
• Example 39:
DROP TABLE IF EXISTS item;
DROP TABLE IF EXISTS company;
CREATE TABLE company(
com_id text(4) NOT NULL UNIQUE PRIMARY KEY,
com_name text(15) NOT NULL);
• Example 40:
CREATE TABLE item(
item_id text(4) NOT NULL UNIQUE PRIMARY KEY,
item_desc text(20) NOT NULL,
rate integer NOT NULL,
icom_id TEXT(4),
FOREIGN KEY (icom_id)
REFERENCES company(com_id)
ON UPDATE CASCADE ON DELETE CASCADE);

75
Cascade
• Example 41:
INSERT INTO company VALUES("COM1","TS LTD.");
INSERT INTO company VALUES("COM2","KMP CORP.");
INSERT INTO company VALUES("COM3","MBD INC.");
INSERT INTO company VALUES("COM4","TS LTD.");
• Example 42:
INSERT INTO item VALUES("ITM1","Pea-n-Nut",15,"COM1");
INSERT INTO item VALUES("ITM2","Cool Pesta",25,"COM3");
INSERT INTO item VALUES("ITM3","Crack-Munch",12,"COM1");
INSERT INTO item VALUES("ITM4","Pepsi",16,"COM2");
INSERT INTO item VALUES("ITM6","Pea-n-Nut",14,"COM2");
INSERT INTO item VALUES("ITM5","Charlie Gold",700,"COM4");

76
Cascade
• Example 43:
– SELECT * FROM company;
com_id com_name
COM1 TS LTD.
COM2 KMP CORP.
COM3 MBD INC.
COM4 TS LTD.

• Example 44:
– SELECT * FROM item;

item_id item_desc rate icom_id


ITM1 Pea-n-Nut 15 COM1
ITM2 Cool Pesta 25 COM3
ITM3 Crack-Munch 12 COM1
ITM4 Pepsi 16 COM2
ITM6 Pea-n-Nut 14 COM2
ITM5 Charlie Gold 700 COM4

77
Cascade
• Example 45:
UPDATE company SET com_id='COM5' WHERE com_id='COM4';

• Example 46:
SELECT * FROM company;
com_id com_name
COM1 TS LTD.
COM2 KMP CORP.
COM3 MBD INC.
COM5 TS LTD.

• Bandingkan hasilnya dengan Example 43


com_id com_name
COM1 TS LTD.
COM2 KMP CORP.
COM3 MBD INC.
COM4 TS LTD.

78
Cascade
• Example 47:
SELECT * FROM item;
item_id item_desc rate icom_id item_id item_desc rate icom_id
ITM1 Pea-n-Nut 15 COM1 ITM1 Pea-n-Nut 15 COM1
ITM2 Cool Pesta 25 COM3 ITM2 Cool Pesta 25 COM3
ITM3 Crack-Munch 12 COM1 ITM3 Crack-Munch 12 COM1
ITM4 Pepsi 16 COM2 ITM4 Pepsi 16 COM2
ITM6 Pea-n-Nut 14 COM2 ITM6 Pea-n-Nut 14 COM2
ITM5 Charlie Gold 700 COM5 ITM5 Charlie Gold 700 COM4

• Bandingkan Example 44.


• Here in the foreign key field 'icom_id', in the child table 'item', will be
updated to match the record(s) in the parent table 'company'.
• Here com_id in company table updated by 'COM5' as well as the child
key i.e. icom_id of mapped rows of chile table, dependant on the
• parent key field i.e. com_id have updated by 'COM5'.

79
Cascade
• Example 48:
DELETE FROM company WHERE com_id='COM2';

• Example 49:
SELECT * FROM company;
com_id com_name
COM1 TS LTD.
COM3 MBD INC.
COM5 TS LTD.

• Bandingkan Example 46
com_id com_name
COM1 TS LTD.
COM2 KMP CORP.
COM3 MBD INC.
COM5 TS LTD.

80
Cascade
• Example 50:
SELECT * FROM item;
item_id item_desc rate icom_id item_id item_desc rate icom_id
ITM1 Pea-n-Nut 15 COM1 ITM1 Pea-n-Nut 15 COM1
ITM2 Cool Pesta 25 COM3 ITM2 Cool Pesta 25 COM3
ITM3 Crack-Munch 12 COM1 ITM3 Crack-Munch 12 COM1
ITM5 Charlie Gold 700 COM5 ITM4 Pepsi 16 COM2
ITM6 Pea-n-Nut 14 COM2
ITM5 Charlie Gold 700 COM5

• Bandingkan example 47

• Here all the rows from parent table will be deleted which matching the
condition as well as
• each row in the child table item that was associated with the deleted
parent key is also deleted.

81
Restrict
• Example 51:
DROP TABLE IF EXISTS item;
DROP TABLE IF EXISTS company;
create table company(
com_id text(4) NOT NULL UNIQUE PRIMARY KEY,
com_name text(15) NOT NULL);
• Example 52:
CREATE TABLE item(
item_id text(4) NOT NULL UNIQUE PRIMARY KEY,
item_desc text(20) NOT NULL,
rate integer NOT NULL,
icom_id TEXT(4),
FOREIGN KEY (icom_id)
REFERENCES company(com_id)
ON UPDATE RESTRICT ON DELETE RESTRICT);

82
Restrict
• Example 53:
INSERT INTO company VALUES("COM1","TS LTD.");
INSERT INTO company VALUES("COM2","KMP CORP.");
INSERT INTO company VALUES("COM3","MBD INC.");
INSERT INTO company VALUES("COM4","TS LTD.");

• Example 54:
INSERT INTO item VALUES("ITM1","Pea-n-Nut",15,"COM1");
INSERT INTO item VALUES("ITM2","Cool Pesta",25,"COM3");
INSERT INTO item VALUES("ITM3","Crack-Munch",12,"COM1");
INSERT INTO item VALUES("ITM4","Pepsi",16,"COM2");
INSERT INTO item VALUES("ITM6","Pea-n-Nut",14,"COM2");

83
Restrict
• Example 55:
SELECT * FROM company;
com_id com_name
• COM1 TS LTD.
COM2 KMP CORP.
COM3 MBD INC.
COM4 TS LTD.

• Example 56:
SELECT * FROM item;
item_id item_desc rate icom_id
ITM1 Pea-n-Nut 15 COM1
ITM2 Cool Pesta 25 COM3
ITM3 Crack-Munch 12 COM1
ITM4 Pepsi 16 COM2
ITM6 Pea-n-Nut 14 COM2

84
Restrict
• Example 57:
UPDATE company SET com_id='COM5' WHERE com_id='COM3';
– Error: UNIQUE constraint failed: company.com_id

• The above statement shows that the application is prohibited from


modifying the parent key com_id(COM3) by COM5 when there exists
one or more child keys(COM3) mapped to it.

85
Restrict
• Example 58:
UPDATE company SET com_id='COM5' WHERE com_id='COM4';

• Example 59:
SELECT * FROM company;
com_id com_name com_id com_name
COM1 TS LTD. COM1 TS LTD.
COM2 KMP CORP. COM2 KMP CORP.
COM3 MBD INC. COM3 MBD INC.
COM5 TS LTD. COM4 TS LTD.

• Bandingkan Example 55
• But this example shows that the modification take place in parent table
without disturbing the child table, because no such value for parent key
column exists in a child table.

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

87
Jadwal
Prt Tgl Teori T P
9 03/10 Relational Database: Relational Algebra V
10 03/10 Relational Database: Relational Algebra V
11 10/10 Relational Database: Relational Algebra V
12 10/10 SQLite: Aggregate Function, Set Operation, Join Operation V
13 24/10 Project 1: Presentasi V
14 24/10 SQLite: Subquery (set membership, set comparison, empty V
relation)
15 26/10 UTS V
16

88
Jadwal
Prt Tgl Teori T P
17 31/10 Data Modeling: ER Model V
18 31/10 Data Modeling: ER Model V
19 07/11 SQLite: Subquery V
20 07/11 SQLite: Views V
21 14/11 Data Modeling: ER Model V
22 14/11 Data Modeling: ER Model (Tugas 2) V
23 21/11 Data Modeling: Integrity Rules & Normalization V
24 21/11 Data Modeling: Integrity Rules & Normalization V

89
Jadwal
Prt Tgl Teori T P
25 28/11 Data Modeling: Integrity Rules & Normalization V
26 28/11 Data Modeling: Integrity Rules & Normalization V
27 05/12 SQLite: Modification database V
28 05/12 Constraints V
29 12/12 Project 2: Presentasi V
30 12/12 Diskusi V
31 UAS V
32

90

Anda mungkin juga menyukai

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