Sunteți pe pagina 1din 13

Section 3 Lesson 1: Review of SQL DML

Vocabulary
Identify the vocabulary word for each definition below:
DELETE- Statement used to remove existing rows in a table.
INSERT- Statement used to add new rows to a table.
MERGE Statement used to INSERT and/or UPDATE a target table, based on matching
values in a source table.
UPDATE Statement used to modify existing rows in a table.
DDL-When you create, change, or delete an object in a database.
DMLWhen you change data in an object (for example, by inserting or deleting rows).

Try It / Solve It

1. DELETE FROM students;
This SQL statement will:
A.Not execute due to wrong syntax
B.Delete the first row from STUDENTS
C.Delete all rows from STUDENTS
D.None of the above
Rezolvare: C.Delete all rows from STUDENTS


2. INSERT INTO STUDENTS (id, last_name, first_name)
VALUES (29,'Perez','Jessica');

This SQL statement:
a. Does an explicit insert
b.Does an implicit insert
Rezolvare: Does an explicit insert

Use the following table for questions 3 through 8.
grocery_items
product_id brand description
110 Colgate Toothpaste
111 Ivory Soap
112 Heinz Ketchup


3. Write a SQL statement to create the above table.
Rezolvare:
CREATE TABLE grocery_items
(
product_id NUMBER(3,0),
brand VARCHAR2(20),
descriptionVARCHAR2(20));

4. Write and execute three SQL statements to explicitly add the above data to the table.
Rezolvare:
INSERT INTO grocery_items(product_id, brand, description) VALUES (110, Colgate,
Toothpaste)
INSERT INTO grocery_items(product_id, brand, description) VALUES (111, Ivory, Soap)
INSERT INTO grocery_items(product_id, brand, description) VALUES (112, Heinz,
Ketchup)

5. Write and execute a SQL statement that will explicitly add your favorite beverage to the table.
Rezolvare:
INSERT INTO grocery_items(product_id, brand, description) VALUES (113, Fanta, Soda)

6. Write and execute a SQL statement that modifies the description for Heinz ketchup to tomato
catsup.
Rezolvare:
UPDATE grocery_items SET description = tomato catsup WHERE brand = Heinz

7.Write and execute a SQL statement that will implicitly add your favorite candy to the table.
Rezolvare:
INSERT INTO grocery_items VALUES (114, Halls, Candy)

8.Write and execute a SQL statement that changes the soap brand from Ivory to Dove.
Rezolvare:
UPDATE grocery_items SET brand = Dove WHERE brand = Ivory

Use the following table for questions 9 through 14.
new_items
product_id brand description
110 Colgate Dental paste
175 Dew Soda
275 Palmolive Dish detergent

9. Write and execute SQL statements to create the new_items table and populate it with the data
in the table.
Rezolvare:
CREATE TABLE new_items
(
product_id NUMBER(3,0),
brand VARCHAR2(20),
descriptionVARCHAR2(20));




INSERT INTO new_items(product_id, brand, description) VALUES (110, Colgate,
Dentalpaste)
INSERT INTO new_items(product_id, brand, description) VALUES (175, Dew, Soda)
INSERT INTO new_items(product_id, brand, description) VALUES (275, Palmolive, Dish
detergent)

10. Write a SQL statement that will update the grocery_items table with the brand and description
from the new_items table when the product ID values match. If they dont match, add a new
row to the grocery_items table. DO NOT EXECUTE YOUR STATEMENT YET.
Rezolvare:

MERGE INTO grocery_items a
USING new_items i
ON (a.produc_id = i.product_id)
WHEN MATCHED
THEN UPDATE SET
a.brand= i.brand, a.description= i.description
WHEN NOT MATCHED
THEN INSERT VALUES(i.product_id, i.brand, i.description);

11. How many rows will be updated by the SQL statement in question 10?
Rezolvare:1

12. How many rows will be inserted by the SQL statement in question 10?
Rezolvare:2

13.Which of the following is true about the SQL statement in question 10?
A. new_items is the source table and grocery_items is the target table.
B. grocery_items is the source table and new_items is the target table.
Rezolvare: new_items is the source table and grocery_items is the target table.

14.Execute the SQL statement you wrote in question 10, and then SELECT all data from the target
table to verify your answers to questions 11 and 12.
Rezolvare: Aceleasi rezultate



Section 3 Lesson 2: Retrieving Data in PL/SQL

Vocabulary
No new vocabulary for this lesson

Try It / Solve It
1. State whether each of the following SQL statements can be included directly in a PL/SQL block.

Statement Valid in Not Valid
PL/SQL in PL/SQL
ALTER USER SET password='oracle'; X

CREATE TABLE test (a NUMBER); X

DROP TABLE test;

SELECT emp_id INTO v_id FROM employees; X

GRANT SELECT ON employees TO PUBLIC; X

INSERT INTO grocery_items (product_id, brand, description) X
VALUES (199,'Coke','Soda');
REVOKE UPDATE ON employees FROM PUBLIC; X

ALTER TABLE employees X
RENAME COLUMN employee_id TO emp_id;
DELETE FROM grocery_items X
WHERE description='Soap';



2.Create a PL/SQL block that selects the maximum department_id in the departments table and
stores it in the v_max_deptno variable. Display the maximum department_id.

A.Declare a variable v_max_deptno of the same datatype as the department_id column.

B.Start the executable section with the keyword BEGIN and include a SELECT statement
to retrieve the highest department_id from the departments table.

C. Display the variable v_max_deptno and end the executable block

D.Execute your block.

DECLARE
v_dept_id departments.department_id%TYPE;
BEGIN
SELECT MAX(department_id)
INTO v_dept_id
FROM departments;
DBMS_OUTPUT.PUT_LINE( v_dept_id);
END;



190

Statement processed.

3.The following code is supposed to display the lowest and highest elevations for a country name
entered by the user. However, the code does not work. Fix the code by following the guidelines for
retrieving data that you learned in this lesson.

DECLARE
v_country_name wf_countries.country_name%TYPE := 'United States of America';
v_lowest_elevation wf_countries.lowest_elevation%TYPE;
v_highest_elevation wf_countries.highest_elevation%TYPE;
BEGIN
SELECT lowest_elevation,
highest_elevation FROM wf_countries;
DBMS_OUTPUT.PUT_LINE('The lowest elevation
in '||v_country_name||' is '||v_lowest_elevation
||' and the highest elevation is
'|| v_highest_elevation||'.');
END;


DECLARE
v_country_name wf_countries.country_name%TYPE := 'United States of America';
v_lowest_elevation wf_countries.lowest_elevation%TYPE;
v_highest_elevation wf_countries.highest_elevation%TYPE;

BEGIN
SELECT lowest_elevation, highest_elevation
INTO v_lowest_elevation, v_highest_elevation
FROM wf_countries
WHERE country_name = v_country_name;

DBMS_OUTPUT.PUT_LINE('The lowest elevation in '||v_country_name||' is
'||v_lowest_elevation

||' and the highest elevation is '|| v_highest_elevation||'.');

END;

4.Enter and run the following anonymous block, observing that it executes successfully.

DECLARE
v_emp_lname employees.last_name%TYPE;
v_emp_salary employees.salary%TYPE;
BEGIN
SELECT last_name, salary INTO v_emp_lname,
v_emp_salary FROM employees
WHERE job_id = 'AD_PRES';
DBMS_OUTPUT.PUT_LINE(v_emp_lname||' '||v_emp_salary);
END;

A.Now modify the block to use IT_PROG instead of AD_PRES and re-run it. Why
does it fail this time?

ORA-01422: exact fetch returns more than requested number of rows

B.Now modify the block to use IT_PRAG instead of IT_PROG and re-run it. Why
does it still fail?

ORA-01403: no data found

5.Use the following code to answer this question:

DECLARE
last_name VARCHAR2(25) := Fay';
BEGIN
UPDATE emp_dup SET first_name = 'Jennifer'
WHERE last_name = last_name;
END;

What do you think would happen if you ran the above code? Write your answer here and
then follow the steps below to test your theory.

A. Create a table called emp_dup that is a duplicate of employees.

CREATE TABLE emp_dup
AS (SELECT * FROM employees);

B. Select the first_name and last_name values for all rows in emp_dup.

SELECT first_name, last_name FROM emp_dup;

C. Run the above anonymous PLSQL block.

Statement processed.

0.00 seconds

D. Select the first_name and last_name columns from emp_dup again to confirm your theory.

E. Now we are going to correct the code so that it changes only the first name for the
employee whose last name is Chen. Drop emp_dup and re-create it.

DECLARE
last_name VARCHAR2(25) := Chen';
BEGIN
UPDATE emp_dup SET first_name = 'Jennifer'
WHERE last_name = last_name;
END;

F. Modify the code so that for the employee whose last_name=Fay, the first_name is updated to
Jennifer. Run your modified block.

G. Confirm that your update statement worked correctly.

Extension Activity

1. Is it possible to name a column in a table the same name as the table? Create a table to
test this question. Don't forget to populate the table with data.
Rezolvare: NU

2. Is it possible to have a column, table, and variable, all with the same name? Using the
table
you created in the question above, write a PL/SQL block to test your theory.
Rezolvare: NU




Section 3 Lesson 3: Manipulating Data in PL/SQL


Vocabulary
Identify the vocabulary word for each definition below:
Cursor implicit- Defined automatically by Oracle for all SQL data manipulation statements,
and for queries that return only one row
Cursor explicit- Defined by the programmer for queries that return more than one row.
Merge- Statement selects rows from one table to update and/or insert into another table. The
decision whether to update or insert into the target table is based on a condition in the ON clause
Insert- Statement adds new rows to the table.
Delete - Statement removes rows from the table.
Update- Statement modifies existing rows in the table.

Try It / Solve It

1. True or False: When you use DML in a PL/SQL block, Oracle uses explicit cursors to track
the data changes.
Rezolvare True

2. Explicit cursors are created by the programmer.

3. I mplicit cursors are created by the Oracle server.

4. SQL%FOUND, SQL%NOTFOUND, and SQL%ROWCOUNT are cursor attributes, and are
available when you use implicit cursors.

The following questions use a copy of the departments table. Execute the following SQL
statement to create the copy table.

CREATE TABLE new_depts AS SELECT * FROM departments;

5. Examine and run the following PL/SQL code, which obtains and displays the maximum
department_id from new_depts.

DECLARE
v_max_deptno new_depts.department_id%TYPE;
BEGIN
SELECT MAX(department_id) INTO v_max_deptno
FROM new_depts;
DBMS_OUTPUT.PUT_LINE('The maximum department id is: '||
v_max_deptno);
END;


The maximum department id is: 190

Statement processed.

6. Modify the code to declare two additional variables, (assigning a new department name to one of
them) by adding the following two lines to your Declaration section:

v_dept_name new_depts.department_name%TYPE
:= 'A New Department' ;
v_dept_id new_depts.department_id%TYPE;

DECLARE
v_max_deptno new_depts.department_id%TYPE;
v_dept_name new_depts.department_name%TYPE := 'A New Department' ;

v_dept_id new_depts.department_id%TYPE;

BEGIN
SELECT MAX(department_id) INTO v_max_deptno
FROM new_depts;
DBMS_OUTPUT.PUT_LINE('The maximum department id is: '||
v_max_deptno);
END;

7. Modify the code to add 10 to the current maximum department number and assign the result
to v_dept_id.

DECLARE
v_max_deptno new_depts.department_id%TYPE;
v_dept_name new_depts.department_name%TYPE := 'A New Department' ;

v_dept_id new_depts.department_id%TYPE;
BEGIN
SELECT MAX(department_id) INTO v_max_deptno
FROM new_depts;
v_dept_id := v_max_deptno + 10;
DBMS_OUTPUT.PUT_LINE('The maximum department id is: '||
v_max_deptno);
DBMS_OUTPUT.PUT_LINE(v_dept_id: '||
v_dept_id);
END;


The maximum department id is: 190
v_dept_id: 200

Statement processed.

8. Modify the code to include an INSERT statement to insert a new row into the new_depts table,
using v_dept_id and v_dept_name to populate the department_id and department_name columns.
Insert NULL into the location_id and manager_id columns. Save your code.

DECLARE
v_max_deptno new_depts.department_id%TYPE;
v_dept_name new_depts.department_name%TYPE := 'A New Department' ;

v_dept_id new_depts.department_id%TYPE;
BEGIN
SELECT MAX(department_id) INTO v_max_deptno
FROM new_depts;
v_dept_id := v_max_deptno + 10;
INSERT INTO new_depts(department_id, department_name, manager_id, location_id)
VALUES(v_dept_id, v_dept_name, NULL, NULL)
END;

9. Execute the block and check that the new row has been inserted.


1 row(s) inserted.




10. Now modify the code to use SQL%ROWCOUNT to display the number of rows inserted, and
execute the block again.

DECLARE
v_max_deptno new_depts.department_id%TYPE;
v_dept_name new_depts.department_name%TYPE := 'A New Department' ;

v_dept_id new_depts.department_id%TYPE;
BEGIN
SELECT MAX(department_id) INTO v_max_deptno
FROM new_depts;
v_dept_id := v_max_deptno + 10;
INSERT INTO new_depts(department_id, department_name, manager_id, location_id)
VALUES(v_dept_id, v_dept_name, NULL, NULL);
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);
END;

1

1 row(s) inserted.

11. Now modify the block, removing the INSERT statement and adding a statement that will
UPDATE all rows with location_id = 1700 to location_id = 1400. Execute the block again to see
how many rows were updated.


DECLARE
v_max_deptno new_depts.department_id%TYPE;
v_dept_name new_depts.department_name%TYPE := 'A New Department' ;

v_dept_id new_depts.department_id%TYPE;
BEGIN
SELECT MAX(department_id) INTO v_max_deptno
FROM new_depts;
v_dept_id := v_max_deptno + 10;
UPDATE new_depts SET location_id = 1400 WHERE location_id=1700;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);
END;


4
200 A New Department - -

1 row(s) updated.





Section 3 Lesson 4: Using Transaction Control Statements


Vocabulary
Identify the vocabulary word for each definition below:
Transaction -An inseparable list of database operations, which must be executed either in its entirety
or not at all.
ROLLBACK-Used for discarding any changes that were made to the database after the last
COMMIT.
SAVE POINT Used to mark an intermediate point in transaction processing.
END Keyword used to signal the end of a PL/SQL block, not the end of a transaction.
COMMIT Statement used to make database changes permanent.


Try It / Solve It

For all the questions in this Practice, you need to disable the Autocommit feature in Application
Express, so that you can COMMIT and ROLLBACK transactions explicitly. Uncheck the
Autocommit check box in the top left corner of the SQL Commands window.

1. How many transactions are shown in the following code? Explain your reasoning.

BEGIN
INSERT INTO my_savings (account_id, amount)
VALUES (10377,200);
INSERT INTO my_checking(account_id, amount)
VALUES (10378,100);
END;
Rezolvare :1


2. Create the endangered_species table by running the following statement in Application
Express:

CREATE TABLE endangered_species
(species_id NUMBER(4)
CONSTRAINT es_spec_pk PRIMARY KEY,
common_name VARCHAR2(30)
CONSTRAINT es_com_name_nn NOT NULL,
scientific_name VARCHAR2(30)
CONSTRAINT es_sci_name_nn NOT NULL);




Table created.
3. Examine the following block. If you were to run this block, what data do you think would be
saved in the database?

BEGIN
INSERT INTO endangered_species
VALUES (100, Polar Bear,Ursus maritimus);
SAVEPOINT sp_100;
INSERT INTO endangered_species
VALUES (200, Spotted Owl,Strix occidentalis);
SAVEPOINT sp_200;
INSERT INTO endangered_species
VALUES (300, Asiatic Black Bear,Ursus thibetanus);
ROLLBACK TO sp_100;
COMMIT;
END;

Rezolvare: 100, Polar Bear, Ursus maritimus


4. Run the block to test your theory. Select from the table to confirm the result.
Rezolvare:
SPECIES_ID COMMON_NAME SCIENTIFIC_NAME
100 Polar Bear Ursus maritimus

5. Examine the following block. If you were to run this block, what data do you think would be
saved in the database?

BEGIN
INSERT INTO endangered_species
VALUES (400, 'Blue Gound Beetle','Carabus intricatus');
SAVEPOINT sp_400;
INSERT INTO endangered_species
VALUES (500, 'Little Spotted Cat','Leopardus tigrinus');
ROLLBACK;
INSERT INTO endangered_species
VALUES (600, 'Veined Tongue-Fern','Elaphoglossum nervosum');
ROLLBACK TO sp_400;
END;

Rezolvare: nu se salveaza nimic

6. Run the block to test your theory.

'SP_400' never established in this session or is invalid

S-ar putea să vă placă și