Download as pdf or txt
Download as pdf or txt
You are on page 1of 151

Topic-1 : DBMS

=============
What is Data ?
- it is a rawfact i.e characters,numbers,special characters and symbols.
- it never give meaningfull statements.

Ex:
SMITH is data 1021 is data
ALLEN is data 1022 is data
WARNER is data 1023 is data

What is Information ?
- processing data is called as "Information".
- it always provide meaningfull statements to user.

Ex:
Customer_Name Customer_Id
============== ============
SMITH 1021
ALLEN 1022
WARNER 1023

What is Database ?
- it is a collection of inter-related information.
Ex: BankingDB,UniversityDB,HMDB,HRMDB,.......etc

Types of Databases?
- there are two types of databases.
i) OLTP(online transaction processing)
ii) OLAP(online analytical processing)

i) OLTP:
=======
- these databases are used for storing "day-to-day" transactions
information.
Ex: oracle,sqlserver,mysql,db2,postgresql,..................etc

ii) OLAP:
========
- these databases are used for storing "Historical information" i.e Bigdata.
Ex: Datawarehouse

What is DBMS?
- it is a software which is used to manage and maintain data / information
in database memory.
- by using DBMS s/w user can perform the following operations are,
> creating database memory
> creating table
> inserting data
> updating data
> selecting data
> deleting data
- Here DBMS s/w will act as an interface between User and Database.

User <--------------> DBMS s/w <-----------> Database


(Interface)
Models of DBMS?
- there are three types of DBMS models.
1) Hierarchical database management system(HDBMS)
Ex: IMS s/w (information management system)
2) Network database management system(NDBMS)
Ex: IDBMS s/w (integrated database management system)
- HDBMS,NDBMS models are outdated in real time.
3) Relational database management system(RDBMS)
i) Object Relational database management system(ORDBMS)
- data can be stored in the form of "Table".
a table = collection of rows & columns
a row = group of columns
a database = group of tables
- row / record / tuple are same.
- column / attribute / field are same.
ii) these databases are completely depend on "SQL".
so that these databases are called as "SQL databases".
Ex: Oracle,SQLServer,Mysql,Db2,..........etc

ii) Object Oriented database management system(OODBMS)


- data can be stored in the form of "Objects".
- it depends on "OOPS" concept.so that these
databases are called as "NOSQL databases".
Ex: MongoDB,Cassandra,.......etc
======================================================================
Topic-2: ORACLE
===============
What is oracle?
- Oracle is a Backend tool / DB software / RDBMS product / ORDBMS model.
- Oracle was introduced by "Oracle corporation" in 1979.
- Oracle is used to design and develop backend applications.these
backend applications are also called as "Databases".
- Backend application(Database) is an application where we can store
data / information of a particular business organization.
- When we work with oracle first we need to deployee(installation) oracle
s/w in a computer.
- To install oracle s/w we need a platform.

What is Platform?
- it is combination of "operating system and micro processor".
- it again classified into two types.

1. Platform dependent:
====================
- supporting only one operating system with any micro processor is
called as "platform dependent".
Ex: Cobal,Pascal,C,C++.

2. Platform independent:
====================
- supporting any operating system with any micro processor is
called as "platform independent".
Ex: Oracle,Java,.Net core,Python,......etc

Versions of Oracle:
================
- The first version of oracle s/w is "oracle1.0" to "oracle19c".
- The very very latest version of oracle is "oracle21c".
- versions are oracle1.0,2.0,3.0.4.0,5.0,6.0,7.0,8.0,
> oracle8i(internet)
> oracle9i
> oracle10g(grid technologies)
> oracle11g
> oracle12c(cloud technologies)
> oracle18c
> oracle19c(latest version)
> oracle21c(very latest version)

Types of oracle s/w editions:


========================
- oracle s/w is available in two editions in the market.
i) Oracle express edition:
- it doesnot supports all features of oracle db.
Ex: recyclebin,flashback,purge,partition tables,....etc are not
allowed.
ii) Oracle enterprise edition:
- it supports all the features of oracle db.
Ex: recyclebin,flashback,purge,partition tables,....etc are
allowed.

How to download oracle19c enterprise edition s/w:


===========================================
https://www.oracle.com/in/database/technologies/oracle19c-windows-downloads.html

STEP1: DOWNLOAD
STEP2: ZIP FOLDER
STEP3: UNZIP / EXTRACT
STEP4: FOLLOW THE FOLLOWING VIDEO

How to install oracle19c enterprise edition s/w:


========================================
- once we install oracle s/w internally there are two components are
installed in the system.
1. Client component
2. Server component

1. Client:
========
- by using client tool we can perform the following three operations,
STEP1: User can connect to oracle server.
STEP2: User can send request to oracle server.
STEP3: User can get response from oracle server.
Ex: SQLplus,Toad,SQLDeveloper......etc

2. Server :
=========
- server contains two more sub components,
i) Instance
ii) Database

i) Instance:
=========
- it is a temporary memory which is used to store data temporarly.
- this sub component memory is allocating by the system from RAM.

ii) Database:
===========
- it is a permenent memory which is used to store data permanently.
- this sub component memory is allocating by the system from ROM(i.e Harddisk)
How to connect to oracle database server:
====================================
> go to all programs
> open oracle-oradb19_home1 folder
> click on SQLPLUS icon
Enter username : system(default username)
Enter password : tiger (created at the time of installation)
connected.

How to create a new username and password in oracle:


==============================================
syntax:
======
CREATE USER <USERNAME> IDENTIFIED BY <PASSWORD>;

EX:
SQL> CREATE USER MYDB11AM IDENTIFIED BY 123;
User created.

Granting permissions to MYDB11AM user:


===================================
Enter username : system
Enter password : tiger
syntax:
=======
SQL> GRANT <PERMISSIONS> TO <USERNAME>;

EX:
SQL> GRANT DBA TO MYDB11AM;
Grant succeeded.

SQL> CONN
Enter user-name: MYDB11AM/123
Connected.

How to change a password for user:


===============================
SQL> PASSWORD
Changing password for MYDB11AM
Old password: 123
New password: ABC
Retype new password: ABC
Password changed.

How to re-create a new password if we forgot it:


=========================================
syntax:
=======
ALTER USER <USERNAME> IDENTIFIED BY <NEW PASSWORD>;

EX:
Enter user-name: system/tiger
Connected.

SQL> ALTER USER MYDB11AM IDENTIFIED BY MYDB11AM;


User altered.

SQL> CONN
Enter user-name: MYDB11AM/MYDB11AM
Connected.

How to view username if we forgot it:


================================
syntax:
======
SELECT USERNAME FROM ALL_USERS;

EX:
SQL> CONN
Enter username : system/tiger

SQL> SELECT USERNAME FROM ALL_USERS;

How to drop a user from oracle database:


===================================
SYNTAX:
========
DROP USER <USER NAME> CASCADE;

EX:
SQL> CONN
Enter user-name: system/tiger
Connected.

SQL> DROP USER MYDB11AM CASCADE;


User dropped.
=======================================================================
Topic-3 : SQL
===========
- SQL stands for structure query language which was introduced by "IBM".
- SQL is used to communicate with database.
- The initial name is "SEQUEL" and later renamed as a "SQL".
- SQL is not a case-sensitive language i.e we can write sql queries in upper / lower
/ combination of upper and lower characters.
Ex: SELECT * FOMM EMP; -----------executed
Ex: select * from emp;-----------------executed
Ex: SelecT * From Emp;---------------executed
- Every sql statement must be ends with " ; ".

Sub-Languages of SQL:
===================
1) Data Definition Language(DDL):
============================
- create
- alter
> alter - modify
> alter - add
> alter - rename
> alter - drop
- rename
- truncate
- drop

2) Data Manipulation Language(DML):


===============================
- insert
- update
- delete
3) Data Retrieval / Query Language(DRL / DQL):
========================================
- select (read only)

4) Transaction Control Language(TCL):


================================
- commit
- rollback
- savepoint

5) Data Control Language(DCL):


===========================
- grant
- revoke

Datatypes in oracle:
=================
- it is an attribute which is used to store the type of data into a variable/
into a column.
- oracle supports the following datatypes are,

i) INT:
=====
- storing interger values only.

Ex:
SNO int
STID int
EMPNO int

ii) NUMBER(P,S):
==============
- storing interger values and also float values.
NUMBER(P) : storing integer values only.
NUMBER(P,S) : storing float values only.

Precision(P):
==========
- counting all digits including left and right sides digits of a decimal
point.

Ex:
36.21 ------------> P=4
4723.83 --------> P=6

Scale(S):
========
- counting the right side digits of a decimal point.

Ex:
76.12 ------------> P=4 , S=2
9867.24---------> P=6 , S=2
785678.364----> P=9, S=3

Ex:
Price number(7,2)
===============
0.0
45.12
99.99
999.99
9999.99
10000.00
99999.99
100000.00----------------error
6534.234---error

Ex:
SNO number(4)
=============
0
999
1000
9999
7853
10000-------error

iii) CHAR(size):
=============
- it allowed string format values only.
- it is a fixed length datatype.(i.e static)
- the maximum size is 2000 bytes.
Disadvantage:
============
- memory wasted.

iv) VARCHAR2(size):
=================
- it allowed string format values only.
- it is a variable length datatype.(i.e dynamic)
- the maximum size is 4000 bytes.

Advantage:
============
- memory saved.

v) Long :
=======
- it allowed string format values only.
- it is a variable length datatype.(i.e dynamic)
- the maximum size is 2gb.
- a table is having only one long datatype column.

vi) DATE:
=======
- it allowed date and time information.(time is optional)
- if user cannot insert time then system will take '12:00:00am' by default.
- the range of date datatype is from '01-jan-4712 bc' to '31-dec-9999 ad'.
- the default format of date in oracle database is,
' DD-MON-YY/YYYY HH:MI:SS am/pm'
' 20-SEP-23/2023 12:00:00 AM '
1 1 2 1 1 1 -------------> 7 BYTES(FIXED MEMORY)
- the maximum size of date datatype is 7 bytes.

vii) TIMESTAMP:
==============
- it will store date and time along with milli seconds.
- the default format of timestamp in oracle database is,
' DD-MON-YY/YYYY HH:MI:SS.MS am/pm'
' 20-SEP-23/2023 12:00:00:0000 AM '
1 1 2 1 1 1 4 -------------> 11 BYTES(FIXED MEMORY)
- the maximum size of timestamp datatype is 11 bytes.

viii) RAW :
=========
- it will store image / audio / video file in the form of 01010001010101
binary format.
- it is a fixed length datatype(i.e static)
- the maximum size is 2000 bytes.

ix) LONG RAW :


==============
- it will store image / audio / video file in the form of 01010001010101
binary format.
- it is a variable length datatype(i.e dynamic)
- the maximum size is 2gb.

xi) BLOB(binary large object):


==========================
- it will store image / audio / video file in the form of 01010001010101
binary format.
- it is a variable length datatype(i.e dynamic)
- the maximum size is 4gb.

xii) CLOB(character large object)


=============================
- it allowed string format values only.
- it is a variable length datatype.(i.e dynamic)
- the maximum size is 4gb.

String format data :


=================
char(size) : 2000 bytes
varchar2(size) : 4000 bytes
long : 2gb
clob : 4gb

Binary format data :


================
raw : 2000 bytes
long raw : 2gb
blob : 4gb
======================================================================
Data Definition Language(DDL):
===========================
CREATE :
========
- to create a new object in database such as Tables,Views,Sequences,
Indexes,Procedure,Functions,Triggers.........etc

How to create a new table in oracle database:


=======================================
syntax:
======
CREATE TABLE <TABLE NAME>(<COLUMN NAME1> <DATATYPE>[SIZE],
<COLUMN NAME2> <DATATYPE>[SIZE],.............................);

- Here a table can have maximum 1000 columns and unlimited rows.

Ex:
SQL> CREATE TABLE STUDENT(STID INT,SNAME CHAR(10),SFEE NUMBER(6,2));

How to view structure of a table:


============================
syntax:
=======
DESC <table name>; [ Describe ]

Ex:
SQL> DESC STUDENT;

ALTER:
======
- To modify the structure a table.
> ALTER - MODIFY
> ALTER - ADD
> ALTER - RENAME
> ALTER - DROP

ALTER - MODIFY:
===============
- to change datatype and also the size of the datatype of a specific
column.
Syntax:
=======
ALTER TABLE <TN> MODIFY <COLUMN NAME> <NEW DATATYPE>[NEW SIZE];

EX:
SQL> ALTER TABLE STUDENT MODIFY SNAME VARCHAR2(20);

ALTER - ADD:
===========
- to add a new column to an existing table.
syntax:
=======
ALTER TABLE <TN> ADD <NEW COLUMN NAME> <DATATYPE>[SIZE];

EX:
SQL> ALTER TABLE STUDENT ADD SADDRESS VARCHAR2(50);

ALTER - RENAME:
================
- to change a column name.
syntax:
=======
ALTER TABLE <TN> RENAME COLUMN <OLD COLUMN NAME> TO <NEW COLUMN
NAME>;

EX:
SQL> ALTER TABLE STUDENT RENAME COLUMN SNAME TO STUDENTNAME;

ALTER - DROP:
============
- to drop / delete a column from a table.

syntax:
======
ALTER TABLE <TN> DROP COLUMN <COLUMN NAME>;

EX:
SQL> ALTER TABLE STUDENT DROP COLUMN SFEE;

RENAME:
========
- to change a table name.
syntax:
======
RENAME <OLD TABLE NAME> TO <NEW TABLE NAME>;

EX:
SQL> RENAME STUDENT TO SDETAILS;
SQL> RENAME SDETAILS TO STUDENT;

TRUNCATE:
==========
- to delete all rows but not columns from a table.
- by using truncate command we cannot delete a specific row because
it does not supports "WHERE" claues condition.
- it is a permanent data deletion.

syntax:
======
TRUNCATE TABLE <TABLE NAME>;

EX:
SQL> TRUNCATE TABLE STUDENT WHERE STID=1022;----------NOT ALLOWED
SQL> TRUNCATE TABLE STUDENT;----------ALLOWED

DROP :
======
- to drop / delete a table permanently.
syntax:
=======
DROP TABLE <TABLE NAME> PURGE;

EX:
SQL> DROP TABLE STUDENT PURGE;

II) Data Manipulation Language(DML):


================================
INSERT:
=======
- to insert a new row data into a table.

Method-1:
=========
- we should insert values for all columns in a table (i.e without left any column).

syntax:
======
INSERT INTO <TN> VALUES(VALUE1,VALUE2,..............);

EX:
SQL> INSERT INTO STUDENT VALUES(1021,'JONES',2500);

Method-2:
=========
- inserting values for the required column only.

syntax:
=======
INSERT INTO <TN>(<Required Columns Names>) VALUES(VALUE1,VALUE2,........);

EX:
SQL> INSERT INTO STUDENT(STID,SNAME,SFEE)VALUES(1022,'ALLEN',3500);
SQL> INSERT INTO STUDENT(STID,SNAME) VALUES(1023,'WARD');
SQL> INSERT INTO STUDENT(STID) VALUES(1024);

- Here missing columns will take by default "NULL".

UPDATE:
========
- to update all rows data and also a specific row data in a table.
- if we want to update a specific row data then we should use
"WHERE" clause condition.
syntax:
======
UPDATE <TN> SET <COLUMN NAME1>=<VALUE1>,<COLUMN NAME2>=<VALUE2>,
..........................................[ WHERE <CONDITION>];

EX:
SQL> UPDATE STUDENT SET SNAME='SMITH',SFEE=5600 WHERE STID=1024;
SQL> UPDATE STUDENT SET SNAME='SCOTT' WHERE SNAME='JONES';
SQL> UPDATE STUDENT SET SFEE=5000;

DELETE:
=======
- to delete all rows at a time and a specific row by using "WHERE"
clause condition.
- it is a temporary data deletion.
syntax:
======
DELETE FROM <TN> [ WHERE <CONDITION>];

EX:
SQL> DELETE FROM STUDENT WHERE STID=1023;
SQL> DELETE FROM STUDENT;

TRUNCATE vs DELETE:
===================

TRUNCATE DELETE
========== ========
1. we cannot delete a specific row. 1. we can delete a specific row.

2. it does not support "WHERE" 2. it supports "WHERE" clause


clause condition. condition.

3. it is a permanent data deletion. 3. it is a temporary data deletion.

4. we cannot restore deleted data 4. we can restore deleted data


by using ROLLBACK command. by using ROLLBACK command.

5. the execution speed is fast. 5. the execution speed is slow.


( deleting all rows as page wise) ( deleting one-by-one row wise)

Data Query / Retrieval Language(DQL / DRL):


======================================
SELECT :
========
- retrieving all rows from a table at a time and also a specific row
by using "WHERE" cluase condition.

syntax:
======
SELECT * / <LIST OF COLUMNS > FROM <TN> [WHERE <CONDITION>];

Here " * " ----- all columns in a table.

EX:
SQL> SELECT * FROM DEPT;
(OR)
SQL> SELECT DEPTNO,DNAME,LOC FROM DEPT;

EX:
SQL> SELECT * FROM EMP WHERE JOB='MANAGER';
======================================================================
OPERATORS IN ORACLE:
=====================
- Operators are used to perform some operation on the given operand
values.oracle supports the following operators are,

1. Assignment operator => =


2. Arithmetic operators => +,-,*,/
3. Relational operators => < , > , <=, >=,!= (or) <>
4. Logical operators => AND,OR,NOT
5. Set operators => UNION,UNION ALL,INTERSECT,MINUS.

6. Special operators => (+ve) (-ve)


===== =====
IN NOT IN
BETWEEN NOT BETWEEN
IS NULL IS NOT NULL
LIKE NOT LIKE

1. Assignment operator:
====================
- to assign a value to a variable / to a attribute.
syntax:
======
where <column name> <assignment operator> <value>;
Ex:
SQL> SELECT * FROM EMP WHERE JOB = 'MANAGER';
SQL> UPDATE EMP SET SAL=45000 WHERE EMPNO=7788;
SQL> DELETE FROM EMP WHERE SAL=5000;

2. Arithmetic operators:
====================
- to perform arithmetic operations like addition,subtraction,multiple and
division.
syntax:
======
<column name> <arithmetic operator> <value>

Ex:
waq to display employees salaries after adding 5000?
SQL> SELECT SAL,SAL+5000 FROM EMP;

Ex:
waq to display EMPNO,ENAME,SALARY and ANNUAL SALARY of employees
who are working under deptno is 10?
SQL> SELECT EMPNO,ENAME,SAL,SAL*12 FROM EMP WHERE DEPTNO=10;

Ex:
waq to display employees salaries after increment of 10% who are working as
a CLERK?
SQL> SELECT ENAME,JOB,SAL,SAL+SAL*10/100 FROM EMP WHERE JOB='CLERK';

Ex:
waq to display all employees salaries after increment of 5%?
SELECT ENAME,JOB,SAL,SAL+SAL*0.05 FROM EMP;

3) Relational operators:
====================
- comparing a specific column values with user defined condition.
syntax:
======
where <column name> <relational operator> <value>

Ex:
waq to display employees who are joined after 1981?
SQL> SELECT * FROM EMP WHERE HIREDATE > '31-DEC-81';

Ex:
waq to display employees who are joined before 1981?
SQL> SELECT * FROM EMP WHERE HIREDATE < '01-JAN-81';

Ex:
waq to display employees who are joined in 1981?
SQL> SELECT * FROM EMP WHERE HIREDATE

4) Logical operators:
==================
- to check more than one condition.
- these operators are "AND,OR,NOT".

AND:
====
- it return a value if both conditions are true.

COND1 COND2
====== =======
T T ===> T
T F ===> F
F T ===> F
F F ===> F

syntax:
=======
where <condition1> and <condition2>

Ex:
waq to display employee whose name is SMITH and working as a CLERK?
SQL> SELECT * FROM EMP WHERE ENAME='SMITH' AND JOB='CLERK';

OR:
===
- it return a value if any one condition is true from the given group of
conditions.

COND1 COND2
====== =======
T T ===> T
T F ===> T
F T ===> T
F F ===> F
syntax:
=======
where <condition1> or <condition2>

Ex:
waq to display employees who are working as a ANALYST or whose salary is more
than 2500?
SQL> SELECT * FROM EMP WHERE JOB='ANALYST' OR SAL>2500;

NOT:
====
- it return all values except the given conditional values.

syntax:
=======
where not <condition1> and not <condition2>

Ex:
waq to display employees who are not working under deptno is 10 and 30?
SQL> SELECT * FROM EMP WHERE NOT DEPTNO=10 AND NOT DEPTNO=30;

SET OPERATORS:
===============
- are used to combined the results of two select statements.

syntax:
=======
<select query1> <set operator> <select query2>;

Ex:

A={10,20,30} B={30,40,50}

UNION:
======
A U B = {10,20,30,40,50}

UNION ALL:
===========
A UL B = {10,20,30,30,40,50}

INTERSECT:
==========
A I B = { 30}
MINUS :
=======
A - B = { 10,20 }
B - A = { 40,50 }

Examples in database :
====================
SQL> SELECT * FROM EMP_HYD;

EID ENAME SAL


---------- ---------- ----------
1021 SMITH 85000
1022 ALLEN 56000
1023 WARD 62000

SQL> SELECT * FROM EMP_CHENNAI;

EID ENAME SAL


---------- ---------- ----------
1021 SMITH 85000
1024 MILLER 45000
1025 WARNER 28000

EX:
waq to display all employees details who are working in the organization?
SQL> SELECT * FROM EMP_HYD UNION ALL SELECT * FROM EMP_CHENNAI;(with
duplicate rows)
SQL> SELECT * FROM EMP_HYD UNION SELECT * FROM EMP_CHENNAI;(without
duplicate rows)

Ex:
waq to displays employees who are working in HYD but not in CHENNAI branch?
SQL> SELECT * FROM EMP_HYD MINUS SELECT * FROM EMP_CHENNAI;

Ex:
waq to display employees who are working in both branches?
SQL> SELECT * FROM EMP_HYD INTERSECT SELECT * FROM EMP_CHENNAI;

SPECIAL OPERATORS:
===================
IN :
===
- comparing the list of values with a single condition.
syntax:
======
where <column name> in (<list of values>);
Ex:
waq to dsiplay employees whose EMPNO is 7369,7566,7788,7900?
SQL> SELECT * FROM EMP WHERE EMPNO IN(7369,7566,7788,7900);

NOT IN:
======
Ex:
waq to dsiplay employees whose EMPNO is not 7369,7566,7788,7900?
SQL> SELECT * FROM EMP WHERE EMPNO NOT IN(7369,7566,7788,7900);

BETWEEN:
=========
- comparing a particular range value.
syntax:
=======
where <column name> between <low value> and <high value>;

Ex:
waq to display employees who are joined in 1981?
SQL> SELECT * FROM EMP WHERE HIREDATE BETWEEN '01-JAN-81' AND '31-DEC-81';
(OR)
SQL> SELECT * FROM EMP WHERE (HIREDATE>='01-JAN-81') AND (HIREDATE<='31-
DEC-81');

NOT BETWEEN:
=============
Ex:
waq to display employees who are not joined in 1981?
SQL> SELECT * FROM EMP WHERE HIREDATE NOT BETWEEN '01-JAN-81' AND '31-DEC-
81';

IS NULL:
========
- comparing NULLS in a table.
syntax:
=======
where <column name> is null

Ex:
waq to display employees whose commission is empty / null ?
SQL> SELECT * FROM EMP WHERE COMM IS NULL;

IS NOT NULL:
============
Ex:
waq to display employees whose commission is not empty / not null ?
SQL> SELECT * FROM EMP WHERE COMM IS NOT NULL;

Working with NULL:


=================
- NULL is an empty.
- NULL != 0 and NULL != space.

Note:
=====
- If any arthimetic operator is performing some operations with NULL
then it again returns NULL only.
Ex:
If x =1000 then
i) x+null ===> 1000+null ====> null
ii) x-null ===> 1000-null ====> null
iii) x*null ===> 1000*null ====> null
iv) x/null ====> 1000/null ====> null

Ex:
waq to display EMPNO,ENAME,SALARY,COMMISSION and SALARY+COMMISSION
of the employee "SMITH"?
SQL> SELECT EMPNO,ENAME,SAL,COMM,SAL+COMM FROM EMP WHERE
ENAME='SMITH';

EMPNO ENAME SAL COMM SAL+COMM


---------- ---------- ---------- ---------- ----------
7369 SMITH 800

- In the above example the employee SMITH salary is 800 and there is no
commission so that sal+comm is 800 only but it returns NULL.
- To overcome the above problem we use a pre-defined function in oracle
is NVL().

What is NVL(Exp1,Exp2):
=====================
- it stands for NULL VALUE.
- it is used to replace a user defined value inplace of NULL.
- this function is having two arguments those are Expression1 & Expression2.
- if EXP1 is NULL then it returns EXP2 value(User defined value)
- if EXP1 is NOT NULL then it returns EXP1 value only.

EX:
SQL> SELECT NVL(NULL,0) FROM DUAL;

NVL(NULL,0)
-----------
0

SQL> SELECT NVL(NULL,100) FROM DUAL;

NVL(NULL,100)
-------------
100

SQL> SELECT NVL(100,500) FROM DUAL;

NVL(100,500)
------------
100

SOLUTION:
SQL> SELECT EMPNO,ENAME,SAL,COMM,SAL+NVL(COMM,0)
FROM EMP WHERE ENAME='SMITH';

EMPNO ENAME SAL COMM SAL+NVL(COMM,0)


---------- ---------- ---------- ---------- ---------------
7369 SMITH 800 800

NVL2(EXP1,EXP2,EXP3):
=====================
- it is an extension of NVL().
- this function is having 3 arguments are Expression1,Expression2 and
Expression3.

- if Exp1 is NULL then it returns Exp3 value(UD value)


- if Exp1 is NOT NULL then it returns Exp2 value(UD value)

Ex:
SQL> SELECT NVL2(NULL,100,200) FROM DUAL;

NVL2(NULL,100,200)
------------------
200

SQL> SELECT NVL2(0,100,200) FROM DUAL;

NVL2(0,100,200)
---------------
100

EX:
waq to update all employees commissions in a table based on the following
conditions,
i) if the employee commission is NULL then update those employees
commission as 600.
ii) if the employee commission is NOT NULL then update those employees
commission as commission+300.

SQL> UPDATE EMP SET COMM=NVL2(COMM,COMM+300,600);

LIKE:
=====
- comparing a specific character pattern.
- when we use LIKE operator we should follow the following
"wildcard operators" are,
% - it represent the remaining group of characters after
selected character.
_ - counting a single character in the expression.

syntax:
=======
where <column name> LIKE ' [<wildcard operator>] <character pattern>[<wildcard operator>] '

Ex:
waq to display employees whose name starts with "S" character?
SQL> SELECT * FROM EMP WHERE ENAME LIKE 'S%';-----RESULT

Ex:
waq to display employees whose name ends with "N" character?
SQL> SELECT * FROM EMP WHERE ENAME LIKE '%N';

Ex:
to display employees whose name is having "I" character?
SQL> SELECT * FROM EMP WHERE ENAME LIKE '%I%';

Ex:
to display employees whose name starts with "M" and ends with "N" character?
SQL> SELECT * FROM EMP WHERE ENAME LIKE 'M%N';

Ex:
waq to display employees whose name is having 4 characters?
SQL> SELECT * FROM EMP WHERE ENAME LIKE '____';

Ex:
to display employees whose name is having the 2nd character is "O"?
SQL> SELECT * FROM EMP WHERE ENAME LIKE '_O%';

EX:
to display employees whose empno is starts with 7 and ends with 8?
SQL> SELECT * FROM EMP WHERE EMPNO LIKE '7%8';

Ex:
to display employees who are joined in 1981?
SQL> SELECT * FROM EMP WHERE HIREDATE LIKE '%81';

Ex:
to display employees who are joined in "December" month?
SQL> SELECT * FROM EMP WHERE HIREDATE LIKE '%DEC%';

Ex:
to display employees who are joined in "May" ,"December" month?
SQL> SELECT * FROM EMP WHERE HIREDATE LIKE '%MAY%' OR HIREDATE LIKE
'%DEC%';

LIKE OPERATOR WITH SPECIAL CHARACTERS:


========================================
DEMO_TABLE:
============
SQL> SELECT * FROM DEMO1;

SNO NAME
---------- ----------
1 _SMITH
2 WAR@NER
2 JONE#S
4 MILL%ER
5 SCO_TT
6 ALLEN%

EX:
waq to display names which name is having "@" symbol?
SQL> SELECT * FROM DEMO1 WHERE NAME LIKE '%@%';

EX:
waq to display names which name is having "#" symbol?
SQL> SELECT * FROM DEMO1 WHERE NAME LIKE '%#%';

EX:
waq to display names which name is having "_" symbol?
SQL> SELECT * FROM DEMO1 WHERE NAME LIKE '%_%';

- When we excute the above query it returns wrong result because


by default oracle will treat " % , _ " as wildcard operators but not treat as
special characters.so to overcome this problem we should use
a pre-defined keyword is "ESCAPE '\' " in oracle db.

SOLUTION:
==========
SQL> SELECT * FROM DEMO1 WHERE NAME LIKE'%\_%'ESCAPE'\';
SQL> SELECT * FROM DEMO1 WHERE NAME LIKE'%\%%'ESCAPE'\';
=====================================================================
ALIAS NAMES:
=============
- it is a temporary name for column / table.
- there are two types of aliases.
i) column level:
==============
- creating alias name for column.

ii) table level:


============
- creating alias name for table.

syntax:
=======
SELECT <COLUMN NAME1> [AS] <COLUMN ALIAS NAME1>,
<COLUMN NAME2> [AS] <COLUMN ALIAS NAME2>,.............
FROM <TABLE NAME> <TABLE ALIAS NAME>;

EX:
SQL> SELECT DEPTNO AS X,DNAME AS Y,LOC AS Z FROM DEPT D;
(OR)
SQL> SELECT DEPTNO X,DNAME Y,LOC Z FROM DEPT D;
CONCATENATION OPERATOR ( || ) :
==============================
- adding two string expressions.
syntax:
======
string1||string2||string3||..................;

Ex:
SQL> SELECT 'THE EMPLOYEE'||' '||ENAME||' '||'IS WORKING AS A'||' '||JOB FROM EMP;

DISTINCT KEYWORD:
==================
- to eliminate duplicate values from a specific column temporarly.

syntax:
======
distinct <column name>

EX:
SQL> SELECT DISTINCT JOB FROM EMP;
SQL> SELECT DISTINCT DEPTNO FROM EMP;

NOTE:
=====
- to display the large scale data tables in proper systematically in
sqlplus environment then we should set the following two properties,

i) pagesize n:
===========
- by default a page can display 14 rows in sqlplus editor.
- if we want to change the pagesize in sqlplus editor then we use
"pagesize" property.
- pagesize property is used to display no.of rows in a page.
- here "n" is nothing no.of rows.
- the maximum size of pagesize property is 50000.

syntax:
======
set pagesize n;

EX:
SQL> SET PAGESIZE 100;

ii) lines n:
=========
- by default each line is having 80 bytes of memory.
- lines property is used to display no.of characters in a single line.
- here "n" is represent no.of bytes (i.e no.of cahr's, 1 char = 1 byte)
- the maximum size of lines property is 32767 bytes.

syntax:
=======
set lines n;

EX:
SET LINES 160;
=====================================================================
FUNCTIONS IN ORACLE:
=====================
- to perform some task and must be return a value.
- oracle supports the following two types of functions.
1. Pre-defined functions
- use in SQL & PL/SQL
2. User-defined functions
- use in PL/SQL only

1. Pre-defined functions:
======================
- these functions are called as "Built In Functions" in oracle.
i) single row functions / scalar functions
ii) multiple row function / grouping funcitons / aggregative functions

i) single row functions:


====================
- these functions are returns a single value.
- Numeric functions
- String functions
- Date functions
- Conversion functions
- Null functions( NVL(),NVL2() ).

How to call a function:


====================
syntax:
======
SELECT <FNAME>(VALUE/(S)) FROM DUAL;

What is Dual ?
=============
- it is system defined table in oracle.
- it contains only one row & one column.
- this table is used to test function functionalities(i.e work flow).
- Dual is also called as "Dummy" table in oracle.

How to view the structure of Dual table:


===================================
SQL> DESC dual;

Name Null? Type


------------------------- -------- -------------------------
DUMMY VARCHAR2(1)

How to view data in dual table:


==========================
SQL> SELECT * FROM DUAL;

D ------------> column
--
X ------------> row

Numeric functions:
================
ABS():
======
- to convert from (-ve) value to (+ve) value.

syntax:
======
abs(n)
Ex:
SQL> SELECT ABS(-12) FROM DUAL;

ABS(-12)
----------------
12
EX:
SQL> SELECT EMPNO,ENAME,SAL,COMM,ABS(COMM-SAL) AS RESULT FROM EMP;

CEIL():
=====
- it return a value which is greater than or is equals to the given expression.
syntax:
=======
ceil(n)

EX:
SQL> SELECT CEIL(9.8) FROM DUAL;

CEIL(9.8)
----------
10

SQL> SELECT CEIL(9.2) FROM DUAL;

CEIL(9.2)
----------
10

SQL> SELECT CEIL(9.0) FROM DUAL;

CEIL(9.0)
----------
9

FLOOR():
=======
- it return a value which is less than or is equals to the given expression.

syntax:
=======
floor(n)

Ex:
SQL> SELECT FLOOR(9.8) FROM DUAL;

FLOOR(9.8)
----------
9

SQL> SELECT FLOOR(9.2) FROM DUAL;

FLOOR(9.2)
----------
9
MOD():
======
- it return the remainder value of the given expression.

syntax:
=======
mod(m,n)

EX:
SQL> SELECT MOD(10,2) FROM DUAL;

MOD(10,2)
-----------------
0

EX:
SQL> SELECT * FROM EMP WHERE MOD(EMPNO,2)=0;

ROUND():
========
- it returns the nearest value of the given expression.
- if an expression value is >= 0.5 then we add "1" to the main value.
- if an expression value is < 0.5 then we add "0" to the main value.

syntax:
======
round(expression,[decimal places])

Ex:
SQL> SELECT ROUND(34.58) FROM DUAL;

ROUND(34.58)
------------
35

SQL> SELECT ROUND(56.265,2) FROM DUAL;

ROUND(56.265,2)
---------------
56.27

TRUNC():
========
- it return an exact value from the given expression.
- this function will not consider 0.5 expression mechanism.

syntax:
=======
trunc(expression,[decimal places])

Ex:
Ex:
SQL> SELECT TRUNC(34.58) FROM DUAL;

TRUNC(34.58)
------------
34

SQL> SELECT TRUNC(56.265,2) FROM DUAL;

TRUNC(56.265,2)
---------------
56.26
===================================================================
STRING FUNCTIONS:
==================
LENGTH():
=========
- it return the length of the given string expression.

syntax:
=======
length(string)

EX:
SQL> SELECT LENGTH('HELLO') FROM DUAL;

LENGTH('HELLO')
---------------
5

SQL> SELECT LENGTH('WEL COME') FROM DUAL;

LENGTH('WELCOME')
-----------------
8

EX:
SQL> SELECT ENAME,LENGTH(ENAME) FROM EMP;
SQL> SELECT * FROM EMP WHERE LENGTH(ENAME)=6;
SQL> SELECT * FROM EMP WHERE LENGTH(ENAME)<5;

LOWER():
========
- it convert upper case characters into lower case characters.
syntax:
=======
lower(string)

Ex:
SQL> SELECT LOWER('HELLO') FROM DUAL;

LOWER
-----
hello

EX:
SQL> SELECT ENAME,LOWER(ENAME) FROM EMP;
SQL> UPDATE EMP SET ENAME=LOWER(ENAME) WHERE JOB='MANAGER';
SQL> UPDATE EMP SET ENAME=LOWER(ENAME);

UPPER():
========
- to convert lower case characters into upper case characters.

syntax:
=======
upper(string)

Ex:
SQL> UPDATE EMP SET ENAME=UPPER(ENAME);

LTRIM():
=======
- to remove unwanted characters from the given string expression
on left side.

syntax:
======
ltrim(string,[<trimming character>])
EX:
SQL> SELECT LTRIM(' HELLO')FROM DUAL;

LTRIM
-----
HELLO

SQL> SELECT LTRIM('XXXXHELLO','X')FROM DUAL;

LTRIM
-----
HELLO

RTRIM():
=======
- to remove unwanted characters from the given string expression
on right side.

syntax:
======
rtrim(string,[<trimming character>])

EX:
SQL> SELECT RTRIM('HELLOAAAA','A') FROM DUAL;

RTRIM
-----
HELLO

TRIM():
======
- to remove unwanted characters from both sides of the given string
expression.

syntax:
======
trim(<trimming character> from STRING)

EX:
SQL> SELECT TRIM('X' FROM 'XXXXHELLOXXX') FROM DUAL;

TRIM(
-----
HELLO
INITCAP():
=========
- to convert the initial character as a capital in the given expression.

syntax:
=======
initcap(string)

EX:
SQL> SELECT INITCAP('kamal kumar') FROM DUAL;

INITCAP('KA
-----------
Kamal Kumar

EX:
SQL> UPDATE EMP SET ENAME=INITCAP(ENAME);

REPLACE():
==========
- to replace a string expression with another string expression.

syntax:
=======
replace(string,'<old string>','<new string>')

EX:
SQL> SELECT REPLACE('HELLO','ELL','XYZ') FROM DUAL;

REPLA
-----
HXYZO

SQL> SELECT REPLACE('JACK AND JUE','J','BL') FROM DUAL;

REPLACE('JACKA
--------------
BLACK AND BLUE

TRANSLATE():
============
- to translate character by character.
syntax:
=======
translate(string,'<old characters>','<new characters>')

EX:
SQL> SELECT TRANSLATE('HELLO','ELO','XYZ') FROM DUAL;

TRANS
-----
HXYYZ

SQL> SELECT TRANSLATE('HELLO','ELO','XY') FROM DUAL;

TRAN
----
HXYY

SUBSTR():
=========
- it returns the required sub string from the given string expression.

syntax:
======
substr(string,<starting position of character>,<length of char's>)

EX:
SQL> SELECT SUBSTR('WELCOME',3,1) FROM DUAL;

S
-
L

SQL> SELECT SUBSTR('WELCOME',3,4) FROM DUAL;

SUBS
----
LCOM

SQL> SELECT SUBSTR('WELCOME',-4,2) FROM DUAL;

SU
--
CO
INSTR():
=======
- it returns the position of the occurrence character.

syntax:
======
instr(string,<specific character>,<starting position of character>,<occurrence position of
chacracter>)

EX:
'WELCOME HELLO'
1 234567 8 90123 --------> FIXED POSITIONS( from left to right / from right to left)

EX:
SQL> SELECT INSTR('WELCOME HELLO','O') FROM DUAL;

INSTR('WELCOMEHELLO','O')
-------------------------
5

SQL> SELECT INSTR('WELCOME HELLO','O',1,2) FROM DUAL;

INSTR('WELCOMEHELLO','O',1,2)
-----------------------------
13

SQL> SELECT INSTR('WELCOME HELLO',' ',1,1) FROM DUAL;

INSTR('WELCOMEHELLO','',1,1)
----------------------------
8

SQL> SELECT INSTR('WELCOME HELLO','E',-1,3) FROM DUAL;

INSTR('WELCOMEHELLO','E',-1,3)
------------------------------
2

SQL> SELECT INSTR('WELCOME HELLO','E',-11,1) FROM DUAL;

INSTR('WELCOMEHELLO','E',-11,1)
-------------------------------
2

CONCAT():
==========
- to add two string expressions.

syntax:
======
concat(string1,string2)

Ex:
SQL> SELECT CONCAT('HELLO','HAI') FROM DUAL;

CONCAT('
--------
HELLOHAI

Ex:
SQL> SELECT CONCAT('Mr.',ENAME) FROM EMP;

LPAD():
======
- to fill a string with specific string character on left side
whenever the string length is less than to the given user defined length.

syntax:
======
lpad(string1,<length>,string2)

Ex:
SQL> SELECT LPAD('HAI',2) FROM DUAL;

LP
--
HA

EX:
SQL> SELECT LPAD('HAI',10,'@') FROM DUAL;

LPAD('HAI'
----------
@@@@@@@HAI

RPAD():
======
- to fill a string with specific string character on right side
whenever the string length is less than to the given user defined length.

syntax:
======
rpad(string1,<length>,string2)

Ex:
SQL> SELECT RPAD('HAI',10,'@') FROM DUAL;

RPAD('HAI'
----------
HAI@@@@@@@

DATE FUNCTIONS:
================
SYSDATE:
=========
- it returns the current date information of the system.

syntax:
======
sysdate

Ex:
SQL> SELECT SYSDATE FROM DUAL;

SYSDATE
---------
02-OCT-23

Ex:
SQL> SELECT SYSDATE AS CURRENT_DATE,
2 SYSDATE+5 AS NEW_DATE,SYSDATE-5 AS OLD_DATE
3 FROM DUAL;

ADD_MONTHS():
==============
- to add / subtract the months to / from the given date expression.

syntax:
======
add_months(date,<no.of months>)
Ex:
SQL> SELECT SYSDATE,ADD_MONTHS(SYSDATE,3) AS NEW_DATE,
2 ADD_MONTHS(SYSDATE,-3) AS OLD_DATE FROM DUAL;

Ex:
SQL> CREATE TABLE PRODUCTS(PCODE INT,
2 PNAME VARCHAR2(10),MFG_DATE DATE,EXP_DATE DATE);

SQL> INSERT INTO PRODUCTS(PCODE,PNAME,MFG_DATE)


2 VALUES(1021,'XYZ','02-OCT-2020');

SQL> INSERT INTO PRODUCTS(PCODE,PNAME,MFG_DATE)


2 VALUES(1022,'ABC','15-JAN-2021');

SQL> COMMIT;

SQL> SELECT * FROM PRODUCTS; ( Before updating data)

SQL> UPDATE PRODUCTS SET EXP_DATE=ADD_MONTHS(MFG_DATE,24);

SQL> SELECT * FROM PRODUCTS; (After updating data)

LAST_DAY():
===========
- it returns the last day of given month in date expression.

syntax:
=======
last_day(date)

Ex:
SQL> SELECT LAST_DAY(SYSDATE) FROM DUAL;

LAST_DAY(
---------
31-OCT-23

MONTHS_BETWEEN():
==================
- it returns the no.of months between the given two dates.

syntax:
======
months_between(date1,date2)

EX:
SQL> SELECT MONTHS_BETWEEN('05-JAN-22','05-JAN-23') FROM DUAL;-----> -12
SQL> SELECT MONTHS_BETWEEN('05-JAN-23','05-JAN-22') FROM DUAL;------> 12

NOTE:
=====
- Here date1 is always greater than to date2 otherwise it returns (-ve)
sign value.

CONVERSION FUNCTIONS:
=======================
i) TO_CHAR()
ii) TO_DATE()

i) TO_CHAR():
============
- to convert date into character and also display date expression in
different formats.

syntax:
=======
to_char(sysdate,<interval>)

Year Formats:
---------------------------
YYYY - year in four digits format (2023)
YY - the last two digits format(23)
YEAR - Twenty Twenty-Three
CC - Centuary 21
AD / BC - AD Year / BC Year

Ex:
SQL> SELECT TO_CHAR(SYSDATE,'YYYY YY YEAR CC BC') FROM DUAL;

OUTPUT:
----------------------------------------------------------------
2023 23 TWENTY TWENTY-THREE 21 AD

Month Format:
----------------------------
MM - Month In Number Format
MON - First Three Char's From Month Spelling
MONTH - Full Name Of Month

EX:
SQL> SELECT TO_CHAR(SYSDATE,'MM MON MONTH') FROM DUAL;

OUTPUT
----------------------------------------------------
10 OCT OCTOBER

Day Formats:
-------------------------
DDD - Day Of The Year.
DD - Day Of The Month.
D - Day Of The Week.
Sun - 1
Mon - 2
Tue - 3
Wen - 4
Thu - 5
Fri - 6
Sat - 7
DAY - Full Name Of The Day
DY - First Three Char's Of Day Spelling

EX:
SQL> SELECT TO_CHAR(SYSDATE,'DDD DD D DAY DY') FROM DUAL;

OUTPUT:
----------------------------------------------------------
275 02 2 MONDAY MON

Week Format:
--------------------------
WW - Week Of The Year
W - Week Of Month

EX:
SQL> SELECT TO_CHAR(SYSDATE,'WW W') FROM DUAL;

OUTPUT
-------------
40 1
Quater Format:
----------------------------
Q - One Digit Quater Of The Year
1 - Jan - Mar
2 - Apr - Jun
3 - Jul - Sep
4 - Oct - Dec

EX:
SQL> SELECT TO_CHAR(SYSDATE,'Q') FROM DUAL;

T
--
4

Time Format:
-------------------------
HH - Hour In 12hrs format
HH24 - Hour In 24hrs Fromat
MI - Minute Part
SS - Seconds Part
AM / PM - Am Time (Or) Pm Time

Ex:
SQL> SELECT TO_CHAR(SYSDATE,'HH24 HH MI SS AM') FROM DUAL;

OUTPUT:
--------------
12 12 39 40 PM

EX:
waq to display employees who are joined in 1981 by using to_char()?
SOL:
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'YY')='81';
(OR)
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'YYYY')='1981';
(OR)
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'YEAR')='NINETEEN EIGHTY-
ONE';

EX:
waq to display employees who are joined in 1980,1982,1983 by using to_char()?
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'YY') IN('80','82','83');
EX:
waq to display employees who are joined in the month of "december" by using
to_char()?
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'MM')='12';

EX:
waq to display employees who are joined in the month of "december" in 1981
by using to_char()?
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'MM')='12' AND
TO_CHAR(HIREDATE,'YYYY')='1981';
(OR)
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'MMYYYY')='121981';

EX:
waq to display employees who are joined in the 2nd quater of 1981?
SQL> SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'QYYYY')='21981';

ii) TO_DATE():
============
- to convert character type to oracle default date format.

syntax:
======
to_date(string expression)

EX:
SQL> SELECT TO_DATE('12/AUGUST/2023') FROM DUAL;

TO_DATE('
---------
12-AUG-23

SQL> SELECT TO_DATE('12/AUGUST/2023')+10 FROM DUAL;

TO_DATE('
---------
22-AUG-23

SQL> SELECT TO_DATE('12/AUGUST/2023')-10 FROM DUAL;

TO_DATE('
---------
02-AUG-23
II) MULTIPLE ROW FUNCTIONS:
===========================
- these functions are also called as "grouping /aggregative" functions
in oracle database.
- these functions are SUM(),AVG(),MIN(),MAX(),COUNT().

SUM():
======
- it returns the total value.

Ex:
SQL> SELECT SUM(SAL) FROM EMP;

SUM(SAL)
----------
29025

SQL> SELECT SUM(SAL) FROM EMP WHERE JOB='MANAGER';

SUM(SAL)
----------
8275

AVG():
=====
- it returns the average of total value.

Ex:
SQL> SELECT AVG(SAL) FROM EMP;

MIN():
=====
- it returns the minimum value.

EX:
SQL> SELECT MIN(HIREDATE) FROM EMP;

MIN(HIRED
---------
17-DEC-80

SQL> SELECT MIN(SAL) FROM EMP;


MIN(SAL)
----------
800

SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO=20;

MIN(SAL)
----------
800

MAX():
=====
- it returns maximum value.

Ex:
SQL> SELECT MAX(SAL) FROM EMP;

MAX(SAL)
----------
5000

COUNT():
=========
i) count(*)
ii) count(column name)
iii) count(distinct <column name>)

i) count(*):
=========
- counting all rows including duplicates and also nulls.

EX:
SQL> SELECT * FROM TEST;

SNO NAME
---------- ----------
1A
2B
3
4C
5A
6C

SQL> SELECT COUNT(*) FROM TEST;


COUNT(*)
----------
6

ii) count(column name):


====================
- counting all rows including duplicates but not nulls.
Ex:
SQL> SELECT COUNT(NAME) FROM TEST;

COUNT(NAME)
-----------
5

iii) count(distinct columnname):


===========================
- counting unique values only.

EX:
SQL> SELECT COUNT(DISTINCT NAME) FROM TEST;

COUNT(DISTINCTNAME)
-------------------
3
=====================================================================
CLAUSES:
=========
- a clause is a statement which will add to a sql query for providing
some additional facilities like "filtering rows,sorting values,grouping similar data,
finding sub total and grand total " based on a particula column / columns from a
table automatically.
- oracle supports the following clauses are,
i) WHERE
ii) ORDER BY
iii) GROUP BY
iv) HAVING
v) ROLLUP
vi) CUBE

syntax:
======
<sql query> + <clause>;
WHERE:
=======
- filtering rows before grouping data in a table.

syntax:
=======
where <filtering condition>;

NOTE:
=====
- this WHERE clause is used in "SELECT,UPDATE,DELETE" commands
only.

Ex:
SQL> SELECT * FROM EMP WHERE EMPNO=7788;
SQL> UPDATE EMP SET SAL=34000 WHERE ENAME='SMITH';
SQL> DELETE FROM EMP WHERE DEPTNO=20;

ORDER BY:
==========
- to arrange a specific column values either in ascending order (or)
in descending order.
- by default order by clause will arrange the values in ascending order
only.if we want to arrange the values in descending order then we use "desc"
keyword.

syntax:
======
SELECT * FROM <TN> ORDER BY <COLUMN NAME1> <ASC/DESC>,
<COLUMN NAME2> <ASC/DESC>,..........;

EX:
SQL> SELECT * FROM EMP ORDER BY SAL;
SQL> SELECT * FROM EMP ORDER BY ENAME;
SQL> SELECT * FROM EMP ORDER BY HIREDATE DESC;

EX:
waq to display employees who are working under deptno is 20 and arrange those
employees salaries in descending order?
SQL> SELECT * FROM EMP WHERE DEPTNO=20 ORDER BY SAL DESC;

EX:
waq to arrange employee deptno's in ascending order and those employees salaries
in descending order from each deptno wise?
SQL> SELECT * FROM EMP ORDER BY DEPTNO,SAL DESC;

NOTE:
=====
- order by clause can apply on not only column names eventhough
we can apply on position of column in select query.

EX:
SQL> SELECT * FROM EMP ORDER BY SAL DESC;
SQL> SELECT * FROM EMP ORDER BY 6 DESC;
SQL> SELECT EMPNO,ENAME,SAL FROM EMP ORDER BY 3 DESC;
SQL> SELECT ENAME,SAL FROM EMP ORDER BY 2 DESC;
SQL> SELECT SAL FROM EMP ORDER BY 1 DESC;

ORDER BY WITH NULL CLAUSES:


============================
I) nulls first:
===========
- by default in ascending order,
> first values
> later nulls
- to change the bove order then we use "nulls first" clause.
> first nulls
> later values

Ex:
SQL> SELECT * FROM EMP ORDER BY COMM;
SQL> SELECT * FROM EMP ORDER BY COMM NULLS FIRST;

II) nulls last:


===========
- by default in descending order,
> first nulls
> later values
- to change the bove order then we use "nulls last" clause.
> first values
> later nulls
Ex:
SQL> SELECT * FROM EMP ORDER BY COMM;
SQL> SELECT * FROM EMP ORDER BY COMM NULLS LAST;

GROUP BY:
==========
- it is used to divide groups based on a specific column / columns
in a table.
- when we use group by clause we must use an "aggregative / grouping "
functions to get the result.

syntax:
=======
SELECT <COLUMN NAME1>,<COLUMN NAME2>,.....................................,
<AGGREGATIVE FUNCTION NAME1>,.................... FROM <TABLE NAME>
GROUP BY <COLUMN NAME1>,<COLUMN NAME2>,..........;

DEMO_TABLE:
=============
SQL> SELECT * FROM STUDENTS;

SNAME GENDER
---------- ----------
SMITH MALE
ALLEN FEMALE
WARD FEMALE
SCOTT MALE
JONES MALE

EX:
waq to find out no.of male and female students in a table?
SQL> SELECT GENDER,COUNT(*) FROM STUDENTS GROUP BY GENDER;

EX:
waq to find out no.of employees in each job?
SQL> SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB;

EX:
waq to find out no.of employees in each job along with their deptno wise?
SQL> SELECT JOB,DEPTNO,COUNT(*) FROM EMP GROUP BY JOB,DEPTNO ORDER BY
JOB;

Ex:
waq to display sum of salaries of each deptno wise?
SQL> SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO;

Using all grouping functions in a single query:


=====================================
SQL> SELECT DEPTNO,COUNT(*) AS NO_OF_EMPLOYEES,
2 SUM(SAL) AS SUM_OF_SALARY,MAX(SAL) AS MAX_SALARY,
3 MIN(SAL) AS MIN_SAALRY,AVG(SAL) AS AVG_SAALRY
4 FROM EMP GROUP BY DEPTNO ORDER BY DEPTNO;

HAVING:
=======
- filtering rows after grouping data.

syntax:
=======
SELECT <COLUMN NAME1>,<COLUMN NAME2>,.....................................,
<AGGREGATIVE FUNCTION NAME1>,.................... FROM <TABLE NAME>
GROUP BY <COLUMN NAME1>,<COLUMN NAME2>,........HAVING<FILTERING
CONDITION>;

EX:
waq to display the jobs in which job the no.of employees are more than 3?
SQL> SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB
2 HAVING COUNT(*)>3;

EX:
waq to display deptno's if the sum of salary of deptno is less than 10000?
SQL> SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO
HAVING SUM(SAL)<10000;

ROLLUP & CUBE:


===============
- these clauses are used to find out sub total and grand total based on
a column / columns.
- these are implementing along with "group by" clause.
rollup : working on a single column wise.
cube : working on multiple columns wise.

syntax for rollup:


===============
SELECT <COLUMN NAME1>,<COLUMN NAME2>,.....................................,
<AGGREGATIVE FUNCTION NAME1>,.................... FROM <TABLE NAME>
GROUP BY ROLLUP(<COLUMN NAME1>,<COLUMN NAME2>,........);
.............................. .....................................
| |
operational column supporting columns

Ex on rollup with a single column:


=============================
SQL> SELECT JOB,COUNT(*) FROM EMP GROUP BY ROLLUP(JOB);
Ex on rollup with multiple columns:
==============================
SQL> SELECT DEPTNO,JOB,COUNT(*) FROM EMP
2 GROUP BY ROLLUP(DEPTNO,JOB);

SQL> SELECT JOB,DEPTNO,COUNT(*) FROM EMP


2 GROUP BY ROLLUP(JOB,DEPTNO);

syntax for cube:


===============
SELECT <COLUMN NAME1>,<COLUMN NAME2>,.....................................,
<AGGREGATIVE FUNCTION NAME1>,.................... FROM <TABLE NAME>
GROUP BY CUBE(<COLUMN NAME1>,<COLUMN NAME2>,........);
...................................................................
|
all columns are operational columns

Ex on cube with a single column:


=============================
SQL> SELECT DEPTNO,COUNT(*) FROM EMP
2 GROUP BY CUBE(DEPTNO) ORDER BY DEPTNO;

Ex on cube with multiple columns:


==============================
SQL> SELECT DEPTNO,JOB,COUNT(*) FROM EMP
2 GROUP BY CUBE(DEPTNO,JOB) ORDER BY DEPTNO,JOB;
=====================================================================
JOINS:
======
- In RDBMS data can be stored in multiple tables.if we want to retrieve
our required data / information from those multiple tables then we use a technique
is called as "JOINS".
- Joins are used to retrieve data / information from multiple tables at a
time.
- oracle is supporting the following joins are,
1. Inner joins:
- Equi join
- Non-equi join
2. Outer joins:
- Left outer join
- Right outer join
- Full outer join
3. Cross join
4. Natural join
5. Self join

syntax:
=======
SELECT * / <list of columns> FROM <TN1> <JOIN KEY> <TN2> ON <JOINING CONDITION>;

1. Inner joins:
===========
- Equi join:
=========
- when we are retrieving data from multiple tables based on
an " = " operator is called as "equi join".
- when we use equi join we should have at least one common
column in between tables.
- a common column datatype must be match in both tables.
- there is no need to have relationship between tables it is a
optional.
- retrieving matching rows from tables.

syntax for joining condition:


=======================
ON <TN1 / TABLE ALIAS NAME1>.<COMMON COLUMN> = <TN2 / TABLE ALIAS
NAME2>.<COMMON COLUMN>;

Demo_tables:
============
SQL> SELECT * FROM COURSE;

CID CNAME CFEE


---------- ---------- ----------
1 C 500
2 ORACLE 2500
3 JAVA 3500

SQL> SELECT * FROM STUDENTS;

STID SNAME CID


---------- ---------- ----------
1021 SMITH 2
1022 ALLEN 3
1023 WARD 2
1024 JONES

EX:
waq to retrieve students and their corresponding course details from students,course tables?
SQL> SELECT * FROM STUDENTS INNER JOIN COURSE ON
STUDENTS.CID=COURSE.CID;
(OR)
SQL> SELECT * FROM STUDENTS S INNER JOIN COURSE C ON S.CID=C.CID;

RULE OF JOINS:
==============
- a row in a table is comparing with all rows of another table.

Ex:
waq to retrieve students,course details from students,course tables who are joined
in oracle course?
SQL> SELECT STID,SNAME,CNAME,CFEE FROM STUDENTS S
2 INNER JOIN COURSE C ON S.CID=C.CID WHERE CNAME='ORACLE';
(OR)
SQL> SELECT STID,SNAME,CNAME,CFEE FROM STUDENTS S
2 INNER JOIN COURSE C ON S.CID=C.CID AND CNAME='ORACLE';

EX:
waq to retrieve employees details who are working in the location is "chicago"
from emp,dept tables?
SQL> SELECT ENAME,DNAME,LOC,D.DEPTNO FROM EMP E
2 INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO
3 AND LOC='CHICAGO';

EX:
waq to display sum of salaries of departments from emp,dept tables?
SQL> SELECT DNAME,SUM(SAL) FROM EMP E INNER JOIN DEPT D
2 ON E.DEPTNO=D.DEPTNO GROUP BY DNAME;

EX:
waq to display deptnos,sum of salaries of departments from emp,dept tables?
SQL> SELECT D.DEPTNO,DNAME,SUM(SAL)FROM EMP E INNER JOIN
2 DEPT D ON E.DEPTNO=D.DEPTNO GROUP BY D.DEPTNO,DNAME;

EX:
waq to display sum of salaries of departments from emp,dept tables if the sum
of salary of a department is more than 10000?
SQL> SELECT DNAME,SUM(SAL) FROM EMP E INNER JOIN DEPT D
2 ON E.DEPTNO=D.DEPTNO GROUP BY DNAME
3 HAVING SUM(SAL)>10000;

NON-EQUI JOIN:
===============
- retrieving data from multiple tables based on any operator except an
" = " operator.
- it supports the following operators are < , > , <= , >= , != , AND,
OR,BETWEEN,....etc.

DEMO_TABLES:
=============
SQL> SELECT * FROM TEST1;

SNO NAME
---------- ----------
10 SMITH
20 ALLEN

SQL> SELECT * FROM TEST2;

SNO SAL
---------- ----------
10 23000
30 33000

Ex:
SQL> SELECT * FROM TEST1 T1 INNER JOIN TEST2 T2 ON T1.SNO < T2.SNO;
SQL> SELECT * FROM TEST1 T1 INNER JOIN TEST2 T2 ON T1.SNO > T2.SNO;
SQL> SELECT * FROM TEST1 T1 INNER JOIN TEST2 T2 ON T1.SNO <= T2.SNO;
SQL> SELECT * FROM TEST1 T1 INNER JOIN TEST2 T2 ON T1.SNO >= T2.SNO;
SQL> SELECT * FROM TEST1 T1 INNER JOIN TEST2 T2 ON T1.SNO != T2.SNO;

EX:
waq to display employees whose salary is between low salary and high salary
from emp,salgrade tables?
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP INNER JOIN
SALGRADE ON SAL BETWEEN LOSAL AND HISAL;
(OR)
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP INNER JOIN SALGRADE
ON (SAL>=LOSAL) AND (SAL<=HISAL);

OUTER JOINS:
=============
- In the above inner joins we are loosing matching rows for non-equi join
and unmatching rows for equi join.
- to overcome the above problems we use "outer joins" technique for
retreiving matching and also unmatching rows from multiple tables.
- outer joins are three types,

i) LEFT OUTER JOIN:


==================
- retrieving matching rows from both tables but unmatching rows from
left side table only.

Ex:
SQL> SELECT * FROM STUDENTS S LEFT OUTER JOIN COURSE C ON S.CID=C.CID;

ii) RIGHT OUTER JOIN:


==================
- retrieving matching rows from both tables but unmatching rows from
right side table only.

Ex:
SQL> SELECT * FROM STUDENTS S RIGHT OUTER JOIN COURSE C ON S.CID=C.CID;

iii) FULL OUTER JOIN:


==================
- it is a combination of left outer and right outer jion.
- by using full outer join we can retrieve matching and unmatcing rows
from both tables at a time.

Ex:
SQL> SELECT * FROM STUDENTS S FULL OUTER JOIN COURSE C ON S.CID=C.CID;

CROSS JOIN:
===========
- joining tables without any condition.
- it is a default join in database.
- in cross join mechanism,a table is having (m) no.of rows and another
table is having (n) no.of rows then the result of cross join is (mXn) rows.

Ex:
SQL> SELECT * FROM STUDENTS CROSS JOIN COURSE;

DEMO_TABLES:
==============
SQL> SELECT * FROM ITEMS1;

SNO INAME PRICE


---------- ---------- ----------
1 PIZZA 180
2 BURGER 75

SQL> SELECT * FROM ITEMS2;

SNO INAME PRICE


---------- ---------- ----------
101 PEPSI 25
102 COCACOLA 20

EX:
SQL> SELECT I1.INAME,I1.PRICE,I2.INAME,I2.PRICE,
2 I1.PRICE+I2.PRICE AS TOTAL_BILL_AMOUNT FROM
3 ITEMS1 I1 CROSS JOIN ITEMS2 I2;

NATURAL JOIN:
==============
- it is a similar to equi join but preparing a join condition by oracle server
by default based on an " = " operator only.
- it is also retrieving matching rows only just lika a equi-join.
- this join will remove duplicate columns from a result set.

EX:
SQL> SELECT * FROM STUDENTS S NATURAL JOIN COURSE C;

SELF JOIN:
==========
- This technique will work on a single table in database.
- Self join is nothing but joning a table by itself (or)
comparing a table data by itself.
- When we use self join we should create alias names on a table name
otherwise we cannot implement self join mechanism.
- Once we created alias name on a table name internally oracle server
is preparing virtual table on each alias name.
- We can create any no.of alias names on a single table but each alias
name must be different.
- There are two cases where we can use self join technique.

Case-1: Comparing a single column values by itself with in the table.


Case-2: Comparing two different columns values to each other with in the table.

Case-1: Comparing a single column values by itself with in the table.


=========================================================
Ex:
waq to display employees who are working in the same location where the
employee "SMITH" is also working?
SQL> SELECT T1.ENAME,T1.LOC FROM TEST T1 JOIN TEST T2
2 ON T1.LOC=T2.LOC AND T2.ENAME='SMITH';

Ex:
waq to fetch employees whose salary is same as the employee SCOTT salary?
SQL> SELECT E1.ENAME,E1.SAL FROM EMP E1 JOIN EMP E2
2 ON E1.SAL=E2.SAL AND E2.ENAME='Scott';

Case-2: Comparing two different columns values to each other with in the table:
===================================================================
Ex:
waq to display managers and their employees from emp table?
SQL> SELECT M.ENAME AS MANAGERS,E.ENAME AS EMPLOYEES
FROM EMP E JOIN EMP M ON M.EMPNO=E.MGR

Ex:
waq to display employees who are working under "Blake" manager?
SQL> SELECT M.ENAME AS MANAGERS,E.ENAME AS EMPLOYEES
2 FROM EMP E JOIN EMP M ON M.EMPNO=E.MGR
3 AND M.ENAME='Blake';

Ex:
waq to display manager of "Blake"?
SQL> SELECT M.ENAME AS MANAGERS
2 FROM EMP E JOIN EMP M ON M.EMPNO=E.MGR
3 AND E.ENAME='Blake';

Ex:
waq to display employees who are joined before their manager?
SQL> SELECT E.ENAME AS EMPLOYEES,E.HIREDATE AS E_DOJ,
2 M.ENAME AS MANAGER,M.HIREDATE AS M_DOJ FROM
3 EMP E JOIN EMP M ON M.EMPNO=E.MGR
4 AND E.HIREDATE < M.HIREDATE;

Ex:
waq to display employees whose salary is more than their manager?
SQL> SELECT E.ENAME AS EMPLOYEE,E.SAL AS E_SALARY,
2 M.ENAME AS MANAGER,M.SAL AS M_SALARY FROM
3 EMP E JOIN EMP M ON M.EMPNO=E.MGR AND
4 E.SAL>M.SAL;

How to join more than two tables:


=============================
syntax:
======
SELECT * FROM <TN1> <JOIN KEY> <TN2> ON <JOIN CONDITION1>
<JOIN KEY> <TN3> ON <JOIN CONDITION2>
<JOIN KEY> <TN4> ON <JOIN CONDITION3>
.....................................................................
.....................................................................
<JOIN KEY> <TN n> ON <JOIN CONDITION n-1>;

EX:
SQL> SELECT * FROM STUDENTS S INNER JOIN COURSE C
2 ON S.CID=C.CID INNER JOIN REGISTER R ON C.CID=R.CID;
=====================================================================
CONSTRAINTS:
=============
- are used to restricted unwanted data / invalid data into a table.
- oracle supports the following constraints are,
> Unique
> Not null
> Check
> Primary key
> Foreign key(references key)
> Default
- we can defined a constraint in two levels in oracle database.
1. column level
2. table level

1. column level:
==============
- we can defined a constraint on each column wise in a table.
syntax:
======
CREATE TABLE <TN>(<COLUMN NAME1> <DATATYPE>[SIZE] <CONSTRAINT TYPE>,
<COLUMN NAME2> <DATATYPE>[SIZE] <CONSTRAINT TYPE>,................);

2. table level:
============
- we can defined a constraint after all columns definitions i.e
end of the table.

syntax:
======
CREATE TABLE <TN>(<COLUMN NAME1> <DATATYPE>[SIZE],
<COLUMN NAME2> <DATATYPE>[SIZE],......,<constraint
type>(columnname1,columnname2,........));

Unique:
======
- to restricted duplicate values but allowed nulls into a column.

column level:
============
Ex:
SQL> CREATE TABLE TEST1(SNO INT UNIQUE,NAME VARCHAR2(10) UNIQUE);

TESTING:
SQL> INSERT INTO TEST1 VALUES(1,'A');----------------allowed
SQL> INSERT INTO TEST1 VALUES(1,'A');---------------not allowed
SQL> INSERT INTO TEST1 VALUES(NULL,NULL);----allowed

table level:
=========
Ex:
SQL> CREATE TABLE TEST2(SNO INT,NAME VARCHAR2(10),UNIQUE(SNO,NAME));

TESTING:
SQL> INSERT INTO TEST2 VALUES(1,'A');-----allowed
SQL> INSERT INTO TEST2 VALUES(1,'A');----not allowed
SQL> INSERT INTO TEST2 VALUES(1,'B');----allowed
SQL> INSERT INTO TEST2 VALUES(NULL,NULL);-----allowed

NOT NULL:
=========
- to restricted NULLS but allowed duplicate values into a column.
- it can be defined at column level but not table level.

column level:
===========
Ex:
SQL> CREATE TABLE TEST3(SNO INT NOT NULL,NAME VARCHAR2(10)NOT NULL);

TESTING:
SQL> INSERT INTO TEST3 VALUES(1,'A');------------allowed
SQL> INSERT INTO TEST3 VALUES(1,'A');------------allowed
SQL> INSERT INTO TEST3 VALUES(NULL,NULL);-----not allowed

Using combination of UNIQUE and NOT NULL constraint:


================================================
Ex:
SQL> CREATE TABLE TEST4(SNO INT UNIQUE NOT NULL,
2 NAME VARCHAR2(10) UNIQUE NOT NULL);

TESTING:
SQL> INSERT INTO TEST4 VALUES(1,'A');------------------allowed
SQL> INSERT INTO TEST4 VALUES(1,'A');-----------------not allowed
SQL> INSERT INTO TEST4 VALUES(NULL,NULL);------not allowed

CHECK:
=======
- to check values with user defined condition on a column.

column level:
===========
Ex:
SQL> CREATE TABLE TEST5(LOC VARCHAR2(10) CHECK(LOC IN('HYD','PUNE')),
2 SAL NUMBER(10) CHECK(SAL>=15000));

TESTING:
SQL> INSERT INTO TEST5 VALUES('HYD',12000);----------not allowed
SQL> INSERT INTO TEST5 VALUES('DELHI',15000);------not allowed
SQL> INSERT INTO TEST5 VALUES('HYD',15000);-----allowed

table level:
==========
EX:
SQL> CREATE TABLE TEST6(ENAME VARCHAR2(10),SAL NUMBER(10),
2 CHECK(ENAME=LOWER(ENAME) AND SAL>8000));

TESTING:
SQL> INSERT INTO TEST6 VALUES('SMITH',12000);-------not allowed
SQL> INSERT INTO TEST6 VALUES('smith',8000);-------not allowed
SQL> INSERT INTO TEST6 VALUES('smith',12000);-----allowed

PRIMARY KEY:
============
- it is a combination of UNIQUE and NOT NULL.
- by using primary key we can restricted duplicate and null values
into a column at a time.
- a table is having only one primary key constraint.

column level:
============
SQL> CREATE TABLE TEST7(PCODE INT PRIMARY KEY,PNAME VARCHAR2(10) UNIQUE
NOT NULL);

TESTING:
SQL> INSERT INTO TEST7 VALUES(1021,'C');-------------allowed
SQL> INSERT INTO TEST7 VALUES(1021,'C');------------not allowed
SQL> INSERT INTO TEST7 VALUES(1022,'C++');-------- allowed

table level: ( composite primary key )


===============================
- When we apply a primary key constraint on combination of multiple
columns are called as "composite primary key".

Ex:
SQL> CREATE TABLE TEST8(BCODE INT,BNAME VARCHAR2(10),
2 BLOC VARCHAR2(10),PRIMARY KEY(BCODE,BNAME));

TESTING:
SQL> INSERT INTO TEST8 VALUES(1021,'SBI','SR NAGAR');------allowed
SQL> INSERT INTO TEST8 VALUES(1021,'SBI','AMEERPET');-----not
SQL> INSERT INTO TEST8 VALUES(1022,'SBI','AMEERPET');-----allowed

FOREIGN KEY:
============
- to create relationship between tables.
- by using realtionship a table can take referencial data(i.e identity)
from another table.

Basic Rules:
===========
1. we have atleast one common column in tables.
2. thise common column datatype must be match.
3. a common column should have Primary key in one table and Foreign key in another
table.
4. a Primary key table is called as "parent table" and a Forign key table is called
"child table".
5. a Foreign ky column is allowed values which was found in Primary key column
only.
(parent) (child)
sno(pk) sno(fk)
======= =======
1 1
2 1
3 1
2
2
3
3
4----->error
null-----> allowed

6. by default a Foreign key column is allowed duplicates and nulls.

syntax:
=======
<common column of child table> <datatype>[size] references <parent table name>(common
column of parent table)

EX:
SQL> CREATE TABLE DEPT1(DNO INT PRIMARY KEY,DNAME VARCHAR2(10) UNIQUE
NOT NULL);

SQL> INSERT INTO DEPT1 VALUES(10,'JAVA');


SQL> INSERT INTO DEPT1 VALUES(20,'ORACLE');
SQL> COMMIT;

SQL> CREATE TABLE EMP1(EID INT PRIMARY KEY,


2 ENAME VARCHAR2(10),DNO INT REFERENCES
3 DEPT1(DNO));

SQL> INSERT INTO EMP1 VALUES(1021,'SMITH',10);----allowed


SQL> INSERT INTO EMP1 VALUES(1022,'ALLEN',10);---allowed
SQL> INSERT INTO EMP1 VALUES(1023,'ADAMS',20);-----allowed
SQL> INSERT INTO EMP1 VALUES(1024,'WARD',30);----not allowed
SQL> INSERT INTO EMP1 VALUES(1024,'WARD',NULL);----allowed
SQL> COMMIT;

Updating nulls in child table with references of parent table primary key values:
===================================================================
SQL> UPDATE EMP1 SET DNO=10 WHERE DNO IS NULL;
(OR)
SQL> UPDATE EMP1 SET DNO=20 WHERE DNO IS NULL;

NOTE:
=====
- once we created a relationship between tables there are two rules
come into picture those are,
Rule-1:(insertion rule)
===================
- We cannot insert values into foreign key column which are not found
in primary key column of parent table.
NO PARENT = NO CHILD

Ex:
SQL> INSERT INTO EMP1 VALUES(1024,'WARD',30);
ERROR at line 1:
ORA-02291: integrity constraint (MYDB11AM.SYS_C008436) violated - parent key not found

Rule-2(deletion rule):
=================
- We cannot delete a row from parent table which was found a child in
child table without addressing to child.

EX:
SQL> DELETE FROM DEPT1 WHERE DNO=10;
ERROR at line 1:
ORA-02292: integrity constraint (MYDB11AM.SYS_C008436) violated - child record found

- when we want to delete a row from parent table which was found a
child in child table with addressing to child by using "cascade rules".
i) ON DELETE CASCADE
ii) ON DELETE SET NULL

i) ON DELETE CASCADE:
=====================
- once we delete a row from parent table then the corresponding child
rows are also deleted from child table automatically.

Ex:
SQL> CREATE TABLE DEPT2(DNO INT PRIMARY KEY,DNAME VARCHAR2(10) UNIQUE
NOT NULL);

SQL> INSERT INTO DEPT2 VALUES(10,'JAVA');


SQL> INSERT INTO DEPT2 VALUES(20,'ORACLE');
SQL> COMMIT;

SQL> CREATE TABLE EMP2(EID INT PRIMARY KEY,


ENAME VARCHAR2(10),DNO INT REFERENCES
DEPT2(DNO) ON DELETE CASCADE);
SQL> INSERT INTO EMP2 VALUES(1021,'SMITH',10);----allowed
SQL> INSERT INTO EMP2 VALUES(1022,'ALLEN',20);---allowed

TESTING:
SQL> DELETE FROM DEPT2 WHERE DNO=10;
1 row deleted.

ii) ON DELETE SET NULL:


======================
- once we delete a row from parent table then the corresponding child
rows of a foreign column values are converting into nulls(empty) automatically.

Ex:
SQL> CREATE TABLE DEPT3(DNO INT PRIMARY KEY,DNAME VARCHAR2(10) UNIQUE
NOT NULL);

SQL> INSERT INTO DEPT3 VALUES(10,'JAVA');


SQL> INSERT INTO DEPT3 VALUES(20,'ORACLE');
SQL> COMMIT;

SQL> CREATE TABLE EMP3(EID INT PRIMARY KEY,


ENAME VARCHAR2(10),DNO INT REFERENCES
DEPT3(DNO) ON DELETE SET NULL);

SQL> INSERT INTO EMP3 VALUES(1021,'SMITH',10);----allowed


SQL> INSERT INTO EMP3 VALUES(1022,'ALLEN',20);---allowed

TESTING:
SQL> DELETE FROM DEPT3 WHERE DNO=10;
1 row deleted.

EX:
create a relationship between CUSTOMER,PRODUCTS and ORDERS?

SQL> CREATE TABLE CUSTOMERS(CID INT PRIMARY KEY,


2 CNAME VARCHAR2(10),CADDRESS VARCHAR2(10));

SQL> INSERT INTO CUSTOMERS VALUES(1,'SMITH','HYD');


SQL> INSERT INTO CUSTOMERS VALUES(2,'ALLEN','MUMBAI');

SQL> CREATE TABLE PRODUCTS(PCODE INT PRIMARY KEY,


2 PNAME VARCHAR2(10),PRICE NUMBER(6,2));

SQL> INSERT INTO PRODUCTS VALUES(1021,'C',500);


SQL> INSERT INTO PRODUCTS VALUES(1022,'C++',1000);

SQL> CREATE TABLE ORDERS(ORDID INT PRIMARY KEY,


2 ORDDATE DATE,QUANTITY INT,CID INT REFERENCES
3 CUSTOMERS(CID) ON DELETE CASCADE,PCODE INT
4 REFERENCES PRODUCTS(PCODE)ON DELETE CASCADE);

SQL> INSERT INTO ORDERS VALUES(1001,'17-OCT-23',1,1,1021);


SQL> INSERT INTO ORDERS VALUES(1003,'18-OCT-23',3,2,1022);

TESTING:
SQL> DELETE FROM CUSTOMERS WHERE CID=1;
SQL> DELETE FROM PRODUCTS WHERE PCODE=1021;
=======================================================================
DATADICTIONARIES / READ ONLY TABLES:
=====================================
- when we installed oracle s/w internally system will create some
pre-defined tables are called as "datadictionaries".
- these datadictionaries are used to store the information(meta data)
about tables,views,indexes,procedures,functions,triggers,.......etc.
- datadictionaries are supporting "select" statement but DML operations
so that these are called as "read only tables".
- if we want to view all datadictionaries in oracle database then follow
the following syntax is,

SYNTAX:
=======
SELECT * FROM DICT; (Main Dictionary)

EX:
SQL> CREATE TABLE TEST9
2 (
3 EID INT PRIMARY KEY,
4 ENAME VARCHAR2(10) UNIQUE NOT NULL,
5 SAL NUMBER(10) NOT NULL CHECK(SAL>=15000)
6 );

- If we want to view constraint name along with column name of a


particular table in oracle database then use a datadictionary is "user_cons_columns".

Ex:
SQL> DESC USER_CONS_COLUMNS;
SQL> SELECT CONSTRAINT_NAME,COLUMN_NAME FROM USER_CONS_COLUMNS
WHERE TABLE_NAME='TEST9';
CONSTRAINT_NAME COLUMN_NAME
---------------------------------------- --------------------------------------------------------------
SYS_C008485 ENAME
SYS_C008486 SAL
SYS_C008487 SAL
SYS_C008488 EID
SYS_C008489 ENAME

How to add a constraint to an existing table:


=====================================
syntax:
======
ALTER TABLE <TN> ADD CONSTRAINT <UD CONSTRAINT KEY NAME>
<CONSTRAINT TYPE>(COLUMN NAME);

EX:
Adding a primary key:
===================
SQL> CREATE TABLE PARENT(EID INT,ENAME VARCHAR2(10),SAL NUMBER(10));
SQL> ALTER TABLE PARENT ADD CONSTRAINT PK_EID PRIMARY KEY(EID);

Adding unique,check constraint:


===========================
SQL> ALTER TABLE PARENT ADD CONSTRAINT UQ_ENAME UNIQUE(ENAME);
SQL> ALTER TABLE PARENT ADD CONSTRAINT CHK_SAL CHECK(SAL>=8000);

NOTE:
=====
- to view constraint name along with check condition value of a specific
column in a table then use a datadictionary is called as "user_constraints".

Ex:
SQL> DESC USER_CONSTRAINTS;
SQL> SELECT CONSTRAINT_NAME,SEARCH_CONDITION FROM USER_CONSTRAINTS
WHERE TABLE_NAME='PARENT';

CONSTRAINT_NAME SEARCH_CONDITION
---------------------------------------- ----------------------------------------
CHK_SAL SAL>=8000

Adding "NOT NULL" constraint:


==========================
syntax:
=======
ALTER TABLE <TN> MODIFY<COLUMN NAME> <CONSTRAINT>
<UD CONSTRAINT KEY NAME> NOT NULL;

EX:
SQL> ALTER TABLE PARENT MODIFY ENAME CONSTRAINT
2 NN_ENAME NOT NULL;

Adding a foreign key:


==================
syntax:
=======
ALTER TABLE <TN> ADD CONSTRAINT <UD CONSTRAINT KEY NAME>
FOREIGN KEY(COMMON COLUMN OF CHILD TABLE) REFERENCES
<PARENT TABLE NAME>(COMMON COLUMN OF PARENT TABLE)
ON DELETE CASCADE / ON DELETE SET NULL;

EX:
SQL> CREATE TABLE CHILD(DNAME VARCHAR2(10),EID INT);
SQL> ALTER TABLE CHILD ADD CONSTRAINT FK_EID
2 FOREIGN KEY(EID) REFERENCES PARENT(EID)
3 ON DELETE CASCADE;

HOW TO REMOVE A CONSTRAINT FROM AN EXISTING TABLE:


=====================================================
SYNTAX:
========
ALTER TABLE <TN> DROP CONSTRAINT <CONSTRAINT KEY NAME>;

Drop a primary key:


=================
CASE-1:(WITH RELATIONSHIP)
==========================
SQL> ALTER TABLE PARENT DROP CONSTRAINT PK_EID CASCADE;

CASE-2:(WITHOUT RELATIONSHIP)
==============================
SQL> ALTER TABLE PARENT DROP CONSTRAINT PK_EID;

Drop unique,check,not null constraint:


================================
SQL> ALTER TABLE PARENT DROP CONSTRAINT UQ_ENAME;
SQL> ALTER TABLE PARENT DROP CONSTRAINT CHK_SAL;
SQL> ALTER TABLE PARENT DROP CONSTRAINT NN_ENAME;
HOW TO RENAME A CONSTRAINT KEY NAME :
========================================
SYNTAX:
=======
ALTER TABLE <TN> RENAME CONSTRAINT <OLD CONSTRAINT KEY NAME>
TO <NEW CONSTRAINT KEY NAME>;

EX:
SQL> CREATE TABLE TEST10(SNO INT PRIMARY KEY);

SQL> SELECT COLUMN_NAME,CONSTRAINT_NAME FROM


USER_CONS_COLUMNS WHERE TABLE_NAME='TEST10';

COLUMN_NAME CONSTRAINT_NAME
------------------------------------ ---------------------------------------------------------------------
SNO SYS_C008505

SQL> ALTER TABLE TEST10 RENAME CONSTRAINT SYS_C008505 TO PK_SNO;

SQL> SELECT COLUMN_NAME,CONSTRAINT_NAME FROM


USER_CONS_COLUMNS WHERE TABLE_NAME='TEST10';

COLUMN_NAME CONSTRAINT_NAME
------------------------------------ ---------------------------------------------------------------------
SNO PK_SNO

DEFAULT CONSTRAINT:
=====================
- to assign a user defined default value to a column.
Ex:
SQL> CREATE TABLE TEST11(NAME VARCHAR2(10),LOC VARCHAR2(10) DEFAULT
'HYD');

TESTING:
SQL> INSERT INTO TEST11(NAME,LOC) VALUES('A','MUMBAI');----allowed
SQL> INSERT INTO TEST11(NAME) VALUES('B');----allowed

HOW TO ADD A DEFAULT VALUE TO AN EXISTING COLUMN IN A TABLE:


=============================================================
syntax:
=======
ALTER TABLE <TN> MODIFY <COLUMN NAME> DEFAULT <VALUE>;
EX:
SQL> CREATE TABLE TEST12(NAME VARCHAR2(10),SAL NUMBER(10));
SQL> ALTER TABLE TEST12 MODIFY SAL DEFAULT 5000;

TESTING:
=========
SQL> INSERT INTO TEST12(NAME,SAL)VALUES('ALLEN',12000);-----ALLOWED
SQL> INSERT INTO TEST12(NAME)VALUES('JONES');-----ALLOWED

NOTE:
======
- if we want to see the default value of a particular column in a table then
use a datadictionary is called as "user_tab_columns".

EX:
SQL> DESC USER_TB_COLUMNS;
SQL> SELECT COLUMN_NAME,DATA_DEFAULT FROM USER_TAB_COLUMNS
WHERE TABLE_NAME='TEST12';

COLUMN_NAME DATA_DEFAULT
----------------------------------------- ---------------------------------------
SAL 5000

HOW TO REMOVE DEFAULT VALUE OF A PARTICULAR COLUMN:


======================================================
EX:
SQL> ALTER TABLE TEST12 MODIFY SAL DEFAULT NULL;

SQL> SELECT COLUMN_NAME,DATA_DEFAULT FROM USER_TAB_COLUMNS


2 WHERE TABLE_NAME='TEST12';

COLUMN_NAME DATA_DEFAULT
----------------------------------------- ---------------------------------------
SAL NULL
======================================================================
TRANSACTION CONTROL LANGUAGE(TCL):
=====================================
- a transaction is nothing but to do some operation over database tables.
- to control our transactions then we use the following command are,
I) COMMIT
II) ROLLBACK
III) SAVEPOINT

I) COMMIT:
=========
- to make a transaction is permanent.
- these are twp types:
i) Implicit commit transactions
===========================
- these transactions are committed by system by
default.
Ex: DDL commands.

ii) Explicit commit transactions:


============================
- these transactions are committed by user as per
the requirement.

Ex: DML commands.

Ex:
SQL> CREATE TABLE BRANCH(BCODE INT,BNAME VARCHAR2(10),LOC VARCHAR2(10));

SQL> INSERT INTO BRANCH VALUES(1021,'SBI','DELHI');


SQL> COMMIT;

SQL> UPDATE BRANCH SET LOC='HYD' WHERE BCODE=1021;


SQL> COMMIT;

SQL> DELETE FROM BRANCH WHERE BCODE=1021;


SQL> COMMIT;
(OR)
SQL> INSERT INTO BRANCH VALUES(1021,'SBI','DELHI');
SQL> UPDATE BRANCH SET LOC='HYD' WHERE BCODE=1021;
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> COMMIT;

II) ROLLBACK:
============
- to cancel a transaction.
- once a transaction is COMMIT(permanent) then we cannot rollback.

Ex:
SQL> INSERT INTO BRANCH VALUES(1021,'SBI','DELHI');
SQL> ROLLBACK;

SQL> UPDATE BRANCH SET LOC='HYD' WHERE BCODE=1021;


SQL> ROLLBACK;
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> ROLLBACK;
(OR)
SQL> INSERT INTO BRANCH VALUES(1021,'SBI','DELHI');
SQL> UPDATE BRANCH SET LOC='HYD' WHERE BCODE=1021;
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> ROLLBACK;

III) SAVEPOINT:
=============
- when we created a savepoint internally system is allocating a special
memory for a savepoint and it will store the information about rows
which will delete / inserte / update rows and rollback in the future.

SYNTAX TO CREATE A SAVEPOINT:


==============================
SQL> SAVEPOINT <POINTER NAME>;

SYNTAX TO ROLLBACK A SAVEPOINT:


=================================
SQL> ROLLBACK TO <POINTER NAME>;

DEMO_TABLE:
============
SQL> SELECT * FROM BRANCH;

BCODE BNAME LOC


---------- ---------- ----------
1021 SBI HYD
1022 HDFC MUMBAI
1023 ICICI DELHI
1024 AXIS KERALA
1025 BOI CHENNAI

EX1:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> DELETE FROM BRANCH WHERE BCODE=1025;

SQL> SAVEPOINT S1;


SQL> DELETE FROM BRANCH WHERE BCODE=1023;

CASE-1:
=======
SQL> ROLLBACK TO S1; -------> it will rollback 1023 record only

CASE-2:
=======
SQL> COMMIT / ROLLBACK;

EX2:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;

SQL> SAVEPOINT S1;


SQL> DELETE FROM BRANCH WHERE BCODE IN(1023,1025);

CASE-1:
=======
SQL> ROLLBACK TO S1; -------> it will rollback 1023,1025 records only

CASE-2:
=======
SQL> COMMIT / ROLLBACK;
======================================================================
SUBQUERY:
==========
- a query inside another query is called as "subquery / nested query".
syntax:
=======
select * from <tn> where <condition>(select * from .......(select * from ........));

- a subquery statement is having two more queries those are,


i) inner query / child query / subquery
ii) outer query / parent query / main query
- as per the execution process of subquery statement it again classified
into two types,
1. Non-corelated subquery:
First : Inner query
Later : Outer query
2. Co-related subquery:
First : Outer query
Later : Inner query

1. Non-corelated subquery::
=======================
- In NCRSQ first inner query is executed and return some value/(s) and
later outer query will execute.
i) Single row subquery
ii) Multiple row subqeury

i) Single row subquery:


====================
- whenever a subquery returns a single value then we called as "SRSQ".
- in SRSQ we can use the following operators are " = , < , > , <= , >= , != ,......etc".

Ex:
waq to display the first highest salary employee details?
===============================================
|| SUBQUERY statement = OUTER query + INNER query ||
===============================================

STEP1: INNER QUERY:


===================
SQL> SELECT MAX(SAL) FROM EMP;

MAX(SAL)
------------------
5000

STEP2: OUTER QUERY:


====================
SELECT * FROM EMP WHERE SAL=(INNER QUERY);

STEP3: SUBQUERY(OUTER+INNER):
==============================
SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP);

EX:
waq to display the senior most employee details from emp table?
SQL> SELECT * FROM EMP WHERE HIREDATE=(SELECT MIN(HIREDATE) FROM EMP);

EX:
waq to display employees whose salary is more than the maximum salary of
"SALESMAN" ?
SQL> SELECT * FROM EMP WHERE SAL>(SELECT MAX(SAL)
2 FROM EMP WHERE JOB='SALESMAN');

EX:
waq to fetch the second highest salary employee details?
SQL> SELECT * FROM EMP WHERE SAL=
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP));
EX:
waq to fetch the 3rd highest salary employee details?
SQL> SELECT * FROM EMP WHERE SAL=
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP)));

ii) Multiple row subquery:


=====================
- whenever a subquery returns more than one value then we called as
"MRSQ".
- in this subquery we can use the following operators are " IN,ANY,ALL".

Ex:
waq to display employees whose job is same as the job of "SMITH","JONES"?
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM
2 EMP WHERE ENAME IN('SMITH','JONES'));

Ex:
waq to display employees who are getting minimum,maximum salaries from emp
table?
SQL> SELECT * FROM EMP WHERE SAL IN(SELECT MAX(SAL)FROM EMP) OR SAL
IN(SELECT MIN(SAL) FROM EMP);
(OR)
SQL> SELECT * FROM EMP WHERE SAL IN((SELECT MAX(SAL)FROM EMP),(SELECT
MIN(SAL) FROM EMP));
(OR)
SQL> SELECT * FROM EMP WHERE SAL IN
2 (
3 SELECT MAX(SAL) FROM EMP
4 UNION
5 SELECT MIN(SAL) FROM EMP
6 );

Ex:
waq to display employees who are getting maximum salary from each job wise?
SQL> SELECT * FROM EMP WHERE SAL IN(SELECT MAX(SAL)
2 FROM EMP GROUP BY JOB);

Ex:
waq to display the senior most employees from each deptno wise?
SQL> SELECT * FROM EMP WHERE HIREDATE IN
2 (
3 SELECT MIN(HIREDATE) FROM EMP
4 GROUP BY DEPTNO
5 );

ANY operator:
============
- it return a value if any one value is satisfied with user defined
condition value from the list of values.

EX:
X(09) >ANY(10,20,30)
If X=09 ====> FALSE
If X=25 ====> TRUE
If X=40 ====> TRUE

ALL operator:
============
- it return a value if all values are satisfied with user defined
condition value from the list of values.

EX:
X(40) >ALL(10,20,30)
If X=09 ====> FALSE
If X=25 ====> FALSE
If X=40 ====> TRUE

Ex:
waq to display employees whose salary is more than any salesman salary in emp
table?
SQL> SELECT * FROM EMP WHERE SAL>ANY(SELECT SAL FROM
2 EMP WHERE JOB='SALESMAN');

Ex:
waq to display employees whose salary is more than all salesman salaries in emp
table?
SQL> SELECT * FROM EMP WHERE SAL>ALL(SELECT SAL FROM
2 EMP WHERE JOB='SALESMAN');

LIKE USE:
=========
for "ANY" operator for "ALL" operator
=============== ================
X >ANY X > ALL
X >=ANY X >= ALL
X < ANY X < ALL
X <= ANY X <= ALL
X = ANY X = ALL
X != ANY X != ALL

2. Co-related subquery:
====================
- In CRSQ mechanism first outer query is executed and it returns some
value / (s) and later inner query will execute.

Syntax to find out "Nth" high / low salary:


===================================
SELECT * FROM <TN> <TABLE ALIAS NAME1> WHERE N-1=(SELECT
COUNT(DISTINCT <COLUMN NAME>) FROM <TN> <TABLE ALIAS NAME2>
WHERE <TABLE ALIAS NAME2>.<COLUMN NAME> < / > <TABLE ALIAS NAME1>.
<COLUMN NAME>);

DEMO_TABLE:
=============
SQL> SELECT * FROM EMPLOYEE;

EID ENAME SAL


---------- ---------- ----------
1 SMITH 85000
2 JONES 34000
3 ADAMS 61000
4 WARD 85000
5 JAMES 48000
6 MILLER 55000

EX:
waq to find out the first highest salary employee details?
SQL> SELECT * FROM EMPLOYEE E1 WHERE 0=(SELECT
COUNT(DISTINCT SAL) FROM EMPLOYEE E2
WHERE E2.SAL>E1.SAL);

EX:
waq to find out the 3rd highest salary employee details?
SQL> SELECT * FROM EMPLOYEE E1 WHERE 2=(SELECT
COUNT(DISTINCT SAL) FROM EMPLOYEE E2
WHERE E2.SAL>E1.SAL);

EX:
waq to find out the first lowest salary employee details?
SQL> SELECT * FROM EMPLOYEE E1 WHERE 0=(SELECT
COUNT(DISTINCT SAL) FROM EMPLOYEE E2
WHERE E2.SAL<E1.SAL);

Syntax to find out "Top n" high / low salaries:


=====================================
SELECT * FROM <TN> <TABLE ALIAS NAME1> WHERE N>(SELECT
COUNT(DISTINCT <COLUMN NAME>) FROM <TN> <TABLE ALIAS NAME2>
WHERE <TABLE ALIAS NAME2>.<COLUMN NAME> < / > <TABLE ALIAS NAME1>.
<COLUMN NAME>);

Ex:
waq to display top 3 highest salaries employees details?
SQL> SELECT * FROM EMPLOYEE E1 WHERE 3>(SELECT
COUNT(DISTINCT SAL) FROM EMPLOYEE E2
WHERE E2.SAL>E1.SAL);

Ex:
waq to display top 2 lowest salaries employees details?
SQL> SELECT * FROM EMPLOYEE E1 WHERE 2>(SELECT
COUNT(DISTINCT SAL) FROM EMPLOYEE E2
WHERE E2.SAL<E1.SAL);

Note:
=====
1. To find out "Nth" high / low salary -----------------> N-1
2. To display "Top n" high / low salaries -------------> N>

EXISTS operator:
===============
- it special operator which was used in co-related subquery only.
- this operator is used to check the required row is existing in a table
or not.
> if a row is existing in a table then it return "true".
> if a row is not existing in a table then it return "false".

Ex:
waq to display all departments details in which department the employees are
working?
SQL> SELECT * FROM DEPT S WHERE EXISTS(SELECT DEPTNO FROM EMP E WHERE
E.DEPTNO=S.DEPTNO);

Ex:
waq to display all departments details in which department the employees are
not working?
SQL> SELECT * FROM DEPT S WHERE NOT EXISTS(SELECT DEPTNO FROM EMP E
WHERE E.DEPTNO=S.DEPTNO);
========================================================================
=========================
VIEWS IN ORACLE:
================
- it is virtual table of a base table (or) subset of a base table.
- view doesnot store data / information because it doesnot have physical
existence or it doesnot occupie any memory.
- by using view we can access the required data / information from a base table.
- by using view we can provide security for data in a table at two levels
i) column level security:
====================
> to hide columns

ii) row level security:


==================
> to hide rows

- when we perform DML operations on a view internally those operations are


executed on base table and reflected in a view table to user.
- views are created with the help of "SELECT" command only.

syntax:
======
CREATE VIEW <VIEW NAME> AS <SELECT * FROM <TABLE NAME> [ WHERE
<CONDITION>]>;

TYPES OF VIEWS:
===============
1. simple views
2. complex views

1. simple views:
==============
- when we created a view to access the required data / information from
a single base table.
- simple views are supporting all DML operations.

Ex1:
create a view to access all departments details from DEPT base table?
SQL> CREATE VIEW V1 AS SELECT * FROM DEPT;
View created.
TESTING:
SQL> INSERT INTO V1 VALUES(50,'SAP','HYD');
SQL> UPDATE V1 SET LOC='PUNE' WHERE DEPTNO=50;
SQL> DELETE FROM V1 WHERE DEPTNO=50;
SQL> SELECT * FROM V1;

EX2:
create a view to access empno,ename,sal from emp table?(HIDING COLUMNS)
SQL> CREATE VIEW V2 AS SELECT EMPNO,ENAME,SAL FROM EMP;

TESTING:
SQL> INSERT INTO V2 VALUES(1122,'YUVIN',6000);
SQL> SELECT * FROM V2;

EX3:
create a view to access employees details who are working under deptno is 20? (HIDING
ROWS)
SQL> CREATE VIEW V3 AS SELECT * FROM EMP WHERE DEPTNO=20;

TESTING:
SQL> SELECT * FROM V3;

VIEW OPTIONS:
==============
i) with check option
ii) with read only

i) with check option :


=================
- whenever we restricted invalid data on base table through a view object
then we use "with check option" statement at the time of createing a view.

EX:
create a view to display and accept employee details whose salary is 3000?
SQL> CREATE VIEW V5 AS SELECT * FROM EMP
2 WHERE SAL=3000 WITH CHECK OPTION;

TESTING:
SQL> INSERT INTO V5 VALUES(1125,'SRI','HR',7788,'04-NOV-2023',4000,NULL,10);----NOT
ALLOWED
SQL> INSERT INTO V5 VALUES(1125,'SRI','HR',7788,'04-NOV-2023',2000,NULL,10);----NOT
ALLOWED
SQL> INSERT INTO V5 VALUES(1125,'SRI','HR',7788,'04-NOV-2023',3000,NULL,10);----
ALLOWED

ii) with read only:


===============
- whenever we restricted DML operations on a base table through a
view object then we use "with read only" statement in the view.

Ex:
SQL> CREATE VIEW V6 AS SELECT * FROM DEPT WITH READ ONLY;

TESTING:
SQL> INSERT INTO V6 VALUES(50,'DBA','UP');
SQL> UPDATE V6 SET LOC='HYD' WHERE DEPTNO=30;
SQL> DELETE FROM V6 WHERE DEPTNO=10;
ERROR at line 1:
ORA-42399: cannot perform a DML operation on a read-only view

ii) COMPLEX VIEW:


=================
- when we created a view based on:
> multiple tables
> by using group by
> by using aggregative functions
> by using having
> by using set operators
> by using distinct kyword
> by using joins
> by using subquery
are called as "complex view".
- by default complex views are not allowed DML operations it is a read
only view.

Ex1:
SQL> CREATE VIEW V7 AS
2 SELECT * FROM EMP_HYD
3 UNION
4 SELECT * FROM EMP_CHENNAI;

TESTING:
SQL> INSERT INTO V7 VALUES(1026,'SCOTT',33000);
SQL> UPDATE V7 SET SAL=28000 WHERE EID=1023;
SQL> DELETE FROM V7 WHERE EID=1022;
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view
EX2:
SQL> CREATE VIEW V8
AS
SELECT DEPTNO,SUM(SAL)AS SUM_OF_SALARY FROM EMP
GROUP BY DEPTNO;

TESTING:
SQL> SELECT * FROM V8; -------> before update data in emp table
SQL> UPDATE EMP SET SAL=SAL+1000 WHERE DEPTNO=10;
SQL> SELECT * FROM V8; -------> after updated data in emp table
=====================================================================
INDEXES:
========
- indexes are used to retrieve the required row / rows from a table fastly.
- it is similar to book index page in textbook.
- by using indexes we can save time and improve the performance of
database.
- all databases are supporting the following two types of searching
mechanisms those are,
1. Table scan
2. Index scan

1. Table scan:
============
- it is a default searching mechanism on database tables.
- in this scan, oracle server is searching the entire table for required
data.

Ex:
SQL> SELECT * FROM EMP WHERE SAL=3000;

SOLUTION:
=========
SAL
----------
800
1600
1250
2975
1250
2850
2450
3000 WHERE SAL=3000;
5000 (comparing all 14 rows in a table)
1500
1100
950
3000
1300

2. Index scan:
============
- In this scan the oracle server is searching based on an indexed column
wise only.
i) B-tree index scan (default)
ii) Bitmap index scan
i) B-tree index scan:
=================
- when we created an index object on a particular column in a table internally
system will arrange that column values in "tree" structure format.

syntax:
======
CREATE INDEX <INDEX NAME> ON <TN>(COLUMN NAME);

EX:
SQL> CREATE INDEX I1 ON EMP(SAL);
Index created.

- If we want to view index name along with column name of a particular


table then we use a datadictionary is called as " user_ind_columns".

EX:
SQL> DESC USER_IND_COLUMNS;
SQL> SELECT COLUMN_NAME,INDEX_NAME FROM USER_IND_COLUMNS
2 WHERE TABLE_NAME='EMP';

COLUMN_NAME INDEX_NAME
------------------------------------ ---------------------------------------------------------
SAL I1

EX:
SQL> SELECT * FROM EMP WHERE SAL=3000;

B-TREE FORMAT
==============
|
< lp | SAL=3000 |rp >= ------------> (root level)
| |
< lp|2975|rp > < lp | 5000 | rp >= -------------> (parent level)
| |
2850|* , 2450|* , 1600|*, 3000| *(r8), *(r13)---------------------> (child level)
1500|* , 1300| * , 1250| *(r3),*(r5),
1100| * , 950|* , 800|*

Here,
lp - left pointer
rp - right pointer
* - rowid

NOTE: In this index scan we are comparing 3 times for our required data.
=====

ii) Bitmap index scan:


==================
- are created on "low cardinality of columns" in a table.

What is cardinality?
=================
- it refers the uniqueness values of a column.
(or)
- it refers the distinct values of a column.

Formula:
=======
cardinality of column = no.of distinct values in a column
============================
no.of rows in a table
Ex:
cardinality of empno = 14 / 14 ===> 1 (high cardinality) ----- B-Tree index
cardinality of job = 5 / 14 ====> 0.35 (low cardinality) ---- Bitmap index

> if cardinality of column < 1 then use bitmap index.


> if cardinality of column >= 1 then use b-tree index.
- to improve performance of database.

syntax:
======
create bitmap index <index name> on <tn>(column name);

EX:
SQL> CREATE BITMAP INDEX BIT1 ON EMP(JOB);

- Once we created a bitmap index object on a particular column internally


system is preparing a bitmap indexed table with bit numbers 1 and 0.Here " 1 " is
represent the condition is "true" and "0" is represent the condition is "false".

Ex:
SQL> SELECT * FROM EMP WHERE JOB='PRESIDENT';

BITMAP INDEXED TABLE


|
========================================================================
===================
JOB || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || 10 || 11 || 12 ||
13 || 14
========================================================================
===================
CLERK || 1 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 1 ||
1 || 0 || 1
========================================================================
====================
PRESIDENT || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 1 || 0 || 0 ||
0 || 0 || 0
========================================================================
====================
Here, "1" is rowid.

NOTE:
=====
- to view index name and index type of a particular table then use a
datadictionary is "user_indexes".

EX:
SQL> DESC USER_INDEXES;
SQL> SELECT INDEX_NAME,INDEX_TYPE FROM USER_INDEXES
2 WHERE TABLE_NAME='EMP';

INDEX_NAME INDEX_TYPE
------------------------------- -------------------------------------------------
I1 NORMAL(b-tree index)
BIT1 BITMAP
===================================================================
SEQUENCE:
==========
- it is a database object which is used to generate sequence numbers
on a specific column in a table automatically.
- it will provide "auto incremental values" facility on a table.

syntax:
======
create sequence <sequence name>
[ start with n ]
[ minvalue n ]
[ increment by n ]
[ maxvalue n ]
[ no cycle / cycle ]
[ no cache / cache n ];

start with n:
==========
- it shows the starting value of the sequence (n-number).
minvalue n:
==========
- it shows minimum values in the sequence(n-number).

increment by n:
=============
- it shows incremental value between sequence numbers(n-number).

maxvalue n:
===========
- it shows maximum value in the sequence(n-number).

no cycle:
========
- it is a default parameter.
- when we created a sequence object with "no cycle" then
the set sequence numbers are not repeated again and again.

cycle:
=====
- when we created a sequence object with "cycle" then
the set sequence numbers are repeated again and again.

no cache:
=========
- it is default paramter of sequence.
- when we created a sequence object with "no cache" then the set of
sequence numbers are saved in database memory directly.so that whenever the
user want to access the data based on a sequence number then the oracle server
will go to database and retrive the required data from database memory to client
(user) application for each and every request.
- so that the burdon on database is incresed and reduce the performance
of database.

cache n:
======
- when we created a sequence object with "cache" then the set of
sequence numbers are saved in database memory and also the copy of sequence
numbers are also saved in cache memory.so that whenever the user want to access
the data based on a sequence number then the oracle server will go to cache memory
instead of database and retrive the required data from cache memory to client (user)
application for each and every request.the minimum size of cache size is 2kb and
maximum size is depends on the size of RAM.
- so that it reduce the burdon on database and improve the performance
of database.

NOTE:
=====
- when we apply a sequence facility on a column then we use a pseudo column
is "nextval".whereas nextval is used to generate sequence numbers on a column with
sequence object automatically.

syntax:
=======
<sequence object name>.<nextval>

EX:
SQL> CREATE SEQUENCE SQ1
2 START WITH 1
3 MINVALUE 1
4 INCREMENT BY 1
5 MAXVALUE 3;

TESTING:
SQL> CREATE TABLE TEST20(SNO INT,NAME VARCHAR2(10));

SQL> INSERT INTO TEST20 VALUES(SQ1.NEXTVAL,'SMITH');


SQL> INSERT INTO TEST20 VALUES(SQ1.NEXTVAL,'JONES');
SQL> INSERT INTO TEST20 VALUES(SQ1.NEXTVAL,'ADAMS');

SQL> INSERT INTO TEST20 VALUES(SQ1.NEXTVAL,'MILLER');


ERROR at line 1:
ORA-08004: sequence SQ1.NEXTVAL exceeds MAXVALUE and cannot be instantiated

OUTPUT:
SQL> SELECT * FROM TEST20;

SNO NAME
---------- ----------
1 SMITH
2 JONES
3 ADAMS

EX:
QL> CREATE SEQUENCE SQ2
2 START WITH 1
3 MINVALUE 1
4 INCREMENT BY 1
5 MAXVALUE 3
6 CYCLE
7 CACHE 2;
Sequence created.

TESTING:
SQL> CREATE TABLE TEST21(SNO INT,NAME VARCHAR2(10));

SQL> INSERT INTO TEST21 VALUES(SQ2.NEXTVAL,'A');


SQL> INSERT INTO TEST21 VALUES(SQ2.NEXTVAL,'B');
SQL> INSERT INTO TEST21 VALUES(SQ2.NEXTVAL,'C');
.........................................................................................;
..........................................................................................;
..........................................................................................;

OUTPUT:
SQL> SELECT * FROM TEST21;

SNO NAME
---------- ----------
1 A
2 B
3 C
1 D
2 E
3 F
EX:
SQL> CREATE SEQUENCE SQ3
2 START WITH 3
3 MINVALUE 1
4 INCREMENT BY 1
5 MAXVALUE 5
6 CYCLE
7 CACHE 2;
Sequence created.

TESTING:
SQL> CREATE TABLE TEST22(SNO INT,NAME VARCHAR2(10));

SQL> INSERT INTO TEST22 VALUES(SQ3.NEXTVAL,'A');


...........................................................................................;
............................................................................................;

OUTPUT:
SQL> SELECT * FROM TEST22;

SNO NAME
---------- ----------
3A
4B
5C
1Q
2W
3E
4R
5T
How to drop a sequence object from a table:
======================================
syntax:
======
DROP SEQUENCE <SEQUENCE NAME>;

EX:
SQL> DROP SEQUENCE SQ1;
========================================================================
==
NORMALIZATION:
===============
- it is a technique which is used to organized data into multiple tables.
- it can be used at "DB designing" level.
Why Normalization ?
=================
- when we store two different types of data into a single
table there is chance to occurres the following problems are,

Disadvantages:
=============
1. data redundancy(duplicate data) problem.
2. occupied more memory.
3. data inconsistency( irregular of data) problem.
4. insert problem
5. update problem
6. delete problem

Ex:
student_branch_details
=============================================
STID SNAME BRANCH HOD OFFICE_NUMBER
=============================================
1 SMITH CSE Mr.X 040-22334455
2 ALLEN CSE Mr.X 040-22334455
3 WARD CSE Mr.X 040-22334455
4 MILLER CSE Mr.X 040-22334455
5 JONES CSE Mr.X 040-22334455

- to avoid the above drawbacks we need to use a technique is


called as "Normalization".

Solution:
=======
Using Normalization Technique:
===========================
Ex:
Branch_details Student_details
(pk) ============= ============= (fk)
Bcode Bname HOD Offiec_Number Stid Sname Bcode
====================================== ===================
101 cse Mr.Y 040-22334455 1 smith 101
2 allen 101
3 ward 101
4 miller 101
5 jones 101
6 adams 101
Advantages:
=============
1. To void data redundancy(duplicate data) problem.
2. occupied less memory.
3. To avoid data inconsistency( irregular of data) problem.
4. To avoid insert problem.
5. To avoid update problem.
6. To avoid delete problem.

Types of Normalization Forms:


==========================
1. First Normal Form(1nf)
2. Second Normal Form (2nf)
3. Thrid Normal Form(3nf)
4. Boyce- code Normal Form(BCNF)
5. Fourth Normal Form(4nf)
6. Fifth Normal Form(5nf)

1. First Normal Form(1nf):


======================
- For a table to be in the First Normal Form, it should follow the
following 4 rules:

Rule-1. Each column should contain atomic value (atomic = single value).

Ex: column1 column2


A X, Y

Rule-2. A COLUMN SHOULD CONTAIN VALUES THAT ARE SAME


DATATYPE.

EX: NAME DOB


SAI 01-JAN-92
12-JUN-22 ALLEN

Rule-3. All the columns in a table should have unique names.

EX: NAME NAME DOB

Rule-4. The order in which data is stored, does not matter.

EX:
SNO
====
2
3
4
1

2. Second Normal Form (2nf):


=========================
For a table to be in the Second Normal Form, it must satisfy two
conditions:
1. The table should be in the First Normal Form.
2. There should be no Partial Dependency.

WHAT IS DEPENDENCY:
====================
- IN A TABLE IF NON-KEY COLUMNS (NON PRIMARY KEY) ARE DEPENDS ON KEY
COLUMN (PRIMARY KEY)
THEN IT IS CALLED AS FULLY DEPENDENCY / FUNCTIONAL DEPENDENCY.

(PK)
EX: A B C D

Here, “A “IS A KEY COLUMN - “B”,” C”,” D” ARE NON-KEY COLUMNS.

WHAT IS PARTIAL DEPENDENCY:


===========================
-IN A TABLE IF NON-KEY COLUMN DEPENDS ON PART OF THE KEY
COLUMN,
THEN IT IS CALLED AS PARTIAL DEPENDENCY.

<PRIMARY KEY (A, B) / COMPOSITE PRIMARY KEY>


EX: A B C D

Here, “A AND B “IS A KEY COLUMNS - ” C”,” D” ARE NON-KEY COLUMNS.


THEN “D” DEPENDS ON “B” BUT NOT “A” COLUMN.

3. Thrid Normal Form(3nf):


======================
- For a table to be in the third normal form there is two conditions.
1. It should be in the Second Normal form.
2. And it should not have Transitive Dependency.
TRANSITIVE DEPENDENCY:
=======================
- IN TABLE IF NON-KEY COLUMN DEPENDS ON NON-KEY COLUMN,
THEN IT IS CALLED AS TRANSITIVE DEPENDENCY.

(Composite Primary key)


EX: A B C D

Here, “A AND B “ARE KEY COLUMNS - ” C”,” D” ARE NON-KEY COLUMNS.


THEN “D” DEPENDS ON “C” BUT NOT “A & B” COLUMNS.

4. Boyce- codd Normal Form(BCNF):


=============================
- For a table to satisfy the Boyce- Codd Normal Form, it should
satisfy the following two conditions:
1. It should be in the Third Normal Form.
2. And, for any dependency A → B, A should be a super key.

SUPER KEY:
==========
- A COLUMN (OR) COMBNATION OF COLUMNS WHICH
ARE UNIQUELY IDENTIFYING A ROW IN A TABLE IS CALLED AS SUPER KEY.

CANDIDATE KEY:
==============
- A MINIMAL SUPER KEY WHICH IS UNIQUELY
IDENTIFYING A ROW IN A TABLE IS CALLED AS CANDIDATE KEY.
(OR)
- A SUPER KEY WHICH IS SUBSET OF ANOTHER SUPER KEY, BUT THE
COMBINATION OF SUPER KEYS IS NOT A CANDIDATE KEY.
======================================================================
PL/SQL
======
How to retrieve employee name,salary details of empno is 7788:
======================================================
In SQL:
======
SQL> SELECT ENAME,SAL FROM EMP WHERE EMPNO=7788;

In PL/SQL:
=========
SQL> DECLARE
2 v_ENAME VARCHAR2(10);
3 v_SAL NUMBER(10);
4 BEGIN
5 SELECT ENAME,SAL INTO v_ENAME,v_SAL FROM EMP
6 WHERE EMPNO=7788;
7 DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
8 END;
9 /
SCOTT,3000

How pass employee number at runtime(i.e dynamically):


===============================================
In SQL:
======
SQL> SELECT ENAME,SAL FROM EMP WHERE EMPNO=&EMPNO;
Enter value for empno: 7369

ENAME SAL
---------- ----------
SMITH 800

SQL> /

Enter value for empno: 7900

ENAME SAL
---------- ----------
JAMES 950

In PL/SQL:
=========
SQL> DECLARE
2 v_ENAME VARCHAR2(10);
3 v_SAL NUMBER(10);
4 BEGIN
5 SELECT ENAME,SAL INTO v_ENAME,v_SAL FROM EMP
6 WHERE EMPNO=&EMPNO;
7 DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
8 END;
9 /

Enter value for empno: 7369


SMITH,800

SQL> /
Enter value for empno: 7900
JAMES,950

EX:
SQL> DECLARE
i EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP WHERE EMPNO=&EMPNO;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||I.ENAME||','||I.SAL||','||I.DEPTNO);
END;
/
Enter value for empno: 7788
7788,SCOTT,3000,20
=====================================================================
CURSOR:
========
- it is a temporary memory / a private area / a workspace.
1. Explicit cursors (User defined memory)
2. Implicit cursors (System defined memory)

1. Explicit cursors:
================
- these cursor are created by user for fetching row by row / one by one
row from a table.
- explicit cursor memory is allowed set of rows but we can access only
one row at a time from this cursor memory.
- when a user want to create an explicit cursor(i.e memory) then we need
to follow the following four steps:

step1: Decalre cursor variable:


==========================
syntax:
======
DECLARE CURSOR <CURSOR NAME> IS <SELECT STATEMENT>;

step2: Open cursor connection:


==========================
syntax:
=======
OPEN <CURSOR NAME>;

step3: Fetching one by one row from a cursor :


========================================
syntax:
=======
FETCH <CURSOR NAME> INTO <VARIABLES>;

step4: Close cursor connection:


==========================
syntax:
======
CLOSE <CURSOR NAME>;

Attributes of an explicit cursor:


===========================
- the status of cursor memory.

i) %isopen:
=========
- it is a default attribute.
- it returns "true" when cursor connection is successfully open otherwise
it returns "false".it return type is "boolean".

ii) %not found:


=============
- it returns "true" when a cursor is not having data otherwise it returns
"false".it return type is "boolean".

iii) %found:
=========
- it returns "true" when a cursor is having data otherwise it returns
"false".it return type is "boolean".

iv) %rowcount:
=============
- it return no.of fetch statements are executed. it return type is "number".

syntax:
======
<cursor name>%<attribute name>

Ex:
write a cursor program to fetch a single row from emp table?
SQL> DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP;
v_ENAME VARCHAR2(10);
v_SAL NUMBER(10);
BEGIN
OPEN C1;
FETCH C1 INTO v_ENAME,v_SAL;
DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
CLOSE C1;
END;
/

OUTPUT:
========
SMITH,800

Ex:
write a cursor program to fetch multiple rows from emp table?
SQL> DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP;
v_ENAME VARCHAR2(10);
v_SAL NUMBER(10);
BEGIN
OPEN C1;
FETCH C1 INTO v_ENAME,v_SAL;
DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
FETCH C1 INTO v_ENAME,v_SAL;
DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
CLOSE C1;
END;
/
- In the above example we are used no.of fetch statements to fetch
multiple rows from a cursor table.to overcome this problem we should use
"looping statements".

How to fetch multiple rows from a cursor by using "loops":


==================================================
i) By using "Simple Loop":
======================
SQL> DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP;
2 v_ENAME VARCHAR2(10);
3 v_SAL NUMBER(10);
4 BEGIN
5 OPEN C1;
6 LOOP
7 FETCH C1 INTO v_ENAME,v_SAL;
8 EXIT WHEN C1%NOTFOUND;
9 DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
10 END LOOP;
11 CLOSE C1;
12 END;
13 /

OUTPUT:
========
SMITH,800
ALLEN,1600
WARD,1250
JONES,2975
MARTIN,1250
BLAKE,2850
CLARK,2450
SCOTT,3000
KING,5000
TURNER,1500
ADAMS,1100
JAMES,950
FORD,3000
MILLER,1300

ii) By using "While Loop":


=====================
SQL> DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP;
2 v_ENAME VARCHAR2(10);
3 v_SAL NUMBER(10);
4 BEGIN
5 OPEN C1;
6 FETCH C1 INTO v_ENAME,v_SAL;
7 WHILE(C1%FOUND)
8 LOOP
9 DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
10 FETCH C1 INTO v_ENAME,v_SAL;
11 END LOOP;
12 CLOSE C1;
13 END;
14 /

OUTPUT:
=========
SMITH,800
ALLEN,1600
WARD,1250
JONES,2975
MARTIN,1250
BLAKE,2850
CLARK,2450
SCOTT,3000
KING,5000
TURNER,1500
ADAMS,1100
JAMES,950
FORD,3000
MILLER,1300

iii) By using "For Loop":


====================
SQL> DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP;
2 BEGIN
3 FOR i IN C1
4 LOOP
5 DBMS_OUTPUT.PUT_LINE(i.ENAME||','||i.SAL);
6 END LOOP;
7 END;
8 /

OUTPUT:
========
SMITH,800
ALLEN,1600
WARD,1250
JONES,2975
MARTIN,1250
BLAKE,2850
CLARK,2450
SCOTT,3000
KING,5000
TURNER,1500
ADAMS,1100
JAMES,950
FORD,3000
MILLER,1300

NOTE:
=====
- when we use "for loop" under cursors there is no need to write
open cursor,fetching cursor data and close cursor statements because by default
oracle server will open cursor,fetching data from cursor and closing cursor
connection while executing "for loop".
2) Implicit cursor:
================
- these cursors are created by system when we perform DML
operations on a table in database.
- system will create implicit cursor memory with the name of "SQL".
- this implicit cursor memory is used to store the information of
a DML query is executed successfully or fail.

Attributes of Implicit cursor:


========================
i) %isopen:
==========
- it is a default attribute of implicit cursor.
- it returns "true" when implicit cursor connection is successfully open
otherwise returns "false".

ii) %notfound:
============
- it returns "true" when a dml command execution is fail otherwise
returns "false".

iii) %found:
==========
- it returns "true" when a dml command executed successfully otherwise
returns "false".

iv) %rowcount:
=============
- it returns how many no.of rows are affected by a DML query.

syntax:
======
SQL%<attribute name>

EX:
SQL> DECLARE
2 v_DEPTNO NUMBER(10);
3 BEGIN
4 v_DEPTNO:=&v_DEPTNO;
5 DELETE FROM EMP WHERE DEPTNO=v_DEPTNO;
6 IF(SQL%FOUND) THEN
7 DBMS_OUTPUT.PUT_LINE('RECORD IS FOUND AND DELETED');
8 ELSE
9 DBMS_OUTPUT.PUT_LINE('SORRY,RECORD IS NOT FOUND!!!TRY AGAIN');
10 END IF;
11 END;
12 /
Enter value for v_deptno: 40
SORRY,RECORD IS NOT FOUND!!!TRY AGAIN

SQL> /
Enter value for v_deptno: 10
RECORD IS FOUND AND DELETED
====================================================================
SUB BLOCKS:
============
- are named blocks which will save the code in database automatically.
- by using subblocks we can reusable the code in any application like
DB applications,Java appplications and .Net applications.
- pl/sql supports the following sub-blocks are,
i) stored procedures
ii) stored functions
iii) triggers

i) stored procedures:
==================
- it is named block which contains "pre-compiled code / query".

syntax:
======
create [or replace] procedure <pname>(<parameter name1> [mode type] <datatype>,.........)
is
<declare variables>;
begin
<procedure body / statements>;
end;
/

How to call a stored procedure:


==========================
syntax1: (annonymous block)
=======
Begin
<pname>(value / (s));
End;
/

syntax2: (latest syntax)


=======
Execute / Exec <pname>(value/(s));

Types of parameters modes:


========================
i) IN :
=====
- these are default parameters of stored procedure.
- are storing / accepting input values which was given by user
at runtime.

ii) OUT :
=======
- generally stored procedures are never returns any value.
- if a stored procedure want to return a value then we use
"OUT" parameters.

iii) IN OUT :
===========
- it will accept and also return a value.

Ex on "IN" parameter mode:


========================
create a SP to input EMPNO and display that employee Name,Salary details
from emp table by using "IN" parameter?
SQL> CREATE OR REPLACE PROCEDURE SP1(p_EMPNO IN NUMBER)
2 IS
3 v_ENAME VARCHAR2(10);
4 v_SAL NUMBER(10);
5 BEGIN
6 SELECT ENAME,SAL INTO v_ENAME,v_SAL FROM EMP
7 WHERE EMPNO=p_EMPNO;
8 DBMS_OUTPUT.PUT_LINE(v_ENAME||','||v_SAL);
9 END;
10 /

Calling a stored procedure:


=======================
1)
BEGIN
SP1(7788);
END;
/
SCOTT,3000
2)
SQL> EXECUTE SP1(7788);
(OR)
SQL> EXEC SP1(7788);
SCOTT,3000

NOTE:
======
- to view all sub blocks objects(stored procedure,stored functions,triggers)
in oracle database then use a datadictionary is " user_objects".

EX:
SQL> DESC USER_OBJECTS;
SQL> SELECT OBJECT_NAME FROM USER_OBJECTS WHERE
OBJECT_TYPE='PROCEDURE';

OBJECT_NAME
-------------------------------
SP1

NOTE:
=====
- to view the source code of a sub block object(procedure / function / trigger)
in oracle database then use a datadictionary is "user_source".

EX:
SQL> DESC USER_SOURCE;
SQL> SELECT TEXT FROM USER_SOURCE WHERE NAME='SP1';

EX ON "OUT" parameters:
=======================
Ex:
SQL> CREATE OR REPLACE PROCEDURE SP2(X IN NUMBER,Y OUT NUMBER)
2 IS
3 BEGIN
4 Y:=X*X;
5 END;
6 /
Procedure created.

OUTPUT:
SQL> EXECUTE SP2(5);
ERROR at line 1:
PLS-00306: wrong number or types of arguments in call to 'SP2'

- To overcome the above problem then we need to follow the following


thress steps are,

Step1: Declare referenced variables for "OUT" parameters:


=================================================
syntax:
======
var[iable] <referenced variable name> <datatype>[size];

Step2: To add referenced variables to a stored procedure:


=================================================
syntax:
======
execute <pname>(value1,value2,........, :<referenced variable name1>,....);

Step3: Print referenced variables:


=============================
syntax:
======
print <referenced variable name>;

solution:
=======
SQL> VAR A NUMBER;
SQL> EXECUTE SP2(5,:A);
PL/SQL procedure successfully completed.

SQL> PRINT A;

A
--------------
25

EX:
create a SP to input EMPNO and return that employee provident fund,professional
tax at 5%,10% on basic salary by using "OUT" parameters?
SQL> CREATE OR REPLACE PROCEDURE SP3(p_EMPNO IN NUMBER,PF OUT
NUMBER,PT OUT NUMBER)
2 IS
3 v_BSAL NUMBER(10);
4 BEGIN
5 SELECT SAL INTO v_BSAL FROM EMP WHERE EMPNO=p_EMPNO;
6 PF:=v_BSAL*0.05;
7 PT:=v_BSAL*0.1;
8 END;
9 /

OUTPUT:
========
SQL> VAR rPF NUMBER;
SQL> VAR rPT NUMBER;
SQL> EXECUTE SP3(7788,:rPF,:rPT);
SQL> PRINT rPF rPT;

RPF
----------
150

RPT
----------
300

EX ON " IN OUT " parameter:


========================
Ex:
SQL> CREATE OR REPLACE PROCEDURE SP4(X IN OUT NUMBER)
2 IS
3 BEGIN
4 X:=X*X*X;
5 END;
6 /
Procedure created.

SQL> EXECUTE SP4(5);


ERROR at line 1:
PLS-00363: expression '5' cannot be used as an assignment target

- To overcome the above problem then we need to follow the following


four steps are,

Step1: Declare referenced variables for "OUT" type:


=================================================
syntax:
======
var[iable] <referenced variable name> <datatype>[size];
Step2: To assign a value to referenced variable " IN " type:
================================================
syntax:
=======
execute :<referenced variable name> := <value>;

Step3: To add referenced variables to a stored procedure:


=================================================
syntax:
======
execute <pname>( :<referenced variable name1>,....);

Step4: Print referenced variables:


=============================
syntax:
======
print <referenced variable name>;

OUTPUT:
========
SQL> VAR A NUMBER;
SQL> EXECUTE :A:=5;
SQL> EXECUTE SP4(:A);
SQL> PRINT A;

A
-------------
125

EX:
create a SP to input EMPNO and return that employee salary from emp table by using
"IN OUT" parameter?
SQL> CREATE OR REPLACE PROCEDURE SP5(X IN OUT NUMBER)
2 IS
3 BEGIN
4 SELECT SAL INTO X FROM EMP WHERE EMPNO=X;
5 END;
6 /

Procedure created.

SQL> VAR A NUMBER;


SQL> EXECUTE :A:=7788;
SQL> EXECUTE SP5(:A);
SQL> PRINT A;

A
----------
3000

How drop a stored procedure:


=========================
syntax:
======
DROP PROCEDURE <PNAME>;

EX:
SQL> DROP PROCEDURE SP1;

2) STORED FUNCTIONS:(USER DEFINED FUNCTIONS)


============================================
- a function is nothing but it is a block of code to perform some task and
it must return a value.
- in oracle database stored functions are also called as "user defined functions".

syntax:
======
create [or replace] function <fname>(<parameter name1> <datatype>,..........)
return <type of the variable>
is/as
<declare variables>;
begin
<function body / statements>;
return <name of the variable>;
end;
/

Syntax to call a stored function:


===========================
SELECT <FNAME>(VALUE/(S)) FROM DUAL;

EX:
create a SF to input EMPNO and return that employee NAME from emp table?
SQL> CREATE OR REPLACE FUNCTION SF1(p_EMPNO NUMBER)
2 RETURN VARCHAR2
3 AS
4 v_ENAME VARCHAR2(10);
5 BEGIN
6 SELECT ENAME INTO v_ENAME FROM EMP WHERE EMPNO=p_EMPNO;
7 RETURN v_ENAME;
8 END;
9 /

OUTPUT:
========
SQL> SELECT SF1(7788) FROM DUAL;

SF1(7788)
--------------------------------------------
SCOTT

EX:
create a SF to find out sum of salary of the given department name?
SQL> CREATE OR REPLACE FUNCTION SF2(p_DNAME VARCHAR2)
2 RETURN NUMBER
3 AS
4 v_TOTSAL NUMBER(10);
5 BEGIN
6 SELECT SUM(SAL) INTO v_TOTSAL FROM EMP E INNER JOIN
7 DEPT D ON E.DEPTNO=D.DEPTNO AND DNAME=p_DNAME;
8 RETURN v_TOTSAL;
9 END;
10 /

OUTPUT:
=======
SQL> SELECT SF2('SALES') FROM DUAL;

SF2('SALES')
------------
9400

EX:
create a SF to return the no.of employees are joined in between the given two dates ?
SQL> CREATE OR REPLACE FUNCTION SF3(SD DATE,ED DATE)
2 RETURN NUMBER
3 AS
4 v_NUMEMP NUMBER(10);
5 BEGIN
6 SELECT COUNT(*) INTO v_NUMEMP FROM EMP
7 WHERE HIREDATE BETWEEN SD AND ED;
8 RETURN v_NUMEMP;
9 END;
10 /

OUTPUT:
========
SQL> SELECT SF3('01-JAN-81','31-DEC-81') FROM DUAL;

SF3('01-JAN-81','31-DEC-81')
----------------------------------------------
8

EX:
create a SF to input EMPNO and return that employee gross salary based on
the following conditions are,
i) HRA --------- 10%
ii) DA ---------- 20%
iii) PF ---------- 5% on basic salary?

SQL> CREATE OR REPLACE FUNCTION SF4(p_EMPNO NUMBER)


2 RETURN NUMBER
3 AS
4 v_BSAL NUMBER(10);
5 v_HRA NUMBER(10);
6 v_DA NUMBER(10);
7 v_PF NUMBER(10);
8 v_GROSS NUMBER(10);
9 BEGIN
10 SELECT SAL INTO v_BSAL FROM EMP WHERE EMPNO=p_EMPNO;
11 v_HRA:=v_BSAL*0.1;
12 v_DA:=v_BSAL*0.2;
13 v_PF:=v_BSAL*0.05;
14 v_GROSS:=v_BSAL+v_HRA+v_DA+v_PF;
15 RETURN v_GROSS;
16 END;
17 /

OUTPUT:
=======
SQL> SELECT SF4(7788) FROM DUAL;

SF4(7788)
----------
4050
To view all stored functions in oracle:
================================
SQL> SELECT OBJECT_NAME FROM USER_OBJECTS
2 WHERE OBJECT_TYPE='FUNCTION';

To view the source code of a stored function in oracle:


==============================================
SQL> SELECT TEXT FROM USER_SOURCE WHERE NAME='SF1';

How drop a stored function:


=======================
syntax:
======
DROP FUNCTION <FNAME>;

EX:
DROP FUNCTION SF1;
=====================================================================
TRIGGERS:
=========
- it is a named block which will execute by system automatically.
i) DML triggers
ii) DDL triggers
purpose of triggers:
================
> to raise security alerts.
> to control DML,DDL operations on table / on database.
> to implementing business logical conditions.
> for validating
> for auditing

i) DML triggers:
=============
- when we created a trigger object based on insert,update,delete
commands then we called as "DML trigger"
- these triggers are executed by system automatically when we perform
dml operations on a particular table.

syntax:
=======
create [or replace] trigger <trigger name>
before / after insert (or) update (or) delete on <table name>
[for each row] ------> used in row-level triggers only
begin
<trigger body / statements>;
end;
/

Trigger events:
=============
- there are events of trigger.

i) Before :
=========
- when we created a trigger with "before" event.
first : trigger body (logic) executed
later : DML command will execute

i) After :
=========
- when we created a trigger with "after" event.
first : DML command is executed
later : trigger body(logic) will execute.

NOTE: but both are providing same result.


=====

Levels of trigger:
===============
- we are creating a trigger object at two levels.
i) Row level trigger
ii) Statement level trigger

i) Row level trigger:


================
- in this level a trigger body(logic) is executing for each row wise for
a DML operation.

Ex:
DEMO_TABLE:
===========
SQL> SELECT * FROM TEST;

ENAME SAL
---------- ----------
SMITH 12000
JONES 34000
ADAMS 12000
MILLER 41000

SQL> CREATE OR REPLACE TRIGGER TR1


2 BEFORE UPDATE ON TEST
3 FOR EACH ROW
4 BEGIN
5 DBMS_OUTPUT.PUT_LINE('HELLO');
6 END;
7 /
Trigger created.

TESTING:
SQL> UPDATE TEST SET SAL=23000 WHERE SAL=12000;
HELLO
HELLO
2 rows updated.

ii) Statement level trigger:


======================
- in this level a trigger body is executing only one time for a DML operation.

EX:
SQL> CREATE OR REPLACE TRIGGER TR1
2 AFTER UPDATE ON TEST
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('HELLO');
5 END;
6 /

TESTING:
SQL> UPDATE TEST SET SAL=12000 WHERE SAL=45000;
HELLO
2 rows updated.

Bind variables:
=============
- these are just like normal variables which are used to store values
while inserting,updating and deleting data from a table.
- thses are two types:

i) :NEW :-
=======
- this bind variable is storing new value when we insert.
syntax:
=======
:NEW.<column name>

ii) :OLD:
========
- this bind variable is storing old value when we delete.
syntax:
=======
:OLD.<column name>

NOTE:
=====
- these bind variables are used in row level triggers only.

Ex on to raise a security alert:


==========================
SQL> CREATE OR REPLACE TRIGGER TRINSERT_ALERT
2 AFTER INSERT ON TEST
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Alert:SOME ONE INSERTING A NEW ROW INTO YOUR
TABLE,PLZ CHECK IT !!!');
5 END;
6 /

TESTING:
SQL> INSERT INTO TEST VALUES('JAMES',43000);
Alert: SOME ONE INSERTING A NEW ROW INTO YOUR TABLE,PLZ CHECK IT !!!
1 row created.
- In the above trigger example we raised a alert but not restricted DML
operation.To overcome this problem we should use a statement is called as
"Raise_Application_Error(number,'alert message')".

Raise_Application_Error(number,'alert message'):
=========================================
- it is a pre-defined method which is used to raise an error message
(i.e alert message) when we perform DML operation on a table.
- this method is having two arguments those are,

Number : it returns user defined an error number.


this number must be from -20001 to -20999.
Message : it raise / return a user defined error message
(i.e alert message).
Raising alert with restricted DML operation:
=====================================
SQL> CREATE OR REPLACE TRIGGER TRINSERT_ALERT
2 AFTER INSERT ON TEST
3 BEGIN
4 RAISE_APPLICATION_ERROR(-20453,'Alert:Some one inserting a new row into your
table...plz check it !!!');
5 END;
6 /

TESTING:
SQL> INSERT INTO TEST VALUES('WARD',81000);
ERROR at line 1:
ORA-20453: Alert:Some one inserting a new row into your table...plz check it !!!

EX:
CREATE OR REPLACE TRIGGER TRUPDATE_ALERT
AFTER UPDATE ON TEST
BEGIN
RAISE_APPLICATION_ERROR(-20451,'Alert:Some one updating a row in your table...plz
check it !!!');
END;
/

TESTING:
UPDATE TEST SET SAL=8000 WHERE ENAME='JONES';
ERROR at line 1:
ORA-20451: Alert:Some one updating a row in your table...plz check it !!!

EX:
CREATE OR REPLACE TRIGGER TRDELETE_ALERT
AFTER DELETE ON TEST
BEGIN
RAISE_APPLICATION_ERROR(-20651,'Alert:Some one deleting a row from your table...plz
check it !!!');
END;
/

TESTING:
DELETE FROM TEST WHERE ENAME='MILLER';
ERROR at line 1:
ORA-20651: Alert:Some one deleting a row from your table...plz check it !!!

EX:
CREATE OR REPLACE TRIGGER TRDML_ALERT
AFTER INSERT OR UPDATE OR DELETE ON TEST
BEGIN
RAISE_APPLICATION_ERROR(-20631,'Alert:Some one performing DML operations on your
table...plz check it !!!');
END;
/

TESTING:
SQL> DELETE FROM TEST WHERE ENAME='JAMES';
ERROR at line 1:
ORA-20631: Alert:Some one performing DML operations on your table...plz check it !!!

EX on implementing business logical conditions:


=========================================
create a trigger to restricted all DML operations on a table on every saturday?
SQL> CREATE OR REPLACE TRIGGER TRSATURDAY
2 AFTER INSERT OR UPDATE OR DELETE ON TEST
3 BEGIN
4 IF TO_CHAR(SYSDATE,'DY')='SAT' THEN
5 RAISE_APPLICATION_ERROR(-20631,'WE CANNOT PERFORM DML OPERATIONS ON
TEST TABLE ON EVERY SATURDAY...');
6 END IF;
7 END;
8 /

TESTING:
SQL> INSERT INTO TEST VALUES('SCOTT',55000);----NOT ALLOWED

EX:
create a trigger to restricted all DML operations on saturday,sunday?
SQL> CREATE OR REPLACE TRIGGER TRWEEKEND
2 AFTER INSERT OR UPDATE OR DELETE ON TEST
3 BEGIN
4 IF TO_CHAR(SYSDATE,'DY') IN ('SAT','SUN') THEN
5 RAISE_APPLICATION_ERROR(-20631,'WE CANNOT PERFORM DML OPERATIONS ON
TEST TABLE ON WEEKEND...');
6 END IF;
7 END;
8 /

EX:
create a trigger to restricted all DML operations on a table between 9AM to 5PM?
SQL> CREATE OR REPLACE TRIGGER TRTIME
2 AFTER INSERT OR UPDATE OR DELETE ON TEST
3 BEGIN
4 IF TO_CHAR(SYSDATE,'HH24') BETWEEN 9 AND 16 THEN
5 RAISE_APPLICATION_ERROR(-20754,'INVALID TIME');
6 END IF;
7 END;
8 /

LOGIC:
======
24 hrs FORMAT
=============
9AM(9) = 9:00:00 TO 9:59:59 ------------comes under 9 o clock
5PM(17) = 5:00:00 TO 5:59:59 ---------->upto 6 o clock
4PM(16) = 4:00:00 TO 4:59:59 ---------> upto 5 o clock

EX on validating data:
==================
create a trigger to control insert operation on a table if new salary is less than to 10000?
SQL> CREATE OR REPLACE TRIGGER TRIN
2 BEFORE INSERT ON EMPLOYEE
3 FOR EACH ROW
4 BEGIN
5 IF :NEW.SAL<10000 THEN
6 RAISE_APPLICATION_ERROR(-20783,'NEW SALARY SHOULD NOT BE LESS THAN TO
10000');
7 END IF;
8 END;
9 /

TESTING:
SQL> INSERT INTO EMPLOYEE VALUES(1,'SMITH',9500);----NOT ALLOWED
SQL> INSERT INTO EMPLOYEE VALUES(1,'SMITH',12000);----ALLOWED

EX:
create a trigger to control delete operation on a table if user try to delete the
employee "SMITH" details?
SQL> CREATE OR REPLACE TRIGGER TRDEL
2 BEFORE DELETE ON EMPLOYEE
3 FOR EACH ROW
4 BEGIN
5 IF :OLD.ENAME='SMITH' THEN
6 RAISE_APPLICATION_ERROR(-20643,'NOT ALLOWED');
7 END IF;
8 END;
9 /

TESTING:
SQL> DELETE FROM EMPLOYEE WHERE ENAME='SMITH';----NOT ALLOWED
SQL> DELETE FROM EMPLOYEE WHERE ENAME='ALLEN';----ALLOWED

EX:
create a trigger to control update operation on a table if new salary is less than to
old salary?
SQL> CREATE OR REPLACE TRIGGER TRUP
2 BEFORE UPDATE ON EMPLOYEE
3 FOR EACH ROW
4 BEGIN
5 IF :NEW.SAL<:OLD.SAL THEN
6 RAISE_APPLICATION_ERROR(-20743,'NEW SALARY SHOULD NOT BE LESS THAN TO
OLD SALARY');
7 END IF;
8 END;
9 /

TESTING:
========
SQL> UPDATE EMPLOYEE SET SAL=9000 WHERE SAL=10000;----NOT ALLOWED
SQL> UPDATE EMPLOYEE SET SAL=12000 WHERE SAL=10000;----ALLOWED

Auditing:
========
- When we perform dml operations on a particular table those operational
informations are stored in another table is called as "Auditing Tables".

Ex:
SQL> CREATE TABLE EMP_MAIN(EID INT,ENAME VARCHAR2(10),SAL NUMBER(10));
SQL> CREATE TABLE EMP_AUDIT(EID INT,AUDIT_INFOR VARCHAR2(100));

SQL> CREATE OR REPLACE TRIGGER TRAUDIT


2 AFTER INSERT ON EMP_MAIN
3 FOR EACH ROW
4 BEGIN
5 INSERT INTO EMP_AUDIT VALUES(:NEW.EID,'SOME ONE INSERTED A NEW ROW
INTO EMP_MAIN TABLE ON: ' ||' '||TO_CHAR(SYSDATE,'DD-MON-YYYY HH:MI:SS PM'));
6 END;
7 /
TESTING:
SQL> INSERT INTO EMP_MAIN VALUES(1021,'SMITH',23000);
SQL> SELECT * FROM EMP_MAIN;

EID ENAME SAL


---------- ---------- ----------
1021 SMITH 23000

SQL> SELECT * FROM EMP_AUDIT;

EID AUDIT_INFOR
------------ ------------------------------------------------------------------------------------------------------------
--------------------------------
1021 SOME ONE INSERTED A NEW ROW INTO EMP_MAIN TABLE ON: 25-NOV-
2023 11:39:43 AM

EX:
CREATE OR REPLACE TRIGGER TRAUDIT
AFTER UPDATE ON EMP_MAIN
FOR EACH ROW
BEGIN
INSERT INTO EMP_AUDIT VALUES(:OLD.EID,'SOME ONE UPDATED A ROW IN
EMP_MAIN TABLE ON: ' ||' '||TO_CHAR(SYSDATE,'DD-MON-YYYY HH:MI:SS PM'));
END;
/

EX:
CREATE OR REPLACE TRIGGER TRAUDIT
AFTER DELETE ON EMP_MAIN
FOR EACH ROW
BEGIN
INSERT INTO EMP_AUDIT VALUES(:OLD.EID,'SOME ONE DELETED A ROW FROM
EMP_MAIN TABLE ON: ' ||' '||TO_CHAR(SYSDATE,'DD-MON-YYYY HH:MI:SS PM'));
END;
/
========================================================================
==============================
2) DDL TRIGGERS:
================
- when we created a trigger object based on DDL operations
(create,alter,rename,drop) are called as "DDL triggers".
- these trigger are executed by system automatically when user perform
ddl operations on a specific database.so that DDL triggers are also called as
"Database Triggers".
- these triggers are handling by "DBA" only.

syntax:
=======
create [or replace] trigger <trigger name>
before / after create or alter or rename or drop on <username / database name>.schema
[for each row]
begin
<trigger body / statements>;
end;
/

Ex:
create a trigger to restricted CREATE operation on MYDB11AM database?
SQL> CREATE OR REPLACE TRIGGER TRCREATE
2 AFTER CREATE ON MYDB11AM.SCHEMA
3 BEGIN
4 RAISE_APPLICATION_ERROR(-20643,'WE CANNOT PERFORM CREATE OPERATION
ON MYDB11AM DATABASE');
5 END;
6 /

TESTING:
SQL> CREATE TABLE TEST300(SNO INT);-----NOT ALLOWED
sudhakarnareshit@gmail.com

You might also like