PRAKTIKUM DATABASE DESIGN & PROGRAMMING WITH SQL
TUGAS 12
Dosen Pengampu : Anief Fauzan Rozi, S.Kom., M.Eng., MCE
OLEH:
NAMA :HILDEGARDIS KRISTINA SAKA
NIM :211210041
12D2
PROGRAM STUDI SISTEM INFORMASI
FAKULTAS TEKNOLOGI INFORMASI
UNIVERSITAS MERCU BUANA YOGYAKARTA
2022
Database Programming with SQL
12-1: INSERT Statements
Practice Activities
USER Someone doing “real work” with the
computer, using it as a means rather than an
end
TRANSACTION Consists of a collection of DML statements that
form a logical unit of work
EXPLICIT Fully and clearly expressed; leaving nothing
implied
INSERT INTO Adds a new row to a table
Try It / Solve It
Students should execute DESC tablename before doing INSERT to view the data types for each
column. VARCHAR2 data-type entries need single quotation marks in the VALUES statement.
1. Give two examples of why it is important to be able to alter the data in a database.
Jawaban:
▪I am on a flight booking site. It shows available flights, say I try to book a
ticket and still my transaction is not commenced anywhere, I will be in big
trouble.
▪ I am trying to create a login on a site, it takes my details and say never store
my information in registration request table, I will keep on waiting for
approval which will never happen.
2. DJs on Demand just purchased four new CDs. Use an explicit INSERT statement to add
each CD to the copy_d_cds table. After completing the entries, execute a SELECT *
statement to verify your work.
CD_Number Title Title Produce Year
97 Celebrate the Day R & B Inc 2003
98 Holiday Tunes for All Tunes are Us 2004
Age
99 Party music Old town records 2004
100 Best of rock and roll Old town records 2004
Jawaban :
Create copy of main table to play around:
CREATE TABLE copy_d_cds
AS ( SELECT * FROM d_cds);
see if copy worked well:
DESCRIBE copy_d_cds;
DESCRIBE d_cds;
(clone table lost its primary key constraint and cd_number became nullable.)
see how the copied content looks like.
SELECT * FROM copy_d_cds ;
I see that cd_number 98 will be repeated with my insert statements, but it won't give
error, since primary key constrain is lost in copy.
The Explicit insert statements without even missing nullable columns:
INSERT INTO copy_d_cds(cd_number,title,producer,year)
VALUES(97,'Celebrate the Day','R & B Inc.','2003');
INSERT INTO copy_d_cds(cd_number,title,producer,year)
VALUES(98,'Holiday Tunes for All Ages','Tunes are Us','2004');
INSERT INTO copy_d_cds(cd_number,title,producer,year)
VALUES(99,'Party Music','Old Town Records','2004');
INSERT INTO copy_d_cds(cd_number,title,producer,year)
VALUES(100,'Best of Rock and Roll','Old Town Records','2004');
SELECT * FROM copy_d_cds ;
3. DJs on Demand has two new events coming up. One event is a fall football party and the
other event is a sixties theme party. The DJs on Demand clients requested the songs
shown in the table for their events. Add these songs to the copy_d_songs table using an
implicit INSERT statement.
ID TITLE DURATION TYPE_CODE
52 SURFING NOT KNOWN 12
SUMMER
53 VICTORY 5 MIN 12
VICTORY
Jawaban :
Create copy of main table to play around:
CREATE TABLE copy_d_songs
AS ( SELECT * FROM d_songs);
see if copy worked well:
DESCRIBE copy_d_songs;
DESCRIBE d_songs;
(Also, I see that duration & artist is nullable in source table. I could skip these
column names in insert into / if I decide to include these columns, I will specify it as
NULL in VALUES. I will prefer the later option to be symmetric and avoid missing
something by mistake. One more thing the clone table lost its primary key
constraint and id became nullable.)
The Explicit insert statements without even missing nullable columns:
INSERT INTO copy_d_songs (id,title,duration,artist,type_code)
VALUES(52,'Surfing Summer',NULL,NULL,12);
INSERT INTO copy_d_songs (id,title,duration,artist,type_code)
VALUES(53,'Victory Victory','5 min',NULL,12);
But, problem specifically says to use implicit insert statement:
INSERT INTO copy_d_songs
VALUES(52,'Surfing Summer',NULL,NULL,12);
INSERT INTO copy_d_songs
VALUES(53,'Victory Victory','5 min',NULL,12);
SELECT * FROM copy_d_songs ;
4. Add the two new clients to the copy_d_clients table. Use either an implicit or an explicit
INSERT.
CLIENT_NUMBER FIRST- LAST_NAME PHONE EMAIL
NAME
6655 NICK DAHISH 3608859030
[email protected] 6689 AYAKO NEUVILLE 9048953049
[email protected] Jawaban :
a) Create copy of main table to play around:
CREATE TABLE copy_d_clients
AS ( SELECT * FROM d_clients);
b) see if copy worked well:
DESCRIBE copy_d_clients ;
DESCRIBE d_clients;
(clone table lost its primary key constraint and client_number became nullable.)
SELECT * FROM d_clients ;
SELECT * FROM copy_d_clients ;
c) The Explicit insert statements without even missing nullable columns:
INSERT INTO copy_d_clients(client_number,first_name,last_name,phone,email)
VALUES(6655,'Ayako','Dahish',3608859030,'
[email protected]');
INSERT INTO copy_d_clients(client_number,first_name,last_name,phone,email)
VALUES(6689,'Nick','Neuville',3608859030,'
[email protected]');
d) verify data:
SELECT * FROM copy_d_clients ;
5. Add the new client’s events to the copy_d_events table. The cost of each event has not
been determined at this date.
Jawaban :
a) Create copy of main table to play around:
CREATE TABLE copy_d_events
AS ( SELECT * FROM d_events);
b) see if copy worked well:
DESCRIBE copy_d_events ;
DESCRIBE d_events;
(
All the constraints are lost in this copy.e.g.:
▪ clone table lost its primary key constraint and id became nullable.
▪ 245 and 315 venue_id are not there in d_venues, but it insert will still
work. [This loss of foreign key constraint is not mentioned by
DESCRIBE] one more thing:
▪ cost is not nullable and it needs to be a number. I could either make it
nullable, or give some value like 0 to cost. I go with second choice - give
value as zero.
)
SELECT * FROM d_events ;
SELECT * FROM copy_d_events ;
c) The Explicit insert statements:
INSERT INTO
copy_d_events(id,name,event_date,description,cost,venue_id,package_code,theme_c
ode,client_number)
VALUES(110,'Ayako Anniversary',TO_DATE('07-Jul-2004','dd-Mon-yyyy'),'Party
for 50, sixties dress, decorations',0,245,79,240,6655);
INSERT INTO
copy_d_events(id,name,event_date,description,cost,venue_id,package_code,theme_c
ode,client_number)
VALUES(115,'Neuville Sports Banquet',TO_DATE('09-Sep-2004','dd-Mon-
yyyy'),'Barbecue at residence, college alumni, 100 people',0,315,87,340,6689);
d)verify data:
SELECT * FROM copy_d_events ;
6. Create a table called rep_email using the following statement:
CREATE TABLE rep_email (
id NUMBER(3) CONSTRAINT rel_id_pk PRIMARY KEY,
first_name VARCHAR2(10),
last_name VARCHAR2(10),
email_address VARCHAR2(10))
Populate this table by running a query on the employees table that includes only those
employees who are REP’s.
jawaban :
Those employees could be Marketing Representative, or Sales Representative.
There JOB_ID ends with '_REP'
DESCRIBE rep_email ;
DESCRIBE employees;
Please note, employee_id has precision 6 and scale 0. But id in problem statement
has 2, 0
Similarly other fields also have differences.
Expected to see errors like ORA-01438: value larger than specified precision
allowed for this column
Luckily, rest of the mismatches still work because data is ok, but for id, I will have
alter it:
ALTER TABLE rep_email DROP column id;
ALTER TABLE rep_email ADD id NUMBER(6,0) CONSTRAINT rel_id_pk
PRIMARY KEY;
DESCRIBE rep_email ;
SELECT employee_id, first_name, last_name, email
FROM employees
WHERE job_id LIKE '%\_REP' ESCAPE '\';
INSERT INTO rep_email(id, first_name, last_name, email_address)
SELECT employee_id, first_name, last_name, email
FROM employees
WHERE job_id LIKE '%\_REP' ESCAPE '\';
SELECT * FROM rep_email;
Database Programming with SQL
12-2: Updating Column Values and Deleting Rows
Vocabulary
Identify the vocabulary word for each definition below.
UPDATE Modifies existing rows in a table
correlated subquery update retrieves information from one table & uses
the information to update another table
Integrity Constraints Ensures that the data adheres to a predefined
set of rules
correlated subquery delete deletes information on a linked table based on
what was deleted on the other table
DELETE Removes existing rows from a table
Try It / Solve It
NOTE: Copy tables in this section do not exist
If any change is not possible, give an explanation as to why it is not possible.
1. Monique Tuttle, the manager of Global Fast Foods, sent a memo requesting an immediate
change in prices. The price for a strawberry shake will be raised from $3.59 to $3.75, and
the price for fries will increase to $1.20. Make these changes to the copy_f_food_items
table.
Jawaban :
CREATE TABLE copy_f_food_items
AS ( SELECT * FROM f_food_items);
DESCRIBE f_food_items;
DESCRIBE copy_f_food_items;
SELECT * FROM f_food_items;
SELECT * FROM copy_f_food_items;
UPDATE copy_f_food_items SET price = 3.75
WHERE LOWER(description) = 'strawberry shake';
UPDATE copy_f_food_items SET price = 1.20
WHERE LOWER(description) = 'fries';
SELECT * FROM copy_f_food_items;
2. Bob Miller and Sue Doe have been outstanding employees at Global Fast Foods.
Management has decided to reward them by increasing their overtime pay. Bob Miller
will receive an additional $0.75 per hour and Sue Doe will receive an additional $0.85
per hour. Update the copy_f_staffs table to show these new values. (Note: Bob Miller
currently doesn’t get overtime pay. What function do you need to use to convert a null
value to 0?)
Jawaban :
CREATE TABLE copy_f_staffs
AS ( SELECT * FROM f_staffs);
DESCRIBE f_staffs;
DESCRIBE copy_f_staffs;
SELECT * FROM f_staffs;
SELECT * FROM copy_f_staffs;
UPDATE copy_f_staffs SET overtime_rate = NVL(overtime_rate, 0) + 0.75
WHERE LOWER(first_name || ' ' || last_name) = 'bob miller';
UPDATE copy_f_staffs SET overtime_rate = NVL(overtime_rate, 0) + 0.85
WHERE LOWER(first_name || ' ' || last_name) = 'sue doe';
SELECT * FROM copy_f_staffs;
3. Add the orders shown to the Global Fast Foods copy_f_orders table:
Jawaban :
CREATE TABLE copy_f_orders
AS ( SELECT * FROM f_orders);
DESCRIBE f_orders;
DESCRIBE copy_f_orders;
SELECT * FROM f_orders;
SELECT * FROM copy_f_orders;
INSERT INTO
copy_f_orders(order_number,order_date,order_total,cust_id,staff_id)
VALUES(5680,TO_DATE('June 12, 2004','fmMonth dd, yyyy'),159.78,145,9);
INSERT INTO
copy_f_orders(order_number,order_date,order_total,cust_id,staff_id)
VALUES(5691,TO_DATE('09-23-2004','mm-dd-yyyy'),145.98,225,12);
INSERT INTO
copy_f_orders(order_number,order_date,order_total,cust_id,staff_id)
VALUES(5701,TO_DATE('July 4, 2004','fmMonth dd, yyyy'),229.31,230,12);
SELECT * FROM copy_f_orders;
4. Add the new customers shown below to the copy_f_customers table. You may already
have added Katie Hernandez. Will you be able to add all these records successfully?
Jawaban :
Yes I will be able to add row, even if it has existing id, since in cloning table as
mentioned below, primary key constraint is lost.
CREATE TABLE copy_f_customers
AS ( SELECT * FROM f_customers);
DESCRIBE f_customers;
DESCRIBE copy_f_customers;
In copy table, zip is not nullable same as in master table, so the last row will give
error while insert.
SELECT * FROM f_customers;
SELECT * FROM copy_f_customers;
INSERT INTO
copy_f_customers(id,first_name,last_name,address,city,state,zip,phone_number)
VALUES(145,'Katie','Hernandez','92 Chico Way','Los
Angeles','CA',98008,'8586667641');
INSERT INTO
copy_f_customers(id,first_name,last_name,address,city,state,zip,phone_number)
VALUES(225,'Daniel','Spode','1923 Silverado','Denver','CO',80219,'7193343523');
INSERT INTO
copy_f_customers(id,first_name,last_name,address,city,state,zip,phone_number)
VALUES(230,'Adam','Zurn','5 Admiral Way','Seattle','WA',NULL,'4258879009');
ORA-01400: cannot insert NULL into
("HKUMAR"."COPY_F_CUSTOMERS"."ZIP")
SELECT * FROM copy_f_customers;
5. Sue Doe has been an outstanding Global Foods staff member and has been given a salary
raise. She will now be paid the same as Bob Miller. Update her record in copy_f_staffs.
Jawaban:
UPDATE copy_f_staffs SET salary = (SELECT salary FROM copy_f_staffs
WHERE LOWER(first_name || ' ' || last_name) = 'bob miller')
WHERE LOWER(first_name || ' ' || last_name) = 'sue doe';
SELECT * from copy_f_staffs;
6. Global Fast Foods is expanding their staff. The manager, Monique Tuttle, has hired Kai
Kim. Not all information is available at this time, but add the information shown here.
Jawaban :
It should work since all the mandatory columns have values.
INSERT INTO
copy_f_staffs(id,first_name,last_name,birthdate,salary,overtime_rate,training,staff_
type,manager_id,manager_budget,manager_target)
VALUES(25,'Kai','Kim',TO_DATE('03-Nov-1988','fmdd-Mon-
yyyy'),6.75,NULL,NULL,'Order Taker',NULL,NULL,NULL);
SELECT * FROM copy_f_staffs;
7. Now that all the information is available for Kai Kim, update his Global Fast Foods
record to include the following: Kai will have the same manager as Sue Doe. He does not
qualify for overtime. Leave the values for training, manager budget, and manager target
as null.
Jawaban :
UPDATE copy_f_staffs SET manager_id = (SELECT manager_id FROM
copy_f_staffs WHERE LOWER(first_name || ' ' || last_name) = 'sue doe')
WHERE LOWER(first_name || ' ' || last_name) = 'kai kim';
SELECT * FROM copy_f_staffs;
8. Execute the following SQL statement. Record your results.
DELETE from departments
WHERE department_id = 60;
Jawaban :
ORA-02292: integrity constraint (HKUMAR.EMP_DEPT_FK) violated - child
record found
9. Kim Kai has decided to go back to college and does not have the time to work and go to
school. Delete him from the Global Fast Foods staff. Verify that the change was made.
Jawaban :
SELECT * FROM copy_f_staffs;
DELETE FROM copy_f_staffs
WHERE LOWER(first_name || ' ' || last_name) = 'kai kim';
SELECT * FROM copy_f_staffs;
10. Create a copy of the employees table and call it lesson7_emp; Once this table exists,
write a correlated delete statement that will delete any employees from the
lesson7_employees table that also exist in the job_history table.
Jawaban :
CREATE TABLE lesson7_emp
AS ( SELECT * FROM employees);
DESCRIBE employees;
DESCRIBE lesson7_emp;
SELECT * FROM employees;
SELECT * FROM lesson7_emp;
SELECT DISTINCT employee_id FROM job_history;
7 rows returned in 0.00 seconds
DELETE FROM lesson7_emp
WHERE employee_id IN ( SELECT DISTINCT employee_id FROM job_history) ;
5 row(s) deleted.
0.01 seconds
Database Programming with SQL
12-3: DEFAULT Values, MERGE, and Multi-Table Inserts
Try It / Solve It
1. When would you want a DEFAULT value?
Jawaban :
▪ If no value is given while row creation and I want the field to take some
predefined value. For example there may be a created on column, and I want
that when a row is created, it gets filled up with current time.
2. Currently, the Global Foods F_PROMOTIONAL_MENUS table START_DATE column
does not have SYSDATE set as DEFAULT. Your manager has decided she would like to
be able to set the starting date of promotions to the current day for some entries. This will
require three steps:
a. In your schema, Make a copy of the Global Foods F_PROMOTIONAL_MENUS
table using the following SQL statement:
CREATE TABLE copy_f_promotional_menus
AS (SELECT * FROM f_promotional_menus)
Jawaban :
So first I will create a copy table:
CREATE TABLE copy_f_promotional_menus
AS ( SELECT * FROM f_promotional_menus);
DESCRIBE f_promotional_menus;
DESCRIBE copy_f_promotional_menus;
SELECT * FROM f_promotional_menus;
SELECT * FROM copy_f_promotional_menus;
SELECT TO_CHAR(TRUNC(start_date), 'dd-mm-yyyy-
hh24:mi:ss'),TO_CHAR(start_date, 'dd-mm-yyyy-hh24:mi:ss') FROM
copy_f_promotional_menus;
SELECT TO_CHAR(TRUNC(sysdate), 'dd-mm-yyyy-hh24:mi:ss') FROM dual;
b. Alter the current START_DATE column attributes using:
ALTER TABLE copy_f_promotional_menus
MODIFY(start_date DATE DEFAULT SYSDATE)
Jawaban :
Give default vale to start_date:
ALTER TABLE copy_f_promotional_menus
MODIFY(start_date DATE DEFAULT TRUNC(SYSDATE));
c. INSERT the new information and check to verify the results. INSERT a new row
into the copy_f_promotional_menus table for the manager’s new promotion. The
promotion code is 120. The name of the promotion is ‘New Customer.’ Enter
DEFAULT for the start date and '01-Jun-2005' for the ending date. The giveaway is a
10% discount coupon. What was the correct syntax used?
Jawaban :
INSERT INTO copy_f_promotional_menus(code,name,end_date,give_away)
VALUES('116','Back to School part 3',NULL,'ballpen and highlighter again2');
INSERT INTO
copy_f_promotional_menus(code,name,start_date,end_date,give_away)
VALUES('120','New Customer',DEFAULT,TO_DATE('01-Jun-2005','dd-Mon-
yyyy'),' 10% discount coupon');
3. Allison Plumb, the event planning manager for DJs on Demand, has just given you the
following list of CDs she acquired from a company going out of business. She wants a
new updated list of CDs in inventory in an hour, but she doesn’t want the original
D_CDS table changed. Prepare an updated inventory list just for her.
a. Assign new cd_numbers to each new CD acquired.
Jawaban :
It seems to be, this cd_number assignment is being done manually, I need not
create a sequence for this. If the sequence had to be created, this point would
have come after point b below, original table don’ have a sequence on this
column
b. Create a copy of the D_CDS table called manager_copy_d_cds. What was the correct
syntax used?
Jawaban :
CREATE TABLE manager_copy_d_cds
AS ( SELECT * FROM d_cds);
DESCRIBE d_cds;
DESCRIBE manager_copy_d_cds;
SELECT * FROM d_cds;
SELECT * FROM manager_copy_d_cds;
c. INSERT into the manager_copy_d_cds table each new CD title using an INSERT
statement. Make up one example or use this data: 20, 'Hello World Here I Am',
'Middle Earth Records', '1998' What was the correct syntax used?
Jawaban :
INSERT INTO manager_copy_d_cds(cd_number,title,producer,year)
VALUES(20,'Hello World Here I Am','Middle Earth Records','1998');
INSERT INTO manager_copy_d_cds(cd_number,title,producer,year)
VALUES(97,'Celebrate the Day','R & B Inc.','2003');
INSERT INTO manager_copy_d_cds(cd_number,title,producer,year)
VALUES(99,'Party Music','Old Town Records','2004');
INSERT INTO manager_copy_d_cds(cd_number,title,producer,year)
VALUES(100,'Best of Rock and Roll','Old Town Records','2004');
SELECT * FROM manager_copy_d_cds ;
d. Use a merge statement to add to the manager_copy_d_cds table, the CDs from the
original table. If there is a match, update the title and year. If not, insert the data from
the original table. What was the correct syntax used?
Jawaban :
To verify merge, first
i) I need to edit some record in manager_copy_d_cds, this should get updated
from d_cds to original value.
UPDATE manager_copy_d_cds
SET title = 'hkumar'
WHERE cd_number = 90;
ii) I should delete some record in manager_copy_d_cds which is present in
d_cds. This should be recreated after merge.
DELETE FROM manager_copy_d_cds
WHERE cd_number = 91;
SELECT * FROM manager_copy_d_cds ;
MERGE INTO manager_copy_d_cds tgt USING d_cds src
ON (src.cd_number = tgt.cd_number)
WHEN MATCHED THEN UPDATE
SET tgt.title = src.title, tgt.producer = src.producer, tgt.year = src.year
WHEN NOT MATCHED THEN INSERT
VALUES (src.cd_number, src.title, src.producer, src.year);
If () is missing I will get: ORA-00969: missing ON keyword
SELECT * FROM manager_copy_d_cds ;
4. Run the following 3 statements to create 3 new tables for use in a Multi-table insert
statement. All 3 tables should be empty on creation, hence the WHERE 1=2 condition in
the
WHERE clause.
CREATE TABLE sal_history (employee_id, hire_date, salary)
AS SELECT employee_id, hire_date, salary
FROM employees
WHERE 1=2;
CREATE TABLE mgr_history (employee_id, manager_id, salary)
AS SELECT employee_id, manager_id, salary
FROM employees
WHERE 1=2;
CREATE TABLE special_sal (employee_id, salary)
AS SELECT employee_id, salary
FROM employees
WHERE 1=2;
Once the tables exist in your account, write a Multi-Table insert statement to first select
the employee_id, hire_date, salary, and manager_id of all employees. If the salary is
more than 20000 insert the employee_id and salary into the special_sal table. Insert the
details of employee_id, hire_date, and salary into the sal_history table. Insert the
employee_id, manager_id, and salary into the mgr_history table.
You should get a message back saying 39 rows were inserted. Verify you get this
message and verify you have the following number of rows in each table:
Sal_history: 19 rows
Mgr_history: 19 rows
Special_sal: 1
Jawaban:
If I use FISRT / ALL no difference, since there is only one ‘WHEN’ I am using. In
else there are 2 inserts.
INSERT FIRST
WHEN salary > 20000 THEN
INTO special_sal
VALUES(employee_id, salary)
ELSE
INTO sal_history
VALUES(employee_id, hire_date, salary)
INTO mgr_history
VALUES(employee_id, manager_id, salary)
SELECT employee_id, salary, hire_date, manager_id
FROM employees;
39 row(s) inserted.
SELECT COUNT(*) FROM special_sal;
1
SELECT COUNT(*) FROM sal_history;
19
SELECT COUNT(*) FROM mgr_history;
19