Beruflich Dokumente
Kultur Dokumente
Date:
Objective:
Introduction to SQL. Also design SQL tables for Client Master & Product Master database
and display all the values.
Software Used:
Oracle 12c & DataGrip IDE
i) Client_master
columnname datatype size
client_no varchar2 6
name varchar2 20
address1 varchar2 30
address2 varchar2 30
city varchar2 15
state varchar2 15
pincode number 6
bal_due number 10,2
ii) Product_master
Columnname datatype size
Product_no varchar2
Description varchar2
Profit_percent number
Unit_measure varchar2
Qty_on_hand number
Reoder_lvl number
Sell_price number
Cost_price number
Q3:- On the basis of above two tables answer the following Questionnaires:
View definition-
The SQL DDL includes commands for defining views.
Transaction Control- SQL includes for specifying the beginning and ending of transactions.
Embedded SQL and Dynamic SQL-
Embedded and Dynamic SQL define how SQL statements can be embedded with in general purpose
programming languages, such as C, C++, JAVA, COBOL, Pascal and Fortran.
Integrity-
The SQL DDL includes commands for specifying integrity constraints that the data stored in the
database must specify. Updates that violate integrity constraints are allowed.
Authorization-
The SQL DDL includes commands for specifying access rights to relations and views.
The SQL DDL allows specification of not only a set of relations but also information about each
relation, including-
Schema for each relation
The domain of values associated with each attribute.
The integrity constraints.
The set of indices to be maintained for each relation.
The security and authorization information for each relation.
The physical storage structure of each relation on disk.
Syntax-
Create table tablename
(columnname datatype(size), columnname datatype(size));
Creating a table from a table-
Syntax-
CREATE TABLE TABLENAME
[(columnname, columnname, ………)]
AS SELECT columnname, columnname……..FROM tablename;
Insertion of data into tables-
Syntax-
INSERT INTO tablename
[(columnname, columnname, ………)]
Values(expression, expression);
Syntax-
INSERT INTO tablename
SELECT columnname, columnname, …….
FROM tablename;
Syntax-
INSERT INTO tablename
SELECT columnname, columnname……..
FROM tablename
WHERE columnname= expression;
Syntax-
SELECT * FROM tablename;
Syntax-
SELECT columnname, columnname, ….
FROM tablename;
Syntax-
SELECT DISTINCT columnname, columnname
FROM tablename;
Output:
Query:
Result:
i. ii.
Query:
Result:
i. client_master
ii. product_master
Ans 3.
Result:
ii. Retrieve the list of names and cities of all the clients.
Result :
iii. List the various products available from the product_master table.
Result:
iv. List all the clients who are located in Bombay.
Result:
Result:
vi. Find the products with description as ‘1.44 drive’ and ‘1.22 Drive’.
Result:
vii. Find all the products whose sell price is greater than 5000.
Result:
viii. Find the list of all clients who stay in in city ‘Bombay’ or city ‘Delhi’ or ‘Madras’.
Result:
ix. Find the product whose selling price is greater than 2000 and less than or equal to 5000.
Query: select * from product_master where sell_price >2000 and sell_price <= 5000;
Result:
x. List the name, city and state of clients not in the state of ‘Maharashtra’.
Query: select name,city,state from client_master where state !='Maharashtra' or state is null;
Result:
Experiment 2
Date:
Objective:
Create the SQL queries for commands like update, alter, rename, delete and drop.
Software Used:
Oracle 12c & DataGrip IDE
Q1 Using the table client master and product master answer the following questionnaires.
Deletion Operation:-
A delete reQuestionst is expressed in much the same way as Questionry. We can delete whole tuple
( rows) we can delete values on only particulars attributes.
Syntax:
Delete from tablename :
+ Addition - Subtraction
* multiplication ** exponentiation
/ Division () Enclosed operation
Renaming columns used with Expression Lists: - The default output column names can be renamed
by the user if required
Syntax:
Logical Operators:
The logical operators that can be used in SQL sentenced are
AND all of must be included
OR any of may be included
NOT none of could be included
Pattern Searching:
The most commonly used operation on string is pattern matching using the operation ‘like’ we
describe patterns by using two special characters.
Percent (%) ; the % character matches any substring we consider the following examples.
‘Perry %’ matches any string beginning with perry
‘% idge % matches any string containing’ idge as substring.
‘ - - - ‘ matches any string exactly three characters.
‘ - - - % matches any string of at least of three characters.
Oracle functions:
Functions are used to manipulate data items and return result. function follow the format of function
_name (argument1, argument2 ..) .An arrangement is user defined variable or constant. The structure
of function is such that it accepts zero or more arguments.
Examples:
Avg return average value of n
Syntax:
Avg ([distinct/all]n)
Min return minimum value of expr.
Syntax:
MIN((distict/all )expr)
Count Returns the no of rows where expr is not null
Syntax:
Count ([distinct/all)expr]
Count (*) Returns the no rows in the table, including duplicates and those with nulls.
Max Return max value of expr
Syntax:
Max ([distinct/all]expr)
Sum Returns sum of values of n
Syntax:
Sum ([distinct/all]n)
Sorting of data in table
Syntax:
Select columnname, columnname
From table
Order by columnname;
Output:
Result:
Result:
Result:
iv. Find the products whose selling price is more than 1500 and also find the new
selling price as original selling price *15.
Query: select description from product_master where sell_price > 1500;
update product_master set sell_price=sell_price*15;
select sell_price from product_master;
Result:
v. Find out the clients who stay in a city whose second letter is a.
Result:
vi. Find out the name of all clients having ‘a’ as the second letter in their names.
Result:
Result:
viii. Count the total number of orders
Result:
Result:
Result:
xi. Determine the maximum and minimum prices . Rename the tittle as ‘max_price’ and
min_price respectively.
Result:
xii. Count the number of products having price greater than or equal to 1500.
Query: select count (cost_price) from product_master where cost_price >= 1500;
Result:
xiii. Delete the record with client 0001 from the client master table.
Result:
Experiment 3
Date:
Objective:
To Implement the restrictions on the table.
Software Used:
Oracle 12c & DataGrip IDE
i. Sales_master
ii. Sales_order
iii. Sales_order_details
Insert the following data into their respective tables using insert statement:
Data constraints: Besides the cell name, cell length and cell data type there are other
parameters i.e. other data constrains that can be passed to the DBA at check creation time.
The constraints can either be placed at column level or at the table level.
i. Column Level Constraints: If the constraints are defined along with the column
definition, it is called a column level constraint.
ii. Table Level Constraints: If the data constraint attached to a specify cell in a table
reference the contents of another cell in the table then the user will have to use table
level constraints.
Null Value Concepts:- while creating tables if a row locks a data value for particular
column that value is said to be null . Column of any data types may contain null values
unless the column was defined as not null when the table was created
Syntax:
Create table tablename
(columnname data type (size) not null ……)
Primary Key: primary key is one or more columns is a table used to uniquickly identity
each row in the table. Primary key values must not be null and must be uniQuestion
across the column. A multicolumn primary key is called composite primary key.
UniQuestion key concept:-A uniQuestion is similar to a primary key except that the
purpose of a uniQuestion key is to ensure that information in the column for each
record is uniQuestion as with telephone or devices license numbers. A table may have
many uniQuestion keys.
Default value concept: At the line of cell creation a default value can be assigned to
it. When the user is loading a record with values and leaves this cell empty, the DBA
wil automatically load this cell with the default value specified. The data type of the
default value should match the data type of the column
Syntax:
Create table tablename
(columnname datatype (size) default value,….);
Foreign Key Concept : Foreign key represents relationship between tables. A foreign
key is column whose values are derived from the primary key of the same of some
other table . the existence of foreign key implies that the table with foreign key is
related to the primary key table from which the foreign key is derived .A foreign key
must have corresponding primary key value in the primary key table to have meaning.
Foreign key as a column constraint
Syntax :
Create table table name
(columnname datatype (size) references another table name);
Check Integrity Constraints: Use the check constraints when you need to enforce
intergrity rules that can be evaluated based on a logical expression following are a few
examples of appropriate check constraints.
A check constraints name column of the coient_master so that the name is
entered in upper case.
A check constraint on the client_no column of the client _master so that no
client_no value starts with ‘c’
Syntax:
Create table tablename
(columnname datatype (size) CONSTRAINT constraintname)
Check (expression));
Output:
Ans1.
Query:
Result:
ii. Create sales order table.
Query:
Result:
Query:
Result:
iv. Insert data into sales_master table.
Query:
Result:
Query:
Result:
Query:
Result:
Relationship b/w tables after references.
Experiment 4
Date:
Objective:
To Implement the structure of the table
Software Used:
Oracle 12c & DataGrip IDE
Challan_Header
Column name data type size Attributes
Challan_no varchar2 6 Primary key
s_order_no varchar2 6 Foreign key references s_order_no of
sales_order table
challan_date date not null
billed_yn char 1 values (‘Y’,’N’). Default ‘N’
Challan_Details
Column name data type size Attributes
Challan_no varchar2 6 Primary key
Product_no varchar2 6 Foreign key references to product_master
Qty_disp number 4,2 not null
Q2. Insert the following values into the challan header and challan_details tables:
Modifying the Structure of Tables- Alter table command is used to changing the structure
of a table. Using the alter table clause you cannot perform the following tasks:
The following tasks you can perform through alter table command.
NOTE: Oracle not allow constraints defined using the alter table, if the data in the table,
violates such constraints.
Syntax:
DROP TABLE tabename:
You can also define integrity constraints using the constraint clause in the ALTER TABLE
command. The following examples show the definitions of several integrity constraints.
You can drop an integrity constraint if the rule that if enforces is no longer true or if the
constraint is no longer needed. Drop the constraint using the ALTER TABLE command with
the DROP clause. The following examples illustrate the droping of integrity constraints.
Output:
Ans 1
Query:
Query:
Result:
ANS 2
Query:
Result:
ii. Insert data into challan_details table.
Query:
Result:
Ans 3
Query:
Query: :
iii. Add the not null constraint in the product_master table with the columns description,
profit percent , sell price and cost price.
Query:
Result: (* attributes with circle in bottom right corner represents not null)
iv. Change the size of client_no field in the client_master table.
Query:
Result:
v. Select product_no, description where profit percent is between 20 and 30 both inclusive.
Query:
Result:
Experiment 5
Date:
Objective:
To implement the concepts of joins.
Software Used:
Oracle 12c & DataGrip IDE
Theory:
Joint Multiple Table (Equi Join): Some times we require to treat more than one table as though
manipulate data from all the tables as though the tables were not separate object but one single
entity. To achieve this we have to join tables.Tables are joined on column that have dame data
type and data with in tables.
The tables that have to be joined are specified in the FROM clause and the joining
attributes in the WHERE clause.
1. CARTESIAN PRODUCT:-
Consider two table student and course
Select B.*,P.*
FROM student B, course P;
2. INNER JOIN:
Cartesian product followed by selection
Select B.*,P.*
FROM student B, Course P
WHERE B.course # P.course # ;
Exam:
Select B.*,P.*
From student B RIGHT JOIN course P
B.course# = P course # ;
Questionnaire’s:
1. Find out the product which has been sold to ‘Ivan Sayross.’
2. Find out the product and their quantities that will have do delivered.
3. Find the product_no and description of moving products.
4. Find out the names of clients who have purchased ‘CD DRIVE’
5. List the product_no and s_order_no of customers haaving qty ordered less than 5 from the order
details table for the product “1.44 floppies”.
6. Find the products and their quantities for the orders placed by ‘Vandan Saitwal ’ and “Ivan
Bayross”.
7. Find the products and their quantities for the orders placed by client_no “ C00001” and “C00002”
8. Find the order No,, Client No and salesman No. where a client has been received by more than
one salesman.
9. Display the s_order_date in the format “dd-mm-yy” e.g. “12- feb-96”
10. Find the date , 15 days after date.
Tables:
i. Product master
ii. Client master
Output:
1. Find out the product which has been sold to ‘Ivan Sayross.’
Query:
SELECT PRODUCT_MASTER.DESCRIPTION
FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS ON PRODUCT_MASTER.PRODUCT_NO =
SALES_ORDER_DETAILS.PRODUCT_NO
INNER JOIN SALES_ORDER ON SALES_ORDER_DETAILS.S_ORDER_NO = SALES_ORDER.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SALES_ORDER.CLIENT_NO = CLIENT_MASTER.CLIENT_NO WHERE
CLIENT_MASTER.NAME LIKE 'ivan';
2. Find out the product and their quantities that will have do delivered.
Query:
Query:
4. Find out the names of clients who have purchased ‘CD DRIVE’.
Query:
SELECT CLIENT_MASTER.NAME
FROM CLIENT_MASTER
INNER JOIN SALES_ORDER ON CLIENT_MASTER.CLIENT_NO = SALES_ORDER.CLIENT_NO
INNER JOIN SALES_ORDER_DETAILS S ON SALES_ORDER.S_ORDER_NO = S.S_ORDER_NO
INNER JOIN PRODUCT_MASTER MASTER2 ON S.PRODUCT_NO = MASTER2.PRODUCT_NO WHERE
MASTER2.DESCRIPTION LIKE 'CD_DRIVE';
5. List the product_no and s_order_no of customers haaving qty ordered less
than 5 from the order details table for the product “1.44 floppies”.
Query:
SELECT SALES_ORDER_DETAILS.S_ORDER_NO,SALES_ORDER_DETAILS.PRODUCT_NO
FROM SALES_ORDER_DETAILS
INNER JOIN PRODUCT_MASTER MASTER2 ON SALES_ORDER_DETAILS.PRODUCT_NO =
MASTER2.PRODUCT_NO WHERE
MASTER2.DESCRIPTION LIKE '1.44FLOPPIES' AND SALES_ORDER_DETAILS.QTY_ORDER <5;
6. Find the products and their quantities for the orders placed
by ‘Vandan Saitwal ’ and “Ivan Bayross”.
Query:
7. Find the products and their quantities for the orders placed by
client_no “ C00001” and “C00002”.
Query:
8. Find the order No,, Client No and salesman No. where a client has been
received by more than one salesman.
Query:
Query:
Query:
Objective:
To implement the concepts of grouping of data.
Software Used:
Oracle 12c & DataGrip IDE
Theory:
Questionnaire’s:
Q1.- Print the description and total quantity sold for each product.
Q2.- Find the value of each product sold.
Q3.- Calculate the average quantity sold for each client that has a maximum order value of 15000.
Q4.- Find out the products which has been sold to Ivan.
Q5.- Find the names of clients who have ‘CD Drive’.
Q6.- Find the products and their quantities for the orders placed by ‘Vandana’ and ‘Ivan’.
Q7.- Select product_no, total qty_ordered for each product.
Q8.- Select product_no, product description and qty ordered for each product.
Q9.- Display the order number and day on which clients placed their order.
Q10.- Display the month and Date when the order must be delivered.
Output:
i. Print the description and total quantity sold for each product.
Query:
Query:
Query:
iv. Find out the products which has been sold to Ivan.
Query:
SELECT PRODUCT_MASTER.DESCRIPTION
FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS ON PRODUCT_MASTER.PRODUCT_NO =
SALES_ORDER_DETAILS.PRODUCT_NO
INNER JOIN SALES_ORDER ON SALES_ORDER_DETAILS.S_ORDER_NO = SALES_ORDER.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SALES_ORDER.CLIENT_NO = CLIENT_MASTER.CLIENT_NO WHERE
CLIENT_MASTER.NAME LIKE 'ivan';
v. Find the names of clients who have ‘CD Drive’.
Query:
SELECT CLIENT_MASTER.NAME
FROM SALES_ORDER_DETAILS
INNER JOIN SALES_ORDER ON SALES_ORDER_DETAILS.S_ORDER_NO = SALES_ORDER.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SALES_ORDER.CLIENT_NO= CLIENT_MASTER.CLIENT_NO
INNER JOIN PRODUCT_MASTER MASTER2 on SALES_ORDER_DETAILS.PRODUCT_NO =
MASTER2.PRODUCT_NO WHERE
MASTER2.DESCRIPTION LIKE 'CD_drive';
vi. Find the products and their quantities for the orders placed by ‘Vandana’ and ‘Ivan’.
Query:
Query:
viii. Select product_no, product description and qty ordered for each product.
Query:
Query:
SELECT TO_CHAR(SALES_ORDER.S_ORDER_DATE,'DAY'),SALES_ORDER.S_ORDER_NO
FROM SALES_ORDER;
x. Display the month and Date when the order must be delivered.
Query:
SELECT TO_CHAR(SALES_ORDER.S_ORDER_DATE,'MONTH'),SALES_ORDER.DELY_DATE
FROM SALES_ORDER;
Experiment 7
Date:
Objective:
To implement the concepts of view and indexes.
Software Used:
Oracle 12c & DataGrip IDE
Theory:
Indexes:
An index is an ordered list of content of a column or group of columns in a table. An index created
on the single column of the table is called simple index. When multiple table columns are
included in the index it is called composite index.
Syntax (Simple)
CREATE INDEX index_name
ON tablename(column name);
Composite Index:-
CREATE INDEX index_name
ON tablename(columnname,columnname);
Creating an UniQuestion Index:-
CREATE UNIQUESTION INDEX indexfilename
ON tablename(columnname);
Dropping Indexes:-
An index can be dropped by using DROP INDEX
Syntax:-
DROP INDEX indexfilename;
Views:
Logical data is how we want to see the current data in our database. Physical data is how
this data is actually placed in our database.
Views are masks placed upon tables. This allows the programmer to develop a method
via which we can display predetermined data to users according to our desire.
Views may be created fore the following reasons:
1. The DBA stores the views as a definition only. Hence there is no duplication of data.
2. Simplifies Questionries.
3. Can be Questionried as a base table itself.
4. Provides data security.
5. Avoids data redundancy.
Creation of Views:-
Syntax:-
CREATE VIEW viewname AS
SELECT columnname,columnname
FROM tablename
WHERE columnname=expression_list;
Syntax:-
CREATE VIEW viewname AS
SELECT newcolumnname….
FROM tablename
WHERE columnname=expression_list;
Syntax:-
SELECT columnname, columnname
FROM viewname
WHERE search condition;
Destroying a view-
Syntax:-
DROP VIEW viewname;
Questionnaire’s:
Output:
Query:
Query:
iii. Create an composite index on the sales_order_details table for the columns
s_order_no and product_no.
Query:
iv. Create an composite index ch_index on challan_header table for the columns
challan no and s_order_no.
Query:
Query:
CREATE UNIQUE INDEX SYS_C0012063
ON SALES_MASTER (SALESMAN_NO);
Query:
Query:
Query:
Query:
Query:
Date:
Objective:
To implement the concepts of union, intersection and minus.
Software Used:
Oracle 12c & DataGrip IDE
Theory:
UNION
UNION ALL
Similar to UNION just that UNION ALL returns also the duplicated values.
When using UNION and UNION ALL columns in SELECT statements need to match.
This would return an error:
MINUS
MINUS (also known as EXCEPT) returns the difference between the first and second
SELECT statement. It is the one where we need to be careful which statement will be
put first, cause we will get only those results that are in the first SELECT statement
and not in the second.
INTERSECT
INTERSECT is opposite from MINUS as it returns us the results that are both to be
found in first and second SELECT statement.
SELECT * FROM table1
INTERSECT
SELECT * FROM table2;
EXAMPLE
There is an interesting example that us use SET OPERATORS to compare whether two
tables have identical values, testing symetric difference. If result of this entire query
returns no rows, it will mean that they are identical.
COMPOUND QUERIES
Each query in a compound query will project its own list of selected columns. These
lists must have the same number of elements, be nominated in the same sequence,
and be of broadly similar data type. They do not have to have the same names (or
column aliases), nor do they need to come from the same tables (or subqueries). If
the column names (or aliases) are different, the result set of the compound query
will have columns named as they were in the first query.
The corresponding columns in the queries that make up a compound query must be
of the same data type group. The result set of the compound query will have
columns with the higher level of precision.
UNION, MINUS, and INTERSECT will always combine the results sets of the input
queries, then sort the results to remove duplicate rows. If the sort order (which is
ascending, based on the order in which the columns happen to
appear in the select lists) is not the order you want, it is possible to put a single
ORDER BY clause at the end of the compound query. It is not possible to use ORDER
BY in any of the queries that make up the whole compound query, as this would
disrupt the sorting that is necessary to remove duplicates. UNION ALL is the
exception to the sorting-no-duplicates rule: the result sets of the two input queries
will be concatenated to form the result of the compound query.
Questionnaire’s:
1. Select distinct s_order_no from sales order and sales order no.
2. Select all s_order_no from sales order and sales order no.
3. Select client no’s of only those clients who have a sales order.
4. Select client no.’s of clients who have no sales order.
Output:
i. Select distinct s_order_no from sales order and sales order no.
Query:
Query:
iii. Select client no’s of only those clients who have a sales order.
Query:
Query:
Date:
Objective:
To implement the basics of pl sql.
Software Used:
Oracle 12c
Theory:
The PL/SQL programming language was developed by Oracle Corporation in the late
1980s as procedural extension language for SQL and the Oracle relational database.
Following are certain notable facts about PL/SQL −
PL/SQL is a completely portable, high-performance transaction-processing
language.
PL/SQL provides a built-in, interpreted and OS independent programming
environment.
PL/SQL can also directly be called from the command-line SQL*Plus interface.
Direct call can also be made from external programming language calls to
database.
PL/SQL's general syntax is based on that of ADA and Pascal programming
language.
Apart from Oracle, PL/SQL is available in TimesTen in-memory
database and IBM DB2.
Features of PL/SQL
Advantages of PL/SQL
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within
other PL/SQL blocks using BEGIN and END. Following is the basic structure of a
PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
Questionnaire’s:
Output:
Query:
DECLARE
MESSAGE VARCHAR2(20):= 'HELLO, WORLD!';
BEGIN
DBMS_OUTPUT.PUT_LINE(MESSAGE);
END;
ii. Add two numbers and display the result.
Query:
DECLARE
A NUMBER:=5;
B NUMBER:=6;
C INTEGER;
BEGIN
C:= A+B;
DBMS_OUTPUT.PUT_LINE('C: ' || C);
END;
Query:
DECLARE
A NUMBER:=&A;
B NUMBER:=&B;
C NUMBER:=&C;
SM NUMBER;
AV NUMBER;
BEGIN
SM:=A+B+C;
AV:=SM/3;
DBMS_OUTPUT.PUT_LINE('SUM = '||SM);
DBMS_OUTPUT.PUT_LINE('AVERAGE = '||AV);
END;
iv. Write a PL/SQL code block to find factorial of a number.
Query:
DECLARE
N NUMBER;
I NUMBER;
F NUMBER:=1;
BEGIN
N:=&N;
FOR I IN 1..N
LOOP
F:=F*I;
END LOOP;
DBMS_OUTPUT.PUT_LINE(N||'! = '||F);
END;
Query:
DECLARE
N NUMBER:=10;
I NUMBER;
SUM1 NUMBER:=0;
BEGIN
FOR I IN 1..N
LOOP
SUM1:=SUM1+I;
END LOOP;
DBMS_OUTPUT.PUT_LINE('SUM OF FIRST TEN NATURAL NO IS: ' || SUM1);
END;
vi. Print the name and salary of the employee John.
Query:
DECLARE
B EMP.NAME%TYPE;
C EMP.SALARY%TYPE;
BEGIN
SELECT NAME,SALARY INTO B,C FROM EMP WHERE NAME = 'JOHN';
DBMS_OUTPUT.PUT_LINE(B || ' ' || C);
END;
Experiment 10
Date:
Objective:
To implement the concept of cursors.
Software Used:
Oracle 12c
Theory:
Oracle creates a memory area, known as the context area, for processing an SQL
statement, which contains all the information needed for processing the statement;
for example, the number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set
of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors
−
Implicit cursors
Explicit cursors
Implicit Cursors
%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a
SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement
affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically
after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned
by a SELECT INTO statement.
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement which returns more than one
row.
The syntax for creating an explicit cursor is –
CURSOR cursor_name IS select_statement;
CURSOR c_customers IS
OPEN c_customers;
CLOSE c_customers;
Questionnaire’s:
Output:
Query:
DECLARE
A EMP.NAME%TYPE;
CURSOR C1 IS SELECT NAME FROM EMP;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE' || ' ' || A);
END LOOP;
CLOSE C1;
END;
Query:
DECLARE
EMPREC EMP%ROWTYPE;
BEGIN
SELECT * INTO EMPREC FROM EMP WHERE NAME = 'ALEX';
DBMS_OUTPUT.PUT_LINE(EMPREC.EMP_ID || ' ' || EMPREC.NAME || ' ' || EMPREC.SALARY);
END;
iii. Validate the input using exception.
Query:
DECLARE
S NUMBER:=&S;
EX EXCEPTION;
BEGIN
IF (S<=10) THEN RAISE EX;
END IF;
EXCEPTION
WHEN EX THEN DBMS_OUTPUT.PUT_LINE('ID MUST BE GREATER THAN 10');
END;
When s < 10
When s >10
iv. Update the salary of every employee’s with 500 using exception.
Query:
DECLARE
TNO NUMBER(3);
BEGIN
UPDATE EMP SET SALARY = SALARY + 500;
IF SQL%NOTFOUND
THEN DBMS_OUTPUT.PUT_LINE('NO RECORDS FOUND');
END IF;
IF SQL%FOUND THEN TNO:= SQL%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE(TNO);
END IF;
END;
Before updating:
After updating:
Experiment 11
Date:
Objective:
To implement the concept of functions and procedures.
Software Used:
Oracle 12c
Theory:
PROCEDURES:
A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or program
which is called the calling program.
A subprogram can be created −
Declarative Part
It is an optional part. However, the declarative part for a subprogram does
1 not start with the DECLARE keyword. It contains declarations of types,
cursors, constants, variables, exceptions, and nested subprograms. These
items are local to the subprogram and cease to exist when the subprogram
completes execution.
Executable Part
2 This is a mandatory part and contains statements that perform the
designated action.
Exception-handling
3 This is again an optional part. It contains the code that handles run-time
errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDUREstatement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
{IS | AS}
BEGIN
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT
represents the parameter that will be used to return a value outside of the
procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
Executing a Standalone Procedure
A standalone procedure can be called in two ways −
Using the EXECUTE keyword
Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as
EXECUTE procedure;
The following table lists out the parameter modes in PL/SQL subprograms
IN
1
An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter. Inside the subprogram, an IN parameter acts like a constant. It
cannot be assigned a value. You can pass a constant, literal, initialized
variable, or expression as an IN parameter. You can also initialize it to a
default value; however, in that case, it is omitted from the subprogram
call. It is the default mode of parameter passing. Parameters are passed
by reference.
OUT
An OUT parameter returns a value to the calling program. Inside the
2 subprogram, an OUT parameter acts like a variable. You can change its value
and reference the value after assigning it. The actual parameter must be
variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns
an updated value to the caller. It can be assigned a value and the value can
3 be read.
The actual parameter corresponding to an IN OUT formal parameter must
be a variable, not a constant or an expression. Formal parameter must be
assigned a value. Actual parameter is passed by value.
Positional notation
Named notation
Mixed notation
Positional Notation
In positional notation, you can call the procedure as
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for the first formal
parameter; the second actual parameter is substituted for the second formal
parameter, and so on. So, a is substituted for x, b is substituted for y, c is substituted
for z and d is substituted for m.
Named Notation
In named notation, the actual parameter is associated with the formal parameter
using the arrow symbol ( => ). The procedure call will be like the following −
findMin(x => a, y => b, z => c, m => d);
Mixed Notation
In mixed notation, you can mix both notations in procedure call; however, the
positional notation should precede the named notation.
The following call is legal
findMin(a, b, c, m => d);
Function:
A function is same as a procedure except that it returns a value. Therefore,
all the discussions of the previous chapter are true for functions too.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows –
Where,
Calling a Function
While creating a function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task. When a
program calls a function, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed
or when the last end statement is reached, it returns the program control back to the
main program.
To call a function, you simply need to pass the required parameters along with the
function name and if the function returns a value, then you can store the returned
value.
Questionnaire’s:
Query:
Query:
BEGIN
INSERTUSER(&A,'&B');
DBMS_OUTPUT.PUT_LINE('RECORDS INSERTED SUCCESSFULLY');
END;
iii. Write a function to find minimum of two numbers.
Query:
DECLARE
C NUMBER(8);
BEGIN
C:=F2(20,30);
DBMS_OUTPUT.PUT_LINE('OUTPUT ' || C);
END;
Query:
DECLARE
A NUMBER;
BEGIN
A:= 23;
SQUARENUM(A);
DBMS_OUTPUT.PUT_LINE(' SQUARE OF (23): ' || A);
END;
v. Write a function to find factorial of a number.
Query:
DECLARE
F NUMBER(3);
N NUMBER(3):=&N;
BEGIN
F:=FACT(N);
DBMS_OUTPUT.PUT_LINE('FACTORIAL= ' || F);
END;
Experiment 12
Date:
Objective:
To implement the concept of triggers.
Software Used:
Oracle 12c
Theory:
Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the
following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR,LOGON,LOGOFF,STARTUP,
or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event
is associated.
Benefits of Triggers
Triggers can be written for the following purposes −
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the
trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just
once when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in the
previous chapters −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.
This trigger will display the salary difference between the old values and new values
DECLARE
sal_diff number;
BEGIN
END;
/
When the above code is executed at the SQL prompt, it produces the following result-
Trigger created.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
Because this is a new record, old salary is not available and the above result comes as
null. Let us now perform one more DML operation on the CUSTOMERS table. The
UPDATE statement will update an existing record in the table −
UPDATE customers
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result –
Date: 10-10-2018
Objective:
To optimize the SQL queries in the best possible manner such that they require
minimum amount of operations and hence space.
1. Select c_name from customerl where cid in (Select c_id from depositor
INTERSECT select cid from borrower);
2. Select c_name from customer1 where cid in (Select cid from depositor where cid
(Select cid from borrower));