0% found this document useful (0 votes)
17 views

Lab 9

Uploaded by

noumanzahi7676
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lab 9

Uploaded by

noumanzahi7676
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Lab 09

Manipulating Data using DML Statements


Objective:
The objective of this lab is to make student learn how to use the data manipulation language (DML)
statements to insert rows into a table, update existing rows in a table, and delete existing rows from a
table. The students will also learn how to control transactions with the COMMIT, SAVEPOINT, and
ROLLBACK statements.

Activity Outcomes:
After completing this lesson, you should be able to do the following:

• Describe and apply each data manipulation language (DML) statement


• Control transactions

Instructor Note:
Please make sure that you have completed the previous labs.

94
1) Useful Concepts
Data manipulation language (DML) is a core part of SQL. When you want to add, update, or delete data
in the database, you execute a DML statement. A collection of DML statements that form a logical unit of
work is called a transaction.
Consider a banking database. When a bank customer transfers money from a savings account to a
checking account, the transaction might consist of three separate operations: decreasing the savings
account, increasing the checking account, and recording the transaction in the transaction journal. The
Oracle server must guarantee that all the three SQL statements are performed to maintain the accounts in
proper balance. When something prevents one of the statements in the transaction from executing, the
other statements of the transaction must be undone.
Note: Most of the DML statements in this lesson assume that no constraints on the table are violated.
Constraints are discussed later in the next lab. In SQL Developer, click the Run Script icon or press [F5]
to run the DML statements. The feedback messages will be shown on the Script Output tabbed page.

INSERT Statement

INSERT INTO table [(column [, column...])]


VALUES (value [, value...]);

We can add new rows to a table by issuing the INSERT statement. In the above syntax:
• table is the name of the table
• column is the name of the column in the table to populate
• value is the corresponding value for the column
Note: This statement with the VALUES clause adds only one row at a time to a table.
The INSERT statement can also be used to add rows to a table where the values are derived from existing
tables. To do that, in place of the VALUES clause, you use a subquery as in the following syntax:

INSERT INTO table [(column [, column...])]


VALUES subquery;

The number of columns and their data types in the column list of the INSERT clause must match the
number of values and their data types in the subquery. Zero or more rows are added depending on the
number of rows returned by the subquery.
While insertion, the Oracle server automatically enforces all data types, data ranges, and data integrity
constraints. Any column that is not listed explicitly obtains a null value in the new row unless we have
default values for the missing columns that are used. Common errors that can occur during user input are
checked in the following order:
• Mandatory value missing for a NOT NULL column
• Duplicate value violating any unique or primary key constraint
• Any value violating a CHECK constraint
• Referential integrity maintained for foreign key constraint
• Data type mismatches or values too wide to fit in column

95
UPDATE Statement

We can modify the existing values in a table by using the UPDATE statement.

UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

In the above syntax:


• table is the name of the table
• column is the name of the column in the table to populate
• value is the corresponding value or subquery for the column
• condition identifies the rows to be updated and is composed of column names, expressions,
constants, subqueries, and comparison operators

Note: In general, use the primary key column in the WHERE clause to identify a single row for update.
Using other columns can unexpectedly cause several rows to be updated. For example, identifying a
single row in the EMPLOYEES table by name is dangerous, because more than one employee may have
the same name.

DELETE Statement

DELETE [FROM] table


[WHERE condition];

We can remove existing rows from a table by using the DELETEstatement. In the above syntax:
• table is the name of the table
• condition identifies the rows to be deleted, and is composed of column names, expressions,
constants, subqueries, and comparison operators
Note: If no rows are deleted, the message “0 rows deleted” is returned (on the Script Output tab in SQL
Developer).

2) Solved Lab Activites

Activity No Allocated Time Level of complexity CLO Mapping


Activity 1 5 mins Low CLO-5
Activity 2 5 mins Low CLO-5
Activity 3 5 mins Low CLO-5
Activity 4 5 mins Low CLO-5
Activity 5 5 mins Low CLO-5
Activity 6 5 mins Low CLO-5
Activity 7 5 mins Low CLO-5

96
Activity 8 5 mins Low CLO-5
Activity 9 5 mins Low CLO-5
Activity 10 5 mins Low CLO-5
Activity 11 5 mins Low CLO-5
Activity 12 5 mins Low CLO-5

Activity 1: Inserting New Rows


In this lab activity, we are going to demonstrate the use of INSERT statement by inserting a row in
departments table. Because you can insert a new row that contains values for each column, the column
list is not required in the INSERT clause. However, if you do not use the column list, the values must
be listed according to the default order of the columns in the table, and a value must be provided for
each column. For clarity, it’s better use the column list in the INSERT clause. Normally, we enclose
character and date values within single quotation marks; however, it is not recommended that you
enclose numeric values within single quotation marks.

INSERT INTO departments (department_id, department_name, manager_id,


location_id)
VALUES (70, 'Public Relations', 100, 1700);

Output

Activity 2: Inserting Rows with Null Values


While inserting rows having null values, we can use either of the two methods listed in the following
table:

Method Description
Implicit Omit the column from the column list.
Explicit Specify the NULL keyword in the VALUES list;
specify the empty string ('') in the VALUES list for character strings
and dates.

In this lab activity, we are going to insert rows in department table using both the methods.

Implicit method: Omit the column from the column list.

INSERT INTO departments (department_id, department_name)


VALUES (30, 'Purchasing');

Explicit method: Specify the NULL keyword in the VALUES clause.

97
INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);

Output

Activity 3: Inserting Special Values


In this lab activity, we are going to demonstrate the use of functions to enter special values in the
employees table. The following statement records information for employee Popp in the EMPLOYEES
table. It supplies the current date and time in the HIRE_DATE column. It uses the SYSDATE function
that returns the current date and time of the database server. You may also use the CURRENT_DATE
function to get the current date in the session time zone. You can also use the USER function when
inserting rows in a table. The USER function records the current username.

INSERT INTO employees (employee_id, first_name, last_name, email,


phone_number, hire_date, job_id, salary,
commission_pct, manager_id, department_id)
VALUES (113, 'Louis', 'Popp', 'LPOPP',
'515.124.4567',SYSDATE, 'AC_ACCOUNT', 6900, NULL,
205, 110);

Output

Activity 4: Inserting Specific Date and Time Values


The DD-MON-RR format is generally used to insert a date value. With the RR format, the system
provides the correct century automatically. You may also supply the date value in the DD-MON-YYYY
format. This is recommended because it clearly specifies the century and does not depend on the
internal RR format logic of specifying the correct century. If a date must be entered in a format other
than the default format (for example, with another century or a specific time), you must use the
TO_DATE function.

In this lab activity, we are going to record information for employee Raphealy in the EMPLOYEES
table. It sets the HIRE_DATE column to be February 3, 2003.

INSERT INTO employees


VALUES (114, 'Den', 'Raphealy', 'DRAPHEAL', '515.127.4561',
TO_DATE('FEB 3, 2003', 'MON DD, YYYY'), 'SA_REP', 11000,
0.2, 100, 60);

98
Output

Activity 5: Creating a Script


We can also save commands with substitution variables to a file and execute the commands in the file.
When the script file is run, you are prompted for input for each of the ampersand (&) substitution
variables. After entering a value for the substitution variable, click the OK button. The values that you
input are then substituted into the statement. This enables you to run the same script file over and over,
but supply a different set of values each time you run it.

In this lab activity, we are going to create a script with substitution variables to record information for
a department in the DEPARTMENTS table.

INSERT INTO departments (department_id, department_name, location_id)


VALUES (&department_id, '&department_name',&location);

Output

Activity 6: Copying Rows from Another Table


In this activity, we are going to use a subquery to fetch the data which in turn will be inserted into
sales_reps table. (Here we assume that we have already created the sales_reps table using the CREATE
TABLE statement which will be covered in the next lab)

INSERT INTO sales_reps (id, name, salary, commission_pct)


SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';

99
Output

Here’s another statement that creates a copy of the rows of employees table by using SELECT * in the
subquery:

INSERT INTO copy_emp


SELECT *
FROM employees;

Activity 7: Updating Rows in a Tables


The UPDATE statement modifies the values of a specific row or rows if the WHERE clause is
specified. In this activity, we are going to use the UPDATE statement to transfer the employee 113
(Popp) to department 50. If you omit the WHERE clause, values for all the rows in the table are
modified.

UPDATE employees
SET department_id = 50
WHERE employee_id = 113;
Output

Here’s another UPDATE statement to update an employee who was a SA_REP and has now changed his
job to an IT_PROG. Consequently, his JOB_ID needs to be updated and the commission field needs to be
set to NULL.

UPDATE employees
SET job_id = 'IT_PROG', commission_pct = NULL
WHERE employee_id = 114;

Activity 8: Updating Two Columns with a Subquery


In this activity, we are going to update multiple columns in the SET clause of an UPDATE statement
by writing multiple subqueries.

UPDATE employees
SET (job_id,salary) = (SELECT job_id,salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 103;

100
Output

Activity 9: Updating Rows Based on Another Table


In this lab activity, we are going to use the subqueries in the UPDATE statements to update values in
the copy_emp table based on the values from the EMPLOYEES table. It changes the department
number of all employees with employee 200’s job ID to employee 100’s current department number.

UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
WHERE employee_id = 100)
WHERE employee_id = (SELECT job_id
FROM employees
WHERE employee_id = 200);

Output

Activity 10: Deleting a Row from a Table


In this activity, we are going to use DELETE statement to delete the Finance department from the
DEPARTMENTS table.

DELETE FROM departments


WHERE department_name = 'Finance';

Output

However, if you omit the WHERE clause, all rows in the table are deleted. In the following statement, all
rows from the COPY_EMP table would get deleted, because no WHERE clause was specified.

DELETE FROM copy_emp;

Activity 11: Deleting Rows Based on Another Table


In the activity, we are going to use subqueries to delete rows from a table based on values from another
table. Specifically, we are going to delete all the employees in a department, where the department
name contains the string Public.

101
DELETE FROM employees
WHERE department_id IN
(SELECT department_id
FROM departments
WHERE department_name LIKE '%Public%');

Output

In the above statement, the subquery searches the DEPARTMENTS table to find the department number
based on the department name containing the string Public. The subquery then feeds the department
number to the main query, which deletes rows of data from the EMPLOYEES table based on this
department number.

Activity 12: Efficient method of Emptying a Table


A more efficient method of emptying a table is by using the TRUNCATE statement.

You can use the TRUNCATE statement to quickly remove all rows from a table or cluster. Removing
rows with the TRUNCATE statement is faster than removing them with the DELETE statement for the
following reasons:

• The TRUNCATE statement is a data definition language (DDL) statement and generates no
rollback information. Rollback information is covered later in this lab.
• Truncating a table does not fire the delete triggers of the table.

If the table is the parent of a referential integrity constraint, you cannot truncate the table. You need to
disable the constraint before issuing the TRUNCATE statement. Disabling constraints is covered in the
next lab.

TRUNCATE TABLE copy_emp;

3) Graded Lab Tasks


Note: The instructor can design graded lab activities according to the level of difficulty and complexity
of the solved lab activities. The lab tasks assigned by the instructor should be evaluated in the same lab

Lab Task 1
Write a SQL statement that increases the commission percentage for every employee in department 80 by
5%.

Lab Task 2
Write a SQL statement that inserts you as an employee.

102
Lab Task 3
Write a SQL statement that inserts Network Operations department located in Africa.

Lab Task 4
Write a SQL statement that updates the Sales department’s location to London

Lab Task 5
Write a SQL statement that deletes all the employees who works for Steven Kings

Lab Task 6
Write a SQL statement that deletes you as an employee.

103

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy