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

DBMS Practical Report

The document is a lab report submitted by three students for their Database Management System practical course. It provides an index of 16 topics that will be covered in the report related to SQL and PL/SQL concepts including data definition, data manipulation, data control languages, data constraints, functions, joins, views, indexes, sequences, control structures, subprograms, cursors, triggers, exception handling and packages. It also includes annexure with sample queries on employee and department tables.

Uploaded by

Sukhan Sandhu
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)
178 views

DBMS Practical Report

The document is a lab report submitted by three students for their Database Management System practical course. It provides an index of 16 topics that will be covered in the report related to SQL and PL/SQL concepts including data definition, data manipulation, data control languages, data constraints, functions, joins, views, indexes, sequences, control structures, subprograms, cursors, triggers, exception handling and packages. It also includes annexure with sample queries on employee and department tables.

Uploaded by

Sukhan Sandhu
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/ 94

1

UNIVERSITY INSTITUTE OF ENGINEERING AND TECHNOLOGY PANJAB


UNIVERSITY, SECTOR 25, CHANDIGARH

DATABASE MANAGEMENT SYSTEM(PRACTICAL) (CS-352)

LAB REPORT

CSE DEPARTMENT

BATCH : 2019-23

SUBMITTED BY:
 
UE193099 SARTHAK AGGARWAL 
UE193109 SUKHANDEEP SINGH 
UE193119 UTTAM SINGH

SUPERVISED BY:

DR. MAMTA JUNEJA

ASSISTANT PROFESSOR, CSE, UIET,

PANJAB UNIVERSITY, CHANDIGARH

[email protected]
2

INDEX
Sno  Content   Page  
No 

​1 Introduction to SQL: 1
A. Types of SQL commands:
DDL : Create, Rename, Alter,Describe, Truncate
DML : Insert, Update, Delete,Select
DCL : Grant ,Revoke
TCL : Commit, Rollback, Savepoint
B. Use of CREATE AS, USER_CONSTRAINTS,TAB, SPOOL ON

2 Data Constraints and its types:


A. Naming of a Constraint
B. ​Types of Constraints: Column level, Table
level ​a. Primary key
b. Foreign key
c. Unique
d. Not Null
e. Check
f. Default
C. Behaviors of foreign key table:
D. On delete/Update Restrict
E. On delete/Update Cascade
F. On delete/Update Set Null
G. Integrity constraints via Alter Table command

3 SQL Operators and functions:


A. 1.Operators:
a)Arithmetic
b)Logical
c)Relational
B. 2. Functions:
a)String functions
b)Numeric functions
c)Aggregate functions
d)Date functions

4 Order By, Group by and Having statements

5 Subqueries
A. ​Nested queries ( Single row​, ​Multi row)
B. Correlated queries
3

6 Joins:
A. Cross Join
B. Natural Join
C. Inner Join
D. Outer Join(left ,right and full)

7 Views
A. Introduction
B. Types: Materialised and View Resolution
C. Features/Advantages
D. CREATE, DROP VIEW( using single table, Multiple
Tables E. INSERT UPDATE DELETE IN VIEWS

8 Indexes
A. Introduction
B. Types: Unique, Duplicate, simple, Composite
C. CREATE, DROP INDEX ( on single column, multiple columns)

9 Sequence
A. Introduction
B. CREATE, DROP SEQUENCE
C. USING SEQUENCE TO INSERT VALUES IN COLUMN OF A
TABLE(ex employee id, student rollno etc)
D. ALTER SEQUENCE

10 Introduction to PL/SQL
A. Syntax of PL/SQL
B. Control structures in PL/SQL and their syntax

( Sequential control, Conditional , Iterative)

P1: To check if a year is a leap or not .


P2: To find area and circumference of a circle using a case
statement.
P3: To check whether a prime number or not using while loop
and for loop
P4: To generate fibonacci series
P5: To generate factorial of a given number
P6: To Check Palindrome
P7: To create a dummy calculator taking two numbers as input
as performing selected operation(Addition, subtraction,
multiply, etc) and displaying output
4

11 Subprograms in PL/SQL:
A. Introduction to Procedures
Syntax of Procedures
Write procedure for P1 to P7

B. Introduction to Functions
Syntax of Functions
Write function for P1 to P7

12 Cursors in PL/SQL
A. ​Introduction
B. ​Advantages and Disadvantages of cursor
C. ​Types of cursors:Implicit and Explicit Cursors
Program:To count the number of records using implicit
cursor.
Program:To display records of 5 least paid employees using
explicit cursor.
Program:To display records of 5 highest paid employees
using explicit cursor.

13. Triggers in PL/SQL


A. Introduction to Triggers
B. Advantages and disadvantages of triggers
C. Syntax of Triggers
D. Types of Triggers
Before event Triggers
After event Triggers
Row Trigger
Statement trigger
Hybrid Trigger
E. Write programs to demonstrate D

14 Exception Handling
A. System defined Exception handling
B. User defined Exception handling
C. Write Programs to demonstrate A and B

15 Package in PL/SQL
A. Introduction to Package
B. Package Specification
C. Package Body
D. WAP to Implement Package for your project

​16 Miscellaneous queries ( REFER ANNEXURE 1)


5

ANNEXURE 1
TABLE 1 : EMPLOYEE

TABLE 2 : DEPARTMENT

QUERY 1 : Give Total Salary issued by each Department


QUERY2 : Average salary of each job
QUERY3 : Give the total salary paid to each job within each Department QUERY4 : Give Total,
minimum, maximum and average salary of employees job wise for department numbers 1 and 2 and
displaying rows having average salary > 1,00,000 QUERY5 : Give name, salary of employee having
salary greater than minimum salary of department ‘Research’.
QUERY6 : Give name, salary of employees having salary greater than average salary of Department
‘HR’.
QUERY7 : List all details of the department whose ManagerID = ‘E006’. QUERY8 :
List all employees belonging to Department Finance
6
QUERY9 : List name of employees who do the same job as that of employee having EmployeeID =
‘E008’.
QUERY10 : List the name of employees who do the same job as an employee having EmployeeID =
‘E012’ and get the salary greater than the salary of that employee. QUERY11 : List the name and
salary of Employees who earn more than the Department of ‘Research’.
QUERY12 : List the name of employees who do not manage any Employee QUERY13 : List name of
employees who have at least one person reporting to them. QUERY14 : Give the name of employees
having salary (a)less than / (b)greater than minimum salary of ‘HR’ Department and are not of ‘HR’
department. QUERY15 : List the name of the highest paid employee.
QUERY16 : List the name of lowest paid employee.

1.
Introduction:
SQL stands for Structured Query Language. SQL lets you access and manipulate databases
❖ SQL can execute queries against a database
❖ SQL can retrieve data from a database
❖ SQL can insert records in a database
❖ SQL can update records in a database
❖ SQL can delete records from a database
❖ SQL can create new databases
❖ SQL can create new tables in a database
❖ SQL can create stored procedures in a database
❖ SQL can set permissions on tables, procedures, and views

Types of SQL Commands: (Full Forms)


1. DDL: Data Definition Language
2. DML: Data Manipulation Language
3. DCL: Data Control Language
4. TCL/TCC: Transactional Control Language/Command

1. DDL
A data definition language (DDL) is used to create and modify the structure of database
objects in a database. These database objects include views, schemas, tables, indexes, etc.It
is used to establish and modify the structure of objects in a database by dealing with
descriptions of the database schema.

● CREATE
It is used to create a new table.

SYNTAX
CREATE TABLE table_name (
column1 datatype,
7
column2 datatype,
column3 datatype,
.... );
CREATE TABLE PROGRAMME (
PROGRAMME_ID varchar2(6) not null constraint programme_pk primary key,
Type varchar2(15),
Extra_FEES number,
Max_Enroll number
)

● RENAME
This ​command is used to set a new name for any existing table.
SYNTAX
RENAME TABLE `current_table_name` TO `new_table_name`;

● ALTER
An alter command modifies an existing database table. This command can add up
additional columns ,drop existing columns and even change the data type of columns
involved in a database table.
Syntax
1. ALTER TABLE table_name ADD column_name datatype;
2.ALTER TABLE table_name modify(
column_name datatype
);
ALTER TABLE CUSTOMER ADD WEIGHT number(2);

● DESCRIBE
DESCRIBE is used to describe tables, that’s why we use DESCRIBE or
DESC(both are the same) command to describe the ​structure​ of a table.
SYNTAX
DESCRIBE <table_name>;
OR
DESC <table_name>;
DESC TABLE PROGRAMME;

● DROP
A DROP command is used to delete objects such as a table, index or view. A DROP
statement cannot be rolled back, so once an object is destroyed, there’s no way to
recover it.

SYNTAX
DROP TABLE table_name;
DROP TABLE TAKES_MEMBERSHIP;
8

● TRUNCATE
Similar to DROP, the TRUNCATE statement is used to quickly remove all records from
a table. However, unlike DROP that completely destroys a table, TRUNCATE preserves
its full structure to be reused later.

SYNTAX
TRUNCATE TABLE table_name;
TRUNCATE TABLE SALARY;

2.​DML​-DATA MANIPULATION LANGUAGE


A data manipulation language (​DML​) is used for adding (inserting), deleting, and modifying (updating)
data in a database.

● INSERT-–​ is used to insert data into a table.


Syntax
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);

INSERT INTO EQUIPMENT(Equipment_id,Type,Price)


VALUES('EQP256','TREADMILL','30000');

● UPDATE​ – is used to update existing data within a table.


SYNTAX
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE
condition;
UPDATE TRAINER
SET GRADE=2
WHERE EMP_ID=3017

● DELETE – is used to delete records from a database table.


SYNTAX
DELETE FROM table_name;

DELETE FROM PROGRAMME


WHERE TYPE='ZU​MBA';
9

● ​SELECT
It is used to retrieve data from a database.We can fetch either the entire table or the
columns that we want according to some specified rules. The data returned is stored in
a result table
SYNTAX
SELECT column1, column2, ...
FROM table_name
WHERE condition;

SELECT
SELECT GOAL
FROM CUSTOMER
WHERE CUSTOMER_ID=1029;

SELECT DISTINCT PROGRAMME_ID


FROM ENROLLS_IN;

DCL​-Data Control Language


DCL includes commands such as GRANT and REVOKE which mainly deals with the rights,
permissions and other controls of the database system.
● GRANT
It gives user’s access privileges to the database

SYNTAX

GRANT privileges
ON object
TO user;
10

● REVOKE
It withdraws user’s access privileges given by using the GRANT command.
SYNTAX
REVOKE privilege-type
ON [ TABLE ] { table-Name | view-Name }
FROM grantees
11
TCL​-Transaction Control Language
Transaction Control Language commands are used to manage transactions in the database.
These are used to manage the changes made by DML-statements. It also allows statements
to be grouped together into logical transactions.

● COMMIT​: Commit command is used to permanently save any transaction


into the database.
SYNTAX
COMMIT;

● ROLLBACK​: This command restores the database to the last committed state.
It is also used with savepoint command to jump to a savepoint
in a transaction.
SYNTAX
ROLLBACK TO savepoint_name;

● SAVEPOINT​: Savepoint command is used to temporarily save a transaction so


that you can rollback to that point whenever necessary.
SYNTAX
SAVEPOINT savepoint_name;

B.
CREATE AS- ​ Used to create copy of an existing table
12

USER_CONTRAINTS-​ it contains all constraints set by the user.


13

TAB- ​ ​The SQL Query tab shows the query code to be sent to the SQL server when this
database operation file is executed. This is helpful to verify that the database operation does what
you expect it to do.

SPOOL ON-

Spool on/off
Log the output of a MaxL Shell session to a file. Send standard output, informational messages, error messages,
and/or warning messages generated by the execution of MaxL statements to a file.

If FILE-NAME does not exist, it is created. If FILE-NAME already exists, it is overwritten. If a directory path is not
specified for FILE-NAME, FILE-NAME is created in the current directory of the MaxL Shell. Directories cannot be
created using the spool command.

Message logging begins with ​spool on​ and ends with ​spool off​.
14

Example

spool on to 'output.txt';

{MaxL statements}

spool off;

Sends output of MaxL statements to a file called output.txt, located in the current directory where the MaxL Shell
was invoked, or in eas\console\bin if the MaxL Script Editor is being used.

spool on to 'c:\hyperion\output.txt';

Sends output of MaxL statements to a file called output.txt, located in the pre-existing directory specified by an
absolute path.

spool on to '../../../output.txt';

Sends output of MaxL statements to a file called output.txt, located in the pre-existing directory specified by a
relative path. The file would be located three directories above the current directory, or three directories above
as\console\bin if the MaxL Script Editor is being used.

2.CONSTRAINTS
Constraints are the rules enforced on the data columns of a table. These are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in
the database.
Constraints could be either on a column level or a table level. The column level constraints
are applied only to one column, whereas the table level constraints are applied to the whole
table.
● NOT NULL Constraint​ − Ensures that a column cannot have NULL value.
● DEFAULT Constraint​ − Provides a default value for a column when none is specified.
● UNIQUE Constraint​ − Ensures that all values in a column are different.
● PRIMARY Key​ − Uniquely identifies each row/record in a database table.
● FOREIGN Key​ − Uniquely identifies a row/record in any of the given database tables.
● CHECK Constraint​ − The CHECK constraint ensures that all the values in a column
satisfies certain conditions.
● INDEX​ − Used to create and retrieve data from the database very quickly.
Constraints can be specified when a table is created with the CREATE TABLE statement or
you can use the ALTER TABLE statement to create constraints even after the table is
created.
15

1. Primary key
Primary Key is a field which uniquely identifies each row in the table. If a field in
a table as primary key, then the field will not be able to contain NULL values as
well as all the rows should have unique values for this field.

example:
create​ ​table​ MANAGER (
EMP_ID varchar2(​6​) ​not​ ​null​ c
​ onstraint​ manager_pk ​primary​ ​key​,
First_name varchar2(​15​) ​not​ n ​ ull​,
Last_name varchar2(​15​),
Phone_no ​number​ ​not​ ​null​,

Address varchar2(​25​),
DOB ​date​,
Grade ​number​,

Qualification varchar2(​25​)
)

2. Foreign key
Foreign Key is a field in a table which uniquely identifies each row of a another table.
That is, this field points to the primary key of another table. This usually creates a kind
of link between the tables.

create table MANAGE_MEMBERSHIP (


MEMBERSHIP_ID varchar2(6),
EMP_ID varchar2(6) ,
FOREIGN KEY (EMP_ID) REFERENCES MANAGER(EMP_ID)
);
OR
CREATE TABLE "SUKHAN"."MANAGE_MEMBERSHIP"
( "MEMBERSHIP_ID" VARCHAR2(6 BYTE) NOT NULL ENABLE,
"MANAGER_ID" VARCHAR2(6 BYTE),
CONSTRAINT "MANAGE_MEMBERSHIP_PK" PRIMARY KEY
("MEMBERSHIP_ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
TABLESPACE "USERS" ENABLE,
CONSTRAINT "MM_FK" FOREIGN KEY ("MANAGER_ID")
REFERENCES "SUKHAN"."MANAGER" ("EMP_ID") ENABLE
) SEGMENT CREATION DEFERRED
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
NOCOMPRESS LOGGING
TABLESPACE "USERS" ;
16

3. UNIQUE
This constraint helps to uniquely identify each rowin the table. i.e. for a particular
column, all the rows should have unique values. We can have more than one UNIQUE
column in a table.
create​ ​table​ TRAINER (
EMP_ID varchar2(​6​) ​not​ ​null​ ​constraint​ trainer_pk ​primary​ ​key​,
First_name varchar2(​15​) ​not​ ​null​,
Last_name varchar2(​15​),
Contact ​number​ ​not​ ​null​,
Address varchar2(​25​),
DOB ​date​,
Grade ​number​,
Unique(First_name,Last_name),
Experience varchar2(​10​)
)

4. NOT NULL
If we specify a field in a table to be NOT NULL.Then the field will never accept null
value. That is, you will be not allowed to insert a new row in the table without specifying
any value to this field.
create​ ​table​ TRAINER (
EMP_ID varchar2(​6​) ​not​ ​null​ ​constraint​ trainer_pk ​primary​ ​key​,
First_name varchar2(​15​) ​not​ ​null​,
Last_name varchar2(​15​),
Contact ​number​ ​not​ ​null​,
Address varchar2(​25​),
DOB ​date​,
Grade ​number​,
Unique(First_name,Last_name),
Experience varchar2(​10​)
)
Behaviors of Foreign Key Table

On Delete / Update Restart -


RESTRICT means that any attempt to delete and/or
17
update the parent will fail throwing an error. This is
the default behaviour in the event that a referential
action is not explicitly specified.Following query tries
to delete a row from the table Bill, but the Order
stable references the Bill table’s primary key, so it
throws an error.

On Delete / Update Set NULL -


Delete or update the row from the parent table, and
set the foreign key column or columns in the child
table to NULL. Oracle doesn’t support ON UPDATE
SET NULL.

On Delete / Update Cascade -


ON DELETE CASCADE means that if the parent
record is deleted, any child records are also
deleted. ONUPDATE CASCADE means that if the
parent primary key is changed, the child value will
also change to reflect that. Oracle doesn’t support
ON UP-DATE CASCADE

3​. OPERATORS
An operator is a reserved word or a character used primarily in an SQL
statement WHERE clause to perform operation(s), such as comparisons and
arithmetic operations. These Operators are used to specify conditions in an SQL
statement

SQL Arithmetic Operators


Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator. a + b will give 30

- (Subtraction) Subtracts right hand operand from left hand operand. a - b will give -10

* Multiplies values on either side of the operator.


a * b will give 200
(Multiplication)
18

/ (Division) Divides left hand operand by right hand operand. b / a will give 2

Divides left hand operand by right hand operand and returns


% (Modulus) b % a will give 0
remainder.

SQL Logical Operators


Sr.No Operator & Description
.

1 ALL-The ALL operator is used to compare a value to all values in another value set.

AND--The AND operator allows the existence of multiple conditions in an SQL


2
statement's WHERE clause.

ANY-The ANY operator is used to compare a value to any applicable value in the list as
3
per the condition.

BETWEEN--The BETWEEN operator is used to search for values that are within a set of
4
values, given the minimum value and the maximum value.

EXISTS-The EXISTS operator is used to search for the presence of a row in a specified
5
table that meets a certain criterion.

IN-The IN operator is used to compare a value to a list of literal values that have been
6
specified.
19

LIKE-The LIKE operator is used to compare a value to similar values using wildcard
7
operators.

NOT-The NOT operator reverses the meaning of the logical operator with which it is
8
used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

OR-The OR operator is used to combine multiple conditions in an SQL statement's


9
WHERE clause.

10 IS NULL-The NULL operator is used to compare a value with a NULL value.

UNIQUE--The UNIQUE operator searches every row of a specified table for uniqueness
11
(no duplicates).

Comparison Operators
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Show Examples

Operat Description Example


or

Checks if the values of two operands are equal or not, if yes then (a = b) is not
=
condition becomes true. true.

Checks if the values of two operands are equal or not, if values


!= (a != b) is true.
are not equal then the condition becomes true.

Checks if the values of two operands are equal or not, if values (a <> b) is
<>
are not equal then condition becomes true. true.
20

Checks if the value of left operand is greater than the value of (a > b) is not
>
right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than the value of right
< (a < b) is true.
operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the (a >= b) is not
>=
value of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than or equal to the (a <= b) is
<=
value of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is not less than the value of (a !< b) is
!<
right operand, if yes then condition becomes true. false.

Checks if the value of left operand is not greater than the value
!> (a !> b) is true.
of right operand, if yes then condition becomes true.

B.
a. STRING FUNCTIONS

Function  Example  Result  Purpose 

ASCII  ASCII(‘A’)  65  Returns an ASCII code value of a 


character. 

CHR  CHR(’65’)  ‘A’  Converts a numeric value to its 


corresponding ASCII character. 

CONCAT  CONCAT(‘A’,’BC’)  ‘ABC’  Concatenate two strings and return the 


combined string. 
21

CONVERT  CONVERT( ‘Ä Ê Í’,  ‘A E I’  Convert a character string from one 


‘US7ASCII’,  character set to another. 
‘WE8ISO8859P1’ ) 

DUMP  DUMP(‘A’)  Typ=96  Return a string value (VARCHAR2) that 


Len=1:  includes the datatype code, length 
65  measured in bytes, and internal 
representation of a specified 
expression. 

INITCAP  INITCAP(‘hi there’)  ‘Hi  Converts the first character in each 


There’  word in a specified string to uppercase 
and the rest to lowercase. 

INSTR  INSTR( ‘This is a  3  Search for a substring and return the 


playlist’, ‘is’)  location of the substring in a string 

LENGTH  LENGTH(‘ABC’)  3  Return the number of characters (or 


length) of a specified string 

LOWER  LOWER(‘Abc’)  ‘abc’  Return a string with all characters 


converted to lowercase. 

LPAD  LPAD(‘ABC’,5,’*’)  ‘**ABC’  Return a string that is left-padded with 


the specified characters to a certain 
length. 

LTRIM  LTRIM(‘ ABC ‘)  ‘ABC ‘  Remove spaces or other specified 


characters in a set from the left end of a 
string. 

REGEXP_COUNT  REGEXP_COUNT(‘1  3  Return the number of times a pattern 


2 3 abc’,’\d’)  occurs in a string. 

REGEXP_INSTR  REGEXP_INSTR(  2  Return the position of a pattern in a 


‘Y2K problem’,’\d+’)  string. 

REGEXP_LIKE  REGEXP_LIKE(  true  Match a string based on a regular 


‘Year of 2017′,’\d+’  expression pattern. 

22

REGEXP_REPLA REGEXP_REPLACE(  ‘Year of  Replace substring in a string by a new 


CE  ‘Year of 2017′,’\d+’,  Dragon’  substring using a regular expression. 
‘Dragon’ ) 

REGEXP_SUBST REGEXP_SUBSTR(  10  Extract substrings from a string using a 


R  ‘Number 10’, ‘\d+’ )  pattern of a regular expression. 

REPLACE  REPLACE(‘JACK  ‘BLACK  Replace all occurrences of a substring 


AND JOND’,’J’,’BL’);  AND  by another substring in a string. 
BLOND’ 

RPAD  RPAD(‘ABC’,5,’*’)  ‘ABC**’  Return a string that is right-padded with 


the specified characters to a certain 
length. 

RTRIM  RTRIM(‘ ABC ‘)  ‘ ABC’  Remove all spaces or specified 


character in a set from the right end of a 
string. 

SOUNDEX  SOUNDEX(‘sea’)  ‘S000’  Return a phonetic representation of a 


specified string. 

SUBSTR  SUBSTR(‘Oracle  ‘Oracle’  Extract a substring from a string. 


Substring’, 1, 6 ) 

TRANSLATE    ‘b2x5’  Replace all occurrences of characters 


TRANSLATE(‘1234 by other characters in a string. 
5’, ‘143’, ‘bx’) 

TRIM  TRIM(‘ ABC ‘)  ‘ABC’  Remove the space character or other 
specified characters either from the 
start or end of a string. 

UPPER  UPPER(‘Abc’)  ‘ABC’  Convert all characters in a specified 


string to uppercase. 

b.Numeric functions

Function Description and Example


23

addition The addition operator (+).

SELECT NortheastSales + SoutheastSales AS EastTotalSales

subtraction The subtraction operator (-).

SELECT SalesRevenue - TotalCosts AS Profit

multiplication The multiplication operator (*).

SELECT Price * 0.7 AS SalePrice

division The division operator (/).

SELECT YearTotal / 4 AS QuarterAvg

ABS Returns the absolute value of n.

If n is 0 or a positive integer, returns n.

Otherwise, n is multiplied by -1.

SELECT ABS(-1) AS one

RESULT: ​one = 1

CEIL Returns the smallest integer value not less than n.

SELECT CEIL(123.45) AS x, CEIL(32) AS y, CEIL(-123.45) AS z

RESULT: ​x = 124, y = 32, z = 123

EXP Exponentiation, where the base is e.

Returns the value of e (the base of natural logarithms) raised to the power n.

SELECT EXP(1.0) AS baseE

RESULT: ​baseE = e^1.0 = 2.71828182845905


24

FLOOR Returns the largest integer value not greater than n.

SELECT FLOOR(123.45) AS x, FLOOR(32) AS y, FLOOR(-123.45) AS z

RESULT: ​x = 123, y = 32, z = 124

LN Natural logarithm. Computes the logarithm of its single argument, the base of which is e.

SELECT LN(1.0) AS baseE

RESULT: ​baseE = e^1.0 = 0

LOG Logarithm. log(n, m) takes two arguments, where n is the base, and m is the value you are taking
the logarithm of.

Log(10,1000) = 3

MOD Modulo. Returns the remainder of n divided by m.

Mod(10,3) = 1

EQL uses the fmod floating point remainder, as defined in the C/POSIX standard.

ROUND Returns a number rounded to the specified decimal place.

The unary (one argument) version takes only one argument (the number to be rounded) and
drops the decimal (non-integral) portion of the input. For example:
ROUND(8.2) returns 8

ROUND(8.7) returns 9

The binary (two argument) version takes two arguments (the number to be rounded and a positive
or negative integer that allows you to set the number of spaces at which the number is rounded).
The binary version always returns a double:

● Positive second arguments correspond to the number of places that must be returned
after​ the decimal point. For example:
ROUND(123.4567, 3) returns 123.457

Negative second arguments correspond to the number of places that must be returned ​before​ the
decimal point. For example:
ROUND(123.4, -3) returns 0
25

● ROUND(1234.56, -3) returns 1000

SIGN Returns the sign of the argument as -1, 0, or 1, depending on whether n is negative, zero, or
positive. The result is always a double.

SELECT SIGN(-12) AS x, SIGN(0) AS y, SIGN(12) AS z

RESULT:​ x = -1, y = 0, z = 1

SQRT Returns the nonnegative square root of n.

SELECT SQRT(9) AS x

RESULT:​ x = 3

TRUNC Returns the number n truncated to m decimal places. If m is 0, the result has no decimal point or
fractional part.

The unary (one argument) version drops the decimal (non-integral) portion of the input. For
example:

SELECT TRUNC(3.14159265) AS x

RESULT:​ x = 3

The binary (two argument) version allows you to set the number of spaces at which the number is
truncated. The binary version always returns a double. For example:

SELECT TRUNC(3.14159265, 3) AS y

RESULT:​ y = 3.141

SIN The sine of n, where the angle of n is in radians.

SIN(3.14159/6) = 0.499999616987256
26

COS The cosine of n, where the angle of n is in radians.

COS(3.14159/3) = 0.500000766025195

TAN The tangent of n, where the angle of n is in radians.

TAN(3.14159/4) = 0.999998673205984

POWER Returns the value (as a double) of n raised to the power of m.

Power(2,8) = 256

TO_DURATION Casts a string representation of a timestamp into a number of milliseconds so that it can be used
as a duration.

TO_DOUBLE Casts a string representation of an integer as a double.

TO_INTEGER(boolea Casts TRUE/FALSE to 1/0.


n)

c. Aggregate functions
Function  Description 

AVG  Return the average of values of a set 

COUNT  Return the number of values in a set or number of rows in a 


table 

LISTAGG  Aggregate strings from multiple rows into a single string by 
concatenating them 

MAX  Return the maximum value in a set of values 

MIN  Return the minimum value in a set of values 


27

SUM  Returns the sum of values in a set of values 

d. Date functions 
 

Function  Example  Result  Description 

ADD_MONTHS  ADD_MONTHS( DATE ​ 1-MAR-16 


3 Add a number of 
'2016-02-29', 1 )  months (n) to a 
date and return 
the same day 
which is n of 
months away. 

CURRENT_DATE  ​ ELECT
S ​ 06-AUG-2017 Return the current 
CURRENT_DATE FROM 19:43:44  date and time in 
dual  the session time 
zone 

CURRENT_TIMESTA SELECT 06-AUG-17 Return the current 


MP  CURRENT_TIMESTAMP 08.26.52.742000 date and time 
FROM dual  000 PM ​-07:00  with time zone in 
the session time 
zone 

DBTIMEZONE  ​ ELECT DBTIMEZONE


S ​ 07:00 
- Get the current 
FROM dual;  database time 
zone 

EXTRACT  EXTRACT(YEAR FROM ​ 017 


2 Extract a value of 
SYSDATE)  a date time field 
e.g., YEAR, 
MONTH, DAY, … 
from a date time 
value. 
28

FROM_TZ  FROM_TZ(TIMESTAMP ​ 8-AUG-17


0 Convert a 
'2017-08-08 08.09.10.000000 timestamp and a 
08:09:10', 000 AM -07:00  time zone to a 
'-09:00')  TIMESTAMP
WITH TIME
ZONE​ value 

LAST_DAY  LAST_DAY(DATE ​ 9-FEB-16 


2 Gets the last day 
'2016-02-01')  of the month of a 
specified date. 

LOCALTIMESTAMP  SELECT ​ 6-AUG-17


0 Return a 
LOCALTIMESTAMP FROM 08.26.52.742000 TIMESTAMP​ value 
dual  000 PM  that represents 
the current date 
and time in the 
session time 
zone. 

MONTHS_BETWEEN  MONTHS_BETWEEN( 6  Return the 


DATE '2017-07-01', number of 
DATE '2017-01-01' )  months between 
two dates. 

NEW_TIME  NEW_TIME( TO_DATE( ​ 6-AUG-2017


0 Convert a date in 
'08-07-2017 21:30:45  one time zone to 
01:30:45', another 
'MM-DD-YYYY
HH24:MI:SS' ),
'AST', 'PST' ) 

NEXT_DAY  NEXT_DAY( DATE ​ 2-JAN-00 


0 Get the first 
'2000-01-01', weekday that is 
'SUNDAY' )  later than a 
specified date. 

ROUND  ROUND(DATE ​ 1-AUG-17 


0 Return a date 
'2017-07-16', 'MM')  rounded to a 
specific unit of 
measure. 
29

SESSIONTIMEZONE  ​ ELECT
S ​ 07:00 
- Get the session 
SESSIONTIMEZONE time zone 
FROM dual; 

SYSDATE  ​ YSDATE 
S ​01-AUG-17  Return the current 
system date and 
time of the 
operating system 
where the Oracle 
Database resides. 

SYSTIMESTAMP  ​ ELECT
S 01-AUG-17 Return the system 
SYSTIMESTAMP FROM 01.33.57.929000 date and time 
dual;  000 PM -07:00  that includes 
fractional 
seconds and time 
zone. 

TO_CHAR  ​ O_CHAR(
T ​ unday, January
S Convert a D​ ATE 
DATE'2017-01-01', 01, 2017  or an ​INTERVAL 
'DL' )  value to a 
character string in 
a specified 
format. 

TO_DATE  TO_DATE( '01 Jan ​ 1-JAN-17 


0 Convert a date 
2017', 'DD MON which is in the 
YYYY' )  character string 
to a D
​ ATE​ value. 

TRUNC  ​ RUNC(DATE
T ​ 1-JUL-17 
0 Return a date 
'2017-07-16', 'MM')  truncated to a 
specific unit of 
measure. 

TZ_OFFSET  TZ_OFFSET( ​ 01:00 


+ Get time zone 
'Europe/London' )  offset of a time 
zone name from 
UTC 

 
30

4 ​ORDERBY
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. Some databases sort the query results in an ascending order by
default.
Syntax
The basic syntax of the ORDER BY clause is as follows −

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

SELECT *
FROM TRAINER
ORDERBY Salary DESC;

SELECT *
FROM CUSTOMER
ORDERBY First_name;

GROUP BY
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into
groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.
SYNTAX
The basic syntax of a GROUP BY clause is. The GROUP BY clause must follow the conditions in the WHERE
clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

1.
SELECT Goal,Count (*)
FROM CUSTOMER
GROUPBY Goal;

2.
31
SELECT Experience,Count (*)
FROM TRAINER
GROUPBY Experience

3.
SELECT type,Count (*) FROM Equipment
GROUPBY Type

HAVING
The HAVING Clause enables you to specify conditions that filter which group results appear in the results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions
on groups created by the GROUP BY clause.

Syntax
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

SELECT Grade
FROM TRAINER
GROUPBY Grade
HAVING Count(*)>3

SELECT Goal
FROM CUSTOMER
GROUPBY Goal
HAVING COUNT(*)>3

LIKE
SELECT *
FROM CUSTOMER
WHERE First_name
LIKE '_b%';

IN
SELECT *
FROM CUSTOMER
WHERE Goal IN ('Fat Loss','Muscle Gaining');

SELECT *
FROM MANAGER
WHERE Qualification IN ('BCA','BBA');
32

BETWEEN
SELECT *
FROM CUSTOMER
WHERE weight
BETWEEN 70 AND 90

SELECT *
FROM TRAINER
WHERE Experience
BETWEEN 0 AND 4

5.
SUBQUERIES
A subquery is a SQL query nested inside a larger query.

● The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or
inside another subquery.
● A subquery is usually added within the WHERE Clause of another SQL SELECT statement.

SYNTAX
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name FROM table_name WHERE ... );
33
A single row subquery returns zero or one row to the outer SQL statement. we​can place a subquery
in a WHERE clause, a HAVING clause, or a FROM clause of a SELECT statement.

SELECT First_name ,Last name,address


FROM TRAINER
WHERE experience = (SELECT MAX(Experience)
FROM TRAINER)

Multiple row subquery returns one or more rows to the outer SQL statement. You may use the IN,
ANY, or ALL operator in outer query to handle a subquery that returns multiple rows.

Select First_name, phone_no


FROM CUSTOMER
WHERE address IN (SELECT address
FROM CUSTOMER WHERE PIN =14341);

CORRELATED SUBQUERY
Correlated subqueries are used for row-by-row processing. Each subquery is executed once for
every row of the outer query.
A correlated subquery is evaluated once for each row processed by the parent statement. The parent
statement can be a SELECT, UPDATE, or DELETE statement.

SELECT column1, column2, ....


FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);

SELECT CUSTOMER_ID , First_name


FROM CUSTOMER as C
WHERE Height>(SELECT AVG ( Height)
FROM CUSTOMER
WHERE Goal= C. Goal);

6.JOINS
CROSS JOIN
The SQL CROSS JOIN produces a result set which is the number of rows in the first table multiplied by the
number of rows in the second table if no WHERE clause is used along with CROSS JOIN.This kind of result is
called a Cartesian Product.
34
If WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN.

An alternative way of achieving the same result is to use column names separated by commas after SELECT
and mentioning the table names involved, after a FROM clause.

Syntax:

SELECT *
FROM table1
CROSS JOIN table2;

SELECT C.CUSTOMER_ID,C.First_name,C.Phone_no,C.Goal,P.PROGRAMME_ID,P.TYPE
FROM CUSTOMER AS C
CROSS JOIN PROGRAMME ​AS P;

NATURAL JOIN
The SQL NATURAL JOIN is a type of JOIN THAT is structured in such a way that columns with the same
name of associated tables will appear once only.

Natural Join
- The associated tables have one or more pairs of identically named columns.
- The columns must be the same data type.
- Don’t use ON clauses in a natural join.

Syntax:

SELECT *
FROM table1
NATURAL JOIN table2;

SELECT MM.EMP_ID,M.First_name,M.Grade,M.Salary
FROM MANAGER AS M
NATURAL JOIN MANAGES_MEMEBERSHIP AS MM

INNER JOIN
The INNER JOIN selects all rows from both participating tables as long as there is a match between the
columns. An SQL INNER JOIN is the same as a JOIN clause, combining rows from two or more tables.
Syntax:

SELECT *
FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;

OR

SELECT *
FROM table1
35
JOIN table2
ON table1.column_name = table2.column_name;

SELECT MM.EMP_ID,M.First_name,M.Grade,M.Salary
FROM MANAGER AS M
INNER JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID

OUTER JOINS
The SQL OUTER JOIN returns all rows from both the participating tables which satisfy the join condition
along with rows which do not satisfy the join condition.
The subtypes of SQL OUTER JOIN

LEFT OUTER JOIN or LEFT JOIN


RIGHT OUTER JOIN or RIGHT JOIN
FULL OUTER JOIN

The ​SQL LEFT JOIN ​(specified with the keywords LEFT JOIN and ON) joins two tables and fetches all
matching rows of two tables for which the SQL-expression is true, plus rows from the first table that do not
match any row in the second table.

Left Join: Syntax

SELECT *
FROM table1
LEFT [ OUTER ] JOIN table2
ON table1.column_name=table2.column_name;

SELECT MM.EMP_ID,M.First_name,M.Phone_no,M.email,M.Salary
FROM MANAGER AS M
LEFT JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID

The​ SQL RIGHT JOIN​, joins two tables and fetches rows based on a condition, which is matching in both the
tables ( before and after the JOIN clause mentioned in the syntax below) , and the unmatched rows will also be
available from the table written after the JOIN clause ( mentioned in the syntax below ).

Syntax:
SELECT *
FROM table1
RIGHT [ OUTER ] JOIN table2
ON table1.column_name=table2.column_name;

SELECT MM.EMP_ID,M.First_name,M.Phone_no,M.email,M.Salary
FROM MANAGER AS M
RIGHT JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID
36

In SQL the ​FULL OUTER JOIN​ combines the results of both left and right outer joins and returns all
(matched or unmatched) rows from the tables on both sides of the join clause.
Syntax:

SELECT *
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

SELECT MM.EMP_ID,M.First_name,M.Phone_no,M.Grade,M.Salary
FROM MANAGER AS M
FULL OUTER JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID

7.VIEWS
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one or
many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
● Structure data in a way that users or classes of users find natural or intuitive.
● Restrict access to the data in such a way that a user can see and (sometimes) modify exactly
what they need and no more.
● Summarize data from various tables which can be used to generate reports.

Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a
single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];

You can include multiple tables in your SELECT statement in a similar way as you use them in a
normal SQL SELECT query.

Example
37
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
|​ 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​ ​|
|​ ​7​ ​|​ ​Muffy​ ​|​ ​24​ ​|​ ​Indore​ ​|​ ​10000.00​ ​|
+----+----------+-----+-----------+----------+
Following is an example to create a view from the CUSTOMERS table. This view would be used to
have customer name and age from the CUSTOMERS table.
SQL ​>​ CREATE VIEW CUSTOMERS_VIEW AS
SELECT name​,​ age
FROM CUSTOMERS​;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table. Following is
an example for the same.
SQL ​>​ SELECT ​*​ FROM CUSTOMERS_VIEW​;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+

The WITH CHECK OPTION


The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH
CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view
definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating the same view CUSTOMERS_VIEW with the
WITH CHECK OPTION.
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name​,​ age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION​;
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's
38
AGE column, because the view is defined by data that does not have a NULL value in the AGE
column.

Updating a View
A view can be updated under certain conditions which are given below −
● The SELECT clause may not contain the keyword DISTINCT.
● The SELECT clause may not contain summary functions.
● The SELECT clause may not contain set functions.
● The SELECT clause may not contain set operators.
● The SELECT clause may not contain an ORDER BY clause.
● The FROM clause may not contain multiple tables.
● The WHERE clause may not contain subqueries.
● The query may not contain GROUP BY or HAVING.
● Calculated columns may not be updated.
● All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The following
code block has an example to update the age of Ramesh.
SQL ​>​ UPDATE CUSTOMERS_VIEW
SET AGE ​=​ ​35
WHERE name ​=​ ​'Ramesh'​;
This would ultimately update the base table CUSTOMERS and the same would reflect in the view
itself. Now, try to query the base table and the SELECT statement would produce the following
result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Inserting Rows into a View


Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also
apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all the NOT
NULL columns in this view, otherwise you can insert rows in a view in a similar way as you insert
them in a table.

Deleting Rows into a View


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.
39
SQL ​>​ DELETE FROM CUSTOMERS_VIEW
WHERE age ​=​ ​22​;
This would ultimately delete a row from the base table CUSTOMERS and the same would reflect in
the view itself. Now, try to query the base table and the SELECT statement would produce the
following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The
syntax is very simple and is given below −
DROP VIEW view_name;

Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table.


DROP VIEW CUSTOMERS_VIEW​;

8. INDEXES
Indexes are special lookup tables that the database search engine can use to speed up data
retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to
an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic, you first
refer to the index, which lists all the topics alphabetically and are then referred to one or more
specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input,
with the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on
the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to
specify the table and which column or columns to index, and to indicate whether the index is in an
ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries
in the column or combination of columns on which there is an index.

The CREATE INDEX Command


The basic syntax of a CREATE INDEX is as follows.
CREATE INDEX index_name ON table_name;
40

Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as follows.
CREATE INDEX index_name
ON table_name (column_name);

Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique index does
not allow any duplicate values to be inserted into the table. The basic syntax is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);

Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);

Whether to create a single-column index or a composite index, take into consideration the column(s)
that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be
two or more columns that are frequently used in the WHERE clause as filters, the composite index
would be the best choice.

Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when an object is
created. Indexes are automatically created for primary key constraints and unique constraints.

The DROP INDEX Command


An index can be dropped using SQL DROP command. Care should be taken when dropping an
index because the performance may either slow down or improve.
The basic syntax is as follows −
DROP INDEX index_name;

You can check the ​INDEX Constraint​ chapter to see some actual examples on Indexes.

When should indexes be avoided?


Although indexes are intended to enhance a database's performance, there are times when they
should be avoided.
The following guidelines indicate when the use of an index should be reconsidered.
● Indexes should not be used on small tables.
● Tables that have frequent, large batch updates or insert operations.
● Indexes should not be used on columns that contain a high number of NULL values.
● Columns that are frequently manipulated should not be indexed
41

9 SEQUENCE
A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are
frequently used in databases because many applications require each row in a table to contain a
unique value and sequences provide an easy way to generate them.
This chapter describes how to use sequences in MySQL.

Using AUTO_INCREMENT column


The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and
leave the rest to MySQL to take care.

Example
Try out the following example. This will create a table and after that it will insert a few rows in this
table where it is not required to give a record ID because its auto-incremented by MySQL.
mysql​>​ CREATE TABLE INSECT
​->​ ​(
​->​ id INT UNSIGNED NOT NULL AUTO_INCREMENT​,
​->​ PRIMARY KEY ​(​id​),
​->​ name VARCHAR​(​30​)​ NOT NULL​,​ ​# type of insect
​->​ date DATE NOT NULL​,​ ​# date collected
​->​ origin VARCHAR​(​30​)​ NOT NULL ​# where collected
);
Query​ OK​,​ ​0​ rows affected ​(​0.02​ sec​)
mysql​>​ INSERT INTO INSECT ​(​id​,​name​,​date​,​origin​)​ VALUES
​->​ ​(​NULL​,​'housefly'​,​'2001-09-10'​,​'kitchen'​),
​->​ ​(​NULL​,​'millipede'​,​'2001-09-10'​,​'driveway'​),
​->​ ​(​NULL​,​'grasshopper'​,​'2001-09-10'​,​'front yard'​);
Query​ OK​,​ ​3​ rows affected ​(​0.02​ sec​)
Records​:​ ​3​ ​Duplicates​:​ ​0​ ​Warnings​:​ ​0
mysql​>​ SELECT ​*​ FROM INSECT ORDER BY id​;
+----+-------------+------------+------------+
|​ id ​|​ name ​|​ date ​|​ origin ​|
+----+-------------+------------+------------+
|​ ​1​ ​|​ housefly ​|​ ​2001​-​09​-​10​ ​|​ kitchen ​|
|​ ​2​ ​|​ millipede ​|​ ​2001​-​09​-​10​ ​|​ driveway ​|
|​ ​3​ ​|​ grasshopper ​|​ ​2001​-​09​-​10​ ​|​ front yard ​|
+----+-------------+------------+------------+
3​ rows ​in​ ​set​ ​(​0.00​ sec​)
42
Obtain AUTO_INCREMENT Values
The LAST_INSERT_ID( ) is an SQL function, so you can use it from within any client that
understands how to issue SQL statements. Otherwise PERL and PHP scripts provide exclusive
functions to retrieve auto-incremented value of last record.

PERL Example
Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This
attribute is accessed through either a database handle or a statement handle, depending on how
you issue the query. The following example references it through the database handle.
$dbh​->​do​ ​(​"INSERT INTO INSECT (name,date,origin)
VALUES('moth','2001-09-14','windowsill')"​);
my​ $seq ​=​ $dbh​->{​mysql_insertid​};

PHP Example
After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling the
mysql_insert_id( ) function.
mysql_query ​(​"INSERT INTO INSECT (name,date,origin)
VALUES('moth','2001-09-14','windowsill')"​,​ $conn_id​);
$seq ​=​ mysql_insert_id ​(​$conn_id​);

Renumbering an Existing Sequence


There may be a case when you have deleted many records from a table and you want to
re-sequence all the records. This can be done by using a simple trick, but you should be very careful
to do this and check if your table is having a join with another table or not.
If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it
is to drop the column from the table, then add it again.
The following example shows how to renumber the id values in the insect table using this technique.
mysql​>​ ALTER TABLE INSECT DROP id​;
mysql​>​ ALTER TABLE insect
​->​ ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST​,
​->​ ADD PRIMARY KEY ​(​id​);

Starting a Sequence at a Particular Value


By default, MySQL will start the sequence from 1, but you can specify any other number as well at
the time of table creation.
The following code block has an example where MySQL will start sequence from 100.
mysql​>​ CREATE TABLE INSECT
​->​ ​(
​->​ id INT UNSIGNED NOT NULL AUTO_INCREMENT ​=​ ​100​,
​->​ PRIMARY KEY ​(​id​),
​->​ name VARCHAR​(​30​)​ NOT NULL​,​ ​# type of insect
​->​ date DATE NOT NULL​,​ ​# date collected
​->​ origin VARCHAR​(​30​)​ NOT NULL ​# where collected
);
Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE.
43
mysql​>​ ALTER TABLE t AUTO_INCREMENT ​=​ ​100​;

10.
A. PL/SQL SYNTAX

S.No Sections & Description

Declarations

1 This section starts with the keyword DECLARE. It is an optional section and
defines all variables, cursors, subprograms, and other elements to be used in
the program.

Executable Commands

This section is enclosed between the keywords BEGIN and END and it is a
2
mandatory section. It consists of the executable PL/SQL statements of the
program. It should have at least one executable line of code, which may be just
a NULL command to indicate that nothing should be executed.
44

Exception Handling

3
This section starts with the keyword EXCEPTION. This optional section contains
exception(s) that handle errors in the program.

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;

The 'Hello World' Example


DECLARE
message varchar2​(​20​):=​ ​'Hello, World!'​;
BEGIN
dbms_output​.​put_line​(​message​);
END​;
/
The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you
may need to type / at the beginning of the first blank line after the last line of the code. When the
above code is executed at the SQL prompt, it produces the following result −
Hello World

PL/SQL procedure successfully completed.

The PL/SQL Identifiers


PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words.
The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs,
underscores, and number signs and should not exceed 30 characters.
By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a
numeric value. You cannot use a reserved keyword as an identifier.

The PL/SQL Delimiters


A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −

Delimiter Description
45

+, -, *, / Addition, subtraction/negation, multiplication, division

% Attribute indicator

' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator

" Quoted identifier delimiter

= Relational operator

@ Remote access indicator

; Statement terminator

:= Assignment operator

=> Association operator

|| Concatenation operator

** Exponentiation operator
46

<<, >> Label delimiter (begin and end)

/*, */ Multi-line comment delimiter (begin and end)

-- Single-line comment indicator

.. Range operator

<, >, <=, >= Relational operators

<>, '=, ~=, Different versions of NOT EQUAL


^=

The PL/SQL Comments


Program comments are explanatory statements that can be included in the PL/SQL code that you
write and helps anyone reading its source code. All programming languages allow some form of
comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside any
comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the
delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.
DECLARE
​--​ variable declaration
message varchar2​(​20​):=​ ​'Hello, World!'​;
BEGIN
​/*
* PL/SQL executable statement(s)
*/
dbms_output​.​put_line​(​message​);
END​;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello​ ​World

PL​/​SQL procedure successfully completed​.

PL/SQL Program Units


A PL/SQL unit is any one of the following −
● PL/SQL block
47
● Function
● Package
● Package body
● Procedure
● Trigger
● Type
● Type body

B. CONTROL STRUCTURES

PL/SQL programming language provides the following types of decision-making statements. Click
the following links to check their detail.

S.No Statement & Description

IF - THEN statement

1 The IF statement associates a condition with a sequence of statements enclosed by the


keywords THEN and END IF. If the condition is true, the statements get executed and if
the condition is false or NULL then the IF statement does nothing.

IF-THEN-ELSE statement

2 IF statement adds the keyword ELSE followed by an alternative sequence of statement. If


the condition is false or NULL, then only the alternative sequence of statements get
executed. It ensures that either of the sequence of statements is executed.

IF-THEN-ELSIF statement
3
It allows you to choose between several alternatives.

Case statement

Like the IF statement, the CASE statement selects one sequence of statements to
execute.
4

However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression whose value is used to select one of
several alternatives.
48

Searched CASE statement

5 The searched CASE statement has no selector, and it's WHEN clauses contain search
conditions that yield Boolean values.

nested IF-THEN-ELSE

6 You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or
IF-THEN-ELSIF statement(s).

PL/SQL provides the following types of loop to handle the looping requirements. Click the following
links to check their detail.

S.No Loop Type & Description

PL/SQL Basic LOOP

1 In this loop structure, sequence of statements is enclosed between the LOOP and the
END LOOP statements. At each iteration, the sequence of statements is executed and
then control resumes at the top of the loop.

PL/SQL WHILE LOOP

2 Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

PL/SQL FOR LOOP

3 Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

Nested loops in PL/SQL


4
You can use one or more loop inside any another basic loop, while, or for loop.
49
Labeling a PL/SQL Loop
PL/SQL loops can be labeled. The label should be enclosed by double angle brackets (<< and >>)
and appear at the beginning of the LOOP statement. The label name can also appear at the end of
the LOOP statement. You may use the label in the EXIT statement to exit from the loop.
The following program illustrates the concept −
DECLARE
i number​(​1​);
j number​(​1​);
BEGIN
​<<​ outer_loop ​>>
FOR i IN ​1.​.​3​ LOOP
​<<​ inner_loop ​>>
FOR j IN ​1.​.​3​ LOOP
dbms_output​.​put_line​(​'i is: '​||​ i ​||​ ​' and j is: '​ ​||​ j​);
​END​ loop inner_loop​;
​END​ loop outer_loop​;
END​;
/
When the above code is executed at the SQL prompt, it produces the following result −
i is: 1 and j is: 1
i is: 1 and j is: 2
i is: 1 and j is: 3
i is: 2 and j is: 1
i is: 2 and j is: 2
i is: 2 and j is: 3
i is: 3 and j is: 1
i is: 3 and j is: 2
i is: 3 and j is: 3

PL/SQL procedure successfully completed.

The Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
PL/SQL supports the following control statements. Labeling loops also help in taking the control
outside a loop. Click the following links to check their details.

S.No Control Statement & Description

EXIT statement

1 The Exit statement completes the loop and control passes to the statement immediately
after the END LOOP.
50

CONTINUE statement

2 Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.

GOTO statement

3 Transfers control to the labeled statement. Though it is not advised to use the GOTO
statement in your program.

11. PROGRAMS:
A. PROCEDURES:

P1: To check if a year is a leap or not .

create or replace NONEDITIONABLE procedure leap_year (


year in number
)
is
begin
IF MOD(year, 4)=0
AND
MOD(year, 100)!=0
OR
MOD(year, 400)=0 THEN
dbms_output.Put_line(year
|| ' is a leap year ');
ELSE
dbms_output.Put_line(year
|| ' is not a leap year.');
END IF;
end leap_year;

P2: To find area and circumference of a circle using a case statement.

create or replace NONEDITIONABLE procedure area_circum (rad in number,choice IN varchar)


is
BEGIN
case choice
WHEN 'C' then
dbms_output.put_line('circumference is : '||2*3.14*rad);
WHEN 'A' then
51
dbms_output.put_line('area is : '||3.14*rad*rad);
END case;
END;

P3: To check whether a prime number or not using while loop


and for loop
a. Using for loop
create or replace NONEDITIONABLE procedure is_prime_for (val in number)
is
n number;
i number;
temp number;

begin
n:=val;
i := 2;

-- Assigning 1 to temp
temp := 1;

-- loop from i = 2 to n/2


for i in 2..n/2
loop
if mod(n, i) = 0
then
temp := 0;
exit;
end if;
end loop;

if temp = 1
then
dbms_output.put_line(n|| ' is prime');
else
dbms_output.put_line(n||' is not prime');
end if;
end;

b. Using while loop


create or replace NONEDITIONABLE procedure is_prime_while (val in number)
is
n number;
i number;
temp number;

begin
n:=val;
52
i := 2;

-- Assigning 1 to temp
temp := 1;

-- loop from i = 2 to n/2


while i <=n/2
loop
if mod(n, i) = 0
then
temp := 0;
exit;
end if;
i:=i+1;
end loop;

if temp = 1
then
dbms_output.put_line(n|| ' is prime');
else
dbms_output.put_line(n||' is not prime');
end if;
end;

P4: To generate fibonacci series

create or replace NONEDITIONABLE procedure fibo (fir_num IN NUMBER, sec_num IN NUMBER,


series_length IN NUMBER)
IS
fir NUMBER;
sec NUMBER;
temp NUMBER;
i NUMBER;
BEGIN
fir:=fir_num;
sec:=sec_num;
dbms_output.put_line(fir);
dbms_output.put_line(sec);

for i in 1..series_length
LOOP
temp:=fir+sec;
fir:=sec;
sec:=temp;
dbms_output.put_line(sec);
END LOOP;
END;
53
P5: To generate factorial of a given number

create or replace NONEDITIONABLE procedure factorial(val in number)


is
temp number;
res number;
begin
temp:=val;
res:=1;
while temp>1 loop
res:=res*temp;
temp:=temp-1;
end loop;
DBMS_OUTPUT.PUT_LINE(res);
end;

P6: To Check Palindrome


create or replace NONEDITIONABLE procedure palindrome(str IN varchar)
IS
s VARCHAR2(50) := str;
l VARCHAR2(100);
t VARCHAR2(50);
BEGIN
FOR i IN REVERSE 1..Length(s) LOOP
l := Substr(s, i, 1);

t := t
||''
||l;
END LOOP;

IF t = s THEN
dbms_output.Put_line(t
||''
||' is palindrome');
ELSE
dbms_output.Put_line(s
||''
||' is not palindrome');
END IF;
END;

P7: To create a dummy calculator taking two numbers as input as


performing selected operation(Addition, subtraction, multiply,etc)
And displaying the output.
create or replace NONEDITIONABLE procedure calc(num1 in number, num2 in number, oper VARCHAR2)
is
res number;
54
op varchar(1);
begin
op := oper;
case op
when 'a' then
res:=num1+num2;
when 's' then
res:=num1-num2;
when 'm' then
res:=num1*num2;
when 'd' then
res:=num1/num2;
end case;
dbms_output.put_line(res);
end;

B. FUNCTIONS
P1: To check if a year is a leap or not .
create or replace NONEDITIONABLE function leap_year_func (
year in number
)
return VARCHAR
is
res varchar(5);
begin
IF MOD(year, 4)=0
AND
MOD(year, 100)!=0
OR
MOD(year, 400)=0 THEN
res :='true';
ELSE
res :='false';
END IF;
return res;
end;

P2: To find area and circumference of a circle using a case


Statement.

create or replace NONEDITIONABLE function area_circum_fun (rad in number,choice IN varchar)


return number
is
BEGIN
case choice
WHEN 'C' then
return 2*3.14*rad;
WHEN 'A' then
55
return 3.14*rad*rad;
END case;
END;

P3: To check whether a prime number or not using while loop


and for loop
create or replace NONEDITIONABLE function is_prime_for_func (val in number)
return varchar
as
n number;
i number;
temp number;
begin
n:=val;
i := 2;

-- Assigning 1 to temp
temp := 1;

-- loop from i = 2 to n/2


for i in 2..n/2
loop
if mod(n, i) = 0
then
temp := 0;
exit;
end if;
end loop;

if temp = 1
then
return (n || ' is prime');
else
return (n || ' is not prime');
end if;
end;

create or replace NONEDITIONABLE function is_prime_while_func (val in number)


return varchar
is
n number;
i number;
temp number;

begin
n:=val;
i := 2;
56

-- Assigning 1 to temp
temp := 1;

-- loop from i = 2 to n/2


while i <=n/2
loop
if mod(n, i) = 0
then
temp := 0;
exit;
end if;
i:=i+1;
end loop;

if temp = 1
then
return (n || ' is prime');
else
return (n || ' is not prime');
end if;
end;

P4: To generate fibonacci series

create or replace NONEDITIONABLE function fibo_func (fir_num IN NUMBER, sec_num IN NUMBER,


series_length IN NUMBER)
return VARCHAR
IS
fir NUMBER;
sec NUMBER;
temp NUMBER;
i NUMBER;
res varchar(4000);
BEGIN
fir:=fir_num;
sec:=sec_num;
res:='';
res:= res||fir||','||sec||',';

for i in 1..series_length
LOOP
temp:=fir+sec;
fir:=sec;
sec:=temp;
res:= res||sec||',';
END LOOP;
return res;
END;
57

P5: To generate factorial of a given number


create or replace NONEDITIONABLE function factorial_fun (val in number)
return number
is
res number;
temp number;
BEGIN
temp:=val;
res:=1;
while temp>1 loop
res:=res*temp;
temp:=temp-1;
end loop;
return res;
END;

P6: To Check Palindrome

create or replace NONEDITIONABLE function palindrome_func(str IN varchar)


return varchar
IS
s VARCHAR2(50) := str;
l VARCHAR2(100);
t VARCHAR2(50);
BEGIN
FOR i IN REVERSE 1..Length(s) LOOP
l := Substr(s, i, 1);

t := t ||'' ||l;
END LOOP;

IF t = s THEN
return(t ||'' ||' is palindrome');
ELSE
return(s||'' ||' is not palindrome');
END IF;
END;

P7: To create a dummy calculator taking two numbers as input as


performing selected operation (Addition, subtraction, multiply,etc) and displaying the output.

create or replace NONEDITIONABLE function calc_fun(num1 in number, num2 in number, op in char)


return number
is
res number;
begin
case op
58
when 'a' then
res:=num1+num2;
when 's' then
res:=num1-num2;
when 'm' then
res:=num1*num2;
when 'd' then
res:=num1/num2;
end case;
return res;
end;

12. CURSORS
A. introduction

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
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has
attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has
additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the
FORALL statement. The following table provides the description of the most used attributes −

S.No Attribute & Description


59

%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.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example.

Example
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 |
+----+----------+-----+-----------+----------+
60

The following program will update the table and increase the salary of each customer by 500 and
use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number​(​2​);
BEGIN
UPDATE customers
SET salary ​=​ salary ​+​ ​500​;
IF sql​%​notfound THEN
dbms_output​.​put_line​(​'no customers selected'​);
ELSIF sql​%​found THEN
total_rows ​:=​ sql​%​rowcount​;
dbms_output​.​put_line​(​ total_rows ​||​ ​' customers selected '​);
​END​ IF​;
END​;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected

PL/SQL procedure successfully completed.

If you check the records in customers table, you will find that the rows have been updated −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

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;

Working with an explicit cursor includes the following steps −


● Declaring the cursor for initializing the memory
● Opening the cursor for allocating the memory
● Fetching the cursor for retrieving the data
61
● Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example −
CURSOR c_customers IS
SELECT id​,​ name​,​ address FROM customers​;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows
returned by the SQL statement into it. For example, we will open the above defined cursor as follows

OPEN c_customers​;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the
above-opened cursor as follows −
FETCH c_customers INTO c_id​,​ c_name​,​ c_addr​;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows −
CLOSE c_customers​;

Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers​.​id​%​type​;
c_name customer​.​name​%​type​;
c_addr customers​.​address​%​type​;
CURSOR c_customers ​is
SELECT id​,​ name​,​ address FROM customers​;
BEGIN
OPEN c_customers​;
LOOP
FETCH c_customers ​into​ c_id​,​ c_name​,​ c_addr​;
EXIT WHEN c_customers​%​notfound​;
dbms_output​.​put_line​(​c_id ​||​ ​' '​ ​||​ c_name ​||​ ​' '​ ​||​ c_addr​);
​END​ LOOP​;
CLOSE c_customers​;
END​;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
62
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.


B.
Advantages:

• Using Cursor, we can perform row by row processing so we can perform row wise validation or
operations on each row.
• Cursors can provide the first few rows before the whole result set is assembled. Without using cursors,
the entire result set must be delivered before any rows are displayed by the application. So, using a cursor,
better response time is achieved.
• If we make updates to us without using cursors in your application then we must send separate SQL
statements to the database server to apply the changes. This can cause the possibility of concurrency problems
if the result set has changed since it was queried by the client. In turn, this raises the possibility of lost updates.
So using cursor, better concurrency Control can be achieved.
• Cursors can be faster than a while loop but at the cost of more overhead.

Disadvantages:

• Cursor in SQL is a temporary work area created in the system memory; thus, it occupies memory from
your system that may be available for other processes. So occupies more resources and temporary storage.
• Each time when a row is fetched from the cursor it may result in a network round trip. This uses much
more network bandwidth than the execution of a single SQL statement like SELECT or DELETE etc that
makes only one round trip.
• Repeated network round trips can degrade the speed of the operation using the cursor

C.
Program:To count the number of records using implicit
cursor.

IN our database, salary is determined by the grade, so, in the following programs we sort by grade.

Program:To display records of 5 least paid employees using


explicit cursor.

set serveroutput on;


declare
63
cursor exp_cursor is select emp_id,first_name from trainer order by grade;
e_id trainer.emp_id%type;
e_name trainer.first_name%type;
begin
open exp_cursor;
dbms_output.put_line('name id');
loop

fetch exp_cursor into e_id,e_name;

exit when exp_cursor%rowcount=5 or exp_cursor%notfound;

dbms_output.put_line(e_name||' '||e_id);

end loop;
close exp_cursor;
end;
/

Program:To display records of 5 highest paid employees using


explicit cursor.
set serveroutput on;
declare
cursor exp_cursor is select emp_id,first_name from trainer order by grade desc;
e_id trainer.emp_id%type;
e_name trainer.first_name%type;
begin
open exp_cursor;
dbms_output.put_line('name id');
loop

fetch exp_cursor into e_id,e_name;

exit when exp_cursor%rowcount=5 or exp_cursor%notfound;

dbms_output.put_line(e_name||' '||e_id);

end loop;
close exp_cursor;
64
end;
/

13. TRIGGERS
TRIGGERS​ are stored programs that are fired by Oracle engine automatically when DML
Statements like insert, update, delete are executed on the table or some events occur.
The code to be excecuted in case of a trigger can be defined as per the requirement. You
can choose the event upon which the trigger needs to be fired and the timing of the
execution. The purpose of trigger is to maintain the integrity of information on the
database.

Benefits of Triggers
Following are the benefits of triggers.

● Generating some derived column values automatically


● Enforcing referential integrity
● Event logging and storing information on table access
● Auditing
● Synchronous replication of tables
● Imposing security authorizations
● Preventing invalid transactions

Types of Triggers in Oracle


Triggers can be classified based on the following parameters.

● Classification based on the ​timing


○ BEFORE Trigger: It fires before the specified event has occurred.
○ AFTER Trigger: It fires after the specified event has occurred.
○ INSTEAD OF Trigger: A special type. You will learn more about the further
topics. (only for DML )
● Classification based on the ​level
○ STATEMENT level Trigger: It fires one time for the specified event statement.
65
○ ROW level Trigger: It fires for each record that got affected in the specified
event. (only for DML)
● Classification based on the​ Event
○ DML Trigger: It fires when the DML event is specified
(INSERT/UPDATE/DELETE)
○ DDL Trigger: It fires when the DDL event is specified (CREATE/ALTER)
○ DATABASE Trigger: It fires when the database event is specified
(LOGON/LOGOFF/STARTUP/SHUTDOWN)

So each trigger is the combination of above parameters.

How to Create Trigger


Below is the syntax for creating a trigger.

CREATE [ OR REPLACE ] TRIGGER <trigger_name>

[BEFORE | AFTER | INSTEAD OF ]

[INSERT | UPDATE | DELETE......]

ON<name of underlying object>

[FOR EACH ROW]

[WHEN<condition for trigger to get execute> ]

DECLARE
66
<Declaration part>
BEGIN
<Execution part>
EXCEPTION
<Exception handling part>
END;

Syntax Explanation:

● The above syntax shows the different optional statements that are present in trigger
creation.
● BEFORE/ AFTER will specify the event timings.
● INSERT/UPDATE/LOGON/CREATE/etc. will specify the event for which the trigger
needs to be fired.
● ON clause will specify on which object the above-mentioned event is valid. For
example, this will be the table name on which the DML event may occur in the case
of DML Trigger.
● Command "FOR EACH ROW" will specify the ROW level trigger.
● WHEN clause will specify the additional condition in which the trigger needs to fire.
● The declaration part, execution part, exception handling part is same as that of the
other PL/SQL blocks. Declaration part and exception handling part are optional.

:NEW and :OLD Clause


In a row level trigger, the trigger fires for each related row. And sometimes it is required to
know the value before and after the DML statement.

Oracle has provided two clauses in the RECORD-level trigger to hold these values. We
can use these clauses to refer to the old and new values inside the trigger body.

● :NEW – It holds a new value for the columns of the base table/view during the
trigger execution
● :OLD – It holds old value of the columns of the base table/view during the trigger
execution

This clause should be used based on the DML event. Below table will specify which
clause is valid for which DML statement (INSERT/UPDATE/DELETE).

INSERT UPDA DELETE


TE

:NE VALID VALID INVALID. There is no new value in


W delete case.
67

:OL INVALID. There is no old value in VALID VALID


D insert case

INSTEAD OF Trigger
"INSTEAD OF trigger" is the special type of trigger. It is used only in DML triggers. It is
used when any DML event is going to occur on the complex view.

Consider an example in which a view is made from 3 base tables. When any DML event
is issued over this view, that will become invalid because the data is taken from 3 different
tables. So in this INSTEAD OF trigger is used. The INSTEAD OF trigger is used to modify
the base tables directly instead of modifying the view for the given event.

Example 1​: In this example, we are going to create a complex view from two base table.

● Table_1 is emp table and


● Table_2 is department table.

Then we are going to see how the INSTEAD OF trigger is used to issue UPDATE the
location detail statement on this complex view. We are also going to see how the :NEW
and :OLD is useful in triggers.

● Step 1: Creating table 'emp' and 'dept' with appropriate columns


● Step 2: Populating the table with sample values
● Step 3: Creating view for the above created table
● Step 4: Update of view before the instead-of trigger
● Step 5: Creation of the instead-of trigger
● Step 6: Update of view after instead-of trigger

Step 1)​ Creating table 'emp' and 'dept' with appropriate columns
68

CREATE TABLE emp(


emp_no NUMBER,
emp_name VARCHAR2(50),
salary NUMBER,
manager VARCHAR2(50),
dept_no NUMBER);
/

CREATE TABLE dept(


Dept_no NUMBER,
Dept_name VARCHAR2(50),
LOCATION VARCHAR2(50));
/

Code Explanation

● Code line 1-7​: Table 'emp' creation.


● Code line 8-12​: Table 'dept' creation.

Output

Table Created

Step 2)​ Now since we have created the table, we will populate this table with sample
values and Creation of Views for the above tables.
69

BEGIN
INSERT INTO DEPT VALUES(10,‘HR’,‘USA’);
INSERT INTO DEPT VALUES(20,'SALES','UK’);
INSERT INTO DEPT VALUES(30,‘FINANCIAL',‘JAPAN');
COMMIT;
END;
/

BEGIN
INSERT INTO EMP VALUES(1000,'XXX5,15000,'AAA',30);
INSERT INTO EMP VALUES(1001,‘YYY5,18000,‘AAA’,20) ;
INSERT INTO EMP VALUES(1002,‘ZZZ5,20000,‘AAA',10);
COMMIT;
END;
/

Code Explanation

● Code line 13-19​: Inserting data into 'dept' table.


● Code line 20-26: ​Inserting data into 'emp' table.

Output

PL/SQL procedure completed

Step 3) ​Creating a view for the above created table.


70

CREATE VIEW guru99_emp_view(


Employee_name:dept_name,location) AS
SELECT emp.emp_name,dept.dept_name,dept.location
FROM emp,dept
WHERE emp.dept_no=dept.dept_no;
/

SELECT * FROM guru99_emp_view;

Code Explanation

● Code line 27-32: ​Creation of 'guru99_emp_view' view.


● Code line 33:​ Querying guru99_emp_view.

Output

View created

EMPLOYEE_NAME DEPT_NAME LOCATION

ZZZ HR USA

YYY SALES UK

XXX FINANCIAL JAPAN

Step 4)​ Update of view before instead-of trigger.


71

BEGIN
UPDATE guru99_emp_view SET location='FRANCE' WHERE employee_name=:'XXX’;
COMMIT;
END;
/

Code Explanation

● Code line 34-38: ​Update the location of "XXX" to 'FRANCE'. It raised the exception
because the DML statements are not allowed in the complex view.

Output

ORA-01779: cannot modify a column which maps to a non key-preserved table

ORA-06512: at line 2

Step 5)​To avoid the error encounter during updating view in the previous step, in this step
we are going to use "instead of trigger."

CREATE TRIGGER guru99_view_modify_trg


INSTEAD OF UPDATE
ON guru99_emp_view
FOR EACH ROW
BEGIN
UPDATE dept
SET location=:new.location
72
WHERE dept_name=:old.dept_name;
END;
/

Code Explanation

● Code line 39:​ Creation of INSTEAD OF trigger for 'UPDATE' event on the
'guru99_emp_view' view at the ROW level. It contains the update statement to
update the location in the base table 'dept'.
● Code line 44:​ Update statement uses ':NEW' and ': OLD' to find the value of
columns before and after the update.

Output

Trigger Created

Step 6)​ Update of view after instead-of trigger. Now the error will not come as the "instead
of trigger" will handle the update operation of this complex view. And when the code has
executed the location of employee XXX will be updated to "France" from "Japan."

BEGIN
UPDATE guru99_emp_view SET location='FRANCE' WHERE employee_name='XXX';
COMMIT;
END;
/

SELECT * FROM guru99_emp_view;

Code Explanation:

● Code line 49-53:​ Update of the location of "XXX" to 'FRANCE'. It is successful


because the 'INSTEAD OF' trigger has stopped the actual update statement on
73
view and performed the base table update.
● Code line 55:​ Verifying the updated record.

Output:

PL/SQL procedure successfully completed

EMPLOYEE_NAME DEPT_NAME LOCATION

ZZZ HR USA

YYY SALES UK

XXX FINANCIAL FRANCE

Compound Trigger
The Compound trigger is a trigger that allows you to specify actions for each of four timing
points in the single trigger body. The four different timing point it supports is as below.

● BEFORE STATEMENT – level


● BEFORE ROW – level
● AFTER ROW - level
● AFTER STATEMENT – level

It provides the facility to combine the actions for different timing into the same trigger.
74

CREATE [ OR REPLACE ] TRIGGER <trigger_name>


FOR
[INSERT | UPDATE | DELET.......]
ON <name of underlying object>
<Declarative part>
BEFORE STATEMENT IS
BEGIN
<Execution part>;
END BEFORE STATEMENT;

BEFORE EACH ROW IS


BEGIN
<Execution part>;
END EACH ROW;

AFTER EACH ROW IS


BEGIN
<Execution part>;
END AFTER EACH ROW;

AFTER STATEMENT IS
BEGIN
<Execution part>;
END AFTER STATEMENT;
END;

Syntax Explanation:
75
● The above syntax shows the creation of 'COMPOUND' trigger.
● Declarative section is common for all the execution block in the trigger body.
● These 4 timing blocks can be in any sequence. It is not mandatory to have all these
4 timing blocks. We can create a COMPOUND trigger only for the timings which are
required.

Example 1​: In this example, we are going to create a trigger to auto-populate the salary
column with the default value 5000.

CREATE TRIGGER emp_trig


FOR INSERT
ON emp
COMPOUND TRIGGER
BEFORE EACH ROW IS
BEGIN
:new.salary:=5000;
END BEFORE EACH ROW;
END emp_trig;
/

BEGIN
INSERT INTO EMP VALUES(1004,‘CCC’,15000,‘AAA’,30);
COMMIT;
END;
/
76
SELECT * FROM emp WHERE emp_no=1004;
Code Explanation:

● Code line 2-10​: Creation of compound trigger. It is created for timing BEFORE
ROW- level to populate the salary with default value 5000. This will change the
salary to default value '5000' before inserting the record into the table.
● Code line 11-14​: Insert the record into 'emp' table.
● Code line 16​: Verifying the inserted record.

Output:

Trigger created

PL/SQL procedure successfully completed.

EMP_NAME EMP_NO SALARY MANAGER DEPT_NO

CCC 1004 5000 AAA 30

Enabling and Disabling Triggers

Triggers can be enabled or disabled. To enable or disable the trigger, an ALTER (DDL)
statement needs to be given for the trigger that disable or enable it.

Below are the syntax for enabling/disabling the triggers.

ALTER TRIGGER <trigger_name> [ENABLE|DISABLE];


ALTER TABLE <table_name> [ENABLE|DISABLE] ALL TRIGGERS;
Syntax Explanation:

● The first syntax shows how to enable/disable the single trigger.


● The second statement shows how to enable/disable all the triggers on a particular
table.

14. EXCEPTION HANDLING


An exception is an error condition during a program execution. PL/SQL supports programmers to
catch such conditions using EXCEPTION block in the program and an appropriate action is taken
against the error condition. There are two types of exceptions −
● System-defined exceptions
● User-defined exceptions

Syntax for Exception Handling


The general syntax for exception handling is as follows. Here you can list down as many exceptions
77
as you can handle. The default exception will be handled using ​WHEN others THEN​ −
DECLARE
​<​declarations section​>
BEGIN
​<​executable command​(​s​)>
EXCEPTION
​<​exception handling goes here ​>
WHEN exception1 THEN
exception1​-​handling​-​statements
WHEN exception2 THEN
exception2​-​handling​-​statements
WHEN exception3 THEN
exception3​-​handling​-​statements
​........
WHEN others THEN
exception3​-​handling​-​statements
END​;

Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters −
DECLARE
c_id customers​.​id​%​type ​:=​ ​8​;
c_name customerS​.​Name​%​type​;
c_addr customers​.​address​%​type​;
BEGIN
SELECT name​,​ address INTO c_name​,​ c_addr
FROM customers
WHERE id ​=​ c_id​;
DBMS_OUTPUT​.​PUT_LINE ​(​'Name: '​||​ c_name​);
DBMS_OUTPUT​.​PUT_LINE ​(​'Address: '​ ​||​ c_addr​);

EXCEPTION
WHEN no_data_found THEN
dbms_output​.​put_line​(​'No such customer!'​);
WHEN others THEN
dbms_output​.​put_line​(​'Error!'​);
END​;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!

PL/SQL procedure successfully completed.

The above program displays the name and address of a customer whose ID is given. Since there is
no customer with ID value 8 in our database, the program raises the run-time exception
NO_DATA_FOUND, which is captured in the EXCEPTION block.

Raising Exceptions
78
Exceptions are raised by the database server automatically whenever there is any internal database
error, but exceptions can be raised explicitly by the programmer by using the command RAISE.
Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION​;
BEGIN
IF condition THEN
RAISE exception_name​;
​END​ IF​;
EXCEPTION
WHEN exception_name THEN
statement​;
END​;
You can use the above syntax in raising the Oracle standard exception or any user-defined
exception. In the next section, we will give you an example on raising a user-defined exception. You
can raise the Oracle standard exceptions in a similar way.

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE statement
or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;

Example
The following example illustrates the concept. This program asks for a customer ID, when the user
enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers​.​id​%​type ​:=​ ​&​cc_id​;
c_name customerS​.​Name​%​type​;
c_addr customers​.​address​%​type​;
​--​ user ​defined​ exception
ex_invalid_id EXCEPTION​;
BEGIN
IF c_id ​<=​ ​0​ THEN
RAISE ex_invalid_id​;
ELSE
SELECT name​,​ address INTO c_name​,​ c_addr
FROM customers
WHERE id ​=​ c_id​;
DBMS_OUTPUT​.​PUT_LINE ​(​'Name: '​||​ c_name​);
DBMS_OUTPUT​.​PUT_LINE ​(​'Address: '​ ​||​ c_addr​);
​END​ IF​;

EXCEPTION
WHEN ex_invalid_id THEN
79
dbms_output​.​put_line​(​'ID must be greater than zero!'​);
WHEN no_data_found THEN
dbms_output​.​put_line​(​'No such customer!'​);
WHEN others THEN
dbms_output​.​put_line​(​'Error!'​);
END​;
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when a
SELECT INTO statement returns no rows. The following table lists few of the important pre-defined
exceptions −

Oracle
Exception SQLCODE Description
Error

It is raised when a null object is automatically


ACCESS_INTO_NULL 06530 -6530
assigned a value.

It is raised when none of the choices in the


CASE_NOT_FOUND 06592 -6592 WHEN clause of a CASE statement is selected,
and there is no ELSE clause.

It is raised when a program attempts to apply


collection methods other than EXISTS to an
uninitialized nested table or varray, or the
COLLECTION_IS_NULL 06531 -6531
program attempts to assign values to the
elements of an uninitialized nested table or
varray.

It is raised when duplicate values are attempted


DUP_VAL_ON_INDEX 00001 -1
to be stored in a column with unique index.
80

It is raised when attempts are made to make a


INVALID_CURSOR 01001 -1001 cursor operation that is not allowed, such as
closing an unopened cursor.

It is raised when the conversion of a character


INVALID_NUMBER 01722 -1722 string into a number fails because the string
does not represent a valid number.

It is raised when a program attempts to log on


LOGIN_DENIED 01017 -1017 to the database with an invalid username or
password.

It is raised when a SELECT INTO statement


NO_DATA_FOUND 01403 +100
returns no rows.

It is raised when a database call is issued


NOT_LOGGED_ON 01012 -1012
without being connected to the database.

It is raised when PL/SQL has an internal


PROGRAM_ERROR 06501 -6501
problem.

It is raised when a cursor fetches value in a


ROWTYPE_MISMATCH 06504 -6504
variable having incompatible data type.

It is raised when a member method is invoked,


SELF_IS_NULL 30625 -30625 but the instance of the object type was not
initialized.

It is raised when PL/SQL ran out of memory or


STORAGE_ERROR 06500 -6500
memory was corrupted.

It is raised when a SELECT INTO statement


TOO_MANY_ROWS 01422 -1422
returns more than one row.
81

It is raised when an arithmetic, conversion,


VALUE_ERROR 06502 -6502
truncation, or size constraint error occurs.

It is raised when an attempt is made to divide a


ZERO_DIVIDE 01476 1476
number by zero.

15. ​Packages
I​ n PL/SQL, a package is a schema object that contains definitions for a group of related 
functionalities. A package includes ​variables​, c
​ onstants​, c
​ ursors​, e
​ xceptions​, p
​ rocedures​, ​functions​, 
and subprograms. It is compiled and stored in the Oracle Database. 
Typically, a package has a specification and a body. A package specification is mandatory while the 
package body can be required or optional, depending on the package specification. 

The following picture illustrates PL/SQL packages: 

 
Package specification 
The package specification declares the public objects that are accessible from outside the package. 

If a package specification whose public objects include cursors and subprograms, then it must have 
a body which defines queries for the cursors and code for the subprograms. 

Package body 
A package body contains the implementation of the cursors or subprograms declared in the package 
specification. In the package body, you can declare or define private variables, cursors, etc., used only 
by package body itself. 

A package body can have an initialization part whose statements initialize variables or perform other 
one-time setups for the whole package. 

A package body can also have an exception-handling part used to handle ​exceptions​. 
82
Why using PL/SQL packages 
The package is a powerful feature of PL/SQL that you should use it in any project. The following are 
the advantages of the package: 

Make code more modular 


Packages allow you to encapsulate logically related types, variables, constants, subprograms, 
cursors, and exceptions in named PL/SQL modules. By doing this, you make each package more 
reusable, manageable, readable and reliable. 

Hide implementation details 


Packages allow you to expose the functionality via their specifications and hide the detailed 
implementation in the package body. 

It means that you can enhance the code in the body of the package without affecting other 
dependent packages or applications. 

Improve application performance 


Oracle loads the package into memory at the first time you invoke a package subprogram. The 
subsequent calls of other subprograms in the same package do not require disk I/O. This mechanism 
helps improve performance. 

Minimize unnecessary recompiling code 


Packages help avoid the unnecessary recompiling process. For instance, if you change the body of a 
package function, Oracle does not recompile the subprograms that use the function, because the 
subprograms are only dependent on the package specification, not the package body. 

Manage authorization easily 


By encapsulate objects in a package, you grant role on the package, instead of granting roles on each 
object in the package. 

PL/SQL package concept is simple but powerful. They allow you to encapsulate the code and make 
your application easier to develop and maintain. 
83

PACKAGES FROM PROJECT:

Customer package full code:

CUSTOMER_METHODS
Doc
Details
Grants
References
Dependencies
Code

package CUSTOMER_METHODS
as
procedure add_row (
p_CUSTOMER_ID in VARCHAR2 default null
,p_LAST_NAME in VARCHAR2 default null
,p_ADDRESS in VARCHAR2 default null
,p_FIRST_NAME in VARCHAR2 default null
,p_GOAL in VARCHAR2 default null
,p_EMAIL_ID in VARCHAR2 default null
,p_DOB in DATE default null
,p_HEIGHT in NUMBER default null
,p_WEIGHT in NUMBER default null
,p_PHONE_NO in NUMBER default null
84

);
procedure update_row (
p_CUSTOMER_ID in VARCHAR2 default null
,p_LAST_NAME in VARCHAR2 default null
,p_ADDRESS in VARCHAR2 default null
,p_FIRST_NAME in VARCHAR2 default null
,p_GOAL in VARCHAR2 default null
,p_EMAIL_ID in VARCHAR2 default null
,p_DOB in DATE default null
,p_HEIGHT in NUMBER default null
,p_WEIGHT in NUMBER default null
,p_PHONE_NO in NUMBER default null

);

procedure delete_row (
p_CUSTOMER_ID in VARCHAR2 default null

);

end CUSTOMER_METHODS;

CUSTOMER_METHODS
Doc
Details
Grants
References
Dependencies
Code

package body CUSTOMER_METHODS


as
procedure add_row (
p_CUSTOMER_ID in VARCHAR2 default null
,p_LAST_NAME in VARCHAR2 default null
,p_ADDRESS in VARCHAR2 default null
,p_FIRST_NAME in VARCHAR2 default null
,p_GOAL in VARCHAR2 default null
,p_EMAIL_ID in VARCHAR2 default null
,p_DOB in DATE default null
,p_HEIGHT in NUMBER default null
,p_WEIGHT in NUMBER default null
,p_PHONE_NO in NUMBER default null
85

)
is
begin
insert into CUSTOMER
( CUSTOMER_ID, LAST_NAME, ADDRESS, FIRST_NAME, GOAL, EMAIL_ID, DOB, HEIGHT,
WEIGHT, PHONE_NO)
values
( p_CUSTOMER_ID, p_LAST_NAME, p_ADDRESS, p_FIRST_NAME, p_GOAL, p_EMAIL_ID,
p_DOB, p_HEIGHT, p_WEIGHT, p_PHONE_NO);
end add_row;

procedure update_row (
p_CUSTOMER_ID in VARCHAR2 default null
,p_LAST_NAME in VARCHAR2 default null
,p_ADDRESS in VARCHAR2 default null
,p_FIRST_NAME in VARCHAR2 default null
,p_GOAL in VARCHAR2 default null
,p_EMAIL_ID in VARCHAR2 default null
,p_DOB in DATE default null
,p_HEIGHT in NUMBER default null
,p_WEIGHT in NUMBER default null
,p_PHONE_NO in NUMBER default null

)
is
begin
update CUSTOMER
set LAST_NAME=p_LAST_NAME, ADDRESS=p_ADDRESS, FIRST_NAME=p_FIRST_NAME,
GOAL=p_GOAL, EMAIL_ID=p_EMAIL_ID, DOB=p_DOB, HEIGHT=p_HEIGHT, WEIGHT=p_WEIGHT,
PHONE_NO=p_PHONE_NO
where
(CUSTOMER_ID = p_CUSTOMER_ID);
end update_row;

procedure delete_row (
p_CUSTOMER_ID in VARCHAR2 default null

)
is
begin
delete CUSTOMER
where
CUSTOMER_ID = p_CUSTOMER_ID;
end delete_row;

end CUSTOMER_METHODS;
86

16. QUERRIES:

1 ​Give Total Salary issued by each department


SELECT​ DEPT_NO,​SUM​(SALARY) ​FROM​ EMPLOYEE ​WHERE​ DEPT_NO ​IS​ ​NOT​ ​NULL
GROUP​ ​BY​ DEPT_NO ;

OUTPUT

2 ​Give Average Salary of each job


SELECT​ JOB,​AVG​(SALARY) ​FROM​ EMPLOYEE ​WHERE​ JOB ​IS​ N
​ OT​ ​NULL​ ​GROUP​ ​BY
JOB ;

OUTPUT
87
3 ​Give the total salary paid to each job within each dept.
SELECT​ DEPT_NO,JOB,SALARY ​FROM​ EMPLOYEE ​ORDER​ ​BY​ DEPT_NO;

OUTPUT

4 ​Give total, max, min, avg salary of employee job wise for dept number and
display ​rows having avg salary greater than 1,00,000
SELECT​ * ​FROM​ (​SELECT​ ​SUM​(SALARY), ​AVG​(SALARY) AVER, ​MAX​(SALARY),
MIN​(SALARY),JOB ​FROM​ EMPLOYEE ​WHERE​ DEPT_NO ​IN​(​1​,​2)
​ ​GROUP​ ​BY
JOB)​WHERE​ AVER >​100000​;

OUTPUT
88
5 ​Give name, salary of employees having salary greater than the minimum salary of

Department ML
SELECT​ EMP_NAME,SALARY ​FROM​ EMPLOYEE ​WHERE​ SALARY > ( ​SELECT
MIN​(SALARY) ​FROM​ EMPLOYEE ​WHERE​ DEPT_NO = (​SELECT​ DEPTT_NO F
​ ROM
DEPARTMENT ​WHERE​ DEPTT_NAME=​'RESEARCH'​))

OUTPUT

6 ​Give name, salary, of employee having salary greater than average


salary of ​department ‘HR’
SELECT​ EMP_NAME,SALARY ​FROM​ EMPLOYEE ​WHERE​ SALARY > ( ​SELECT
AVG​(SALARY) ​FROM​ EMPLOYEE ​WHERE​ DEPT_NO = (​SELECT​ DEPTT_NO F
​ ROM
DEPARTMENT ​WHERE​ DEPTT_NAME=​'HR'​))

OUTPUT

7 ​List all details whose manager id = M006 of department


89

​ ROM​ DEPARTMENT ​WHERE​ DEPTT_NO = ( ​SELECT​ DEPT_NO ​FROM


SELECT​ * F
EMPLOYEE W ​ HERE​ EMP_ID =​'E006'​ ​AND​ MANAGERID=​'YES'​);

​OUTPUT

8 ​List all employees belonging to department Marketing.


SELECT​ * ​FROM​ EMPLOYEE ​WHERE​ DEPT_NO ​IN​ (​SELECT​ DEPTT_NO ​FROM
DEPARTMENT ​WHERE​ DEPTT_NAME=​'FINANCE'​) ;

OUTPUT

9 ​List name of employee whose do some job as of employee number


E008.
SELECT​ EMP_NAME ​FROM​ EMPLOYEE ​WHERE​ JOB = (​SELECT​ JOB ​FROM​ EMPLOYEE ​WHERE
EMP_ID=​'E008'​);

OUTPUT-
90

10 ​List the name of employee who do the same job and get the salary greater
than ​salary of employee ID as E008.
SELECT​ EMP_NAME ​FROM​ EMPLOYEE ​WHERE​ JOB=(​SELECT​ JOB F ​ ROM​ EMPLOYEE
WHERE​ EMP_ID=​'E012'​) ​AND​ SALARY>(​SELECT​ SALARY ​FROM​ EMPLOYEE ​WHERE
EMP_ID=​'E012'​);

OUTPUT

11​ ​List the name and salary of the employee who get salary greater than the
average ​salary of department Research

SELECT​ EMP_NAME ​FROM​ EMPLOYEE W ​ HERE​ SALARY > (​SELECT​ ​AVG​(SALARY) ​FROM​ EMPLOYEE
LEFT​ ​OUTER​ ​JOIN​ DEPARTMENT ​ON​ EMPLOYEE.DEPT_NO=DEPARTMENT.DEPTT_NO ​WHERE
DEPTT_NAME=​'RESEARCH'​);

OUTPUT

12 ​List the names of employees who do not manage any


employee.
SELECT​ EMP_NAME ​FROM​ EMPLOYEE ​WHERE​ MANAGERID=​'NO'
91
OUTPUT

13 ​List name of employee who have at least one person reporting to them.

SELECT​ EMP_NAME ​FROM​ EMPLOYEE ​WHERE​ MANAGERID=​'YES'​;

OUTPUT
92
14 ​Name of employee salary less than minimum salary of HR department and
are not ​of HR department.
SELECT​ EMP_NAME ​FROM​ EMPLOYEE W​ HERE​ SALARY > (​SELECT​ ​MIN​(SALARY)
FROM​ EMPLOYEE ​WHERE​ DEPT_NO = (​SELECT​ DEPTT_NO ​FROM​ DEPARTMENT ​WHERE
DEPTT_NAME=​'HR'​)) ​AND​ DEPT_NO !=(​SELECT​ DEPTT_NO ​FROM​ DEPARTMENT
WHERE​ DEPTT_NAME=​'HR'​);
OUTPUT

15 ​List the name of highest paid employee (without using aggregate

function)

​ ELECT​ EMP_NAME ​FROM​ EMPLOYEE ​WHERE​ SALARY=(​SELECT​ ​MAX​(SALARY) ​FROM


S
EMPLOYEE);

OUTPUT-

OR WITHOUT AGGREGATE
93

SELECT​ EMP_NAME,SALARY ​FROM​ EMPLOYEE ​MINUS​ ​SELECT​ E1.EMP_NAME,E1.SALARY ​FROM


EMPLOYEE E1,EMPLOYEE E2 ​WHERE​ E1.SALARY<E2.SALARY;

OUTPUT-

16 ​List the name of lowest paid employee (without using aggregate


function)

SELECT​ EMP_NAME ​FROM​ EMPLOYEE ​WHERE​ SALARY=(​SELECT​ ​MIN​(SALARY) ​FROM​ EMPLOYEE);

OUTPUT-

OR WITHOUT AGGREGATE

SELECT​ EMP_NAME,SALARY ​FROM​ EMPLOYEE ​MINUS​ ​SELECT​ E1.EMP_NAME,E1.SALARY ​FROM


EMPLOYEE E1,EMPLOYEE E2 ​WHERE​ E1.SALARY>E2.SALARY;

OUTPUT-
94

END

You might also like