Oracle 2 PMM
Oracle 2 PMM
Admin:
Mobile: 91541 56192 (Only Whatsapp)
Notes link:
https://bit.ly/batch2pm
Oracle2PM Page 1
ORACLE
Wednesday, October 12, 2022 2:24 PM
Data
Information
Database
DBMS
RDBMS
Metadata
Data:
1234 nareshit
Laptop
Ramu 4
Dell
B.Tech 2 class rooms
100000
67.8 200
Black
Data Information
25
sid sname marks
Ramu Data 25 Ramu 500
500 Processing
Micro processor
RAM
Mother Board Connecting Computer
Keyboard
Mouse
Monitor
Engine
Tyres
Connecting Bike
Break
body
Data:
• Data is a raw collection of facts about the
people, places, things ..etc
• It is unprocessed one.
• It is not in meaningful form
• we cannot make the decisions.
Types of Data:
2 Types:
• Structured Data
• Unstructured Data
Structured Data:
• If data is in the form of letters, digits and
symbols then it is called "Structured Data".
Ex:
1234
Kiran
H.NO.1-2-123/A/B
Unstructured Data:
• if data is in the form of images, audios,
videos, documents then it is called
Oracle2PM Page 2
videos, documents then it is called
"Unstructured Data".
Information:
• If data is arranged in meaningful form then it
is called "Information".
• It is processed one.
• It is in meaningful form.
• Using it, we can make the decisions.
Database:
• Database means,
complete details of an organization stored
in computer in meaningful format.
Example:
College DB
STUDENT
sid sname scity mobile
1001 Ravi Hyd …
MARKS
sid M1 M2 M3
1001 70 60 80
DBMS:
• DataBase management System/Software.
• It is a software that is used to create & maintain the
database.
RDBMS:
• Relational DataBase Management System/Software.
• Relation => Table
• RDBMS is a software that is used to create & maintain
the database in the form of tables.
Ex:
ORACLE, SQL SERVER, My SQL, Postgre SQL, DB2
Oracle2PM Page 3
CUSTOMER => Table / Relation / Entity
Metadata:
• Metadata is the data about the data
• it describes about the data.
Examples:
field names => sid, sname, marks
table name => Marks_details
data types => Number, Varchar2, Date
field sizes => Number(4), Varchar2(10)
Marks_details
sid sname Marks
25 Ramu 500
ORACLE
Oracle2PM Page 4
ORACLE DB SERVER
SQL Database
PL/SQL Tables
rows & columns
STUDENT MARKS
DDL CREATE
Data Definition Language ALTER
TRUNCATE
RENAME
DML INSERT
Data Manipulation Language UPDATE
DELETE
Oracle2PM Page 5
DELETE
It deals with data
manipulations INSERT ALL [Oracle 9i]
MERGE [Oracle 9i]
TCL COMMIT
Transaction Control language ROLLBACK
SAVEPOINT
It deals with transactions
DDL commands:
CREATE:
CREATE command is used to create the database objects like tables, Database Objects:
views, indexes …etc. Tables
< > Any Views
Syntax to create a table: [ ] Optional Indexes
Sequences
CREATE TABLE <table_name> Synonyms
( Materialized views
<field_name> <data_type> [constraint <con_name> <con_type>, procedures
<field_name> <data_type> constraint <con_name> <con_type>, functions
. packages
.] triggers
);
Field Definition:
<field_name> <data_type> [constraint <con_name> <con_type>]
Data Types in SQL:
CREATE TABLE customer
• Data Type tells which type of data that (
column has to accept. cid NUMBER(4)
DOB DATE
ORACLE SQL provides following data types: );
cid DOB
Number Related Number(p)
Int 1234 25-DEC-1990
Integer
Ex: 56 78 1234 5678 45678
567A$
Number(p,s)
Float
Binary_Float
Binary_Double
Ex: 56.78 123.45678
nChar(n)
nVarchar2(n)
nCLOB
n => national
Oracle2PM Page 6
Number related Data Types:
Number(p):
• It is used to hold integers.
• p => precision => max no of digits
• p => range => 1 TO 38
• Number(2) => -99 TO 99
• Number(38) => -9999..999 38digits TO 999..99 38dgits
Aadhar_Num NUMBER(12)
Creditcard_num NUMBER(16)
Mobile_num NUMBER(10)
Number(p,s):
• It is used to floating point data.
• p => precision => max no of digits
• s => scale => no of decimal places
• p => range => 1 to 38
• s => range => -84 to 127
100000.00
100.00
Oracle2PM Page 7
5.0
ename PAN_CARD_NUM
----------- ------------------------
Ravi ABCDE12345
Kiran
sai
Amar
HNO
----------
1-2-123/A/B
Demo
f1 Char(10) f2 Varchar2(10)
Ravi6spaces Ravi
Sai7spaces Sai
Ramesh4spaces Ramesh
Char(n):
• Used to hold string values. string is a group of chars.
• n => max no of chars
• It is Fixed Length Data Type
• max size is: 2000 bytes
• Default size: 1
Varchar2(n):
• Used to hold string values.
• n => max no of chars
• It is Variable Length Data Type
• max size is: 4000 bytes
• Default size: No default size. WE must specify the size.
Why varchar2?
Oracle2PM Page 8
Varchar => ORACLE 2 TO 6
LONG:
• It is used to hold string values.
• It is used to hold large amounts of chars.
• Max size: 2GB
• It has some restrictions:
○ In one table we can create only one column as
LONG type.
○ we cannot use built-in functions on LONG type
CLOB:
• CLOB stands for Character Large Object.
• It is used to hold string values.
• It is mainly used to hold large amounts of chars.
Ex:
product_features CLOB
-----------------------------
Experience_Summary CLOB
----------------------------------
Feedback CLOB
------------------
Character Related
1000
sid Number(4)
sname Varchar2(10)
gender Char
marks Number(4)
avrg Number(5,2)
Date:
• It is used to hold date values.
• It can hold time values also.
• It can hold date, month, year, hours, minutes and
seconds.
• Default oracle date format is: DD-MON-RR
• Default time value is: 12.00.00 AM [midnight time]
• It is Fixed length data type.
• size is: 7 bytes
• To insert a date value, use to_date() function.
to_date() function converts string to date.
Oracle2PM Page 9
to_date() function converts string to date.
• It cannot hold fractional seconds.
Example:
Date_of_Joining
------------------------
23-OCT-2018
17-SEP-2020
Table created.
1 row created.
Timestamp:
• It is used to hold date & time values.
• It is introduced in Oracle 9i version.
• It can hold date, month, year, hours, minutes,
seconds & fractional seconds.
• It is extension of Date data type.
• It is fixed length data type.
• size is: 11 bytes
Date Timestamp
7 bytes 11 bytes
Binary Related:
Binary related data types are used to deal with
unstructured data [audios, videos, documents].
BFILE:
• BFILE stands for Binary File Large Object type.
• max size: 4GB
• It is used to maintain multimedia objects like
audios, videos, animations, documents …etc.
BFILE is a pointer to multimedia object.
Oracle2PM Page 10
• BFILE is a pointer to multimedia object.
• It is not secured one.
employee
empno ename ephoto BFILE
D: drive
1234 Ravi D:\emps\ravi.jpg
emps
ravi.jpg
Database
BLOB:
• BLOB stands for Binary Large Object type.
• max size: 4GB
• It is used to maintain multimedia objects like
audios, videos, animations, documents …etc.
• it is used to main multimedia objects inside of
database.
• It is secured one.
Ex:
employee d: drive
ellison.jpg
empno ename ephoto BLOB
1001 ellison 17623AEF23768ABCD
Database
Opening SQLPLUS:
Creating User:
Log in as DBA:
username: system
password: nareshit
Tablespace:
File in which oracle database will
be stored.
Oracle2PM Page 11
user name: sys as sysdba
password:
[don't enter any password]
username: system
password: nareshit
STUDENT
sid sname m1
1001 Ramu 67 100
1002 Vijay 56
sid Number(4)
sname Varchar2(10)
m1 Number(3)
Output:
Table created.
1001 Ramu 67
Output:
1 row created.
Output:
1 row created.
Output:
enter value for sid:1003
enter value for sname:ravi
enter value for m1: 66
1 row created.
/
enter value for sid:1005
enter value for sname:..
enter value for m1: ..
Oracle2PM Page 12
enter value for m1: ..
COMMIT;
DESC / DESCRIBE:
it is used to see table structure
user_tables:
It maintains all tables information
Output:
TABLE_NAME
--------------------------------------------------------------------------------
T1
STUDENT
sid sname m1
2001 Kiran
Example-2:
EMPLOYEE
Oracle2PM Page 13
INSERT INTO employee
VALUES(5001,'AAA','M',6000,'23-DEC-2019');
Primary Key:
Example:
EMPLOYEE
CREATE TABLE t1
(
f1 NUMBER(4) Primary Key
);
Not Null:
Oracle2PM Page 14
Not Null:
• It does not accept NULL values.
• It accepts DUPLICATE values.
• It demands for the value.
EXAMPLE:
CUSTOMER
NOT NULL
cid cname ccity
1001 Ramu Hyd
1002 Sai Mumbai
1003 Hyd
1004 Ramu Pune
CREATE TABLE t2
(
f1 VARCHAR2(10) NOT NULL
);
UNIQUE:
• It does not accept duplicate values.
• It accepts null values. gmail account
Example:
CUSTOMER [email protected]
[email protected]
cid cname mail_id
1001 ravi [email protected]
1002 kiran
1003 sai [email protected]
Ex:
CREATE TABLE t3
(
f1 NUMBER(4) UNIQUE
);
password
CREATE TABLE t4
---------------
(
abcdefghij
f1 NUMBER(3) CHECK(f1>=0 AND f1<=100)
ravi1234
);
ravi
Oracle2PM Page 15
INSERT INTO t4 VALUES(123);
--ERROR: check constraint violated
Default:
Example:
STUDENT
NOTE:
If we don't pass the value, it takes the default value
If we pass the value, it takes that value
15000.00
CREATE TABLE t5
(
f1 NUMBER(4),
f2 NUMBER(7,2) DEFAULT 15000
);
Ex:
COURSE STUDENT
Example:
CREATE TABLE t6
(
f1 NUMBER(4) PRIMARY KEY
);
CREATE TABLE t7
(
f2 NUMBER(4) REFERENCES t6(f1)
);
Oracle2PM Page 16
INSERT INTO t7 VALUES(1234);
ERROR: integrity constraint violated
Examples On Constraints:
100000.00
EMPLOYEE1
Output:
Table created.
Example-2:
users_list
uname pwd
raju kumar1234
vijay vijay1
Oracle2PM Page 17
Example:
STUDENT2
NOTE:
In default column,
If we don't pass the value, it takes default value.
If we pass the value, it takes that value
Example:
COURSE5 STUDENT5
COURSE5
Oracle2PM Page 18
);
Assignment:
DEPT EMP
Naming Constraints:
STUDENT6
sid sname M1
1001 Ramu 78
Oracle2PM Page 19
INSERT INTO student6 VALUES(1001,'A',78);
user_tables:
It maintains all tables information which are created by the
user.
DESC user_tables;
user_constraints:
It maintains all constraints information which are created by
the user
DESC user_constraints;
DDL commands:
CREATE
ALTER
ALTER:
2 columns
• ALTER => change
• Using ALTER command we can EMPLOYEE
change the structure of table.
• Using ALTER command we can: empno ename gender sal DOB
○ add the columns
○ rename the columns
○ drop the columns
○ modify the field sizes
○ modify the data types
○ add the constraints
○ rename the constraints
○ disable the constraints
○ enable the constraints
○ drop the constraints
Syntax:
Example:
STUDENT
sid sname
Output:
Table created.
DESC student;
Oracle2PM Page 20
Output:
sid
sname
Output:
Table Altered.
sname
------------
arun
sai
vijay
ramesh
NOTE:
To modify the data type column must be empty.
STUDENT
sid NUMBER(4)
HYD_1001
MUM_5001
PUN_4005
Oracle2PM Page 21
Disabling Constraint [disable cc1]:
DDL:
DML
INSERT used to insert the records
DDL Commands:
CREATE
ALTER
DROP
FLASHBACK [oracle 10g]
PURGE [oracle 10g]
TRUNCATE
RENAME
DROP:
Syntax:
FLASHBACK:
Syntax:
Ex:
FLASHBACK TABLE student
Oracle2PM Page 22
FLASHBACK TABLE student
TO BEFORE DROP;
PURGE:
• is used to delete the table from recyclebin.
Syntax:
Ex:
PURGE TABLE student;
Emptying recyclebin:
PURGE recyclebin;
TO see recyclebin:
SHOW recyclebin;
Example:
TRUNCATE:
• used to delete complete information from the table
with auto commit.
it deletes table data. It does not delete table
Oracle2PM Page 23
• it deletes table data. It does not delete table
structure
Syntax:
Ex:
TRUNCATE TABLE student;
STUDENT
sid sname
1 A
2 B
3 C
RENAME:
Syntax:
Ex:
RENAME student TO std;
DRL / DQL:
• DRL => Data Retrieval Language
• DQL => Data Query Language
• Retrieval => opening existing data
○ Ex: checking balance, online shopping
• Query => is a request that is sent to DB
server.
• DRL deals with data retrievals.
• SQL provides only one DRL command i.e:
○ SELECT
Syntax:
ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES
Oracle2PM Page 24
Using SELECT command we can
retrieve:
• Limited Columns
• All Columns
• Limited Rows
• All Rows
emp
empno ename job sal
1001 A clerk 3000
1002 B salesman 1500
1003 C manager 5000
1004 D clerk 2000
SELECT ename,sal
FROM emp
WHERE sal>=2500;
FROM emp:
entire table will be selected
WHERE sal>=2500:
SELECT ename,sal:
Oracle2PM Page 25
Retrieving all columns & all rows:
* All Columns
* = empno,ename,job,mgr,hiredate,sal,comm,deptno
Operators in SQL:
OPERATOR:
• Operator is a symbol that is used to perform operations like
arithmetic or logical operations.
Arithmetic + - * /
SET UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||
SELECT 20+40 FROM dual; in c/java => int/int = int => 5/2 = 2
TOTAL
---------
60
total
----------
60
ToTal
----------
60
TOTAL
---------
60
TOTAL
-----------
60
ERROR: space
Oracle2PM Page 26
ERROR: space
total marks
-------------
60
Column Alias:
• Alias name => alternative name (or) another name
• "AS" keyword is used to give column alias. Using
this keyword is optional.
• Column alias is temporary. Its scope is limited to
the query only. It cannot be used in another query.
• To maintain the case or to give alias name in
multiple words specify alias name in double quotes.
DUAL:
• DUAL is a system table / built-in table /
predefined table.
• In "sys" schema [user] DUAL table is created.
• There are 1 row & 1 column in DUAL table.
DUAL
DUMMY
X
20+40
------------
60
SELECT empno,ename,sal,
sal*0.1 AS TA,
sal*0.2 AS HRA,
sal+sal*0.1+sal*0.2 AS GROSS
FROM emp;
Example:
STUDENT
sid sname m1 m2 m3
1001 A 50 80 70
1002 B 50 30 90
Oracle2PM Page 27
1002 B 50 30 90
COMMIT;
SELECT sid,sname,m1,m2,m3,
m1+m2+m3 AS TOTAL,
(m1+m2+m3)/3 AS AVRG
FROM student;
SELECT empno,ename,sal
FROM emp
WHERE sal>=1600;
SELECT empno,ename,sal
FROM emp
WHERE sal<1250;
1 2020 calendar
2
3 1-jan-2020
4 2-jan-2020
5 3-jan-2020
. 4-jan-2020
. .
10 .
31-dec-2020
1-jan-2021
2-jan-2021
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate>'31-DEC-1981';
Oracle2PM Page 28
Display the emp records who joined before 1981:
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate<'1-jan-1981';
SELECT empno,ename,job
FROM emp
WHERE job='manager';
no rows selected
NOTE:
SQL is not case sensitive language. But,
string comparison is case sensitive.
Ex:
'MANAGER' = 'MANAGER' TRUE
'MANAGER' = 'manager' FALSE
SELECT empno,ename,job
FROM emp
WHERE job='MANAGER';
SELECT empno,ename,job
FROM emp
WHERE job!='MANAGER';
(or)
SELECT empno,ename,job
FROM emp
WHERE job<>'MANAGER';
(or)
SELECT empno,ename,job
FROM emp
WHERE job^='MANAGER';
SELECT empno,ename,deptno
FROM emp
WHERE deptno=20;
SELECT empno,ename,deptno
FROM emp
WHERE deptno!=20;
Logical Operators:
TRUTH TABLE:
Oracle2PM Page 29
AND all conditions should be satisfied
OR at least 1 condition should be satisfied
NOTE:
AND, OR operators are used to separate
multiple conditions
max marks: 100
SID SNAME M1 M2 M3
- --------- ---------- ---------- ---------- ----------
1001 A 50 80 70
1002 B 50 30 90
SELECT empno,ename,job,sal
FROM emp
WHERE job='MANAGER' OR job='CLERK';
job
--------
MANAGER
ANALYST
CLERK
SELECT empno,ename,sal
FROM emp
WHERE empno=7369 OR empno=7521 OR
empno=7900;
SELECT empno,ename,deptno
FROM emp
WHERE deptno=10 OR deptno=30;
SELECT emnpo,ename,sal
FROM emp
WHERE sal>=1600 AND sal<=3000;
SELECT empno,ename,job,sal
FROM emp
WHERE job='MANAGER' AND sal>2500;
SELECT empno,ename,job,hiredate
FROM emp
WHERE job='MANAGER' AND hiredate>'30-APR-1981';
Oracle2PM Page 30
Display all emps records except
managers:
condn NOT(Condn)
job
--------
CLERK
MANAGER
ANALYST
MANAGER
Arithmetic + - * /
Relational > >= < <= = !=
Logical AND OR NOT
Special Operators:
• Special operators are also comparison
operators.
IN:
• used to compare column value with a list of
values.
• It avoids of writing multi equality conditions
using OR.
Syntax:
<column> IN(<value_list>
Ex:
empno IN(7369,7521,7900)
empno
---------
7369
7499
7521
7498
7900
SELECT empno,ename,job,sal
FROM emp
WHERE job IN('MANAGER','CLERK');
(or)
SELECT empno,ename,job,sal
FROM emp
WHERE job='MANAGER' OR job='CLERK';
SELECT empno,ename,job,sal
FROM emp
WHERE empno IN(7369,7521,7900);
SELECT empno,ename,job
Oracle2PM Page 31
SELECT empno,ename,job
FROM emp
WHERE job NOT IN('MANAGER','CLERK');
job
--------
ANALYST
MANAGER
CLERK
SALESMAN
SELECT empno,ename,deptno
FROM emp
WHERE deptno IN(10,30);
SELECT empno,ename,deptno
FROM emp
WHERE deptno NOT IN(30);
(or)
SELECT empno,ename,deptno
FROM emp
WHERE deptno!=30;
(or)
SELECT empno,ename,deptno
FROM emp
WHERE NOT(deptno=30);
BETWEEN AND:
• used to compare a column value with a range
values.
Syntax:
Examples:
SELECT empno,ename,sal
FROM emp
WHERE sal BETWEEN 1600 AND 3000;
(or)
SELECT empno,ename,sal
FROM emp
WHERE sal>=1600 AND sal<=3000;
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-jan-1981'
AND '31-dec-1981';
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-jan-1982'
AND '31-dec-1983';
SELECT empno,ename,sal
FROM emp
WHERE sal BETWEEN 3000 AND 1600;
Output:
no rows selected
Oracle2PM Page 32
no rows selected
SELECT empno,ename,sal
FROM emp
WHERE sal NOT BETWEEN 1600 AND 3000;
(or)
SELECT empno,ename,sal
FROM emp
WHERE sal<1600 OR sal>3000;
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate NOT BETWEEN '1-jan-1981' AND
'31-dec-1981';
In Windows OS,
LIKE:
• is used to compare column value with text pattern.
• SQL provides 2 wildcard chars. They are:
_ replaces 1 char
% replaces 0 or any no of chars
Syntax:
SELECT ename,sal
FROM emp
WHERE ename LIKE 's%';
emp
ename sal
ALLEN
SMITH
WARD
SCOTT
BLAKE
SYMONDS
S
Oracle2PM Page 33
Display the emp records whose names
are ended with 'S':
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '_A%';
ename
-----------
SELECT empno,ename,sal
ALLEN
FROM emp
BLAKE
WHERE ename LIKE '%A%';
JAMES
SMITH
MILLER
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE 'M%';
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%RD';
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE 'S%S';
ename
---------
SMITH
ALLEN
SYMONDS
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '____';
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '__A%';
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate LIKE '%82';
Oracle2PM Page 34
December month:
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate LIKE '%DEC%';
hiredate
------------ SELECT empno,ename,hiredate
17-AUG-1981 FROM emp
07-JAN-1982 WHERE hiredate LIKE '0%';
25-DEC-1983
09-MAY-1981
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%\%%' ESCAPE '\';
SELECT empno,ename,sal
FROM emp
WHERE ename NOT LIKE 'S%';
NULL:
• NULL means empty / blank. STUDENT
• When we don't know the value or
when we are unable to insert the sid sname maths
value we insert NULL value.
1001 A 70
• If NULL is participated operation
then result will be null. 1002 B 0
○ Ex: 1003 C
▪ 100+null = null D 89
▪ 20+30+10+null = null
▪ 10*20-null = null
• For null comparison we cannot
use = [equals to operator].
• For null comparison always use
"IS NULL".
IS NULL:
• It is used to compare column value
with null value.
Syntax:
<column> IS null
Example:
Oracle2PM Page 35
Display the emp records whose comm is 500:
SELECT empno,ename,sal,comm
FROM emp
WHERE comm=500;
SELECT empno,ename,sal,comm
FROM emp
WHERE comm=NULL;
no rows selected
NOTE:
= operator cannot be used for null comparison
SELECT empno,ename,sal,comm
FROM emp
WHERE comm IS null;
SELECT empno,ename,sal,comm
FROM emp
WHERE comm IS not null;
Concatenation Operator:
• Symbol: ||
• Concatenation => combining
• It is used to combine 2 strings.
Syntax:
<string1> || <string2>
Ex:
SELECT 'raj' || 'kumar' FROM dual;
rajkumar
raj kumar
PLAYER
pid fname lname
1001 Virat Kohli
Virat Kohli
1002 Rohit Sharma
Rohit Sharma
pid pname
----- ----------
1001 Virat Kohli
1002 Rohit Sharma
Arithmetic + - * /
Ex: sal*12 sal*10/100
Relational / < > >= <= = != / <> / ^=
Comparison Ex: sal=3000 sal>3000
job='MANAGER'
Logical AND OR NOT
Ex:
job='MANAGER' OR job='CLERK'
sal>=1600 AND sal<=3000
NOT(job='MANAGER')
Special / IN
Comparison Ex: empno IN(7369, 7521, 7900)
Oracle2PM Page 36
Comparison Ex: empno IN(7369, 7521, 7900)
BETWEEN AND
Ex: sal BETWEEN 1600 AND 3000
LIKE
Ex: ename LIKE 'S%'
ename LIKE '_A%'
IS NULL
Ex: comm IS null
Concatenation ||
'sai' || 'teja'
SQL:
DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL SELECT
TCL
DML
DCl
TCL:
• TCL stands for Transaction Control Language.
• It deals with transactions.
• Transaction => a series of actions
• Ex: Withdraw Deposit Check Balance
purchasing a product
DB Server
ATM => Withdraw =>10000
Withdraw Transaction
NOTE:
• A transaction must be successfully
completed or aborted [cancelled]
• If transaction is successful, to save it use
COMMIT
• If transaction is not successful, to cancel
it use ROLLBACK
ORACLE DB SERVER
CLIENT
INSTANCE DB
INSERT
INSERT emp
dept
Oracle2PM Page 37
RAM Hard DISK
ORACLE SERVER:
COMMIT [SAVE]:
• This command is used to save the
transactions.
• When COMMIT command is executed all
changes of ORACLE INSTANCE [RAM]
will be applied to ORACLE DB [HARD DISK]
• It makes the changes permanent.
Syntax:
COMMIT;
Ex:
COMMIT;
Example:
CREATE t2
CREATE t1
CREATE TABLE t1
(
f1 NUMBER(4)
);
SAVEPOINT:
used to set margin for ROLLBACK.
Example:
CREATE TABLE t2 CREATE TABLE t3
INSERT SAVEPOINT p1
INSERT INSERT
INSERT INSERT
INSERT SAVEPOINT p2
INSERT INSERT
INSERT INSERT
ROLLBACK => 6 actions cancelled SAVEPOINT p3
INSERT
INSERT
ROLLBACK TO p1; --6 actions cancelled
Oracle2PM Page 38
ROLLBACK TO p1; --6 actions cancelled
ROLLBACK TO p2; --4 actions cancelled
ROLLBACK TO p3; -- 2 actions cancelled
DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL SELECT
TCL COMMIT [save]
ROLLBACK [ undo all]
SAVEPOINT
DML INSERT
UPDATE
DELETE
INSERT ALL
MERGE
DML:
• Data Manipulation Language.
• It deals with data manipulations.
• Manipulation => INSERT / UPDATE / DELETE STUDENT joined => INSERT
○ Ex: STUDENT mobilenum => UPDATE
▪ customer opening new account => INSERT STUDENT left => DELETE
▪ customer depositing amount => UPDATE
▪ customer closing account => DELETE
NOTE:
• All DDL commands are auto-committed.
• When DDL command is executed, after
executing it, COMMIT will be executed.
Example-1:
Example:
CREATE t5
INSERT
INSERT
CREATE t6 => COMMIT;
INSERT
INSERT
ROLLBACK;
UPDATE:
• is used to modify the data.
• Using UPDATE command we can update: ALTER => modify table structure
○ single field value of single record
○ multiple field values of single record UPDATE => modify data
○ a group of records
○ all records
using parameters
Oracle2PM Page 39
○ using parameters
UPDATE emp
SET job='MANAGER', sal=6000
WHERE empno=7369;
UPDATE emp
SET sal=sal+2000
WHERE job='SALESMAN';
UPDATE emp
SET sal=sal+1000;
UPDATE emp
SET sal=sal+&amount
WHERE empno=&empno;
/
enter value for amount: 1500
enter value for empno: 7499
/
enter value for amount: 3000
enter value for empno: 7521
UPDATE emp
SET sal=sal+sal*0.2
WHERE job IN('MANAGER','CLERK');
Oracle2PM Page 40
WHERE job IN('MANAGER','CLERK');
UPDATE emp
SET sal=sal+sal*0.1
WHERE trunc((sysdate-hiredate)/365)>40;
UPDATE emp
SET sal=sal+sal*0.2, comm=comm+comm*0.1
WHERE comm IS not null;
UPDATE emp
SET deptno=20
WHERE deptno=10;
Example:
EMPLOYEE
empno ename sal TA HRA GROSS
1001 A 5000
1002 B 8000
10% on sal as TA
20% on sal as HRA
GROSS = sal+TA+HRA
COMMIT;
UPDATE employee
SET TA=sal*0.1, HRA=sal*0.2,
GROSS=sal+sal*0.1+sal*0.2;
DELETE:
• used to delete the records from
the table.
• using DELETE command we can
delete:
○ single record
○ a group of records
○ all records
Oracle2PM Page 41
Delete an emp record whose empno is 7900:
Oracle2PM Page 42
TRUNCATE DELETE
TRUNCATE = TRUNCATE+COMMIT
ORCLE SERVER
• We cannot delete single record • We can delete a single record or
or a group of records using it. a group of records or all records
Just we can delete all records ORACLE SERVER
with auto commit. DB
TABLESPACE
segment
block
• WHERE clause cannot be used • WHERE clause can be used extent
extent block [oracle page]
segment records
• It is faster • It is slower TS
DB
BLOCK
10 records
BLOCK
10 records
SQL
DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
Transaction
RENAME
DRL SELECT withdraw
TCL COMMIT COMMIT
ROLLBACK ROLLBACK
SAVEPOINT
DML INSERT
UPDATE
DELETE
INSERT ALL c##userA
ALL emp
DCL GRANT
REVOKE c##userB
emp
c##userC
emp
DCL:
• DCL stands for Data Control Language. c##userA
• It deals with data accessibility. emp
• It provides security for the data.
c##userB
DCL provides 2 commands. They are:
• GRANT
• REVOKE
Oracle2PM Page 43
B.Tech - I yr
SECTION-A SECTION-B
1 1
GRANT: 2 2
It can be used to give permissions on 3 3
DB objects [tables, views] to other users. 4 4
. .
Syntax: . .
100 100
GRANT <priviliges_list>
ON <DB_Object>
TO <users_list>;
Ex:
c##oracle2pm
emp
c##userA
Ex:
Giving select permission to c##userA:
GRANT select
ON emp
TO c##userA;
GRANT all
ON emp
TO c##userA;
GRANT select
ON emp
TO c##userA, c##userB, c##userC;
GRANT select
ON emp
TO public;
c##oracle2pm
emp
c##userA
c##userB
c##oracle2pm:
GRANT all
ON emp
TO c##userA
WITH GRANT OPTION;
Oracle2PM Page 44
REVOKE:
• used to cancel the permissions from
other users on DB objects.
Syntax:
REVOKE privileges_list
ON <DB_Object_name>
FROM <user_list>;
Ex:
c##userA
create table t1
GRANT select
ON t1
TO c##userB;
REVOKE select
ON t1
FROM c##userB;
Creating user:
NOTE:
username is not case sensitive
password is case sensitive
Log in as DBA:
username: system
password: nareshit
conn c##userA/userA
ERROR: user has no permission for log in
Log in as DBA:
conn system/nareshit
Oracle2PM Page 45
CREATE USER c##userB
IDENTIFIED BY userb
DEFAULT TABLESPACE users
QUOTA unlimited ON users; OPEN 2 sqlplus windows
Window + Right Arrow => to arrange windows side by side
GRANT connect, resource TO c##userB; in one window log in as userA
in another window log in as userB
Oracle2PM Page 46
c##userA c##userB
CREATE TABLE t1
(
f1 NUMBER(4),
f2 VARCHAR2(10)
);
GRANT select
ON t1
TO c##userB;
GRANT all
ON t1
TO c##userB;
REVOKE all
ON t1
FROM c##userB;
Oracle2PM Page 47
c##userA => GRANTOR
t1
GRANT select
user_tab_privs_made:
• it is a system table.
• it maintains permissions list given by the
user.
c##userA:
DESC user_tab_privs_made;
user_tab_privs_recd:
• it is system table.
• it maintains permissions list received by
the user.
c##userB:
DESC user_tab_privs_recd;
SQL:
• query language => used to write the queries
• Query => is a request i.e sent to the server
5 sub languages:
DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL SELECT
DCL GRANT
REVOKE
DML INSERT
UPDATE
DELETE
Copying Table:
Creating a new table from existing
table is called "Copying table"
Oracle2PM Page 48
Syntax:
cases:
• copying a table from existing table with
all rows & columns
• copying a table from existing table with
specific rows & specific columns
• copying a table from existing table with
specific columns without records
[copying table structure].
EMP EMP1
8 columns 8 columns
14 rows 14 rows
t1 => Table
f1 f2
1 A
2 B
Ex:
1=2
'A'='B'
Oracle2PM Page 49
'A'='B'
100=200
500=800
Copying Records:
inserting records from the existing table is
called "Copying records".
INSERT ALL:
• Introduced in Oracle 9i version.
• Used to insert multiple records in multiple
tables or single table.
EMP1
EMP empno ename job sal
8 columns
14 rows
EMP2
empno ename job sal
EMP3
empno ename job sal
INSERT ALL:
• Introduced in Oracle 9i version.
• Used to insert multiple records in multiple
tables or single table.
• Normally, it is used to copy one table
records to multiple tables.
• It avoids of writing multiple INSERT queries.
Oracle2PM Page 50
INSERT ALL can be used in 2 ways:
Syntax:
INSERT ALL
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
INTO <table ame>[(<col_list>)] VALUES(<value_list>)
.
.
<SELECT query>;
INSERT
T1
INTO t1
VALUES(1,'A'); F1 F2
1 A
EMP1
EMP empno enmae job sal
8 columns
14 rows
EMP2
empno enmae job sal
EMP3
empno enmae job sal
INSERT ALL
INTO emp1 VALUES(empno,ename,job,sal)
INTO emp2 VALUES(empno,ename,job,sal) 10
INTO emp3 VALUES(empno,ename,job,sal) 4
SELECT empno,ename,job,sal FROM emp;
42 rows created.
Syntax:
Oracle2PM Page 51
Conditional INSERT ALL:
Syntax:
INSERT ALL
WHEN <condition-1> THEN
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
WHEN <condition-2> THEN
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
WHEN <condition-3> THEN
INTO <table ame>[(<col_list>)] VALUES(<value_list>)
.
.
[ELSE
INTO <table ame>[(<col_list>)] VALUES(<value_list>)]
<SELECT query>;
INSERT ALL
WHEN job='MANAGER' THEN
INTO emp_manager VALUES(empno,ename,job,sal)
WHEN job='CLERK' THEN
INTO emp_clerk VALUES(empno,ename,job,sal)
ELSE
INTO emp_others VALUES(empno,ename,job,sal)
SELECT empno,ename,job,sal FROM emp;
Oracle2PM Page 52
10
10 dept20
20 empno ename deptno
20
30
dept_others
40
empno ename deptno
Assignment:
emp1980
..1980
..1980
emp1981
..1981
empno ename hiredate
..1981
..1982
..1983 emp_others
empno ename hiredate
T1
F1 NUMBER(4) F2 VARCHAR2(10)
CREATE TABLE t1
(
f1 NUMBER(4),
f2 VARCHAR2(10)
);
INSERT ALL
INTO t1 VALUES(1,'A')
INTO t1 VALUES(2,'B')
INTO t1 VALUES(3,'C')
INTO t1 VALUES(4,'D')
INTO t1 VALUES(5,'E')
SELECT * FROM dual;
MERGE:
MERGE:
• introduced in Oracle 9i version.
• MERGE => combine
• MERGE = UPDATE + INSERT
• MERGE command is a combination of UPDATE &
INSERT commands.
• That's why it can be also called as "UPSERT"
command.
• MERGE command is used to apply one table
changes to its REPLICA [duplicate copy].
Oracle2PM Page 53
MERGE INTO <target_table_name> <alias>
USING <source_table_name> <alias>
ON(<condition>)
WHEN matched THEN
<UPDATE query>
WHEN not matched THEN
<INSERT query>;
Example on MERGE:
Customer1 S Customer2 T
cid cname ccity cid cname ccity
1 A Bangalore 1 A Hyd
2 B Kolkata 2 B Delhi
3 C Mumbai 3 C Mumbai
4 D Pune
5 E Chennai
Create customer1:
COMMIT;
4 D Pune
5 E Chennai
Updating records:
1 A Bangalore
2 B Kolkata
UPDATE customer1
SET ccity='Bangalore'
WHERE cid=1;
UPDATE customer1
SET ccity='Kolkata'
WHERE cid=2;
COMMIT;
SQL:
Oracle2PM Page 54
SQL:
• It is a query language
• used to write the queries.
• to communicate with DB we write queries.
• query => is a request that is sent to server.
5 sub languages:
DDL CREATE
deals with metadata ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL / DQL SELECT
Oracle2PM Page 55
Built-In Functions
Tuesday, November 8, 2022 3:18 PM
SQL => 4 GL
Built-In Functions:
String Functions:
Lower():
It is used to convert the string to lower case
Syntax:
Lower(<string>)
Exs:
Lower('RAJU') raju
Lower('RAJ KUMAR') raj kumar
Upper():
it is used to convert the string to upper case.
Syntax:
Upper(<string>)
Exs:
Upper('raju') RAJU
Upper('raj kumar) RAJ KUMAR
Oracle2PM Page 56
Initcap() [Initial Capital]:
It is used to get every word's starting letter as capital.
Syntax:
Initcap(<string>)
Exs:
Initcap('RAJU') Raju
Initcap('RAJ KUMAR') Raj Kumar
Initcap('RAK KUMAR VARMA') Raj Kumar Varma
Concat():
• concatenate => combine
• used to combine 2 strings.
Syntax:
Concat(<string1>,<string2>)
Exs:
Concat('raj','kumar') rajkumar
Concat('raj','kumar','varma') ERROR
Concat(Concat('raj','kumar'),'varma') rajkumarvarma
Concatenation Operator ||
length():
• used to find length of the string.
• length of string => no of chars in string
Syntax:
length(<string>)
Exs:
length('raju') 4
length('sai teja') 8
UPDATE emp
SET ename=initcap(ename);
ename
-----------
SMITH
ALLEN
WARD
Oracle2PM Page 57
Display the emp record whose name is
BLAKE when we don't know exact case:
ename
-----------
BLAKE
SELECT empno,ename,sal
FROM emp
WHERE length(ename)=4;
(or)
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '____';
SELECT empno,ename,sal
FROM emp
WHERE length(Ename)=14;
SELECT empno,ename,sal
FROM emp
WHERE length(ename)>4;
Example:
PLAYER
pid Fname Lname
1001 ROHIT SHARMA
1002 VIRAT KOHLI
Oracle2PM Page 58
Add a column with the name PNAME:
UPDATE player
SET pname = Initcap(FNAME || ' ' || LNAME);
PLAYER
pid Fname Lname PNAME
1001 ROHIT SHARMA Rohit Sharma
1002 VIRAT KOHLI Virat Kohli
PLAYER
pid PNAME
1001 Rohit Sharma
1002 Virat Kohli
1003 Sachin Tendulkar
Substr():
• Sub string => part of the string
• is used to get sub string from the string.
Syntax:
Exs:
s a I t e j a
Oracle2PM Page 59
+ve from left to right
-ve from right to left
r a j k u m a r
ASCII():
used to get ASCII value of specified char.
Syntax:
ASCII(<char>)
Exs:
ASCII('A') 65
ASCII('a') 97
ASCII('z') 122
ASCII('Z') 90
Chr():
• used to get char of specified ASCII value
Syntax:
Chr(<ASCII_value>)
Exs:
Chr(65) A
Chr(97) a
REVERSE():
used to get reverse string
Syntax:
Reverse(<string>)
Exs:
Reverse('RAMU') UMAR
Reverse('TEJA') AJET
lower() Substr()
upper() Ascii()
initcap() Chr()
concat() Reverse()
length()
Oracle2PM Page 60
length()
Instr():
• used to check whether sub string is existed in string or not.
Syntax:
Instr(<string>, <sub_string>[, <search_position>, <occurrence>])
Exs:
s a I t e j a
Note:
Instr('sai teja','teja') 5 If sub string is existed in string, it
Instr('sai teja','ramu') 0 returns position number
Instr('sai teja','sai') 1 If sub string is not existed in string it
Instr('sai teja','eja') 6 returns 0.
s a I t e j a s a i
t h I s I s h I s w I s h
SELECT empno,ename,sal
FROM emp
Oracle2PM Page 61
FROM emp
WHERE substr(ename,1,1)='S';
(or)
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE 'S%';
SELECT empno,ename,sal
FROM emp
WHERE substr(ename,1,2)='AD';
SELECT empno,ename,sal
FROM emp
WHERE substr(ename,-2,2)='RD';
SELECT empno,ename,sal
FROM emp
WHERE Substr(ename,1,1)=Substr(ename,-1,1);
SELECT empno,ename,sal
FROM emp WHERE Instr(ename,'AM')>0;
ename
-----------
SMITH => 0
ALLEN => 0
ADAMS => 3
JAMES => 2
SELECT empno,ename,sal
FROM emp
WHERE Instr(ename,'%')>0;
(or)
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%\%%' ESCAPE '\';
ravi%teja
Oracle2PM Page 62
name first 3 chars & empno last 3 chars as
username for the domain 'nareshit.com':
UPDATE emp
SET mail_id = Substr(ename,1,3) ||
Substr(empno,-3,3) || '@nareshit.com';
Lpad():
• used to fill specified char set at left side.
Syntax:
Lpad(<string>,<size>[,<char/chars>])
Rpad():
• used to fill specified char set at right side.
Syntax:
Lpad(<string>,<size>[,<char/chars>])
It fills max_size-string_length no of
chars will be filled
Exs:
Lpad('raju',10,'*') ******raju
Lpad('ramesh',10,'*') ****ramesh
Lpad('kiran',10,'@') @@@@@kiran
Lpad('sai',12,'#$') #$#$#$#$#sai
Lpad('raju',10) 6spacesraju
Rpad('raju',10,'*') raju******
Rpad('ramesh',10,'*') ramesh****
Rpad('kiran',10,'@') kiran@@@@@
Rpad('sai',12,'#$') sai#$#$#$#$#
Rpad('raju',10) raju6spaces
Lpad('A',10,'A') AAAAAAAAAA
Lpad('X',6,'X') XXXXXX
acno:9876551234
Oracle2PM Page 63
Soundex():
• When we don't know the exact spelling, based
on the pronunciation [sounds] if we want to
retrieve the data use "Soundex()" Function.
Syntax:
Soundex(<string1>) = Soundex(<string2>)
SELECT empno,ename,sal
FROM emp
WHERE soundex(ename)=soundex('blek');
Ltrim():
used to remove left side unwanted
chars.
Syntax:
Ltrim(<string> [, <char/chars>])
Rtrim():
used to remove right side unwanted chars.
Syntax:
Rtrim(<string> [, <char/chars>])
Trim():
can be used to remove unwanted chars
from left side or right side or both sides.
Exs:
Ltrim('@@@raju@@@','@') raju@@@
Rtrim('@@@raju@@@','@') @@@raju
Ltrim('@#@#@#ravi@#@#@#','@#') ravi@#@#@#
Rtrim('@#@#@#ravi@#@#@#','@#') @#@#@#ravi
Ltrim(' raju ') raju3paces
Rtrim(' raju ') 3spacesraju
Synyax of Trim():
Oracle2PM Page 64
Trim(Leading / Trailing / Both <char> FROM <string>)
Replace():
used to replace search string with replace string
Syntax:
Replace(<string>, <search_string>, <replace_string>)
Exs:
Replace('sai teja','teja','krishna') sai krishna
Replace('sai teja sai teja','teja','krishna') sai krishna sai krishna
Replace('sai teja','sai','ravi') ravi teja
Translate():
used to replace search char with corresponding replace char.
Syntax:
Translate(<string>, <search_char_set>, <replace_char_set>)
Exs:
Translate('HELLO WELCOME','LO','AB') HEAAB WEACBME
L => replaced with => A
O => replaced with => O
Replace('HELLO WELCOME','LO','AB') HELAB WELCOME
LO replaced with AB
Translate('abcabcaabbccabc','abc','XYZ') XYZXYZXXYYZZXYZ
Replace('abcabcaabbccabc','abc','XYZ') XYZXYZaabbccXYZ
Aggregate =>
if one value is formed from a set of
individual values
50 max => 90
90 min => 30
30 sum => 320
70 count => 5
80 avg => 64
• Sum()
• Avg()
• Min()
• Max()
• Count()
NOTE:
All string functions are single row functions
All group functions are multi-row functions
Oracle2PM Page 66
Sum():
is used to find sum of a set of values.
Syntax:
Sum(<column>)
Examples on Sum():
sum(10,20,30) ERROR
Execution order:
FROM emp
WHERE job='MANAGER'
SELECT sum(Sal)
avg():
used to find average of a set of values.
Syntax:
avg(<column>)
Min():
used to find minimum value in a set of values
Syntax:
Min(<column>)
Examples:
Oracle2PM Page 67
WHERE job='MANAGER';
Max():
used to get max value in a set of
values
Syntax:
Max(<column>)
Examples:
Count():
• can be used to count no of records or no
of column values.
• It cannot count the NULLs.
• it counts result of select query
Syntax:
Count(<column>) / Count(*)
Examples:
Find no of managers:
Oracle2PM Page 68
count(number)
count(8)
count(25)
count(100)
Conversion Functions:
300
300
Implicit Conversion:
• This conversion will be done by the
ORACLE implicitly.
NOTE:
• Oracle company suggesting that Don't
depend on Implicit Conversion.
○ Performance may be degraded
○ In future versions they may remove
implicit conversion programs or they
may change the coding.
Explicit Conversion:
If conversion is done by Built-In Function
then it is called "Explicit Conversion".
• to_Char()
• to_Date()
• to_Number()
Oracle2PM Page 69
• to_Date()
• to_Number()
to_Char():
• can be used to convert Date type to String
type.
• It can be used to change the date formats like
IND data format [DD/MM/YYYY] or US Date
Format [MM/DD/YYYY]
Syntax:
to_Char(<date> [, <format>])
Exs:
to_Char(sysdate) 14-NOV-22
to_char(sysdate,'Year')
Twenty Twenty-Two
1 => sun
2 => mon
3 => tue
.
.
7 => sat
Oracle2PM Page 70
7 => sat
AD / BC AD or BC format to_Char(sysdate,'BC')
AD
SELECT empno,ename,sal,
to_Char(hiredate,'DD/MM/YYYY') as hiredate 31-JAN-2022 => 31
FROM emp; 1-FEB-2022 => 32
2-FEB-2022 => 33
.
.
Display all emp records along with hiredates. 31-DEC-2022 => 365
Display hiredates in US date format
[MM/DD/YYYY]:
SELECT empno,ename,sal,
to_Char(hiredate,'MM/DD/YYYY') as hiredate
Oracle2PM Page 71
to_Char(hiredate,'MM/DD/YYYY') as hiredate
FROM emp;
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'YYYY') = 1982;
(or)
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-jan-1982' AND
'31-dec-1982';
SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'yyyy') IN(1980, 1982, 1984);
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'MM') = 12;
SELECT empno,ename,hiredate
FROm emp
WHERE to_char(hiredate,'mm') IN(1,11,12);
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'Q') = 4;
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'Q') IN(1,4);
Oracle2PM Page 72
Display the emp records who joined on Sunday:
SELECT empno,ename,hiredate
d 1 1 => sun
FROM emp
WHERE to_char(hiredate,'D')=1; dy sun
(or) day sunday
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'DY')='SUN';
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'DAY')='SUNDAY';
Output: SUNDAY3paces = SUNDAY => F
No rows Selected
SUNDAY SUNDAY3spaces
TUESDAY TUESDAY2spaces
WEDNESDAY WEDNESDAY
THURSDAY THURSDAY1space
SELECT empno,ename,hiredate
FROM emp
WHERE RTRIM(to_char(hiredate,'DAY')) = 'SUNDAY';
SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'YYYY') = 1981 AND
to_char(hiredate,'Q')=4;
Syntax:
To_Char(<number>, [<format>])
sal NUMBER(7,2)
---------
$5000 => ERROR
$5,000 => ERROR
USD5000 => ERROR
Oracle2PM Page 73
Exs:
TO_Char(123) '123'
To_Char(123.45) '123.45'
FORMAT PURPOSE
L Currency Symbol
C Currency Name
9 Digit
0 ZERO
, / G Thousand Separator
. / D Decimal Point
$5000.00
USD5,000.00
SELECT empno,ename,
to_Char (sal,'L99999.99') as salary
FROM emp;
NOTE:
Number of 9s will be decided based on
precision & scale of that column.
SELECT empno,ename,
to_Char(sal,'C99,999.99') as sal
FROM emp;
Oracle2PM Page 74
default currency symbol $
default currency name USD
Log in as DBA:
username: system
password: nareshit
TO_CHAR(5000,'L999
------------------
£5000.00
TO_CHAR(5000,'C
---------------
GBP5000.00
TO_Date():
• used to convert string to date.
• It can be used to insert date values.
It can be used get specific part [year, month,
Oracle2PM Page 75
• It can be used get specific part [year, month,
day] from specific date.
Syntax:
To_Date(<string> [, <format>)
Exs:
TO_Date('25-DEC-2019') 25-DEC-19
Example:
T1
F1 DATE
------------
25-DEC-19
17-AUG-18
CREATE TABLE t1
(
f1 DATE f1
); -----
25-DEC-19
INSERT INTO t1 VALUES('25-DEC-2019');
NOTE:
don't depend on implicit conversion because of
2 reasons:
• performance will be degraded
• in future version implicit conversion
programs may be changed or deleted.
INSERT INTO t1 F1
VALUES(to_Date('25-DEC-2019')); ----
25-DEC-19
INSERT INTO t1
VALUES(to_date('&doj','DD/MM/YYYY'));
enter value for doj: 18/11/2021
/
enter value for doj: 17/08/2021
Oracle2PM Page 76
Display year from today's date:
2022
SELECT to_Char(to_Date('25-DEC-2019'),'YYYY')
FROM dual;
2019
SELECT
to_char(to_date('27-OCT-2020'),'day')
FROM dual;
SELECT
to_char(to_date('15-AUG-1947'),'DAY')
FROM dual;
FRIDAY
SELECT
to_char(to_Date('24-APR-1973'),'DAY')
FROM dual;
To_Number():
• can be used to convert string to number.
• String must be numeric string.
Syntax:
To_Number(<string> [, <format>])
Exs:
To_Number('123') 123
To_Number('123.45') 123.45
To_Number('$5000.00') ERROR
TO_Number('$5000.00','L9999.99') 5000
To_Number('USD5000.00','C9999.99') 5000
power() ceil()
Oracle2PM Page 77
Number Functions / Math Functions:
power() ceil()
sqrt() floor()
abs() trunc()
round()
mod()
Power():
used to get power value
Syntax:
Power(<number>, <power>)
Exs:
Power(2,4) 16
Power(5,3) 125
Sqrt():
used to fin d square root value
Syntax:
Sqrt(<number>
Exs:
Sqrt(100) 10
Sqrt(81) 9
Abs():
• used to get absolute value
• Absolute => Non-Negative [+ve]
Syntax:
Abs(<number>)
Exs:
Abs(25) 25
Abs(-25) 25
ceil():
used to get round up int value
Syntax:
ceil(<number>)
floor():
used to get round down int value
Syntax:
floor(<number>)
Exs:
ceil(123.4567) 123 => 123.4567 => 124
124
floor(123.4567) 123 => 123.4567 => 124
123
Example:
Oracle2PM Page 78
Find average salary of all emps. Take upper
integer as average value:
Trunc():
• Trunc => Truncate [remove]
• used to remove decimal places.
Syntax:
Trunc(<number> [,<no_of_decimal_places>])
Exs:
Trunc(123.45678) 123
Trunc(123.45678,2) 123.45
Trunc(567.2345) 567
Trunc(567.234567,3) 567.234
NOTE:
Trunc() function always gives lower value
Example:
SELECT empno,ename,hiredate,
TRUNC((sysdate-hiredate)/365) as experience
FROM emp;
NOTE:
date also contains time value
To remove time value from date we can use
TRUNC()
Oracle2PM Page 79
16-NOV-22 3:19:15:000123 PM
16-NOV-22
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate = sysdate;
no rows selected
SELECT empno,ename,hiredate
FROM emp
WHERE TRUNC(hiredate) = TRUNC(sysdate);
ROUND():
• used to get rounded values.
• If value is avrg or above average, it takes
upper value
• If value is below average, it takes lower value
Syntax:
Round(<number> [,<no_of_decimal_places>])
Exs:
Round(123.789) 123 => 123.5 => 124
124
Trunc(123.789) 123
Round(123.345) 123
Trunc(123.345) 123
Round(123.45678,2) 123.46
Round(123.45378,2) 123.45
Round(678.234567,3) 678.235
Round(678.234267,3) 678.234
Oracle2PM Page 80
Round(678.234567,3) 678.235
Round(678.234267,3) 678.234
Mod():
used to get remainder value
Syntax:
Mod(<number>, <divisor>)
Exs:
Mod(10,7) 3
Mod(5,2) 1
Date Functions:
• Sysdate
• Systimestamp
• Add_Months()
• Last_Day()
• Next_Day()
• Months_Between()
Sysdate:
used to get current system date
Example:
systimestamp:
used to get current system date and time.
Example:
Add_Months():
• used to add months to a date or subtract
months from a date.
Syntax:
Oracle2PM Page 81
Syntax:
Add_Months(<date>,<no_of_months>)
Examples:
19-NOV-22
17-JAN-23
17-NOV-24
15-NOV-22
17-SEP-22
Example:
ORDERS
Order_Id Ordered_date Delivery_date
1234 sysdate sysdate+5 /
17-NOV-22 Ordered_date + 5
22-NOV22
CM_LIST
STATE_CODE CM NAME start_date end_date
TS KCR 19-MAR-2018 Add_Months(start_date,5*12)
AP
..
EMP
Oracle2PM Page 82
EMP
EMPNO ENAME DOB DOR
1001 A 27-OCT-1998 Add_Months(DOB,60*12)
COMMIT;
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate = sysdate;
no rows selected
SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(sysdate);
SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(sysdate-1);
SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(Add_months(sysdate,-1));
Display the emp records who joined 1 year ago from today's
date:
SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(Add_Months(sysdate,-12));
HOME LOANS
3 months transactions
Oracle2PM Page 83
WHERE acno=1234 AND
trans_Date between Add_Months(sysdate,-3) AND
sysdate;
Date_Id Amount
1-jan-2019 600000 today's sales
2-jan-2019 1000000
yesterday's sales
3-jan-2019 800000
.. 1 month ago sales
..
17-NOV-2022 1 year ago sales
Last_Day():
used to get last date in the month.
Syntax:
Last_day(<date>)
Example:
30-NOV-22
28-FEB-22
29-FEB-20
SELECT Last_Day(Add_Months(sysdate,1))
FROM dual;
31-DEC-22
SELECT Last_Day(Add_Months(sysdate,-1))
FROM dual;
SELECT Last_Day(Add_Months(sysdate,-1))+1
FROM dual;
Next_Day():
used to get coming date based on
Oracle2PM Page 84
• used to get coming date based on
weekday name.
• Ex:
○ coming Sunday date
○ coming Friday date
Syntax:
Next_day(<date>,<week_Day>)
Examples:
SELECT Next_day(Last_day(sysdate),'sun')
FROM dual;
SELECT
Next_day(Last_day(Add_months(sysdate,-1)),'sun')
FROM dual;
SELECT
Next_day(Last_day(sysdate)-7,'sun')
FROM dual;
Months_Between():
used to months between 2 dates.
Syntax:
Months_Between(<date1>,<date2>)
Ex:
Months_Between('31-DEC-2022','31-DEC-2021')
trunc(sysdate-hiredate/365)
SELECT empno,ename,hiredate,
trunc(months_between(sysdate,hiredate)/12) as experience
FROM emp;
Oracle2PM Page 85
Miscellaneous Functions:
NVL()
NVL2()
RANK()
DENSE_RANK()
USER
UID
GREATEST()
LEAST()
NVL():
• used to replace null value with other value.
• If null is participated in operation then result will
be NULL.
300
null
10+20*40-30+16-null = null
300
Syntax:
NVL(<argument1>, <argument2>)
Exs:
NVL(100,200) 100
NVL(null,200) 200
Example:
Calculate total salary of all emps
[sal+Comm]:
SELECT empno,ename,sal,comm,
sal+NVL(comm,0) as "total salary"
FROM emp;
SELECT empno,ename,sal,
NVL(comm,'N/A') as comm
FROM emp;
Oracle2PM Page 86
FROM emp;
SELECT empno,ename,sal,
NVL(to_Char(comm),'N/A') as comm
FROM emp;
STUDENT
sid sname M1
1001 A 70
1002 B
1003 C 80
1004 D
1005 E 66
NVL2():
used to replace nulls & not nulls.
Syntax:
NVL2(<arg1>, <arg2>, <arg3>)
Exs:
NVL2(100,200,300) 200
NVL2(null,200,300) 300
NVL() NVL2()
Example:
UPDATE emp
SET comm = NVL2(comm,comm+1000,700);
RANK():
used to apply ranks to the records according to specific
Oracle2PM Page 87
used to apply ranks to the records according to specific
column order
Syntax:
RANK() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/ DESC)
DENSE_RANK():
used to apply ranks to the records according to specific
column order
Syntax:
DENSE_RANK() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/ DESC)
UNIVERSITY
sal DESC
------ sal Rank dense_rank
4000 ---------
8000 8000 => 1 1
6000 8000 => 1 1
7000 7000 => 3 2
3000 6000
5000 5000
8000 4000
3000
SELECT empno,ename,sal,
RANK() OVER(ORDER BY sal DESC) as Rank
FROM emp;
(or)
SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as Rank
Oracle2PM Page 88
DENSE_RANK() OVER(ORDER BY sal DESC) as Rank
FROM emp;
SELECT empno,ename,sal,hiredate,
DENSE_RANK() OVER(ORDER BY sal DESC, hiredate ASC)
as rank
FROM emp;
sal
hiredate
--------
-------------
8000
17-SEP-1983
9000
25-DEC-1981
6000
27-FEB-1982
7000
8500
ORDER BY clause:
• It arranges records in ascending or descending
order according to specific column / columns
PARTITION BY clause:
• It is used to group the records according to
specific column
• If we don't use PATITION BY clause, all records
will be treated as one group.
Syntax:
PARTITION BY <Column>
Ex:
PARTITION BY deptno
EMP
empno ename deptno sal RANK
10 4000 2
10 6000 1
20 8000 1
20 7000 2
30 4000 2
Oracle2PM Page 89
10 6000 1
20 8000 1
20 7000 2
30 4000 2
30 5000 1
SELECT empno,ename,deptno,sal,
DENSE_RANK() OVER(PARTITION BY deptno
ORDER BY sal DESC) as RANK
FROM emp;
USER:
used to get current user name.
UID:
used to get current user ID.
Ex:
SELECT user,uid FROM dual;
GREATEST():
• used to find greatest value in horizontal
values
• can take variable length arguments.
• single row function.
Max():
• used to find max value in vertical values
• can take 1 argument.
• multi row function.
T1
F1 F2 F3
50 90 55
44 81 72
73 24 97
max(f3) => 97
GREATEST(f1,f2,f3)
----------------------
90
81
97
LEAST():
used to find least value in horizontal
Oracle2PM Page 90
• used to find least value in horizontal
values.
• it can take variable length arguments.
• single row function.
Min():
• used to find min value in vertical values
• can take 1 argument.
• multi-row function
Built-In Functions
Ex: Ex:
string functions, math functions Aggregate / Group Functions
date functions, conversion
functions min() max() count() sum() avg()
Oracle2PM Page 91
Clauses
Saturday, November 19, 2022 3:22 PM
Clause:
• Clause is a part of query
• Every clause has specific purpose & than can
perform specific functionality.
ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES
Ex:
UPDATE emp INSERT clause
SET sal=sal+1000 INTO clause
WHERE empno=7369; VALUES clause
UPDATE clause
SET clause
WHERE clause
ALL [default]
ASC [default]
Example:
Display the emp names and salaries of the
employees whose salary is more than 2500:
SELECT ename,sal
FROM emp
WHERE sal>2500;
EMP
EMPNO ENAME JOB SAL
1001 A CLERK 6000
1002 B ANALYST 2000
1003 C MANAGER 4000
1004 D CLERK 2400
FROM emp:
Selects entire table
Oracle2PM Page 92
Selects entire table
Ex:
FROM emp
EMP
EMPNO ENAME JOB SAL
1001 A CLERK 6000
1002 B ANALYST 2000
1003 C MANAGER 4000
1004 D CLERK 2400
WHERE sal>2500:
• It filters the records.
• WHERE clause condition will be applied on
every row.
EMP
EMPNO ENAME JOB SAL
1001 A CLERK 6000
1002 B ANALYST 2000
1003 C MANAGER 4000
1004 D CLERK 2400
SELECT ename,sal:
It selects the specified columns
ENAME SAL
A 6000
C 4000
ORDER BY clause:
• used to arrange the records in Ascending OR Descending
Order according to specific column / columns
• Default order is: ASC [ASCENDING ORDER]
Syntax:
ORDER BY <column> ASC/DESC [, <column> ASC/DESC, …]
NUMBER CHAR
DATE
ASC: DESC:
1 ASC: DESC: ASC:
10 DESC:
2 A Z 1-jan-2022
9 31-DEC-2022
3 B Y 2-jan-2022
8 30-DEC-2022
4 C X 3-jan-2022
7 .
. . . .
. .
. . . 31-jan-2022
. .
10 Z A 1-feb-2022
1 1-JAN-2022
.
.
31.dec-2022
Oracle2PM Page 93
31.dec-2022
Display all emp records along with emp names. Arrange emp
names in alphabetical order:
SELECT empno,ename,sal
FROM emp
ORDER BY ename ASC;
(or)
SELECT empno,ename,sal
FROM emp
ORDER BY ename ; --ASC => is optional [default: ASC]
(or)
SELECT empno,ename,sal
FROM emp
ORDER BY 2 ASC; -- 2 => ename [column number in SELECT]
SELECT empno,ename,sal
FROM emp
ORDER BY sal DESC;
SELECT empno,ename,sal,hiredate
FROM emp
ORDER BY sal DESC, hiredate ASC;
Oracle2PM Page 94
SELECT empno,ename,sal,deptno,hiredate
FROM emp
ORDER BY deptno ASC;
SELECT deptno,empno,ename,hiredate
FROM emp
ORDER BY deptno ASC, hiredate ASC;
SELECT empno,ename,deptno,sal,hiredate
FROM emp
ORDER BY deptno ASC, sal DESC, hiredate ASC;
NOTE:
If column has nulls,
ASCENDING ORDER nulls will be given last
Descending ORDER nulls will be given first
SELECT empno,ename,sal
FROM emp
ORDER BY sal DESC nulls last;
SELECT empno,ename,sal
FROM emp
ORDER BY sal ASC nulls first;
Oracle2PM Page 95
ALL: gives all values
DISTINCT clause:
• DISTINCT clause gives DISTINCT [unique/single]
values.
• It avoids duplicate values.
Examples on DISTINCT:
ALL job
SELECT DISTINCT job FROM emp;
JOB
----------- JOB
MANAGER -------
CLERK MANAGER
CLERK CLERK
SALESMAN SALESMAN
MANAGER
SALESMAN
DEPTNO
--------- SELECT DISTINCT deptno FROM emp
20 ORDER BY deptno;
30
DEPTNO
30
-------------
20
10
10
20
10
30
Oracle2PM Page 96
10 CLERK 10 CLERK
20 CLERK 10 MANAGER
20 CLERK 10 ANALYST
10 CLERK 20 CLERK
10 MANAGER 20 MANAGER
20 MANAGER 20 SALESMAN
10 ANALYST
20 SALESMAN
10 ANALYST
20 SALESMAN
DISTINCT deptno,job
GROUP BY:
• GROUP BY is used to group the records according to
specific column or columns.
• Syntax: GROUP BY <grouping_column_list>
• Ex:
○ GROUP BY deptno => 10, 20, 30 => 3 groups
▪ If deptno is same, it will be treated as one group
Example:
DETAILED DATA
SUMMARIZED DATE
EMP
EMPNO ENAME DEPTNO SAL
deptno sum_of_sal
1001 A 20 5000
20 14000
1002 B 20 9000
30 11000
1003 C 30 4000
10 14000
1004 D 30 7000
1005 E 10 8000
1006 F 10 6000
Oracle2PM Page 97
SELECT deptno, sum(Sal)
FROM emp
GROUP BY deptno
ORDER BY deptno;
Output:
deptno sum(Sal)
10 10000
20 25000
30 12000
EMP
EMPNO ENAME DEPTNO SAL
1003 C 30 4000
1004 D 30 7000
1005 E 10 8000
1006 F 10 6000
GROUP BY deptno:
It groups the records
1003 C 30 4000
1004 D 30 7000
1005 E 10 8000
1006 F 10 6000
SELECT deptno,sum(Sal):
It selects the columns
deptno sum(Sal)
Oracle2PM Page 98
30 11000
10 14000
ORDER BY deptno:
it arranges records in asc / desc
order.
deptno sum(Sal)
10 14000
30 11000
Output:
deptno max_sal min_Sal
10 … ..
20 … …
30 … …
Output:
deptno no_of_emps
10 3
20 5
30 6
Oracle2PM Page 99
count(*) as no_of_emps
FROM emp
GROUP BY to_char(hiredate,'YYYY')
ORDER BY year;
Output:
YEAR no_of_emps
1980 1
1981 10
1982 2
1983 1
Execution Order:
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
Job Sum_Of_Salaries
CLERK …
MANAGER …
ANALYST …
job no_of_emps
CLERK 4
MANAGER 3
Example:
SALES
DateId Amount
1-JAN-2018 1000000
2-JAN-2018 700000
.. ..
31-DEC-2018 1200000
1-JAN-2019 900000
..
..
23-NOV-2022 1300000
2022 …
SALES
DateId Amount
1-JAN-2018 1000000 Quarter Sales
2-JAN-2018 700000 1 ..
.. .. 2 ..
31-DEC-2018 1200000 3 ..
1-JAN-2019 900000 4 ..
..
..
23-NOV-2022 1300000
HAVING clause:
• "HAVING" is used to write the conditions
on groups.
• It cannot be used without GROUP BY.
It must be followed by GROUP BY.
• It will be applied on result of GROUP BY.
• It filters the groups.
• Aggregate functions [group functions]
can be used in HAVING clause.
SELECT deptno,Sum(Sal)
FROM emp
GROUP BY deptno
HAVING sum(Sal)>9000;
ORDER BY deptno;
WHERE HAVING
Ex:
EMP GROUP BY deptno,job
EMPNO ENAME deptno job
10 CLERK
10 CLERK
10 CLERK
20 ANALYST
20 ANALYST
20 ANALYST
10 MANAGER
10 MANAGER
30 SALESMAN
30 SALESMAN
20 MANAGER
30 SALESMAN
30 MANAGER
20 MANAGER
20 CLERK
30 MANAGER
20 CLERK
20 CLERK
Rollup():
• Rollup() function is used to calculate
sub totals & grand total.
• It is used to calculate sub totals &
grand total according to first column in
grouping column list.
Ex:
GROUP BY Rollup(deptno,job)
GROUP BY Rollup(job,deptno)
Cube():
• Cube() function is used to calculate sub
totals & grand total.
• It is used to calculate sub totals &
grand total according to all columns in
grouping column list.
Ex:
GROUP BY Cube(deptno,job)
Example:
SALES
DateId Amount
1-JAN-2018 1000000 year quarter sales
2-JAN-2018 700000 2018 1 ..
.. .. 2 ..
31-DEC-2018 1200000 3 ..
1-JAN-2019 900000 4 ..
.. 2019 1 ..
.. 2 ..
23-NOV-2022 1300000 3 ..
4 ..
Example:
PERSON
Clauses:
Execution ORDER:
• FROM
• WHERE
• GROUP BY
• HAVING
• SELECT
• DISTINCT
• ORDER BY
Syntax:
SELECT <column_list>
FROM <table_name>
Display the emp records whose salary is
WHERE <column> <operator> (<SELECT query>);
more than BLAKE's salary:
BLAKE 2850
SELECT empno,ename,sal
Sub Queries [Nested Queries]: FROM emp
• Writing a query in another query is called WHERE sal>(SELECT sal FROM emp
"Sub Query / Nested Query". WHERE ename='BLAKE');
• Outside query is called "Outer / Main / Parent Query".
• Inside query is called "Inner / Sub / Child query".
• We must write sub query in parenthesis.
○ Ex: SELECT ……(SELECT query);
• When WHERE clause condition value is unkonown, to
find this value we write Sub Query.
• Inner query must be "SELECT" only. It cannot be
INSERT/UPDATE/DELETE. Because, We need to find
WHERE clause condition value. SELECT query finds
[selects] the value. INSERT / UPDATE / DELETE queries
cannot find the value.
• Outer query can be SELECT / INSERT / UPDATE /
SELECT
DELETE.
WHERE …(SELECT
• First inner query gets executed. This inner query result
(SELECT
becomes input for outer query. Then outer query gets
(SELECT ..
executed.
)))
• Sub queries can be nested up to 255 levels.
255 levels
Types of Subqueries:
5 Types:
BLAKE 2850
SELECT empno,ename,sal
FROM emp
WHERE sal>(BLAKE's salary => ?);
SELECT empno,ename,sal
FROM emp
WHERE sal>(SELECT sal FROM emp
WHERE ename='BLAKE');
NOTE:
SELECT ename,max(Sal) FROM emp; -ERROR
Sal
SELECT max(sal) FROM emp
------
WHERE sal < (max sal)
2000
4000 sal<6000
6000
3000 2000
2500 4000
5000 3000 max sal => 2nd max sal
4500 2500
5000 5000 => 2nd max sal
4500
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate>(find KING's hiredate);
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate>(SELECT hiredate FROM emp
WHERE ename='KING');
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate<(SELECT hiredate FROM emp
WHERE ename='KING');
UPDATE emp
SET sal=(SELECT max(sal) FROM emp WHERE deptno=30)
WHERE ename='JAMES';
JAMES CLERK
BLAKE MANAGER
SELECT empno,ename,job,sal
FROM emp
WHERE job IN(find job titles of JAMES and
BLAKE);
SELECT empno,ename,job,sal
FROM emp
WHERE job IN(SELECT job FROM emp
WHERE ename IN('JAMES','BLAKE'));
SELECT empno,ename,job,sal
FROM emp
WHERE sal IN(find salaries of WARD and
FORD);
Ex:
sal > ALL(2000,3000) sal>2000 AND sal>3000
sal
---------
2500
6000
4000
1500
ANY:
• It is used to compare column value with a list of values.
• It is used to avoid of writing multiple conditions using OR.
Syntax:
<column> <relational_operator> ANY(<value_list>)
Exs:
sal > ANY(1000,2000) sal>1000 OR sal>2000
sal < ANY(1000,2000) sal<1000 OR sal<2000
sal = ANY(1000,2000) sal=1000 OR sal=2000
sal IN(1000,2000)
SELECT empno,ename,sal
FROM emp
WHERE sal> ALL(1600,2000);
WARD 1250
FORD 3000
SELECT empno,ename,sal
FROM emp
WHERE sal>ALL(find WARD & FORD salaries);
SELECT empno,ename,sal
FROM emp
WHERE sal>ALL(SELECT sal FROM emp
WHERE ename IN('WARD','FORD'));
WARD 1250
FORD 3000
SELECT empno,ename,sal
FROM emp
WHERE sal>ANY(SELECT sal FROM emp
WHERE ename IN('WARD','FORD'));
EMP
EMPNO ENAME DEPTNO SAL deptno avg(sal)
1001 10 10000 10 15000
1002 10 20000 20 4000
1003 20 5000
1004 20 3000
1002 10 20000
1003 20 5000
SELECT e.empno,e.ename,e.deptno,e.sal
FROM emp e
WHERE e.sal>(SELECT avg(sal) FROM emp
WHERE deptno=e.deptno);
EMP
EMPNO ENAME DEPTNO SAL
deptno max(Sal)
1001 A 10 10000
10 20000
1002 B 10 20000
20 5000
1003 C 20 5000
1004 D 20 3000
1002 B 10 20000
1003 C 20 5000
SELECT e.empno,e.ename,e.deptno,e.sal
FROM emp e
WHERE e.sal = (SELECT max(sal) FROM emp
WHERE deptno=e.deptno);
SELECT e.empno,e.ename,e.deptno,e.hiredate
FROM emp e
WHERE hiredate = (SELECT min(hiredate) FROM
emp WHERE deptno=e.deptno);
6000
/
enter value for n: 5 => displays 5th max sal
/
enter value for n: 10 => displays 10th max sal
/
enter value for n: 5 --displays top 5 salaries
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
sal
----------
7000 9000 1
6000 8000 2
8000 7000 3
9000 6000 4
4000 5000 5
5000
4000 6
SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank=3;
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank=3;
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank=&n;
/
enter value for n: 5 --5th max sal
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank<=3;
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank<=&n;
ROWNUM:
• ROWNUM is a pseudo column.
• pseudo => false.
• It is used to apply row numbers to rows / records.
• Row Number will be applied on result of SELECT
query.
Examples:
SELECT *
FROM (SELECT rownum as rn,Empno,Ename,Sal
FROM emp)
WHERE rn=3;
SELECT *
FROM (SELECT rownum as rn,Empno,Ename,Sal
FROM emp)
WHERE rn IN(3,5,11);
SELECT *
FROM (SELECT rownum as rn,Empno,Ename,Sal
FROM emp)
WHERE mod(rn,2)=0;
SELECT *
FROM (SELECT rownum as rn,empno,ename,sal
FROM emp)
WHERE mod(rn,2)=1;
Examples:
Output:
EMP DEPT
---------- ------------
14 4
Types:
JOINS:
• JOIN => Combine / Connect / Link
• GOAL => used to retrieve data from multiple tables
COLLEGE DB
STUDENT
MARKS
FEE
STAFF
LIBRARY
STUDENT S MARKS M
SID SNAME SCITY SID MATH PHY CHE
1001 A Hyd 1001 70 90 80
1002 B Delhi 1002 55 77 66
1003 C Chennai 1003 45 72 39
JOINS:
• JOIN => Combine / Connect / Link
• GOAL: JOINS concept is used to retrieve the data
from multiple tables.
• JOIN is an operation like SORTING operation,
FILTERING operation that combines one table
records with another based on CONDITION. This
condition is called "JOIN CONDITION".
• JOIN CONDITION decides which record in one
table will be joined with which record in another
table.
Types of Joins:
• Equi Join / Inner Join
• Outer Join
○ Left Outer Join
○ Right Outer Join
○ Full Outer Join
• Non-Equi Join / Inner Join
• Self Join / Inner Join
• Cross Join
Equi Join:
If Join operation is performed based on equality
condition then it is called "Equi Join".
Ex:
WHERE S.SID = M.SID
EMP E DEPT D
EMPNO DEPTNO
ENAME DNAME
JOB LOC
SAL
COMM
HIREDATE
E.DEPTNO = D.DEPTNO
MGR
DEPTNO
ENAME SAL DNAME LOC
emp e
empno ename sal deptno dept d
1001 A .. 20 deptno dname loc
1006 F .. 30
1007 G .. ename sal dname loc
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno;
ANSI standards
NOTE:
In ORACLE style, to separate 2 table names we use , [comma].
In ANSI style, to separate 2 table names, we use KEYWORD.
ORACLE STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;
ANSI STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno;
[OR]
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
USING(deptno);
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno AND d.loc='CHICAGO';
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE d.loc='CHICAGO';
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno AND e.ename='BLAKE';
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename='BLAKE';
Outer Join:
• Inner Join can give matched records only. It
cannot give unmatched records. TO get
unmatched records also we use "OUTER JOIN".
• Outer Join can give matched records & unmatched
records.
emp e
empno ename sal deptno dept d
1001 A .. 20 deptno dname loc
1006 F .. 30
1007 G ..
1008 H .. unmatched record from DEPT
Left Outer:
NOTE:
• In ORACLE style, Join Condition decides left
table & right table
Ex:
WHERE e.deptno = d.deptno
e Left Table
d Right Table
d Left Table
e Right Table
Ex:
FROM emp e JOIN dept d
Example:
Display the emp details along with dept details.
Also display the emp records to whom dept is not
COMMIT;
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+);
ANSI STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptno;
Example:
Display the emp records along with dept details.
Also display the depts in which emps are not
existed:
[RIGHT OUTER JOIN]:
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno;
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno;
Example:
Display all emps records along with dept details.
Also display the emp records to whom dept is not
assigned. Also display the depts in which emps are
not existed: [FULL OUTER JOIN]:
ORACLE STYLE:
FULL OUTER JOIN = Left Outer UNION Right Outer
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+)
UNION
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno;
ANSI STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno;
ORACLE STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+) AND d.dname IS NULL;
ANSY STLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS NULL;
ORACLE STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno AND e.ename IS null;
ANSI STYLE:
ORACLE STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno(+) AND d.dname IS NULL
UNION
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno AND e.ename IS NULL;
ANSI STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname IS null OR e.ename IS null;
Equi Join:
If join operation is performed based on equality
condition then it is called "Equi Join".
Ex:
e.deptno = d.deptno
Non-Equi Join:
If join operation is performed based on other than
equality condition then it is called "Non-Equi Join".
Ex:
WHERE e.deptno != d.deptno
WHERE e.deptno > d.deptno
WHERE e.deptno < d.deptno
EMP e SALGRADE s
ORACLE STYLE:
SELECT e.ename,e.sal,s.grade
FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;
ANSI STYLE:
SELECT e.ename,e.sal,s.grade
FROM emp e INNER JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;
SELF JOIN:
• Self Join can be also called as "Recursive Join".
• If a table is joined to itself then it is called
"Self Join".
• In this, one record in a table will be joined with
another record in same table.
Example:
EMP e EMP m
EMPNO ENAME JOB MGR EMPNO ENAME JOB MGR
1001 A MANAGER 1001 A MANAGER
1002 B CLERK 1001 1002 B CLERK 1001
1003 C ANALYST 1001 1003 C ANALYST 1001
1004 D MANAGER 1004 D MANAGER
1005 E SALESMAN 1004 1005 E SALESMAN 1004
1006 F CLERK 1004 1006 F CLERK 1004
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
Example: AXB = ?
GROUPA a GROUPB b
CID CNAME CID CNAME
10 IND 40 ENG
20 AUS 50 NZ
30 WIN 60 PAK
ORACLE STYLE:
ANSI STYLE:
Output:
IND VS ENG
IND VS NZ
IND VS PAK
AUS VS ENG
AUS VS NZ
AUS VS PAK
WIN VS ENG
WIN VS NZ
WIN VS PAK
Joins
-----------
Types of Joins:
Natural Join:
SELECT *
FROM emp e NATURAL JOIN dept d;
Example:
ORACLE STYLE:
ANSI STYLE:
emp
empno ename sal deptno dept
1001 A .. 20 deptno dname loc
1006 F .. 30
1007 G ..
1008 H ..
SETS
SET Operators:
A = {10,20,30,40}
B = {30,40,80,90}
Syntax:
A U B = {10,20,30,40,80,90}
<SELECT query>
A UA B ={10,20,30,40,30,40,80,90}
<SET OPERATOR>
A I B = {30,40}
<SELECT query>
A M B = {10,20}
B M A = {80,90}
UNION:
• it is used to get all rows selected by
2 select queries without duplicates.
• It does not give duplicate records.
• It gives result in the order.
UNION ALL:
• it is used to get all rows selected by
2 select queries including duplicates.
• It gives duplicate records.
• It does not gives result in order.
Branch-1 Branch-2
CUSTOMER1 CUSTOMER2
CID CNAME CID CNAME
1001 A 5001 D
1002 B 1002 B
1003 C 5002 E
cid cname
1001 A
1002 B
1003 C
5001 D
5002 E
CID CNAME
1001 A
1002 B
1003 C
5001 D
1002 B
5002 E
• Slower • Faster
Rules:
No of Columns in both SELECT queries must
Oracle2PM Page 136
• No of Columns in both SELECT queries must
be same.
Example:
SELECT cid FROM customer1
UNION
SELECT cid,cname FROM customer2;
Example:
ERROR:
expression must have same datatype as
corresponding expression
CUSTOMER1 CUSTOMER2
Output:
cid cname
----------- ------------------
Example:
Display the common customers who are
visiting branch-1 & branch-2:
MINUS:
• it is used to get specific records from
first select query result.
Example:
Display specific customers of Branch-1:
JOB
---------
CLERK CLERK
MANAGER MANAGER
ANALYST ANALYST
CLERK
ANALYST
JOB SALESMAN
--------- MANAGER
SALESMAN CLERK
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
Output:
ANALYST
CLERK
Oracle2PM Page 139
CLERK
MANAGER
SALESMAN
Output:
CLERK
MANAGER
Output:
Analyst
Output:
Salesman
DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL SELECT
DML INSERT
UPDATE
DELETE
Built-In Functions:
String Functions
Aggregate Functions
Conversion Functions
Date Functions
Number Functions
Miscellaneous Functions
FROM
WHERE
GROUP BY
HAVING
SELECT
Oracle2PM Page 141
SELECT
DISTINCT
ORDER BY
Sub Queries:
5 types:
Single Row
Multi Row
Correlated
Inline
Scalar
Joins:
Equi Join
Non-Equi Join
Self-Join
Cross Join
SET OPERATORS
UNION
UNION ALL
INTERSECT
MINUS
VIEW:
• VIEW is a Database Object.
• VIEW is a Virtual Table. [Virtual => Not Real]
• Virtual Table means, it does not have physical data &
does not occupy the memory.
EMP
EMPNO ENAME JOB SAL COMM HIREDATE DEPTNO MGR
CREATE VIEW v1
V1
AS
SELECT empno,ename,job SELECT
FROM emp; empno,ename,job
FROM emp
VIEW:
• VIEW is a Oracle Database Object.
• VIEW is a virtual table.
• Virtual table means, it does not contain physical data &
does not occupy the memory.
• It holds SELECT query.
• When we retrieve data through view, implicitly ORACLE
runs SELECT query which is holded by view.
• Every VIEW is associated with SELECT query.
• A VIEW will be created based on Table. We cannot create
a view without Table.
• A table on which a view is created is called "Base Table".
NOTE:
• To create a view permission is required.
username: system
password: nareshit
Example:
Log in as user:
username: c##oracle2pm
password: nareshit
V1
EMPNO ENAME JOB
CREATE VIEW v1
AS
SELECT empno,ename,job FROM emp;
Output:
View created.
Log in as c##userC:
Output:
1 row created
Output:
1 row ddeleted.
Output:
1 row updated.
EMP
EMPNO ENAME JOB SAL COMM HIREDATE MGR DEPTNO
1001 A 10 v10
1002 B 10
1003 C 20
v20
1004 D 20
1005 E 30
1006 F 30 v30
CREATE VIEW v2
AS
SELECT * FROM emp
WHERE deptno=20;
Output:
1 row created.
Output:
…
…
5001 A .. 20
v2
Example:
CREATE VIEW v3
AS
SELECT * FROM emp
WHERE deptno=20 WITH CHECK OPTION;
CREATE VIEW v4
AS
SELECT <10 tables_column_list>
FROM <10 table_names>
WHERE <9 Join Conditions>;
Advantages:
• security
• reduces complexity & simplifies queries
Disadvantage:
• Less Performance
Types of Views:
2 Types:
Simple View:
• A view which is created on one table is called "Simple
View".
• We can perform DML operations [Insert/Update/Delete]
on Simple view.
It can be also called "Updatable View".
Complex View:
• If a view is created on multiple tables
then it called "Complex View".
• A view which is created using joins or group by or
having or aggregate functions or set operators or
expressions or sub queries is called "Complex view".
We cannot perform DML operations
Example:
CREATE VIEW v5
AS
SELECT e.ename, e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;
CREATE VIEW v6
AS
SELECT empno,ename,job,sal FROM emp;
CREATE VIEW v7
AS
SELECT empno,ename FROM v6;
FORCE VIEW:
• FORCE VIEW is used create a view forcibly with
some errors like base table not existed.
Table created.
commit;
F1
----------
1001
1002
1003
Example:
EMP
EMPNO ENAME JOB SAL hiredate
SELECT * FROMv12;
empno ename
----------- -------------
2001 A
USER_VIEWS:
• "USER_VIEWS" is a system table (or) built-in table.
• It maintains all view information which are
created by the user.
DESC USER_VIEWS;
Dropping view:
Syntax:
DROP VIEW <view_name>;
Ex:
DROP VIEW v1;
VIEW:
• Virtual Table
• Virtual Table => does not contains physical data
• holds SECT query
Types of Views:
• Simple View
• Complex View
SEQUENCES:
• SEQUENCE is a Database Object.
• SEQUENCE is used to create sequential integers.
• SEQUENCE is independent of Table.
Example:
USER_SEQUENCES:
• USER_SEQUENCES is a system table.
• It maintains all sequences information which
are created by the user.
pseudo columns:
To work with sequence we use 2 pseudo columns. pseudo => false
They are:
• NEXTVAL
• CURRVAL ROWNUM
Oracle2PM Page 153
• CURRVAL ROWNUM
NEXTVAL
Syntax: CURRVAL
<sequence_name>.<seudo_column>
Ex:
S1.NEXTVAL
S1.CURRVAL
Example:
CUSTOMER
cid cname
CREATE SEQUENCE s2
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 5;
Output:
Sequence created.
/
enter value for cname:B
/
enter value for cname:C
/
enter value for cname:D
/
enter value for cname:E
/
enter value for cname: F
ERROR: sequence reached maxval
Example:
COURSE
CREATE SEQUENCE s4
START WITH 5001
INCREMENT BY 1
MINVALUE 1000
MAXVALUE 9999
NOCYCLE;
CREATE SEQUENCE s4
START WITH 5001
INCREMENT BY 1
MINVALUE 1000
MAXVALUE 9999
CYCLE;
• Default size: 20
• It improves the performance of generating
sequential integers.
CREATE SEQUENCE s7
START WITH 500
INCREMENT BY 1
MINVALUE 100 goes to DB
MAXVALUE 1000 s7
NOCACHE; 500+1
501+1
502
s7.nextval => 500
s7.nextval => 501
s7.nextval => 502
CREATE SEQUENCE s7
START WITH 500
INCREMENT BY 1
Cache
MINVALUE 100
MAXVALUE 1000 500
CACHE 100; 501
502
.
s7.nextval .
s7.nextval 599
NOTE:
Cache size must be less than one cycle
CREATE SEQUENCE s9
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
CYCLE;
NOTE:
CACHE size must be less than one cycle.
Output:
Sequence created.
OUTPUT:
Sequence created
Output:
Sequence created.
Output:
14 rows updated.
Output:
empno ename
-------------- ----------
1001
1002
1003
..
..
1014
Example:
• Using SEQUENCE
• Using IDENTITY [introduced in ORACLE 12C]
Syntax:
Example:
CUSTOMER
CID CNAME
1 A
2 B
3 C
cid
---------
1
2
3
Example:
COURSE1
CID CNAME
10 JAVA
20 PYTHON
30 C#
SEQUENCE s15
T1 T2
F1 F1
---- -------
1001 1006
1002 1007
1003 1008
1004
1005
Dropping Sequence:
Syntax:
DROP SEQUENCE <sequence_name>;
Example:
DROP SEQUENCE s1;
User_Sequences:
• "User_Sequences" is a system table / built-in
table.
• It maintains all sequences information.
Example:
DESC user_sequences;
Materialized View:
View:
View is a virtual table
View holds SELECT query
When we retrieve data through view, it runs SELECT query
Disadvantage:
• Less Performance
PERSON
PID PNAME STATE AGE GENDER AADHAR
Frequent operation:
CREATE VIEW v1
AS
SELECT state, count(*) as no_of_people
FROM person
GROUP BY state;
Materialized View:
• Materialized view is a Database Object.
• Materialized view is not virtual table. It means, it
contains physical data & it occupies the memory.
• Materialized view holds result of SELECT query
WHEREAS view holds SELECT query.
• It is used to maintain summarized data physically.
• It is mainly used in DataWare Housing for Data
Analysis.
• It holds precomputed result.
Advantages:
• It improves the performance.
• We can maintain local copy of remote database.
EMP
EMPNO ENAME JOB SAL COMM DEPTNO HIREDATE MGR
FREQUENT OPERATION:
Working with dept wise sum of salaries
VIEW M.VIEW
v1
mv1
SELECT ………
deptno sum_of_sal
10 …
20 …
SELECT * FROM v1; 30 …
--runs select query
--calculates dept wise sum of salaries
deptno sum_of_Sal
deptno sum_of_Sal 10 11000
10 21000 20 14000
deptno sum_of_Sal
deptno sum_of_Sal 10 11000
10 21000 20 14000
20 14000 30 19000
30 19000
After inserting new record,
ON DEMAND:
• In "ON DEMAND", we call a procedure to
refresh materialized view.
package_name.procedure_name
dbms_mview.refresh('MV1');
Example:
COMMIT;
EXEC dbms_mview.refresh('MV2');
ON COMMIT:
In this way,
WHEN COMMIT command is executed then
m.view will be refreshed.
COMMIT;