Professional Documents
Culture Documents
Lab Manual
for
ORACLE LAB
Semester IV
Subject Code: CP 09 04 07
Rev .0 June-2017
CREATE:
Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR
(5));
SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of a relation.
Syntax: SELECT a set of fields FROM relation_name WHERE condition;
Example: SQL> select * FROM dept WHERE deptno<=20;
DEPTNO DNAME LOC
------ ----------- ------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
9 Identify the use of the comparison operators used in a WHERE clause to restrict the
query results.
For example, the following query retrieves the rows from the Product table for the
products that are in class H.
For example, the following query retrieves products that fall in a list of colors.
SELECT s.Name
FROM AdventureWorks2008R2.Sales.Customer c
JOIN AdventureWorks2008R2.Sales.Store s
ON c.CustomerID = S.CustomerID
WHERE c.CustomerID IS NOT NULL
ORDER BY s.Name;
11 Identify the methods of the sorting result set of a query using the ORDER BY clause.
FROM employees
OR EMPLOYEE_ID = &EMPNO;
(1) All the dependent columns or columns used in GROUP BY function must form the
basis of grouping, hence must be included in GROUP BY clause also.
FROM employees;
ERROR at line 2:
(2) GROUP BY clause does not support the use of column alias, but the actual names.
(3) GROUP BY clause can only be used with aggregate functions like SUM, AVG,
COUNT, MAX, and MIN.If it is used with single row functions,Oracle throws and
exception as "ORA-00979: not a GROUP BY expression".
(4) Aggregate functions cannot be used in a GROUP BY clause. Oracle will return the
"ORA-00934: group function not allowed" here error message.
FROM employees
GROUP BY DEPARTMENT_ID;
Similarly, below query to find sum of salaries for respective job ids in each department.
Note the group is established based on Department and Job id. So they appear in
GROUP BY clause.
FROM employees
The below query also produces the same result. Please note that grouping is based on
the department id and job id columns but not used for display purpose.
FROM employees
SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY ROLLUP (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;
CUBE
In addition to the subtotals generated by the ROLLUP extension, the CUBE extension
will generate subtotals for all combinations of the dimensions specified. If "n" is the
number of columns listed in the CUBE, there will be 2n subtotal combinations.
SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY CUBE (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;
18 rows selected.
The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
ALTER TABLE table_name
MODIFY column_name datatype;
DROP TABLE Shippers;
Oracle View
In Oracle, view is a virtual table that does not physically exist. It is stored in Oracle data
dictionary and do not store any data. It can be executed when called.
A view is created by a query joining one or more tables.
17 Identify syntax for performing various tasks for managing views.
Oracle CREATE VIEW
Syntax:
1. CREATE VIEW view_name AS
2. SELECT columns
3. FROM tables
4. WHERE conditions;
Parameters:
oview_name: It specifies the name of the Oracle VIEW that you want to create.
Example:
Let's take an example to create view. In this example, we are creating two tables
suppliers and orders first.
Suppliers table:
1.
OR REPLACE
Allows you to recreate the synonym (if it already exists) without having to issue a
DROP synonym command.
PUBLIC
It means that the synonym is a public synonym and is accessible to all users.
Remember though that the user must first have the appropriate privileges to the
object to use the synonym.
schema
The appropriate schema. If this phrase is omitted, Oracle assumes that you are
referring to your own schema.
object_name
The name of the object for which you are creating the synonym. It can be one of
the following:
table
view
sequence
stored procedure
function
package
materialized view
java class schema object
user-defined object
synonym
Example
For example:
SELECT *
FROM suppliers;
If this synonym already existed and you wanted to redefine it, you could always use
the OR REPLACE phrase as follows:
Drop synonym
Once a synonym has been created in Oracle, you might at some point need to drop the
synonym.
Syntax
The syntax to drop a synonym in Oracle is:
PUBLIC
Allows you to drop a public synonym. If you have specified PUBLIC, then you
don't specify a schema.
force
It will force Oracle to drop the synonym even if it has dependencies. It is probably
not a good idea to use force as it can cause invalidation of Oracle objects.
Example
Let's look at an example of how to drop a synonym in Oracle.
For example:
This DROP statement would drop the synonym called suppliers that we defined earlier.
19 Identify the syntax for creating and dropping indexes.
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
Create Sequence
Syntax
The syntax to create a sequence in Oracle is:
sequence_name
The name of the sequence that you wish to create.
Example
Let's look at an example of how to create a sequence in Oracle.
For example:
Now that you've created a sequence object to simulate an autonumber field, we'll cover
how to retrieve a value from this sequence object. To retrieve the next value in the
sequence order, you need to use nextval.
For example:
supplier_seq.NEXTVAL;
Drop Sequence
Once you have created your sequence in Oracle, you might find that you need to
remove it from the database.
Syntax
The syntax to a drop a sequence in Oracle is:
sequence_name
The name of the sequence that you wish to drop.
Example
Let's look at an example of how to drop a sequence in Oracle.
For example:
General functions
The SELECT query below demonstrates the use of NVL function.
FROM employees
Character functions
The SELECT query below demonstrates the use of CONCAT function to concatenate
two string values.
FROM employees
CONCAT(FIRST_NAME,LAST_NAME)
--------------------------------
EllenAbel
SundarAnde
MozheAtkinson
DavidAustin
The SELECT query below demonstrates the use of SUBSTR and INSTR functions.
SUBSTR function returns the portion of input string from 1st position to 5th position.
INSTR function returns the numeric position of character 'a' in the first name.
FROM employees
SUBST INSTR(FIRST_NAME,'A')
----- ---------------------
Ellen 0
Sunda 5
Mozhe 0
David 2
The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print
the employee and job information.
FROM employees
RPAD(FIRST_NAME,10,'_')||
-------------------------
Steven____________AD_PRES
Neena_______________AD_VP
Lex_________________AD_VP
Alexander_________IT_PROG
FROM dual;
ROUND(1372.472,1)
-----------------
1372.5
FROM dual;
TRUNC(72183,-2)
72100
FROM employees
EMPLOYEE_ID EMPLOYMENT_DAYS
----------- ---------------
100 3698.61877
101 2871.61877
102 4583.61877
103 2767.61877
Date functions
The SELECT query below demonstrates the use of MONTHS_BETWEEN,
ADD_MONTHS, NEXT_DAY and LAST_DAY functions.
FROM employees
----------- -----------------
100 121.504216
101 94.3751837
102 150.633248
103 90.9558289
FROM dual;
Syntax
SELECT first_name,
TO_NUMBER function
The TO_NUMBER function converts a character value to a numeric datatype. If the
string being converted contains nonnumeric characters, the function returns an error.
Syntax
The SELECT queries below accept numbers as character inputs and prints them
following the format specifier.
FROM DUAL
TO_NUMBER('121.23','9G999D99')
------------------------------
121.23
TO_NUMBER('1210.73','9999.99')
------------------------------
1210.73
TO_DATE function
The function takes character values as input and returns formatted date equivalent of
the same.
Syntax:
SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.',
'NLS_DATE_LANGUAGE = American')
FROM DUAL;
TO_DATE('
---------
15-JAN-89
ID OUTPUT
---------- ----------
1 ONE
2 ZERO
3 ZERO
4 ZERO
4 rows selected.
The NVL2 function accepts three parameters. If the first parameter value is not null it
returns the value in the second parameter. If the first parameter value is null, it returns
the third parameter.
The following query shows NVL2 in action.
ID OUTPUT
---------- ----------
1 TWO
2 THREE
3 THREE
4 THREE
4 rows selected.
FROM cust_order
FROM cust_order
29 Identify use of single row and multiple row sub queries sub queries to
retrieve from multiple tables.
Single-row subquery
You store information particular to products in one table, Products, and information
that pertains to sales orders in another table, SalesOrdersItems. The Products
table contains the information about the various products. The SalesOrdersItems
table contains information about customers' orders. If a company reorders products
when there are fewer than 50 of them in stock, then it is possible to answer the
question "Which products are nearly out of stock?" with this query:
SELECT ID, Name, Description, Quantity
FROM Products
WHERE Quantity < 50;
However, a more helpful result would take into consideration how frequently a
product is ordered, since having few of a product that is frequently purchased is
more of a concern than having few product that is rarely ordered.
You can use a subquery to determine the average number of items that a customer
orders, and then use that average in the main query to find products that are nearly
out of stock. The following query finds the names and descriptions of the products
which number less than twice the average number of items of each type that a
customer orders.
SELECT Name, Description
FROM Products WHERE Quantity < 2 * (
SELECT AVG( Quantity )
FROM SalesOrderItems
);
In the WHERE clause, subqueries help select the rows from the tables listed in the
FROM clause that appear in the query results. In the HAVING clause, they help
select the row groups, as specified by the main query's GROUP BY clause, that
appear in the query results.
The following example of a single-row subquery calculates the average price of the
products in the Products table. The average is then passed to the WHERE clause
ID Name UnitPrice
1999 Q1 r1 1023
1999 Q2 r1 2033
1999 Q3 r1 2998
1999 Q4 r1 3014
2000 Q1 r1 3114
The ANY and ALL keywords can be used in a similar manner. For example, the
following query returns the same results as the previous query, but uses the ANY
keyword:
SELECT *
FROM FinancialData
WHERE FinancialData.Code = ANY
( SELECT FinancialCodes.Code
FROM FinancialCodes
WHERE type = 'revenue' );
While the =ANY condition is identical to the IN condition, ANY can also be used with
inequalities such as < or > to give more flexible use of subqueries.
The ALL keyword is similar to the word ANY. For example, the following query lists
financial data that is not revenue:
SELECT *
FROM FinancialData
WHERE FinancialData.Code <> ALL
( SELECT FinancialCodes.Code
FROM FinancialCodes
WHERE type = 'revenue' );
This is equivalent to the following command using NOT IN:
You can write subqueries that return multiple columns. The following example retrieves
the order amount with the lowest price, group by agent code.
SQL Code:
the agent_code of orders table must be the same agent_code of agents table and
agent_name of agents table must be Alex,
SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code=(
SELECT b.agent_code
Output:
SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code='A003';
Pictorical Presentation:
We have already used the EXISTS operator to check the existence of a result of a
subquery. EXISTS operator can be used in correlated subqueries also. Using EXISTS
the following query display the employee_id, manager_id, first_name and last_name of
those employees who manage other employees.
SQL Code:
Output:
NOT EXISTS is logically opposite of EXISTS operator. NOT EXISTS is used when we
need to check if rows do not exist in the results returned by a subquery. Using NOT
EXISTS the following query display the employee_id, manager_id, first_name and
last_name of those employees who have no manager status. This query is opposite to
the previous one.
SQL Code:
31 Identify the use of different types of join to retrieve data from multiple
tables.
Natural Join
Consider the one-to-many relationship between the DEPARTMENTS and
EMPLOYEES tables.Each table has a column named DEPARTMENT_ID.This
column is the primary key of the DEPARTMENTS table and a foreign key of
the EMPLOYEES table.
FIRST_NAME DNAME
MILLER DEPT 1
JOHN DEPT 1
MARTIN DEPT 2
EDWIN DEPT 2
The below SELECT query joins the two tables by explicitly specifying the
join condition with the ON keyword.
ON (E.department_id = D.department_id);
USING Clause
Syntax:
USING (department_id);
Self Join
Consider EMPLOYEES table,which contains employee and their reporting
managers.To find manager's name for an employee would require a join on
the EMP table itself. This is a typical candidate for Self Join.
ON (e1.employee_id = e2.manager_id)
Outer Joins
1. Right Outer Join
JOHN 6000 10
EDWIN 2000 20
MILLER 2500 10
MARTIN 4000 20
30
EDWIN 2000 20
MILLER 2500 10
MARTIN 4000 20
30
ON e. depARTMENT_ID = d. depARTMENT_ID;
FIRST_NAME DEPARTMENT_ID
---------- --------------------
MAN -
JOHN 10
EDWIN 20
MILLER 10
MARTIN 20
- 30
To insert multiple rows into a table, you use the following Oracle INSERT
ALL statement:
1 INSERT ALL
2 INTO table_name(col1,col2,col3) VALUES(val1,val2, val3)
3 INTO table_name(col1,col2,col3) VALUES(val4,val5, val6)
4 INTO table_name(col1,col2,col3) VALUES(val7,val8, val9)
5 Subquery;
In this statement, each value expression val1, val2, or val3 must refer to a column
returned by the select list of the subquery.
Summary: in this tutorial, you will learn how to use the Oracle INSERT ALL statement to
insert multiple rows into a table or multiple tables.
In the previous tutorial, you have learned how to insert a row into a table. However, sometimes,
you may want to insert multiple rows into a table or multiple tables. In this case, you use the
Oracle INSERT ALL statement, which is also referred to as multitable insert statement.
Oracle provides you with two types of multitable insert statements: unconditional and
conditional.
To insert multiple rows into a table, you use the following Oracle INSERT ALL statement:
1 INSERT ALL
2 INTO table_name(col1,col2,col3) VALUES(val1,val2, val3)
If you want to use literal values instead of the values returned by the subquery, you use the
following subquery:
You can also use the INSERT ALL statement to insert rows into multiple tables as shown
below.
1 INSERT ALL
2 INTO table_name1(col1,col2,col3) VALUES(val1,val2, val3)
3 INTO table_name2(col1,col2,col3) VALUES(val4,val5, val6)
4 INTO table_name3(col1,col2,col3) VALUES(val7,val8, val9)
5 Subquery;
Conditional Oracle INSERT ALL Statement
The conditional multitable insert statement allows you to insert rows into tables based on
specified conditions.
The following shows the syntax of the conditional multitable insert statement:
34
INTO small_orders
INTO medium_orders
INTO special_orders
INTO large_orders
FROM employees
...
LEVEL Example The next example is similar to the preceding example, but uses
the LEVEL pseudocolumn to show parent and child rows:
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
...
FROM employees
King 100 1
...
Example of UNION
The First table,
ID Name
1 abhi
The Second table,
ID Name
2 adam
3 Chester
ID NAME
1 abhi
2 adam
3 Chester
Union All
This operation is similar to Union. But it also shows the duplicate rows.
ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
ID NAME
1 abhi
2 adam
2 adam
3 Chester
Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the
records which are common from both SELECT statements. In case of Intersect the
number of columns and datatype must be same. MySQL does not support INTERSECT
operator.
ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
ID NAME
2 adam
Minus
Minus operation combines result of two Select statements and return only those result
which belongs to first set of result. MySQL does not support INTERSECT operator.
Example of Minus
The First table,
ID NAME
2 adam
The Second table,
ID NAME
2 adam
3 Chester
ID NAME
1 abhi
DECLARE
num1 INTEGER;
num2 REAL;
BEGIN
null;
END;
39 Identify the syntax for declaring PL/SQL variables using the %type
attributes.
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('name=' || name);
DBMS_OUTPUT.PUT_LINE('surname=' || surname);
END;
name=Smith
surname=Jones
DECLARE
emp_rec employees%ROWTYPE;
my_empno employees.employee_id%TYPE := 100;
CURSOR c1 IS
SELECT department_id, department_name, location_id FROM
departments;
dept_rec c1%ROWTYPE;
BEGIN
SELECT * INTO emp_rec FROM employees WHERE employee_id =
my_empno;
IF (emp_rec.department_id = 20) AND (emp_rec.salary > 2000)
THEN
NULL;
END IF;
END;
/
DECLARE
customer_rec customers%rowtype;
BEGIN zzzzzzzzzzzzzzzz
FROM customers
WHERE id = 5;
END;
Customer ID: 5
Customer Name: Hardik
Customer Address: Bhopal
Customer Salary: 9000
DECLARE
CURSOR customer_cur is
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
END LOOP;
/
1 Ramesh
2 Khilan
3 kaushik
4 Chaitali
5 Hardik
6 Komal
TYPE
type_name IS RECORD
( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION],
field_name2 datatype2 [NOT NULL] [:= DEFAULT EXPRESSION],
...
field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION);
record-name type_name;
The Book record is declared in the following way −
DECLARE
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
DECLARE
BEGIN
IF (a = b) then
ELSE
END IF;
IF (a < b) then
ELSE
END IF;
ELSE
END IF;
a := 5;
b := 20;
IF ( a <= b ) THEN
END IF;
IF ( b >= a ) THEN
END IF;
IF ( a <> b ) THEN
ELSE
END IF;
END;
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either equal or less than b
SET SERVEROUTPUT ON
DECLARE
v_average_cost VARCHAR2(10);
BEGIN
INTO v_average_cost
FROM course;
v_average_cost);
END;
DECLARE
i number(1);
j number(1);
BEGIN
END;
50 Identify the syntax for controlling implicit cursors and use the
attributes.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
/
6 customers selected
c_id customers.id%type;
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
BEGIN
OPEN c_customers;
LOOP
END LOOP;
CLOSE c_customers;
END;
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
UPDATE table_name
SET set_clause
WHERE CURRENT OF cursor_name;
DELETE FROM table_name
WHERE CURRENT OF cursor_name;
DECLARE
net_earnings NUMBER := 0;
pe_ratio NUMBER;
BEGIN
pe_ratio := NULL;
pe_ratio := NULL;
past_due EXCEPTION;
acct_num NUMBER;
BEGIN
acct_num NUMBER;
BEGIN
END IF;
EXCEPTION
DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE
END;
IS
cnumber number;
cursor c1 is
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||
SQLCODE||' -ERROR- '||SQLERRM);
END;
total number(2) := 0;
BEGIN
FROM customers;
RETURN total;
END;
/
Function created.
DECLARE
stock_price NUMBER := 9.73;
net_earnings NUMBER := 0;
pe_ratio NUMBER;
BEGIN
-- Calculation might cause division-by-zero error.
pe_ratio := stock_price / net_earnings;
dbms_output.put_line('Price/earnings ratio = ' || pe_ratio);
END cust_sal;
/
Package created.
c_sal customers.salary%TYPE;
BEGIN
FROM customers
WHERE id = c_id;
END find_sal;
END cust_sal;
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
DECLARE
BEGIN
END;
62 Write program to show use of new and old keywords in a trigger program.
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
/
63 Demonstrate the following TCL operations with suitable example
COMMIT
SAVEPOINT
ROLLBACK
SQL> COMMIT;
SQL> ROLLBACK;
SAVEPOINT SAVEPOINT_NAME;
Savepoint created.
1 row deleted.
Savepoint created.
1 row deleted.
Savepoint created.
1 row deleted.