You are on page 1of 228

Friday, April 15, 2022 5:57 AM

Sandeep Sir:
Whatsapp:
Notes Link:
799 799 7809
https://bit.ly/oracle7am
send fee receipt, batch details
&gmail id

Note: Oracle DB 19c installation process


https://bit.ly/oracleinstall

Oracle @ 7:00 AM (IST) by Mr. Shiva chaitanya


Day-1 https://youtu.be/venvbCN-6Jw
Day-2 https://youtu.be/rWGcBnvlu8A
Day-3 https://youtu.be/8XjnzCRggSU
Day-4 https://youtu.be/Pg4f8CWfU2Q
Day-5 https://youtu.be/1focKe5AuAI

ORACLE 7AM Page 1


ORACLE
Thursday, April 14, 2022 7:25 AM

Data
Information
Database
DBMS
RDBMS
Metadata

Data:

People Places
Things
1234 nareshit
smartphone
Ravi 3 floors samsung
Oracle 8 classrooms
A71
567 200 30000
78.9 Black
manager 56.4
8000

• Data is a raw collection of facts about


people, places or things …etc.
• Data is unprocessed one.
• It is not in meaningful form.

Data Information

1234 sid sname marks


Ravi Data
1234 Ravi 500
500 Processing

Tyre
Bike
Engine connecting
handle
break

Information:
• If data is arranged in meaningful form then it is
called "Information".
• It is processed one.
• It is in meaningful form.

Types of data:

ORACLE 7AM Page 2


Data

Structured Data Unstructured Data

Letters audios
Digits videos
Special Symbols images
animations
Ex: documents
25
Ravi
H.NO. 1-2-123/A

Database:

College DB Bank DB OnlineShopping DB

Student Customer Products


Marks Transaction Customers
Fee Products Orders
Scolarship Employee Suppliers
Employee

• Database is a collection of interrelated data in


an organized form.
• It contains records & fields.

College DB

Student field

sid sname scity


1001 Kiran Hyd
record

Marks
sid M1 M2 M3 Total
1001 60 80 70 …

Fee
sid total fee paid fee balance
1001 15000 10000 5000

Online Shopping DB

Products
pid pname price qty

Customers
cid cname ccity

ORACLE 7AM Page 3


Customers
cid cname ccity

Orders
oid pid ord_date qty del_date cid

to edit the photos => Photoshop


to watch the movies => media player
to read pdf files => acrobat reader

To create & maintain the database => DBMS

DBMS:
• DataBase Management Software.
• It is a software that is used to create & maintain the
database.
• This software allows us to store, manipulate &
retrieve the data of Database.
• Manipulate => add [insert], delete & modify [update]
• retrieve => opening existing data

sid sname scity customer


1001 Vijay Delhi cid cname ccity
4567 Raju Hyd

RDBMS:
• RDBMS => Relational DataBase Management Software.
• Relation => Table
• In RDBMS, we create & maintain the database in the
form of tables.

Before 1960s => DB maintained in books


1960s => FMS
1970s => Hierarchical DBMS
Network DBMS

1976 => E.F.Codd => RDBMS => Relation => Table

1979 => RDBMS => ORACLE

ORACLE 7AM Page 4


CUSTOMER => Table

cid cname ccity


1234 Vijay Hyd row / record /
tuple / entity instance

column / field /
attribute / property

Table: is a collection of rows & columns


Row: record / tuple / entity instance
Column: Field / attribute / property

Field => holds individual values


Ex:
sid mobile_num cust_name

Record => is a collection of field values

RDBMS Exs:
ORACLE SQL SERVER My SQL DB2 Postgre SQL

ORACLE 21c
-----------------------
duration: 3 months 7.00 AM to 8.30 AM

SQL
PL/SQL

SQL
PL/SQL
------------
----------------
5 sub languages
Introduction
DDL
Control Structures
DML
Cursors
DRL
Exception Handling
DCL
Procedures
TCL
Functions
Built-In Functions
Packages
Clauses in SQL
Triggers
SET Operators
Working with LOBs
Joins
Dynamic SQL
Sub Queries
Collections
VIEWS
INDEXES
Materialized Views
Sequences

ORACLE 7AM Page 5


Sequences
Synonyms

Metadata:
• is Data about the data.
• It describes about the data

Customers

cid cname ccity


1234 Ramu Hyd

Ex:
Table Name => Customers
Column Name => cid, cname, ccity
Data Type => Number(4), Varchar2(20)
Field size => Number(4) => 4 => field size

Data raw collection of facts


Ex: Ramu 567
Informati If data is in meaningful form
on
Database colln of interrelated data
DBMS software used to create & maintain the
DB
RDBMS software used to maintain DB in the
form of tables
Metadata Data about the data

ORACLE

• ORACLE is the Relational DataBase Management


Software.
• Relation => Table
• It is used to create & maintain the Database in the
form of Tables.
ORACLE 7AM Page 6
form of Tables.
• It allows us to store, manipulate & retrieve the
data of Database.
• Manipulate => add, delete & modify
• Ex:
○ emp joined => add
○ emp left => delete
○ emp got promotion => update [modify]
• Retrieve => Opening existing data
• ORACLE 2nd Version introduced in 1979.
• ORACLE 21c is the latest version

RDBMS => 1976 => E.F.Codd => 12 rules

Larry Ellison

1977 => Software Development Laboratories


1979 => renamed company name: Relational Software Inc.
ORACLE 2nd version
1983 => renamed company name: Oracle Corp.

To communicate with Oracle Database we


can use 2 Languages:
• SQL
• PL/SQL

SQL => Structured Query Language


PL/SQL => Procedural language

Java => Programming Language

Programming Language => developing the software


software
=> set of programs
=> set of instructions

In C: In Java:
Function Method
-set of statements -set of statements

In PL/SQL:

Procedure => set of statements


Function => set of statements

ORACLE 7AM Page 7


Function => set of statements

SQL:
• Stands for Structured Query Language.
• SQL is used to write the queries.
• We write the queries to communicate with
the database.
• Query is a request that is sent to database
server.
• SQL is Non-Procedural Language. It means,
we cannot write a set of statements.
• SQL is 4GL [4th Generation Language]. In
4GL, we much concentrate on what to do
rather than how to do.
• SQL is Unified Language. It means, It is
common language for Relational Database
Management Softwares.

ORACLE SQL SERVER MY SQL DB2 Postgre SQL

SQL SQL SQL SQL SQL

• SQL provides operators.


• SQL provides built-in functions. Every function is
defined to perform particular task.
• SQL provides Joins Concept to retrieve the data
from multiple tables.

Ex:

emp e Dept d
empno ename job sal deptno deptno dname
1234 Ravi clerk 5000 20 10 Accounts
1235 .. .. .. 10 20 Research
30 Sales

emp dept

empno ename dname


1234 Ravi Research
1235 .. Accounts

SELECT e.empno, e.ename, d.dname


FROM emp e, dept d
WHERE e.deptno=d.deptno;

• SQL provides Sub Queries.


• SQL provides 5 sub languages:

DDL Create
[Data Definition Language] Alter
ORACLE 7AM Page 8
[Data Definition Language] Alter
Drop
Truncate
Rename
Flashback [Oracle 10g]
Purge [Oracle 10g]

DML Insert
[Data Manipulation Language] Update
Delete
Insert All [Oracle 9i]
Merge [Oracle 9i]

DCL / ACL Grant


[Data Control Language / Revoke
Accessing Control Language]
DRL / DQL SELECT
[Data Retrieval Language / Data
Query Language]
TCL Commit
[Transaction Control Language] Rollback
Savepoint

DDL:
• Data Definition Language.
• It deals with metadata.
student
sid sname

CREATE TABLE student 5001 Ravi


(
sid Number(4),
sname Varchar2(10),
Alter
marks Number(4)
);

DML:
• Data Manipulation Language.
• It deals with data.
• Manipulation => add [insert], delete & modify [update]
• student joined => insert
• student left => delete
• student mobile num changed => update

DCL:
• Data Control Language.
• It deals with data accessibility.

ORACLE 7AM Page 9


c##batch6pm
emp
grant
revoke

C##Raju

DRL:
• Data Retrieval Language.
• It deals with data retrievals.
• Retrieval => Opening existing data.

TCL:
• Transaction Control Language.
• It deals with Transactions.

Transaction => is a series of actions

Withdraw => ATM

Reads card info


Enter PIN
Valid PIN
Menu => withdraw
Enter amount: 10000
checks sufficient balance is there or not
gives money
update the account balance

Every Transaction must be successfully completed or


aborted

ORACLE:
• It is RDBMS.
• used to create & maintain the database.
• we maintain DB in the form of tables.

we use 2 Languages to work with


Oracle Database:
• SQL
• PL/SQL

SQL:
is a Query Language.

ORACLE 7AM Page 10


• is a Query Language.
• used to write the queries.
• Query => is a request that is sent DB server
• Ex: SELECT ename,sal FROM emp;

5 Sub Languages:
• DDL
• DML
• DCL
• DRL
• TCL

DDL:
• Data Definition Language.
• It deals with metadata.

SQL provides following DDL Commands:


• CREATE
• ALTER
• DROP
• TRUNCATE
• RENAME
• FLASHBACK [Oracle 10g]
• PURGE [Oracle 10g]

CREATE:
• used to create the Database Objects like
tables, views …etc.

DB OBJECTS:
• Table
• View
• Index
• Materialized View
• Sequence
• Synonym
• Procedure
• Trigger
• Function
• Package

Syntax to create the Table:

CREATE TABLE <Table_Name>


(
<field_name> <data_type> [constraint <constraint_name> <constraint_type>,

ORACLE 7AM Page 11


CREATE TABLE <Table_Name>
(
<field_name> <data_type> [constraint <constraint_name> <constraint_type>,
<field_name> <data_type> constraint <constraint_name> <constraint_type>,
……………………………… ,
…………………………………]
);

[ ] Optional
< > Any

Syntax of Column Definition:

<field_name> <data_type> constraint <constraint_name> <constraint_type>

Data Types in SQL:


• Data Type tells the type of data which a C / Java
column can hold. ----------------
• It also tells how much memory has to be
allocated for the data. int
• It identifies valid range for that column. float
char

sid sname DOB


1234 Ramu ---------
1235 Arun 25-dec-1998
1236 Kiran

sid Number(4) => -9999 to 9999

SQL provides following Data Types:

Number Related Number(p)


int
integer

Number(p,s)
float
real
binary_float
binary_double

Character Related Char(n)


Varchar2(n)
Long
CLOB

ORACLE 7AM Page 12


nChar(n)
nVarchar2(n)
nCLOB

Date & Time Related Date


Timestamp

Binary Related BFILE


BLOB

Number(p):
• It is used to hold integers.
• Integer => number without decimal places Ex: 23 567 1234
• p => Precision => Max Number of digits
• Max Precision is 38
• Precision => valid range => 1 to 38
• -9999…..99 [38 digits] to 9999..999 [38 digits]

Ex:

maths_marks maths_marks Number(3)


---------------------
45
78
93
100
40

empid empid Number(4)


-----------
7001
7002
7003

custid custid Number(6)


----------------
123456
123457
123458

Mobile_Num Mobile_num Number(10)


-----------------------
9012345678

Debit_card_num Number(16)

Aadhar_Num Number(12)

ORACLE 7AM Page 13


Number(p,s):
• It is used to hold floating point type data.
• floating point => Number with decimal places
○ Ex: 567.89 45.23 6.7
• p => Precision => Max Number of Digits
• s => Scale => Max number of decimal places
• p => Precision => valid range => 1 to 38
• s => Scale => valid range => -84 to 127

salary Max Salary => 100000.00


------------
6000.00 salary Number(8,2)
12000.00
25000.00 -999999.99 to 999999.99
15000.00
7000.00
3 subjects

Avrg
(100+100+100)/3 = 100
------------
100.00
67.89
76.54 Avrg Number(5,2)

-999.99 to 999.99

Height Precision => 2


------------- Scale => 1
5.8
6.0
5.4 Height Number(2,1)
6.2

-9.9 to 9.9

Number(p):
• Precision => Max no of digits

sid Number(4) -9999 to 9999


-------
5001
5002
5003

avrg Number(5,2) 100.00


--------

ORACLE 7AM Page 14


100.00
--------

Character Related Data Types:

Char(n)
Varchar2(n)
Long
CLOB

nChar(n)
nVarchar2(n)
nCLOB

Char(n):
• used to hold a set of characters [string]
• It is Fixed length Character Data Type.
• n => Max no of characters
• Default size: 1
• Max Size: 2000 Bytes

Ex:

State_Code State_Code Char(2)


-------------------
TS => 2
AP => 2
WB => 2
UP => 2

Country_Code Char(3)
-----------------------
IND
AUS
USA
PAK

Vehicle_Num Char(10)
------------------------
TS09AA1234

PAN_NUM Char(10)
---------------- sid Number(4)
ABC1D12345 ----
4567
1234
1A23 //Error
1#@2 //Error

Gender
ORACLE 7AM Page 15
Gender
Char
---------------
M
F

Note:
Number Data Type can accept digits only. It
cannot accept letters or special symbols.

Varchar2(n):
• it is used to hold a set of characters [string].
• it is variable length character data type.
• n => max no of characters.
• Default size: No default size. We must specify
the size

Ex:

sname Varchar2(10)
------------
Raju => 4
Sai => 3
naresh => 6
vijay => 5

pname Varchar2(20) Job Varchar2(10)


------------ -----------
laptop manager
smartphone clerk
smartwatch salesman

CREATE TABLE demo5(


f1 Char(10),
f2 varchar2(10)
);

f1 Char(10) f2 Varchar2(10)
sai sai
naresh4spaces naresh
Raju Raju

Differences between Char & Varchar2:

ORACLE 7AM Page 16


Char(n) Varchar2(n)

• Fixed Length Data Type • Variable Length data type

• Default size : 1 • No Default size. We must specify


the size.

• Max size: 2000 Bytes • Max size: 4000 Bytes

• When fixed length characters • When variable length chars are


are required then use "Char" required then use "Varchar2"

Ex: State_code, Gender Ex: emp_name, job

• Varchar2(n) Data Type introduced in


ORACLE 7 version
• In Oracle 2 to 6 versions we were using
"Varchar" Data type.

Any RDBMS must follow E.F Codd 12 Rules.


"Varchar" data type was not following one of
the E.F.Codd Rules.

Rule:
There should be difference b/w space and null
There should be difference b/w 0 and null

Varchar data type was treating space & null as same

null => when the value is unknown

m1
--------
45
56
24

89
0

Note:
Varchar data type was not following one of the

ORACLE 7AM Page 17


Varchar data type was not following one of the
E.F.Codd Rules. That's why they introduced
"Varchar2" data type in Oracle 7 vesion.

In latest versions,
Varchar & Varchar2 both are same.

Oracle company suggesting that,


Don't use "Varchar" data type. It is deprecated.

Long:
• is used to hold a set of characters [string].
• Max size: 2GB
• is used to hold large amounts of data.
• It is outdated.
• Some limitations are there on this data type:
○ We cannot use built-in functions on Long
Type Column.
○ We can create only one column as Long type
per a table.

CLOB:
• Character Large Object.
• It is used to hold a set of characters (String).
• It is used to hold large amounts of data.
• Max size: 4GB

Ex:
Experience_Summary CLOB

Product Features CLOB

Customer Feedback CLOB

100

maths Number(3) empno Number(4)


--------- ------------
56 1001
78 1002
66

sal Number(8,2) avrg Number(4,1)


----------- ------

ORACLE 7AM Page 18


sal Number(8,2) avrg Number(4,1)
----------- ------
100000.00 67.8
56.7
78.2
100.0

height Number(2,1)
----------
5.9
6.0
5.5
5.7
5.3

Gender Char / Char(1) State_Code Char(2)


-------------- --------------
M TS
F MR
AP
WB
ename Varchar2(20)
-------------
Raju
Charan
Sai

experience_summary CLOB
-----------------------------------

feedback CLOB

complaints CLOB

Char(n) Single Byte Char Data Types


Varchar2(n) ASCII Code Char Data Types
Long can hold English lang chars only
CLOB
nChar(n) Multi Byte Char Data Types
nVarchar2(n) UNI Code Char Data Types
nCLOB English + other lang chars

n => National

ASCII English only 255


ORACLE 7AM Page 19
ASCII English only 255
------------
0 t0 255

A = 65 a = 97
B = 66 b = 98
. .
. .
Z = 90 z = 12

UNI English + other language


--------
0 to 65535

256

Date:
• is used to hold date values.
• It can hold time values also.
• It can hold date, month, year, hour, minute &
second.
• It cannot hold fractional seconds.
• Default Date Format: dd-mon-rr
• to insert date value use to_date() function
• default time value is: 12:00:00 AM [mid night]
• Fixed length data type
• memory: 7 Bytes Ex:
DOB

DOJ

DOR

Ord_Date

Del_Date

CREATE TABLE demo9


(
dob date
);

INSERT INTO demo9 VALUES('23-dec-22');

INSERT INTO demo9 VALUES(to_date('17-OCT-21'));

ORACLE 7AM Page 20


INSERT INTO demo9 VALUES(to_date('17-OCT-21'));

In C / Java : In SQL:

"hello" 'hello'

RR

2022 2070

0 TO 49 20 => 2020 20 => 2120


19 => 2019 19 => 2119
50 TO 99 52 => 1952 52 => 2052
81 => 1981 81 => 2081

Changing date format:

Alter session set nls_date_format='dd/mm/yyyy';

Alter system => permanent

Alter session => temporary

Timestamp:
• introduced in Oracle 9i version.
• used to hold date & time values.
• It can hold date, month, year, hour,
minute, second & fractional seconds.
• memory: 11 Bytes
• fixed length data type

CREATE TABLE demo10


(
f1 timestamp
);

INSERT INTO demo10 VALUES(systimestamp);

INSERT INTO demo10 VALUES('23-dec-2019');

ORACLE 7AM Page 21


Date Timestamp

cannot hold fractional seconds can hold fractional seconds

7 Bytes 11 Bytes

Binary Related data types:

• BFILE
• BLOB

These 2 data types are used to maintain


multimedia objects like audios, videos, images
and documents.

emp BFILE d:
empno ename ephoto emps
1234 Ravi d:\emps\ravi.jpg ravi.jpg

emp BLOB
empno ename ephoto
1234 Ravi 12AD34F66abcd6575

BFILE to maintain multimedia object path

BLOB to maintain multimedia object inside of


DB

BFILE:
• BFILE => binary file
• used to maintain multimedia objects
• It is a pointer to multimedia object.
• It can be also called as "External Large Object".
• Because, multimedia object will be stored out of
the Database.
• It maintains path [locator] inside of Database.
• It is not secured one.
• max size: 4 GB
bfilename() function is used to maintain the path

ORACLE 7AM Page 22


• bfilename() function is used to maintain the path

BLOB:
• BLOB => Binary Large Object
• it is used to maintain multimedia objects.
• It can be also called as "Internal Large Object".
Because, multimedia object will be stored
inside of Database.
• It is secured one.
• max size: 4GB
• we need to write a separate program to store
multimedia object

Downloading & Installing Oracle Software:

www.oracle.com
RAM => 2GB
ORACLE 19c, 21c ORACLE 11g

RAM => 4GB


Hard Disk => 10GB
Windows 10, 11

Syntax for Creating user:

CREATE USER <user_name>


IDENTIFIED BY <password>
DEFAULT TABLESPACE <tablespace_name>
QUOTA <size> ON <tablespace_name>;

Creating Common User:


Common user name must be prefixed with c##

Log in as DBA: Tablespace


username: system .DBF
password: nareshit

CREATE USER c##batch7am


IDENTIFIED BY nareshit
DEFAULT TABLESPACE users
ORACLE 7AM Page 23
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO c##batch7am;

CREATING USER:

Log in as DBA:

username: system
password: nareshit
2 users:

ramu
CREATE USER c##batch7am c##ramu
IDENTIFIED BY nareshit
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect,resource TO c##batch7am;

Changing password of DBA:

username: sys as sysdba


password: [don't enter any pasword. press enter key]

ALTER USER system IDENTIFIED BY naresh;

Changing password of USER:

Log in as DBA:
user name: system
password: naresh

ALTER USER c##batch7am IDENTIFIED BY naresh;

Dropping user:

DROP USER c##ramu;


(or)
DROP USER c##ramu cascade;

student
sid sname scity

ORACLE 7AM Page 24


sid sname scity

Syntax to create the Table:

CREATE TABLE <table_name>


(
<field_name> <data_type> [constraint <constraint_name> <constraint_type>,
<field_name> <data_type> constraint <constraint_name> <constraint_type>,
…………………………………………………..,
…………………………………………..]
);

Examples on creating tables: 100


STUDENT
sid sname M1
1001 Ramu 67 sid => Number(4)
sname => Varchar2(10)
1002 Kiran 50
M1 => Number(3)

Creating Table:

CREATE TABLE student


(
sid Number(4),
sname Varchar2(10),
M1 Number(3)
);

To see Table Structure:

Desc Student;
Output:
sid Number(4)
sname Varchar(10)

To see Tables Information:

"user_tables" maintains all tables information

desc user_tables;

SELECT table_name FROM user_tables;

Syntax for INSERT command:

ORACLE 7AM Page 25


Syntax for INSERT command:

INSERT INTO <table_name>[(<column_list>)]


VALUES(<value_list>);

INSERT INTO student VALUES(1001,'Ramu',78);

INSERT INTO student VALUES(1002,'Vijay',45);

To see the table data:

SELECT sid,sname,M1 FROM student;


(or)
SELECT * FROM student;

* All COlumns

Inserting records using parameters:

&sid => parameter

INSERT INTO student VALUES(&sid,'&sname',&m1);


enter value for sid:1003
enter value for sname: Sai
enter value for m1: 74

1 row created
Run /
/
enter value for sid: 1004
enter value for sname: Ramu
enter value for m1:50

1 row created

Inserting Limited Column Values:

student
sid sname m1
1010 45
1011 Srinu

INSERT INTO student(sid,m1)


VALUES(1010,45);
ORACLE 7AM Page 26
VALUES(1010,45);

INSERT INTO student(sid,sname)


VALUES(1011,'Srinu');

Inserting limited column values by


changing the order: 1015 60
1016 Raju
INSERT INTO student(m1,sid)
VALUES(60,1015);

INSERT INTO student(sname,sid)


VALUES('Raju',1016);

INSERT INTO student


VALUES(1020,'Sridhar',80);

INSERT INTO student(sname,m1,sid)


VALUES('Ramesh',70,1030);

Ex-2:

EMPLOYEE
empno ename job sal gender doj
7001 A clerk 6000 M 25-jan-20

empno Number(4)
ename Varchar2(15)
job varchar2(10)
sal Number(8,2)
gender Char
doj date

CREATE TABLE employee


(
empno Number(4),
ename Varchar2(15),
Job Varchar2(10),
Sal Number(8,2),
Gender Char,
doj date
);

INSERT INTO employee


VALUES(1234,'A','Clerk',6000,'M','25-dec-2019');
(or)
INSERT INTO employee
VALUES(1234,'A','Clerk',6000,'M',
to_date('25-dec-2019'));
ORACLE 7AM Page 27
to_date('25-dec-2019'));

INSERT INTO employee


VALUES(&empno,'&ename','&job',&sal,
'&gender','&doj');
enter value for empno: 1235
enter value for ename: B
enter value for job: manager
enter value for sal: 10000
enter value for gender: F
enter value for doj: 13-oct-2018

/
enter value for empno: …
enter value for ename: ..

..
..

/
enter value for empno: …
enter value for ename: ..

..
..

CREATE TABLE <TN>


(
<fn> <dt> [constraint <constraint_name> <con_type>,
<fn> <dt> constraint <constraint_name> <con_type>,
………………,
……………..]
);

Constraint: Max marks: 100


• Constraint => Restrict / Limit min marks: 0
• Constraint is a rule that is
applied on a column. M1 => 0 to 100
• It is used to restrict the user M1 => Number(3)
from entering invalid data. student
• It is used to maintain accurate &
sid sname M1
quality data.
1001 A 78
• It is used to implement Data
Integrity. 1002 B 564 invalid
• Data Integrity means,
flight => 500 seats
maintaining accurate & quality
1 to 500
data.

passenger
ORACLE 7AM Page 28
• Data Integrity means,
flight => 500 seats
maintaining accurate & quality
1 to 500
data.

passenger
pid pname seatnum
1001 A 68
1002 B 794

ORACLE SQL provides following constraints:


• Primary key
• Not Null
• Unique
• Check
• Default
• References [Foreign Key]

Primary Key:
• should not accept duplicate values
• should not accept null values

Ex:
student
PK
sid sname M1
1001 Ravi 45
1002 Sai 50
1003 Ravi 50
Arun 80

1002 Vijay 60

Not Null:
• accepts duplicate values.
• does not accept null values.
• It demands for the value.

student

sid sname M1
1001 Ravi 45
1002 78
1003 Ravi 78

ORACLE 7AM Page 29


Unique:
• It does not accept duplicate values.
• It accepts null values.

Customer
cid cname mobile_num mail_id aadhar
1001 A ….. …
1002 B .. .. 1234
1003 C .. .. 1234
1004 D .. abcd@gmail
1005 E .. abcd@gmail
1006 F .. 5678

Constraint Duplicate Null


Primary Key
Not null
Unique

Primary Key = Unique + Not Null

Check:
• It is used to apply our own conditions

student
Max marks: 100
sid sname M1 0 to 100
101 A 78
102 B 55
103 C 674
103 D 100
104 E 101

Gender
--------------
M
F

ORACLE 7AM Page 30


F
Z => ERROR

Default:
It is used to apply default value to a column.

student

sid sname college_name college_city FEE


501 A nareshit hyd 15000
502 B nareshit hyd 5000

If we pass value, it takes that value.


If we don't pass the value, it takes default value

References [Foreign Key]:

Course Student
cid cname sid sname cid
10 Java 5001 A 20
20 Python 5002 B 50
30 HTML 5003 C 90
40 Oracle 5004 D 30
50 C#.Net 5005 E 100

Foreign Key refers to Primary key


values of another table.

dept employee
deptno dname empno ename deptno
10 sales 7001 A 30
20 accounts 7002 B 40
30 HR 7003 C 80
40 Research

ORACLE 7AM Page 31


Ex-1:
STUDENT
sid sname m1 sid Number(4) Primary key
1001 Ravi 60 sname Varchar2(10) Not Null
m1 Number(3) Check => 0 to 100

CREATE TABLE std


(
sid Number(4) primary key,
sname Varchar2(10) Not Null,
m1 Number(3) Check(m1>=0 and m1<=100)
);

INSERT INTO std VALUES(1001,'A',55);

INSERT INTO std VALUES(1002,'B',78);

INSERT INTO std VALUES(1001,'C',60);


--ERROR: unique constraint violated

INSERT INTO std VALUES(null,'D',45);


--ERROR: cannot insert null std.sid

INSERT INTO std VALUES(1005,'A',40);

INSERT INTO std VALUES(1006,null,80);


ERROR: cannot insert null into std.sname

INSERT INTO std VALUES(1006,'null',80);

INSERT INTO std VALUES(1007,'F',123);


ERROR: check constraint violated

Ex-2:
std1

sid sname cname ccity Fee


1001 A nareshit hyd 15000 15000.00
B

sid Number(4) Unique


sname Varchar2(10) not null
cname Varchar2(10) default 'nareshit'
ccity Varchar2(5) default 'HYD'
FEE Number(7,2) default 15000

CREATE TABLE std1


(
sid Number(4) Unique,
sname Varchar2(10) Not Null,
cname Varchar2(10) Default 'nareshit',
ORACLE 7AM Page 32
cname Varchar2(10) Default 'nareshit',
ccity Varchar2(5) Default 'HYD',
fee Number(7,2) Default 15000
);

INSERT INTO std1 VALUES(5001,'A');


--ERROR: not enough values

INSERT INTO std1(sid,sname) VALUES(5001,'A');

INSERT INTO std1(sid,sname) VALUES(null,'B');

INSERT INTO std1(sid,sname) VALUES(5001,'C');


ERROR: Unique constraint violated

INSERT INTO std1(sid,sname,fee) VALUES(5005,'D',5000);

Ex-3:
COURSE STD2
cid cname sid sname cid
10 JAVA 9001 A 20
20 PYTHON 9002 B 30
30 ORACLE 9003 C 80

CREATE TABLE course


(
cid Number(2) Primary Key,
cname Varchar2(10)
);

CREATE TABLE std2


(
sid Number(4),
sname Varchar2(10),
cid Varchar2(10) REFERENCES COURSE(cid)
);
ERROR:
column type incompatible with referenced column
type

Note:
• Primary Key column data type & foreign key
column data type must be same.

CREATE TABLE std2


(
sid Number(4),
sname Varchar2(10),
cid Number(2) REFERENCES COURSE(cid)
ORACLE 7AM Page 33
cid Number(2) REFERENCES COURSE(cid)
);

INSERT INTO course VALUES(10,'JAVA');

INSERT INTO course VALUES(20,'PYTHON');

INSERT INTO course VALUES(30,'ORACLE');

INSERT INTO std2 VALUES(9001,'A',30);


INSERT INTO std2 VALUES(9002,'B',10);

INSERT INTO std2 VALUES(9003,'C',90);


--ERROR: Integrity constraint violated

Assignment:

dept empoyee
deptno dname empno ename deptno
10 SALES 1001 Srinu 20
20 ACCOUNTS 1002 Kiran 30
30 RESEARCH 1003 Sai 70

deptno number(2) PK empno Number(4) PK


dname Varchar2(15) ename Varchar2(10)
deptno number(2) FK

CREATE TABLE dept


(
deptno number(2) primary key,
dname varchar2(15)
);

INSERT INTO dept VALUES(10,'SALES');


INSERT INTO dept VALUES(20,'ACCOUNTS');
INSERT INTO dept VALUES(30,'RESEARCH');

CREATE TABLE employee1


(
empno number(4) primary key,

ORACLE 7AM Page 34


empno number(4) primary key,
ename varchar2(10),
deptno number(2) references dept(deptno)
);

INSERT INTO employee1 VALUES(1001,'A',20);


INSERT INTO employee1 VALUES(1002,'B',10);

INSERT INTO employee1 VALUES(1003,'C',80);


ERROR: integrity constraint violated

Naming Constraints:
• Giving names to constraints is called "Naming
Constraints".
• When we define a field with constraint we can
give constraint name. If we don't give
constraint name implicitly ORACLE gives
constraint name. This name will be prefixed
with "sys_c".
• To disable or enable or rename or drop the
constraint this name is useful.
• "USER_CONSTRAINTS" maintain all
constraints information.
• Constraint name must be unique with in the
schema [user => c##batch7am]

to see constraint info:

SELECT
CONSTRAINT_NAME,CONSTRAINT_TYPE,
TABLE_NAME FROM user_constraints;

Ex-1:

std5
sid sname m1

sid Number(4) PK x
sname Varchar2(10) Not Null y
m1 Number(3) Check => 0 to z
100

CREATE TABLE std5


(
sid Number(4) constraint x primary key,
sname Varchar2(10) constraint y not null,
m1 number(3) constraint z check(m1>=0 and m1<=100)
);

ORACLE 7AM Page 35


We can specify constraints at 2 levels:
• Column Level
• Table Level

Column Level:
If constraint is defined in field definition then it is
called "Column level constraint"

Ex:
create table std6
(
sid number(4) primary key,
sname varchar2(10)
);

Table Level:
• If constraint is defined after defining all columns then
it is called "Table Level".

EX:
CREATE TABLE std7
(
sid number(4),
sname varchar2(10),
primary key(sid)
);

Note:
All 6 constraints can be created at column level.
[PK, U, NN, C, D, R]

Only 4 constraints can be created at table level.


[PK, U, C, R]
Not Null & default cannot applied at table level.

We cannot give name to default constraint.

Exs on table level constraints:

std8
sid sname m1

sid PK a
sname Not Null b
m1 Check c

ORACLE 7AM Page 36


CREATE TABLE std8
(
sid number(4),
sname Varchar2(10) constraint b Not Null,
m1 number(3),
constraint a primary key(sid),
constraint c check(m1>=0 and m1<=100)
);

unique(sid)

course1 std9
cid cname sid sname cid

cid PK p cid FK q
cname

CREATE TABLE course1


(
cid number(2),
cname varchar2(10),
constraint p primary key(cid)
);

CREATE TABLE std9


(
sid number(4),
sname varchar2(10),
cid number(2),
constraint q foreign key(cid) references course1(cid)
);

CREATE TABLE <TN>


(
<fn> <dt> constraint <cn> <ct>,
<fn> <dt> constraint <cn> <ct>,
….
);

DDL Commands:

CREATE
ORACLE 7AM Page 37
CREATE
ALTER
DROP
TRUNCATE
RENAME

FLASHBACK
PURGE

ALTER: emp
• ALTER => Change empno ename job
• ALTER command is used to change 1001 A clerk
structure of table.
• Using ALTER command we can:
○ add the columns
○ rename the columns
○ drop the columns
○ add the constraint
○ disable the constraint
○ enable the constraint
○ rename the constraint
○ drop the constraint
○ modify the field size
○ modify the data type

Syntax of ALTER Command:

ALTER TABLE <Table_Name> [add(field_definitions)];


[rename column <old_name> To <new_name>];
[drop column <column_name>];
[drop(<column_list>)];
[modify(<field_definitions>)];
[add constraint <con_name> <con_type>];
[rename constraint <old_name> TO <new_name>];
[disable constraint <constraint_name>];
[enable constraint <constraint_name>];
[drop constraint <constraint_name>];

add used to add the columns


drop column used to drop the column
drop to drop one or multiple columns
rename column used to rename the column
modify to modify data type or field size
add constraint to add the constraint
rename constraint to rename the constraint

ORACLE 7AM Page 38


rename constraint to rename the constraint
disable constraint to disable the constraint
enable constraint to enable the constraint
drop constraint to drop the constraint

Ex on ALTER:

std11 sid number(4)


sid sname sname varchar2(10)

CREATE TABLE std11


(
sid number(4),
sname varchar2(10)
);

Adding M1 column:

ALTER TABLE std11 ADD M1 Number(3);

desc std11;
sid
sname
m1

Adding M2 & M3 Columns:

ALTER TABLE std11 ADD(m2 number(3), m3 number(3));

Rename M3 to Maths:

ALTER TABLE std11 RENAME COLUMN m3 TO maths;

Dropping maths column:

ALTER TABLE std11 DROP COLUMN maths;

Dropping M1 & M2 Columns:

ALTER TABLE std11 DROP(m1,m2);

Modifying field size:

ALTER TABLE std11 MODIFY sname varchar2(20);

15
ORACLE 7AM Page 39
15
sname
-----------
raju
naresh
kiran
sai

sid
----
H-1001
H-1002
H-1003
D-2001
D-2002
P-3001
P-3003

Modifying the data type:

ALTER TABLE std11 Modify sid varchar2(10);

Add primary key constraint to sid:

ALTER TABLE std11 ADD CONSTRAINT c1


Primary Key(sid);

NOTE:
Using ADD CONSTRAINT we can add 4 constraints only.
PK, Unique, Check & Foreign key

Using MODIFY we can add not null & default constraints

Disabling constraint:

ALTER TABLE std11 DISABLE CONSTRAINT c1;

Enabling Constraint:

ALTER TABLE std11 ENABLE CONSTRAINT c1;

Renaming constraint:

ALTER TABLE std11 RENAME CONSTRAINT c1 TO aaa;

Dropping Constraint:

ALTER TABLE std11 DROP CONSTRAINT aaa;

ORACLE 7AM Page 40


ALTER TABLE std11 DROP CONSTRAINT aaa;

DROP
FLASHBACK [Oracle 10g]
PURGE [Oracle 10g]

DROP:
• It is used to drop the database objects like tables,
views, indexes …etc,

Syntax for dropping the table:

DROP TABLE <TABLE_NAME> [PURGE];

Ex:
DROP TABLE employee;

When we drop the table that table goes to recycle bin.

show recyclebin

-- it displays dropped tables list

FLASHBACK:
It is used to recollect the dropped DB Objects
from recycle bin.

Syntax:
FLASHBACK TABLE <table_name> TO
BEFOR DROP [RENAME TO <new_name>];

Ex:
FLASHBACK TABLE employee TO BEFORE DROP;

-- employee table will be restored

STUDENT Recyclebin
DROP STUDENT STUDENT

ORACLE 7AM Page 41


STUDENT

CREATE TABLE student

FLASHBACK TABLE student


TO BEFORE DROP RENAME
TO abc;

Purge:
• It is used to remove dropped
objects from recycle bin.

Syntax:
Purge Table <Table_name>;

Ex:
Purge Table employee;

--removes from recycle bin

drop table abc;


(or) Drop Table abc purge;
PURGE TABLE abc;

--Table will be dropped permanently

Emptying recyclebin:

Purge recyclebin;

TRUNCATE:
• used to delete all records from the table.
• It clears the memory.
• It deletes block by block.
• It works faster.
• When we want to delete all records then use it.

Syntax:
TRUNCATE TABLE <table_name>;

Ex:
TRUNCATE TABLE student;

-- deletes all records from table block by block


ORACLE 7AM Page 42
-- deletes all records from table block by block

ORACLE DB
TALESPACE
SEGMENT
Extent
Block => Oracle page [set of records]

1 Block => 8KB


1 Extent => can have 8 Blocks => 64 KB

RENAME:
• used to rename the DB Objects
like tables, views, indexes…etc.

Syntax:
RENAME <old_name> TO <new_name>;

Ex:
RENAME employee TO emp;

DDL Commands:
• Data Definition Language
• deals with metadata

CREATE to create DB Objects like tables


ALTER to change structure of table like
adding column, dropping column
…etc
DROP used to drop db objects like tables
FLASHBACK used to recollect dropped table from
recycle bin
PURGE used to delete dropped table from
recyclebin
TRUNCATE to delete all records block by block
RENAME used to rename the DB objects

DRL / DQL:
• DRL => Data Retrieval Language
• DQL => Data Query Language
• Retrieval => opening existing data.
• Query => is a request.
It deals with data retrievals.

ORACLE 7AM Page 43


• It deals with data retrievals.

ORACLE SQL provides only one DRL command


i.e:
• SELECT

SELECT:
• is used to retrieve the data from existing database.
• Ex: Check Balance, Online shopping
• Using this command we can retrieve:
○ All columns & All rows
○ Limited Columns
○ Limited Rows
○ Limited Rows & Columns

Syntax:

SELECT [DISTINCT] <column_list>/*


FROM <table_list>
[WHERE <condition>]
[GROUP BY <grouping_clumn_list>]
[HAVING <group_condition>]
[ORDER BY <column_list> Asc/Desc];

emp
empno ename job mgr hiredate sal comm deptno
7369 SMITH CLERK .. .. .. … ..
.. ..

Retrieving Limited Columns:

Display empno,ename & salary from emp table:

SELECT empno,ename,sal
FROM emp;

Execution Order:
FROM => selects all rows & all columns
SELECT => selects empno,ename & sal

Displaying all columns & all rows:

SELECT * FROM emp;

* All Columns

* empno,ename,job,sal,mgr,comm,hiredate,deptno

ORACLE 7AM Page 44


Note:
For our convenience purpose we write * to get all
columns. Implicitly ORACLE replaces * with all column
names.

Limited Rows:

Display the employee records whose salary is


greater than 2500:

SELECT * FROM emp


WHERE sal>2500;

FROM selects entire table


WHERE applies condition on every row. If
condition is TRUE then row will be
selected
SELECT it selects columns from the result of
WHERE

Displaying Limited Rows & Columns:

Display the emp records whose salary is >2500. Just


display emp names & salaries:

SELECT ename,sal
FROM emp
WHERE sal>2500;

Operators in SQL:
Operator: is a symbol that is used to perform
operations like arithmetic or logical operations.

Ex:
sal>2500
m1+m2+m3
Logical
Arithmetic

ORACLE SQL provides following operators:

Arithmetic + - * /
Relational / Comparison > >= < <= = <> / != / ^=
equals not equals
Logical AND OR NOT
SET UNION
UNION ALL
MINUS
INTERSECT
ORACLE 7AM Page 45
INTERSECT
Special IN NOT IN
Between And Not Between And
IS NULL IS NOT NULL
LIKE NOT LIKE

ANY
ALL
EXISTS
Others PIVOT
UNPIVOT

|| (Concatenation)

Arithmetic Operators:
• are used to perform Arithmetic
operations: IN C/JAVA
+ Addition 5/2 = 2
- Subtraction
* Multiplication
/ Division In SQL:
5/2 = 2.5

Calculate 10+20+30:

Dual:
SELECT 10+20+30 FROM dual;
• is a system table
• is created in "SYS" schema[user]
10+20+30
• Oracle Developers created DUAL table with
-----------------
one column & one row.
60
• For temporary calculations we can use this
table.
Changing column name:
• It is used to work with the non-Database
values
SELECT 10+20+30 AS total FROM
dual;

TOTAL
-----------------
60

Column Alias:
• We can change column headings by giving column
alias (another name / alternative name).
• "AS" keyword is used to give alias name for a column.
Using "AS" keyword is optional.
○ Ex:
SELECT 10+20+30 AS total FROM dual;
[or]
SELECT 10+20+30 total FROM dual;
• To maintain case & to give alias name in the form of
multiple words specify column alias in double quotes.
• Ex:
SELECT 10+20+30 total marks FROM dual;

ORACLE 7AM Page 46


SELECT 10+20+30 total marks FROM dual;
--ERROR

SELECT 10+20+30 AS "total marks" FROM dual;

total marks
----------------
60

empno ename job sal


1001
1002
1003

sid sname sub marks


1001 A m1 50
1001 A m2 60
1002 B m1 70
1001 m1

Examples on Arithmetic Operators:

+ - * /

student
sid sname M1 M2 M3
1001 A 50 80 70
1002 B 66 35 71

CREATE TABLE student


(
sid Number(4),
sname Varchar2(10),
M1 Number(3),
M2 Number(3),
M3 Number(3)
);

INSERT INTO student VALUES(1001,'A',50,70,60);


INSERT INTO student VALUES(1002,'B',55,35,82);

ORACLE 7AM Page 47


Calculate total marks & avrg marks:

SELECT sid,sname,
M1+M2+M3 as TOTAL,
(M1+M2+M3)/3 as AVRG
FROM student;

Calculate TA, HRA, ITAX and GROSS salary:


10% on sal as TA
20% on sal as HRA
5% on sal as TAX
GROSS = sal +TA + HRA -TAX

emp
empno ename job sal mgr hiredate comm deptno
1001 A 6000
1002 B 5000

SELECT empno,ename,sal,
sal*0.1 as TA,
sal*0.2 as HRA,
sal*0.05 as TAX,
sal+sal*0.1+sal*0.2-sal*0.05 as GROSS
FROM emp;

Calculate Annual Salary:

SELECT empno,ename,sal,
sal*12 AS "Annual Salary"
FROM emp;

Calculate experience:

SELECT empno,ename,hiredate,
trunc((sysdate-hiredate)/365) as experience
FROM emp;

Relational Operators [Comparison


Operators]:
• are used to compare 2 values.

> greater than


>= greater than or equals to
< less than
<= less than or equals to
= equals
!= / <> / ^= not equals

ORACLE 7AM Page 48


Examples on Relational Operators:

Display the emp records whose salary is > 2500:

SELECT * FROM emp


WHERE sal>2500;

SELECT is used to specify column list


WHERE is used to apply the condition on every row
FROM is used to specify table names

Display the emp records whose sal


is 3000 or greater:

SELECT * FROM emp


WHERE sal>=3000;

Display the emp records whose sal


is less than 1200:

SELECT * FROM emp


WHERE sal<1200;

Display the emp records whose


salary is 1500 or less:

SELECT * FROM emp


WHERE sal<=1500;

Display the emp records who joined after 1981:

SELECT * FROm emp


WHERE hiredate>'31-dec-1981';

Display the emp records who joined before 1981:

SELECT * FROm emp


WHERE hiredate<'1-jan-1981';

Display the emp records who are


working in deptno 20:

SELECT empno,ename,deptno
FROm emp

ORACLE 7AM Page 49


FROm emp
WHERE deptno=20;

Display the emp records who are not working


in deptno 20:

SELECT empno,ename,deptno
FROM emp
WHERE deptno!=20;

Display all managers records:

SELECT empno,ename,job
FROM emp
WHERE job='manager';

no rows selected

Note:
SQL is not case sensitive.
But, in string comparison it is case sensitive.
'MANAGER'='manager' => FALSE
'MANAGER' = 'MANAGER' => TRUE

SELECT empno,ename,job
FROM emp
WHERE job='MANAGER';

Display all emp records except clerks:

SELECT * FROM emp


WHER job!='CLERK';

Display the emp records who are having greater than 40


years experience:

SELECT * FROM emp


WHERE (sysdate-hiredate)/365>40;

Logical Operators:
• are used to perform logical operations.
• Oracle SQL provides following Logical Operators:
○ AND
○ OR
○ NOT

AND used to perform Logical AND operations

ORACLE 7AM Page 50


OR used to perform Logical OR operations
NOT used to perform Logical NOT operations

c1 c2 c1 AND c2 c1 OR c2
T T T T
T F F T
F T F T
F F F F

AND All conditions should be satisfied


OR At least one condition should be satisfied

C1 Not(C1)
T F
F T

Student max marks: 100


sid sname M1 M2 M3 min marks: 40 => pass
1001 A 60 50 80
1002 B 55 35 75

Display passed students records:

SELECT * FROM student


WHERE M1>=40 AND M2>=40 AND M3>=40;

Display failed students records:

SELECT * FROM student


WHERE M1<40 OR M2<40 OR M3<40;

emp
empno ename job sal hiredate mgr comm deptno

Display all managers & clerks records:

SELECT empno,ename,job
FROm emp
WHERE job='MANAGER' OR job='CLERK';

ORACLE 7AM Page 51


Display the emp records whose sal is more than
1600 and less than 3000:

SELECT * FROM emp


WHERE sal>1600 AND sal<3000;

Display all managers records who are earning more


than 2500:

SELECT empno,ename,job,sal FROM emp


WHERE job='MANAGER' AND sal>2500;

Display all managers records who joined after april 1981:

SELECT * FROM emp


WHERE job='MANAGER' AND hiredate>'30-apr-1981';

Display all managers records whose salary is more than


2500 and joined after april 1981:

SELECT empno,ename,job,sal,hiredate
FROM emp
WHERE job='MANAGER' AND sal>2500 AND
hiredate>'30-apr-1981';

Display emp records who are working in 10 & 30 depts:

SELECT * FROM emp


WHERE deptno=10 OR deptno=30;

Display the emp records whose names are SMITH


and ALLEN:

SELECT * FROM emp


WHERE ename='SMITH' OR ename='ALLEN';

Display the emp records whose empnos are


7369,7900:

SELECT * FROM emp


WHERE empno=7369 OR empno=7900;

Display all emp records except clerks:

ORACLE 7AM Page 52


SELECT * FROM emp
WHERE job!='CLERK'; job
-----
(or)
CLERK
SELECT * FROM emp
MANAGER
WHERE Not(job='CLERK');
CLERK
SALESMAN

Special Operators:
Special operators are also comparison operators.

IN:

displaying all managers, clerks & salesman


record:

SELECT * FROM emp


WHERE job='MANAGER' OR job='CLERK' OR
job='SALESMAN';
(OR)
SELECT * FROM emp
WHERE job IN('MANAGER','CLERK','SALESMAN');

IN:
• is used to compare column value with list of values.
• It avoids of writing multi equality conditions using
OR.

Syntax:

<column_name> IN(<value_list>)

displaying all managers, clerks & salesman


record:

SELECT * FROM emp


WHERE job='MANAGER' OR job='CLERK' OR
job='SALESMAN';
(OR)
SELECT * FROM emp
WHERE job IN('MANAGER','CLERK','SALESMAN');

Display emp records who are


working in 10 & 20 depts:

ORACLE 7AM Page 53


working in 10 & 20 depts:

SELECT empno,ename,deptno
FROM emp
WHERE deptno IN(10,20);

Display emp records whose names are SMITH,


WARD, BLAKE:

SELECT * FROM emp


WHERE ename IN('SMITH','WARD','BLAKE');

Display the emp records whose empnos are


7900, 7499, 7369:

SELECT * FROM emp


WHERE empno IN(7900,7499,7369);

Display all emp records excepts clerks and managers:

SELECT * FROM emp


WHERE job NOT IN('CLERK','MANAGER');

job
----
CLERK
ANALYST
MANAGER
SALESMAN

Between And:
• It is used to compare column value with a range of
values.

Syntax:

<column_name> BETWEEN <lower> AND <upper>

Display the emp records whose salary is


between 1600 to 3000:

SELECT empno,ename,sal
FROM emp

ORACLE 7AM Page 54


FROM emp
WHERE sal BETWEEN 1600 AND 3000;
(or)
SELECT empno, ename, sal
FROM emp
WHERE sal>=1600 AND sal<=3000;

SELECT empno,ename,sal
FROM emp
WHERE sal BETWEEN 3000 AND 1600;

No rows selected

Display the emp records who joined in 1981:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-JAN-1981' AND '31-DEC-1981';

Display the emp records who joined in 1981,1982 & 1983:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-JAN-1981' AND '31-DEC-1983';

Display the employee who are not joined in 1981:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate NOT BETWEEN '1-JAN-1981' AND
'31-DEC-1981';

Display the emp records whose empnos between


7300 to 7600:

SELECT empno,ename,job
FROM emp
WHERE empno BETWEEN 7300 AND 7600;

Bank DB

Home loan
ORACLE 7AM Page 55
Home loan
previous 6 months transactions

NOV 1-NOV-2021 TO 30-APR-2022


DEC
JAN
FEB Transaction
MAR Transaction_date Trans_type amount
APR

IS NULL:

NULL:
• NULL means empty or blank. Ex:
• When the value is unknown we insert NULL value.
• NULL is not equals to 0 or space. sid sname M1
• If Null is participated in operation then result will 1001 A 55
be null.
1002 B 0
• Ex: M1+M2+M3 => 50+40+NULL => NULL
1003 C
○ something + null = null
○ something-null = null
• For NULL comparison we cannot use = OPERATOR.
FOR NULL comparison use "IS NULL" OPERATOR.

NULL value can be inserted in 2 styles:


• Using NULL keyword
• By Inserting limited column values

student5

sid sname M1
1001 Ramu 45
1002 Kiran
1003 Sai

CREATE TABLE student5


(
sid Number(4),
sname Varchar2(10),
M1 Number(3)
);

1st way: using null keyword

INSERT INTO student5 VALUES(1001,'A',null);

2nd way: by inserting limited column values:

ORACLE 7AM Page 56


INSERT INTO student5(sid,sname) VALUES(1002,'B');

IS NULL:
• It is used to compare column value with NULL.

Syntax:

<column_name> IS NULL;

Display the employee records who are not getting


commission:

SELECT empno,ename,comm
FROM emp
WHERE comm IS null;

Display the emp records who are


getting commission:

SELECT empno,ename,comm
FROM emp
WHERE comm IS NOT NULL;

LIKE:
• It is used to compare column with text pattern

Syntax:

<Column_Name> LIKE <text_pattern>

*.jpg searches for all jpg files * 0 or any no of chars


a*.jpg searches for jpg files which are started with ? 1 char
a
?a*.jpg searches for jpg files which are having 2nd
char as a
??s*.jpg searches for jpg files which are having 3rd
char as s

In ORACLE SQL, There are 2 wildcard characters.

ORACLE 7AM Page 57


In ORACLE SQL, There are 2 wildcard characters.
They are:

_ replaces 1 character
% replaces 0 or any number of characters

Display the emp records whose


name is started with 'S':

SELECT empno,ename,sal
FROM emp
WHERE ename LIKE 'S%';

Display the emp records whose


name is ended with 'S':

SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%S';

Display the emp records whose


name's are having 'A':

SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%A%';

Display the emp records whose


name is having 4 chars:

SELECT empno,ename FROM emp


WHERE ename LIKE '____';

Display the emp records whose


names are ended with 'RD':

SELECT * FROM emp


WHERE ename LIKE '%RD';

Display the emp record who are earning 3 digits salary:

SELECT empno,ename,sal
FROM emp
WHERE sal LIKE '___';

Display all emp records whose name is not


started with 'S':

ORACLE 7AM Page 58


started with 'S':

SELECT empno,ename FROM emp


WHERE ename NOT LIKE 'S%';

Concatenation Operator:
Symbol: ||

to concatenate [combine] 2
strings, we use it

SELECT 'RAJ' || 'KUMAR' FROM dual;

RAJKUMAR

SELECT empno || ename FROM emp;

SQL
• DDL
• DRL
• DML
• DCL
• TCL

DML:
• Data Manipulation Language
• It deals with Data.
• Manipulation => INSERT / UPDATE / DELETE
• Ex:
○ employee joined => INSERT
○ employee got promotion => UPDATE
○ employee left => DELETE
• ORACLE SQL provides following DML
commands:
▪ INSERT
▪ UPDATE
▪ DELETE
▪ INSERT ALL [Oracle 9i]
▪ MERGE [Oracle 9i]

• All DML commands are not auto-committed.

ORACLE 7AM Page 59


• All DML commands are not auto-committed.
Whereas All DDL commands are auto-committed.
• After using DML command, to save the transaction, use
'COMMIT'.
• After using DML command, to cancel the transaction, use
Rollback

TCL Commands:

• Transaction => is a series of commands


○ A series of UPDATE commands
○ A series of INSERT commands
○ A series of DELETE commands
○ A series of SELECT commands
○ A series of UPDATE, INSERT, DELETE & SELECT
commands

Ex: check_balnce, withdraw, Placing Order

If transaction is successfully completed, use COMMIT.


If transaction is not successfully completed, use Rollback.

COMMIT [SAVE]:
• is used to save the transaction.
• When we perform DML operations like INSERT,
UPDATE & DELETE, these will be applied on
ORACLE INSTANCE [RAM]. To apply the changes of
Oracle Instance to Database, use COMMIT.
• When COMMIT is executed, it applies all changes of
ORACLE INSTANCE to ORACLE DATABASE.

Rollback [Undo All]:


• It is used to cancel previous transactions.
• It cancels all previous uncommitted transactions.
• After commit, we cannot use rollback.

INSERT => 1001 DELETE =>


INSERT => 1002 DELETE =>
INSERT => 1003 DELETE =>
ROLLBACK Rollback

ORACLE 7AM Page 60


INSERT
DELETE
UPDATE
Rollback

All DDL commands are auto-committed


All DML commands are not auto-committed

DDL command = DDL Command + Commit

CREATE => t1 => f1,f2 CREATE TABLE => t2


INSERT INSERT
INSERT INSERT
ROLLBACK CREATE TABLE => t3 => commit
INSERT
2 insertions will be canceled INSERT
Rollback

2 insertions will be cancelled

INSERT:
• is used to insert the records.
• Using this command we can:
○ insert single record
○ insert multiple records using parameters
○ Inserting limited column values
○ Inserting limited column values by changing the order
○ Copying records from existing table.

Syntax:

INSERT INTO <table_name>([<Column_List>])


VALUES(<value_list>);

Example On INSERT:

Customer
cid cname ccity
5001 A Hyd cid Number(4)
5002 B Delhi cname Varchar2(15)
5003 C Mumbai ccity Varchar2(10)

Creating Table:

CREATE TABLE customer


(
cid Number(4),
cname Varchar2(15),
ccity Varchar2(10)

ORACLE 7AM Page 61


ccity Varchar2(10)
);

Inserting single record:

INSERT INTO customer VALUES(5001,'A','Hyd');


INSERT INTO customer VALUES(5002,'B','Delhi');
COMMIT;

Inserting multiple records using parameters:

INSERT INTO customer VALUES(&cid,'&cname','&ccity');


Enter value for cid: 5003
Enter value for cname: C
Enter value for ccity: Mumbai

/
Enter value for cid: 5004
Enter value for cname: D
Enter value for ccity: Pune

Inserting Limited Column Values:


cid,cname

INSERT INTO customer VALUES(5005,'E');


ERROR: not enough values

INSERT INTO customer(cid,cname) VALUES(5005,'E');

Inserting limited column values by changing the order:

INSERT INTO customer(cname,cid)


VALUES('F',5006);

Copying records from existing table:

emp Customer
empno ename job sal cid cname ccity
clerk 7782 CLARK
clerk 7566 JONES
7782 CLARK manager 7698 BLAKE
7566 JONES manager
7698 BLAKE manager

Syntax for copying records from existing table:

INSERT INTO <table_name>([<column_list>])


<SELECT query>;

ORACLE 7AM Page 62


INSERT INTO customer(cid,cname)
SELECT empno,ename FROM emp
WHERE job='MANAGER';

Select query result will be copied into CUSTOMER table

DML:
• All DMLs are not auto-committed.
• COMMIT => to save the transaction
• ROLLBACK => to cancel the transaction

Update:
• This command is used to modify the data. emp
• Using this command, we can perform empno ename job sal
calculations. 1001 A clerk 6000
• Using this command we can update: 1002 B Manager 9000
○ single value of single record
○ multiple values of single record
○ a set of records
○ all records
○ using parameters

Syntax:

UPDATE <table_name>
SET <column_name>=<value>,
<column_name>=<value>, …..
[WHERE <condition>];

○ modifying single value of single record:

Increase 2000 rupees salary to an employee


whose empno is 7499:

UPDATE emp SET sal=sal+2000


WHERE empno=7499;

○ modifying multiple values of single record:

update job value as manager, sal value as 9000 to

ORACLE 7AM Page 63


update job value as manager, sal value as 9000 to
the employee whose empno is 7369:

UPDATE emp
SET job='MANAGER', sal=9000
WHERE empno=7369;

modifying a set of records:

Increase 10% salary to all managers:

UPDATE emp
SET sal=sal+sal*0.1
WHERE job='MANAGER';

Modifying all records:

Increase 20% sal to all employees:

UPDATE emp SET sal=sal+sal*0.2;

modifying records using parameters:

7369 => 10%


7499 => 20%
7521 => 15%
7900 => 5%

UPDATE emp SET sal=sal+sal*&per/100


WHERE empno=&empno;
enter value for per: 10
enter value for empno: 7369

/
enter value for per: 20
enter value for empno: 7499

/
enter value for per:
enter value for empno:

ORACLE 7AM Page 64


Ex-1:

student9
sid sname M1 M2 M3 Total Avrg
1001 A 60 80 50
1002 B 35 75 64

CREATE TABLE student9


(
sid Number(4), 100.00
sname Varchar2(10),
M1 Number(3),
M2 Number(3),
M3 Number(3),
Total Number(3),
Avrg Number(5,2)
);

INSERT INTO student9(sid,sname,m1,m2,m3)


VALUES(1001,'A',60,70,50);

INSERT INTO student9(sid,sname,m1,m2,m3)


VALUES(1002,'B',35,65,81);

Calculating total and average:

UPDATE student9
SET total=m1+m2+m3,avrg=(m1+m2+m3)/3;
(or)
UPDATE student9
SET total=m1+m2+m3;

UPDATE student9
SET avrg=total/3;

Ex-2:

employee12
empno ename job sal TA HRA TAX GROSS
1001 A clerk 10000
1002 B manager 15000

10% on sal as TA
20% on sal as HRA
5% on sal as TAX
GROSS = sal+ta+hra-tax

CREATE TABLE employee12


(
empno number(4),
ename varchar2(10),
job varchar2(10),
ORACLE 7AM Page 65
job varchar2(10),
sal Number(8,2),
TA Number(8,2),
HRA Number(8,2),
TAX Number(8,2),
GROSS Number(8,2)
);

INSERT INTO employee12(empno,ename,job,sal)


VALUES(1001,'A','CLERK',10000);

INSERT INTO employee12(empno,ename,job,sal)


VALUES(1002,'B','MANAGER',15000);

Calculating TA, HRA, TAX & GROSS:

UPDATE employee12
SET TA=sal*0.1,
HRA=sal*0.2,
TAX=sal*0.05,
GROSS=sal+sal*0.1+sal*0.2-sal*0.05;

Transfer all deptno 10 emps to deptno 20:

UPDATE emp SET deptno=20


WHERE deptno=10;

Increase 20% salary to the employees who are having


more than 40 years experience:

UPDATE emp SET sal=sal+sal*0.2


WHERE (sysdate-hiredate)/365>40;

Increase 15% sal & 5% comm to the employees who


are getting commission:

UPDATE emp
SET sal=sal+0.15, comm=comm+comm*0.05
WHERE comm is not null;

Set comm as 400 to the employees


who are not getting commission:

ORACLE 7AM Page 66


UPDATE emp SET comm=400
WHERE comm is null;

Increase 2000 rupees salary to the emps who joined in


1982:

UPDATE emp
SET sal=sal+2000
WHERE hiredate like '%82';
(or)
UPDATE emp
SET sal=sal+2000
WHERE hiredate BETWEEN '1-jan-1982' AND '31-dec-1982';

DELETE:
• used to delete the records.
• using delete command we can delete:
○ single record
○ a set of records
○ all records
○ using parameters

Syntax:

DELETE FROM <table_name>


[WHERE <condition>];

Deleting single record:

Delete an emp record whose empno is 7900:

DELETE FROM emp WHERE empno=7900;

Delete all salesman records:

DELETE FROM emp


WHERE job='SALESMAN';

Deleting all records:

DELETE FROM emp;


(or)
DELETE emp;

ORACLE 7AM Page 67


Deleting records using parameters:

DELETE FROM emp WHERE


empno=&empno;

Delete the emp records who are having more than 40


years experience:

DELETE FROM emp


WHERE (sysdate-hiredate)/365>40;

Differences between Truncate & Delete:

TRUNCATE DELETE

• DDL command • DML command

• It is auto-committed. • It is not auto-committed.

• It cannot be rolled back • it can be rolled back.

• It can delete all records • It can delete single record or a


only. It cannot delete set of records or all records
single record or a set of
records.

• WHERE clause cannot • WHERE clause can be used


be used

• Clears the memory • Does not clear the memory

• deletes page by page • deletes row by row


[block by block]

• It is faster • It is slower

Drop & Truncate:

Table => Table structure + Data

emp
empno ename sal
1001 A 5000
1002 B 7000

ORACLE 7AM Page 68


TCL Commands:
• Transaction Control Language.
• It deals with the transactions.

ORACLE SQL provides following TCL commands:


• COMMIT
• ROLLBACK
• SAVEPOINT

COMMIT [SAVE]:
• It is used to save the transaction.
• When 'COMMIT' command is executed, ORACLE
INSTANCE changes will be applied to ORACLE
DATABASE.

Syntax:
COMMIT;

ROLLBACK [UNDO ALL]:


• It is used to cancel the previous actions.
• After COMMIT, we cannot use ROLLBACK.
• ROLLBACK cancels uncommitted actions.

Syntax:
ROLLBACK [TO <savepoint_name>];

Ex:
ROLLBACK;

SAVEPOINT:
• used to set margin for rollback
• Syntax:
Savepoint <savepoint_name>;
Ex: Savepoint aaa;

INSERT SAVEPOINT aaa;


INSERT INSERT
INSERT INSERT
INSERT SAVEPOINT bbb;
INSERT INSERT
INSERT INSERT
Rollback; SAVEPOINT ccc;
INSERT
6 actions will be INSERT
canceled
Rollback TO ccc; => 2 actions
(or)
Rollback TO bbb; => 4 actions
(or)

ORACLE 7AM Page 69


(or)
Rollback TO aaa; => 6 actions

Ex on savepoint:

Create Table t1
(
f1 number(4),
f2 varchar2(10)
);

INSERT INTO t1 VALUES(1,'A');


INSERT INTO t1 VALUES(2,'B');
INSERT INTO t1 VALUES(3,'C');
INSERT INTO t1 VALUES(4,'D');
INSERT INTO t1 VALUES(5,'E');
INSERT INTO t1 VALUES(6,'F');

ROLLBACK; --6 actions will be cancelled

SAVEPOINT aaa;

INSERT INTO t1 VALUES(1,'A');


INSERT INTO t1 VALUES(2,'B');

SAVEPOINT bbb;

INSERT INTO t1 VALUES(3,'C');


INSERT INTO t1 VALUES(4,'D');

SAVEPOINT ccc;

INSERT INTO t1 VALUES(5,'E');


INSERT INTO t1 VALUES(6,'F');

Rollback to ccc;
Rollback to bbb;
Rollback to aaa;

COMMIT => to save the transaction


ROLLBACK => to cancel the transaction
SAVEPOINT => to set margin for rollback

SQL
DDL DRL DML TCL DCL

DCL / ACL:
• DCL => Data Control Language
• ACL => Accessing Control Language
It deals with data accessibility.
ORACLE 7AM Page 70
• It deals with data accessibility.
• Using DCL commands, we can implement the
security.

ORACLE SQL provides following DCL commands:


• GRANT
• REVOKE

GRANT:
• is used to grant the permissions
to other users c##batch7am c##batch6pm
emp
Syntax: GRANT
GRANT <privileges_list> REVOKE
ON <DB_Object_name>
TO <user_names>;

REVOKE:
• is used to cancel the
permissions from other users

Syntax:
REVOKE <privileges_list>
ON <Db_Object_Name>
FROM <user_names>;

Example on GRANT & REVOKE:

Create two users => c##userA, c##userB

CREATE USER c##userA


IDENTIFIED BY usera
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

CREATE USER c##userB


IDENTIFIED BY userb
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO c##userA,c##userB;

c##userA c##userB

create table t1(f1 number(4), c##batch7am


f2 varchar2(10)); emp

insert into t1 values(1,'a'); c##batch6pm


insert into t1 values(2,'b'); emp
commit;
SELECT * FROM c##userA.t1;
ERROR: table or view does not exist

GRANT select ON t1

ORACLE 7AM Page 71


ERROR: table or view does not exist

GRANT select ON t1
TO c##userB;
SELECT * FROM c##userA.t1;
f1 f2
-----------
1 A
2 B

INSERT INTO c##userA.t1 VALUES(3,'c');


ERROR: insufficient privileges

DELETE FROM c##userA.t1 WHERE f1=1;


ERROR: insufficient privileges

UPDATE c##userA.t1 SET f2='Ravi'


WHERE f1=1;
ERROR: insufficient privileges

GRANT insert,update
ON t1 TO c##userB;

INSERT INTO c##userA.t1 VALUES(3,'c');


1 row created

UPDATE c##userA.t1 SET f2='Ravi'


WHERE f1=1;
1 row updated

DELETE FROM c##userA.t1 WHERE f1=1;


ERROR: insufficient privileges

GRANT all ON t1
TO c##userB;

DELETE FROM c##userA.t1 WHERE


f1=1;
1 row deleted

GRANT all ON c##userA.t1


TO c##batch7am;
ERROR: insufficient privileges

GRANT all ON t1
TO c##userB
WITH GRANT OPTION;

--userB can give permissions to


other users

GRANT all ON c##userA.t1


TO c##batch7am;

ORACLE 7AM Page 72


TO c##batch7am;
GRANT succeeded

REVOKE all ON t1
TO c##userB;

select * from c##userA.t1;


ERROR: table or view does not
exist

SQL

DDL DRL DML TCL DCL

C S I C G
A U R R
D D S
T IA
R M
F
P

INSERT ALL:
• is used to insert multiple records in multiple
tables or single table.
• It avoids of writing multiple INSERT commands

emp emp1
empno ename job sal empno ename job sal
1001 .. .. ..
..
emp2
1010
empno ename job sal

emp3
empno ename job sal

Copying Table
Copying records

Copying Table:

Syntax:

CREATE TABLE <table_name>


AS
<SELECT query>;
ORACLE 7AM Page 73
CREATE TABLE <table_name>
AS
<SELECT query>;

Creating table from existing table:

CREATE TABLE employee1


AS
SELECT empno,ename,job,sal FROM emp;

-- emp table structure & data will be copied to employee1


-- with SELECT query result new table is created

CREATE TABLE employee2


AS
SELECT * FROM emp;

-- emp exact copy is created

copying a table structure from existing table


[without data]:

CREATE TABLE employee3


AS
SELECT * FROM emp WHERE 1=2;

--write any false condition


-- table structure will be copied
-- records will not be copied

Copying records:

Syntax:

INSERT INTO <table_name>


<select query>;

emp employee2

managers

INSERT INTO employee2


SELECT * FROM emp WHERE job='MANAGER';

ORACLE 7AM Page 74


INSERT ALL:
• introduced in Oracle 9i.
• is used to insert multiple records in multiple
tables or single table.
• It avoids of writing multiple INSERT commands
• It can be used in 2 ways:
○ Unconditional INSERT ALL
○ Conditional INSERT ALL

○ Unconditional INSERT ALL:

Syntax:

INSERT ALL
INTO <table_name>(<column_list>) VALUES(<value_list>)
INTO <table_name>(<column_list>) VALUES(<value_list>)
INTO <table_name>(<column_list>) VALUES(<value_list>)

<SELECT query>;

emp emp1
empno ename job sal empno ename job sal
1001
..
1010 emp2
empno ename job sal

emp3
empno ename job sal

Create emp1, emp2, emp3 tables


from emp table without data:

CREATE TABLE emp1


AS
SELECT empno,ename,job,sal
FROM emp WHERE 1=2;

CREATE TABLE emp2


AS
SELECT empno,ename,job,sal
FROM emp WHERE 1=2;

CREATE TABLE emp3


AS
SELECT empno,ename,job,sal
FROM emp WHERE 1=2;

ORACLE 7AM Page 75


INSERT ALL
into emp1 VALUES(empno,ename,job,sal)
into emp2 VALUES(empno,ename,job,sal)
into emp3 VALUES(empno,ename,job,sal)
SELECT empno,ename,job,sal FROM emp;

emp table data will be copied to


emp1, emp2 & emp3.

Conditional INSERT ALL:

Syntax:

INSERT ALL
WHEN <condition-1> THEN
into <table_name>(<column_list>) VALUES(<value_list>)
WHEN <condition-2> THEN
into <table_name>(<column_list>) VALUES(<value_list>)
WHEN <condition-3> THEN
into <table_name>(<column_list>) VALUES(<value_list>)
.
.
[ELSE
into <table_name>(<column_list>) VALUES(<value_list>)]
<SELECT query>;

emp emp1
empno ename job sal empno ename job sal
1001 MANAGER
CLERK
CLERK
emp2
MANAGER
empno ename job sal
SALESMAN

emp3
empno ename job sal

INSERT ALL
WHEN job='MANAGER' THEN
into emp1 VALUES(empno,ename,job,sal)

ORACLE 7AM Page 76


into emp1 VALUES(empno,ename,job,sal)
WHEN job='CLERK' THEN
into emp2 VALUES(empno,ename,job,sal)
ELSE
into emp3 VALUES(empno,ename,job,sal)
SELECT * FROM emp;

Assignment-1:
emp1 => 1980
emp
empno ename hiredate sal
emp2 => 1981

emp3 => others

Assignment-2:
emp emp1 deptno 10

empno ename deptno sal empno ename deptno sal

emp2 deptno 20
empno ename deptno sal

emp3 others
empno ename deptno sal

There are 2 types of database:

OLTP OLAP [DWH / DSS]

Online Transaction Processing Online Analytical Processing /


DataWare Housing /
Decision Support System

Used to perform day to day Used for data analysis.


operations It maintains Historical Data.

2022-23 2020
2021 transactions

2015 sales
C => CREATE 2016
R => READ
U => Update
READ operations only
D => Delete

ORACLE 7AM Page 77


Replication:
• The process of making duplicate
copy is called "Replication".

Replica => Duplicate Copy

Merge:
• is used to apply the changes of table to its Replica.
• It is a combination of Update & Insert Commands
• It can be also called as UPSERT command.

OLTP
OLAP
Customer1 Customer2
cid cname ccity cid cname ccity
1 A Bangalore 1 A Hyd
2 B Delhi 2 B Delhi
3 C Mumbai 3 C Mumbai
4 D Pune

Merge = UPdate + inSERT

Syntax:

MERGE INTO <target_table_name> <alias>


USING <source_table_name> <alias>
ON(<condition>)
WHEN matched THEN
UPDATE command
WHEN not matched THEN
INSERT command ;

MERGE INTO customer2 t


USING customer1 s
ON(s.cid=t.cid)
WHEN matched THEN
UPDATE SET t.cname=s.cname,t.ccity=s.ccity
WHEN not matched THEN
INSERT VALUES(s.cid,s.cname,s.ccity);

INSERT ALL & MERGE commands are introduced in ORACLE


9i

INSERT • we can insert multiple records in multiple


ALL tables
• It avoids of writing multiple INSERT commands
MERGE • used to apply changes of one table to its replica
• It avoids of writing another PL/SQL program.

ORACLE 7AM Page 78


ORACLE
=> RDBMS
=> create & maintain database in the form of tables

To work with ORACLE database, we use 2 languages:


1. SQL
2. PL/SQL

SQL:
• Structured Query Language
• It is used to write the queries.
• To communicate with database we write queries
• query => is a request sent to database

5 Sub Languages:

DDL- deals with metadata CREATE


ALTER
DROP
FLASHBACK (oracle 10g)
PURGE (oracle 10g)
RENAME
TRUNCATE
DML- deals with data INSERT
DELETE
UPDATE

INSERT ALL (oracle 9i)


MERGE (oracle 9i)
DRL- deals with data retrievals SELECT
DCL- deals with data accessibility GRANT
REVOKE
TCL- deals with transactions COMMIT
ROLLBACK
SAVEPOINT

ORACLE 7AM Page 79


Built-In Functions
Saturday, May 14, 2022 7:30 AM

Built-In Function:
• Function is a set of statements that gets
executed on calling.
• Function => Task / Action / Job
• Every function is defined to perform particular
task.
• Function ca take arguments & function can
return the result.
• Built-In Function can be also called as
"Predefined Function".

ORACLE SQL provides following Functions:

• String Functions [Text Functions]


• Aggregate Functions [Group Functions]
• Number Functions [Math Functions]
• Conversion Functions
• Date Functions
• Miscellaneous Functions

• String Functions [Text Functions]:

Upper() Substr() Lpad() ASCII()


Lower() Instr() Rpad() Chr()
InitCap() Soundex()
Length() Ltrim() Replace()
Concat() Rtrim() Translate()
Trim() Reverse()

Upper():
Used to convert the string to upper case.

Syntax:
Upper(<string>)

EX:
Upper('ramu') RAMU
Upper('sai') SAI

SELECT upper('arun') FROM dual;

ARUN

lower():
used to convert the string to lower
case.

ORACLE 7AM Page 80


case.

Syntax:
Lower(<string>)

Ex:
Lower('RAMU') ramu
LOWER('SAI') sai

SELECT lower('ARUN') FROM dual;

arun

Initcap():
used to get every word starting letter as
capital.

Syntax:
Initcap(<string>)

Ex:
Initcap('RAMU') Ramu
Initcap('SAI TEJA') Sai Teja

SELECT Initcap('RAM GOPAL VARMA')


FROM dual;

Ram Gopal Varma

Length():
used to find length of the string.

Syntax:
Length(<string>)

Ex:
Length('Arun') 4
Length('sai') 3

SELECT length('naresh') from dual;

concat():
• concatenate => combine
• used to combine 2 strings

Syntax:
concat(<string-1>,<string-2>)

Ex:
concat('sai','teja') saiteja
concat('sai',' ','teja') ERROR

ORACLE 7AM Page 81


concat('sai',' ','teja') ERROR
concat(concat('sai',' '),'teja') sai teja

SELECT concat('raj','kumar') from


dual;

rajkumar

Display emp names in lower case:

SELECT lower(ename),sal FROM emp;

Display every emp name's starting letter as


capital:

SELECT initcap(ename) as ename,sal


FROM emp;

Display the emp record whose name is blake


& when we don't know the exact case:

SELECT * FROM emp


WHERE lower(ename) = 'blake';

Display the emp records whose names are having


4 characters:

SELECT * FROM emp


WHERE ename LIKE '____';
(or)
SELECT * FROM emp
WHERE length(ename)=4;

Display the emp names whose names are


having more than 4 chars:

SELECT * FROM emp


WHERE length(ename)>4;

Example:

Player
pid fname lname name
1001 rohit sharma ----------
1002 virat kohli Rohit Sharma
Virat Kohli
ORACLE 7AM Page 82
pid fname lname name
1001 rohit sharma ----------
1002 virat kohli Rohit Sharma
Virat Kohli

CREATE TABLE player


(
pid number(4),
fname varchar2(15),
lname varchar2(15)
);

INSERT INTO player VALUES(1001,'ROHIT','SHARMA');


INSERT INTO player VALUES(1002,'VIRAT','KOHLI');
INSERT INTO player VALUES(1003,'SACHIN','TENDULKAR');

Adding name column:

ALTER TABLE player ADD name varchar2(30);

UPDATE player SET


name= initcap(concat(concat(fname,' '),lname));

Drop fname, lname columns:

ALTER TABLE player DROP(fname,lname);

Display the player names which


are having 12 chars:

SELECT * FROM player


WHERE length(name)=12;

Display the player names which


are having more than 12 chars:

SELECT * FROM player


WHERE length(name)>12;

Substr() & Instr():

Substr():
• is used to get sub string from the string.
• sub string => part of the string

Syntax:
Substr(<string>,<position>[,no_of_chars])
1 2 3 4 5 6 7 8 9
R a j K u m a r

+ve position from left side


-ve position from right side

ORACLE 7AM Page 83


-ve position from right side

Ex:
Substr('Raj Kumar',5) Kumar
Substr('Raj Kumar',6) umar
Substr('Raj Kumar',1,3) Raj
Substr('Raj Kumar',1,5) Raj K
Substr('Raj Kumar',6,3) uma
Substr('Raj Kumar,-4) umar
Substr('Raj Kumar',-4,3) uma
Substr('Raj Kumar',-5) Kumar
SubStr('Raj Kumar',-5,3) Kum

emp
empno ename job sal hiredate comm mgr deptno
7369 SMITH
7499 ALLEN

Add one column => mail_id


mail_id
--------------
SMI369@nareshit.com
ALL499@gmail.com

ALTER TABLE emp ADD mail_id varchar2(50);

Generating e-mail ids for all employees by taking


first 3 chars in ename & last 3 chars from empno as
username:

UPDATE emp SET


mail_id=Substr(ename,1,3) || Substr(empno,-3,3) ||
'@nareshit.com';

Instr():
used to get position of the sub string.

Syntax:

Instr(<string>,<sub_string>[,<position>,<occurrence>]

T h i s i s h i s w i s h

default position=1 occurrence=1

Ex:
Instr('This is his wish','is') 3
Instr('This is his wish','is',4) 6

ORACLE 7AM Page 84


Instr('This is his wish','is',4) 6
Instr('This is his wish','is',7) 10
Instr('This is his wish','is',11) 14
Instr('This is his wish','is',15) 0
Instr('This is his wish','is',1,2) 6
Instr('This is his wish','is',1,3) 10
Instr('This is his wish','is',4,2) 10
Instr('This is his wish','is',-1) 14
Instr('This is his wish','is',-1,2) 10
Instr('This is his wish','is',-4) 10
Instr('This is his wish,'is',-4,2) 6

Note:
If sub string is not found in the string it returns 0
If sub string is found in the string it returns position
number of the sub string.

Display the employee records


whose names are started with 'S':

SELECT * FROM emp


WHERE ename LIKE 'S%';
(or)
SELECT * FROM emp
WHERE Substr(ename,1,1)='S';

Display the emp records whose


names are ended with 'S':

SELECT * FROM emp


WHERE ename LIKE '%S';
(or)
SELECT * FROM emp
WHERE Substr(ename,-1,1) = 'S';

Display the emp records whose


names are ended with 'RD':

SELECT * FROM emp


WHERE ename LIKE '%RD';
(or)
SELECT * FROM emp
WHERE Substr(ename,-2,2)='RD';

Display the emp names whose


names are having 'M' char:

SELECT * FROM emp


WHERE Instr(ename,'M')>0;

ALLEN
SMITH

ORACLE 7AM Page 85


SMITH

Display the emp names whose name's starting


letter & ending letter is same:

ename
----------
SMITH
DAVID
SRINIVAS

SELECT * FROM emp


WHERE substr(ename,1,1)=substr(ename,-1,1);

Substr() used to get sub string from the string


Instr() used to get position of sub string

Lpad() & Rpad():

Lpad():
• pad => fill
• used to fill specified chars from left side.

Syntax:
Lpad(<string>,<max_size>[,<char_set>])

char_set => char/chars


default char => space

max_size-no_of_chars
10-4 = 6

Ex:
Lpad('Ramu',10,'*') ******Ramu
Lpad('Naresh',10,'@') @@@@Naresh
Lpad('Sai',12','#$') #$#$#$#$#Sai
Lpad('Raju',10) 6spacesRaju
Lpad('*',10,'*') **********
Lpad('X',10,'X') XXXXXXXXXX

Rpad():
• used to fill specified chars from right side.
• default char is: space

Syntax:
Rpad(<string>,<max_size>[,<char_set>])

ORACLE 7AM Page 86


Ex:
Rpad('Raju',10) Raju6spaces
Rpad('Raju',10,'*') Raju******
Rpad('Sai',10,'&$') Sai&$&$&$&

Amount Debited From XXXXXX7890

Acno => 1234567890

'Amount debited from ' || Lpad('X',6,'X') ||


Substr('1234567890',-4,4)

Amount debited from XXXXXX7890

Ltrim(), Rtrim() & Trim():

Ltrim():
• trim => remove
• used to remove unwanted characters from left
side.
• default char is: space

Syntax:
Ltrim(<string>[,<char_set>])

char_Set => char / chars

Exs:
Ltrim('***Raju***','*') Raju***
Ltrim(' Raju ') Raju3spaces

Rtrim():
used to remove unwanted chars from
right side.
default char is: space

Syntax:
Rtrim(<string>[,<char_set>])

Exs:
Rtrim('***Ramu***','*') ***Ramu
Rtrim(' Ramu ') 3spacesRamu

Trim():
used to remove unwanted chars from left side or right side
or both sides.

ORACLE 7AM Page 87


Syntax:
Trim(Leading/Trailing/Both '<char_set> FROM <string>)

Ex: @@@Raju@@@

Trim(Leading '@' FROM '@@@Raju@@@') Raju@@@


Trim(Trailing '@' FROM '@@@Raju@@@' @@@Raju
Trim(Both '@' FROM '@@@Raju@@@' Raju

Trim(' Ramu ') Ramu

Replace() & Transalte():

Replace():
used to replace search string with replace string.

Syntax:
Replace(<string>,<serach_string>,<replace_string>)

EX:
Replace('Rama Krishna','Rama','Sai') Sai Krishna
Replace('abcdefabctseabc','abc','XYZ' XYZdefXYZtseXY
) Z

Transalte():
used to replace search char with corresponding
replace char.

Syntax:
Translate(<string>,<search_chars>,<replace_chars>)

Exs:
Translate('hello','lo','ab') heaab
Replace('hello','lo','ab') helab
all l chars replaced with a
all o chars replaced with b

Translate('abcaaabbbcccabcaaabbabc','abc','XYZ') XYZXXXYYYZZZXYZXXXYYXYZ
Replace('abcaaabbbcccabcaaabbabc','abc','XYZ') XYZaaabbbcccXYZaaabbXYZ

Using Translate() function we can apply mask


chars for sensitive data like salaries, pin numbers,
passwords.

Translate(sal,'0123456789',')!@#$%^&**(')
sal
-------
8000
ORACLE 7AM Page 88
8000
9500
4600

Revrse():
used to get reverse string.

Syntax:
Reverse(<string>)

Ex:
Reverse('ramu') umar
Reverse(sai') ias

ASCII():
used to get ascii value of specific
char.

Syntax:
ASCII(<char>)

Ex: 0-255
ASCII('A') 65
ASCCI('B') 66
ASCCI('Z') 90
ASCII('a') 97
ASCII('b') 98
ASCII('z') 122
ASCII('0') 48

Chr():
used to get char of specified ASCII
value.

Syntax:
Chr(<ASCII_value>)

Ex:
Chr(65) A
Chr(97) a

Soundex():
• it used to display the records based on
sounds [pronunciation].
• When we don't know exact spelling, it is
useful.

Syntax:
Soundex(String)

Ex:
Soundex('SMYT')
Soundex('BLEK')
ORACLE 7AM Page 89
Soundex('BLEK')

SELECT * FROM emp


WHERE soundex(ename) = soundex('SMYT');

SELECT * FROM emp


WHERE soundex(ename) = soundex('SKAT');

upper() lpad() Substr() Replace()


lower() rpad() Instr() Transalte()
initcap()
length() Ltrim() ASCII() Soundex()
concat() Rtrim() Chr()
Trim() Reverse()

Aggregate Functions [Group Functions]:

Sum()
Avg()
Min()
Max()
Count()

Sum():
used to find sum of a set of values.

Syntax:
Sum(<column_name>)

Ex:
Sum(sal)
Sum(amount) amount
--------------
20000
30000
50000

Ex:
calculating sum of salaries of all emps:

SELECT sum(Sal) FROM emp;

calculate sum of salaries of deptno 20:

SELECT sum(sal) FROM emp


WHERE deptno=20;

ORACLE 7AM Page 90


calculate sum of salaries of all managers:

SELECT sum(sal) FROM emp


WHERE job='MANAGER';

Avg():
used to find average of a set of values.

Syntax:
Avg(<column_name>

Ex:
Calculate average salary:

SELECT avg(sal) FROM emp;

Calculate average salary of deptno 30:

SELECT avg(sal) FROM emp


WHERE deptno=30;

Calculate avrg salary of clerks:

SELECT avg(sal) FROM emp


WHERE job='CLERK';

Max():
used to get maximum value in a
set of values.

Syntax:
max(<column_name>

Ex:
Find Maximum salary in all emps:

SELECT max(Sal) FROM emp;

Find max salary in all managers:

SELECT max(Sal) FROM emp


WHERE job='MANAGER';

Find max salary in deptno 30:

SELECT max(Sal) FROM emp


WHERE deptno=30;

Min():
used to get minimum value in a set of values.

Syntax:
Min(<column_name>)

ORACLE 7AM Page 91


Min(<column_name>)

Ex:
calculate min salary in all emps:

SELECT min(sal) FROM emp;

calculate min salary in all managers:

SELECT min(Sal) FROM emp


WHERE job='MANAGER';

calculate min salary in deptno 30:

SELECT min(Sal) FROM emp


WHERE deptno=30;

count():
used to count number of records or no of column values.

Syntax:
Count(<column_name> / *)

Ex:
Find how many emps are getting commission:

SELECT count(comm) FROM emp;

Note:
If we specify column name, it will not count null
values.

Find number of emps / number of records:

SELECT count(*) from emp;


count(*) count(8)

SELECT count(*) FROM emp;

it displays number of records. number of records


returned by SELECT query will be counted.

SELECT count(8) FROM emp;

it displays number of records. number of 8s returned


by SELECT query will be counted.

count(8) works faster than count(*)

Find no of clerks:

ORACLE 7AM Page 92


SELECT count(*) FROM emp
WHERE job='CLERK';

Find no of emps in deptno 30:

SELECT count(*) FROM emp


WHERE deptno=30;

Sum() used to find sum value in a set of numbers


Avg() used to find average value in a set of numbers
Min() used to find min value in a set of numbers
Max() used to find max value in a set of numbers
Count() used to count no of records / column values

Find Max salary:

SELECT max(Sal) FROM emp;

Find Second max salary:

emp
empno ename job sal
SELECT max(sal) FROM emp
8000
WHERE sal<9000;
6000
9000 8000
7000 6000
7000

Sub Query:
• Writing query in another query is called "Sub
Query".
• First inner query gets executed. then outer query
gets executed.
• Inner query result will become input for the outer
query.

Finding 2nd Max salary:

SELECT max(sal) FROM emp


WHERE sal<(SELECT max(sal) FROM emp);

ORACLE 7AM Page 93


Find the emp name who is getting max salary:

SELECT ename FROM emp


WHERE sal=(SELECT max(Sal) FROM emp);

Find the emp name who is getting 2nd max salary:

SELECT ename FROM emp


WHERE sal=(SELECT max(sal) FROM emp
WHERE sal<(SELECT max(Sal) FROM emp));

Find 2nd min salary: 8000


9000
6000
SELECT min(sal) FROM emp 7000
WHERE sal>(SELECT min(Sal)
FROM emp); sal>min sal

8000
9000
7000

Find the emp name who is earning 2nd min salary:

SELECT ename FROM emp


WHERE sal=(SELECT min(sal) FROM emp
WHERE sal>(SELECT min(Sal) FROM emp));

Conversion Functions:
• are used to convert the data from one type
to another.
• There are 2 types of conversions:
○ Implicit Conversion
○ Explicit Conversion

○ Implicit Conversion:
This conversion will be done by the ORACLE
implicitly.

Ex:
SELECT '100'+'200' FROM dual;

300

ORACLE 7AM Page 94


SELECT * FROM emp WHERE empno='7369';

displays 7369 record

Explicit Conversion:
If conversion is done explicitly by using built-in function
then it is called "Explicit Conversion".

ORACLE SQL provides following conversion functions


for Explicit Conversion:
• to_char()
• to_date()
• to_number()

Char

Date
Number

to_char() [Date To String]:


• using this function we can convert date type to
string or number type to string.
• Using this function we can get date value in
different formats like US date Format, IND date
format …
US Date Format mm/dd/yyyy

IND Date Format dd/mm/yyyy

Syntax:
to_char(<date>,<format>)

FORMAT Example Result


yyyy to_char(sysdate,'yyyy') 2022
19-may-22
yy to_char(sysdate,'yy') 22
yyy to_char(sysdate,'yyy') 022
y to_char(sysdate,'y') 2
year / to_Char(sysdate,'year') twenty twenty-two

ORACLE 7AM Page 95


year / to_Char(sysdate,'year') twenty twenty-two
YEAR to_Char(sysdate,'YEAR') TWENTY TWENTY-TWO
mm to_char(sysdate,'mm') 05
mon / to_char(sysdate,'mon') may [jan, feb]
MON to_char(sysdate,'MON') MAY
month / to_char(sysdate,'month') may [january]
MONTH to_char(sysdate,'MONTH') MAY
dd gives day number in the month 19
to_char(sysdate,'dd')
d gives day number in the week 5
1-sun 2-mon ….. 7-sat
to_char(sysdate,'d')
ddd gives day number in the year 139
to_char(sysdate,'ddd')
dy / DY gives short weekday name
sun mon tue
to_char(sysdate,'dy')
to_char(sysdate,'DY') thu
THU
day / to_char(sysdate,'day') thursday
DAY to_char(sysdate,'DAY') THURSDAY

q used to get quarter number


1st qtr => jan - mar
2nd qtr => apr-jun
3rd qtr => jul-sep
4th qtr => oct-dec
to_char(sysdate,'q')
2
cc used to get century
to_char(sysdate,'cc') 21
HH / used to get hours part 8
HH12 to_char(sysdate,'HH')
HH24 used to get hours part in 24 hours
format
to_char(sysdate,'HH24') 8 [2:30 PM => 14]
MI to_char(sysdate,'MI') 08:10 => 10
SS to_char(sysdate,'SS') gives seconds
FF to_char(systimestamp,'FF') gives fractional
seconds
w weekday number in the month
to_char(sysdate,'w')
3
ww weekday number in the year
to_char(sysdate,'ww') 20
AD / BC to_char(sysdate,'BC') AD
AM / PM to_char(sysdate(sysdate,'hh:mi AM) 8:14 AM

2022
Display emp records with hiredates. Display
hiredate in IND date format [dd/mm/yyyy]: 1-jan-2022 1st day
31-dec-2022 365th day
SELECT ename, 19-may-2022 139th day
to_char(hiredate,'dd/mm/yyyy') as hiredate
FROM emp;

ORACLE 7AM Page 96


FROM emp;

23-DEC-82 => 23/12/1982

Display the emp records with hiredates. Display


hiredate in US DATE FORMAT [mm/dd/yyyy]:

SELECT empno,ename,
to_char(hiredate,'mm/dd/yyyy') as hiredate
FROM emp;

Display the emp records who joined in 1982:

hiredate between '1-jan-1982' and '31-dec-1982'


hiredate>='1-jan-1982' AND '31dec-1982'

SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'yyyy')=1982;

Display the emp records who joined in 1980,1982,1983:

SELECT empno,ename,
to_Char(hiredate,'dd/mm/yyyy') as hiredate
FROM emp
WHERE to_char(hiredate,'yyyy') IN(1980,1982,1983);

Display the emp records who joined in 4th quarter:


4th quarter => oct, nov, dec

SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'q')=4;

Display the emp records who joined in 1st & 4th quarters:

SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'q') IN(1,4);

Display the emp records who joined on Sunday:


d 1-sun
2-mon
SELECT empno,ename,hiredate

ORACLE 7AM Page 97


Display the emp records who joined on Sunday:
d 1-sun
2-mon
SELECT empno,ename,hiredate
FROM emp dy sun
WHERE to_Char(hiredate,'d')=1; day sunday
(or)
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'dy')='sun';
(or)

SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'day')='sunday';

no rows selected

SELECT empno,ename,hiredate
FROM emp
WHERE Rtrim(to_Char(hiredate,'day'))='sunday';

to_char() [Number to String]:


• using to_char(), we can convert number to string.
• using this, we can apply currency formats like
currency symbol, currency name, thousand
separator …etc.

sal
------------
5000 $5,000.00
9000
6000 USD5,000.00
4000

Syntax:
to_char(<number>[,<format>])

Ex:
to_char(123) '123'
to_char(123.45) '123.45'

ORACLE 7AM Page 98


FORMAT purpose
L currency symbol [$]
C currency name [USD]
9 Digit [0 to 9]
, Thousand separator
. Decimal Point

5000.00

Applying currency symbol:

SELECT to_char(5000,'L9999.99') FROM dual;

$5000.00

Applying currency name:

SELECT to_char(5000,'C9999.99') FROM dual;

USD5000.00

Applying currency symbol & thousand separator:

SELECT to_char(5000,'L9,999.99') FROM dual;

$5,000.00

Display emp records with salaries. Display the


salaries using currency symbol '$':

SELECT empno,ename,
to_char(sal,'L99,999.99') as SALARY
FROM emp; sal Number(7,2)

99999.99

sal Number(8,2)

999999.99

JAPAN => ¥
UK => £

NLS_TERRITORY AMERICA
NLS_CURRENCY $

Log in as DBA:
username: system
password: nareshit

ORACLE 7AM Page 99


ALTER session SET NLS_TERRITORY='UNITED KINGDOM';

ALTER session SET NLS_CURRENCY='£';

to_char() convert date to string to apply different date


formats.
to extract date, month, year,
quarter …etc
to_char() convert the number to to apply different currency
string formats.

to_date():
used to convert the string to date.

Syntax:
to_date(<string>[,<format>])

Ex:
to_date('23-DEC-2019') 23-DEC-2019
to_date('23 december, 2019') 23-DEC-2019
to_Date('23/12/2019') ERROR
to_Date('23/12/2019','dd/mm/yyyy') 23-DEC-2019
to_Date('12/23/2019') ERROR
to_Date('12/23/2019',mm/dd/yyyy') 23-DEC-2019

Extract date part from sysdate:

SELECT to_char(sysdate,'dd') FROM dual;

20

Extract date part from specific date:

SELECT to_char('23-DEC-2019','dd') FROM dual;

ERROR

SELECT to_Char(to_date('23-DEC-2019'),'dd') FROM


dual;
23

Extract year part from specific date:

SELECT to_Char(to_date('23-dec-2019'),'yyyy')
FROM dual;

2019

ORACLE 7AM Page 100


Display the week day name on which weekday
india got freedom:

SELECT to_char(to_Date('15-AUG-1947'),'day')
FROM dual;

Display the weekday name on which weekday SACHIN


born:
24-APR-1973

SELECT to_char(to_date('24-APR-1973'),'day') FROM


dual;

CREATE TABLE t1(f1 date);

INSERT INTO t1 VALUES('23-dec-2019');

INSERT INTO t1 VALUES(to_date('23-dec-2019'));

to_number():
• used to convert string to number.

Syntax:
to_number(<string>[,<format>])

Note:
string must be numeric string

Ex:
to_number('123') 123
to_number('123.45') 123.45
to_number('Ramu') ERROR
to_number('$5000.00') ERROR
to_number('$5000.00','L9999.99') 5000
to_number('USD5,000.00','C9,999.99') 5000

ORACLE 7AM Page 101


Number String Date

Math Functions:

power() abs() ceil()


sqrt() sign() floor()
sin() log() trunc()
cos() ln() round()
tan() mod()

power():
used to find power values

Syntax:
power(number,power)

Ex:
power(2,3) 8
power(5,3) 125

sqrt():
used to find square root value.

Syntax:
sqrt(number)

Ex:
sqrt(100) 10
sqrt(81) 9

sin(): used to sine values

Syntax:
sin(angle)

Ex:
sin(90*3.14/180)

cos(): used to find cosine values

Syntax:

ORACLE 7AM Page 102


Syntax:
cos(angle)

Ex:
cos(0*3.14/180)

tan(): used to tangent values.

Syntax:
tan(Angle)

Ex:
tan(45*3.14/180)

abs():
• used to get absolute value.
• absolute value => non-negative

Syntax:
abs(number)

Ex:
abs(5) 5
abs(-5) 5

sign():
used to check whether the number is +ve
or -ve or zero.

Syntax:
sign(number)

Ex:
sign(20) 1
sign(-20) -1
sign(0) 0

mod():
used to get remainder values

Syntax:
mod(number,dvisor)

Ex:
mod(5,2) 1
mod(20,7) 6

log():
used to get logarithmic values.

Syntax:
log(number,base)

Ex:

ORACLE 7AM Page 103


log(10,10) 1

ln():
used to find natural logarithmic values.

Syntax:
ln(number)

Ex:
ln(7)

Ceil():
used to get upper integer value.

Syntax:
Ceil(number) 123 124

Exs:
Ceil(123.45) 124
Ceil(5678.234) 5679

Floor():
used to get lower integer value.

Syntax:
Floor(number)

Ex:
Floor(123.45) 123
Floor(786.457) 786

Trunc():
used to remove decimal places.

Syntax:
Trunc(number,no_of_decimal_places)

Trunc(123.4567) 123
Trunc(123.456789,2) 123.45
Trunc(123.456789,3) 123.456

2nd argument as:


-1 rounded value in 10s
-2 rounded value in 100s
-3 rounded value in 1000s

Trunc() always gives lower value.

10,20,30,….100,110,120,130

Trunc(123.4567,-1) 120 120 to 130

ORACLE 7AM Page 104


Trunc(123.4567,-1) 120 120 to 130
Trunc(5678.234,-1) 5670 5670 to 5680
Trunc(786.4592,-1) 780 780 to 790
Trunc(1234.4567,-2) 1200 1200 to 1300
Trunc(1234.4567,-3) 1000 1000 to 2000

Trunc(456.789,-2) 400

400 to 500

Round():
• used to get rounded values.
• if value is >= avrg value, it takes upper
• if value < avrg value, it takes lower

Syntax:
Round(number,no_of_Decimal_places)

Exs:
Round(123.45) 123
Round(123.678) 124
Round(123.5678) 124
Round(123.5567,2) 123.56
Round(123.5547,2) 123.55
Round(45.67893,3) 45.679
Round(45.67833,3) 45.678
Round(123.4567,-1) 120
120 to 130
Round(127.456,-1) 130
120 to 130
Round(1234.5678,-2) 1200
1200 to 1300
Round(1284.5678,-2) 1300
1200 to 1300

120+130 = 250 /2 = 125

percentage
------------------ 78.69 78 & 79
78.69
65.45
56.52 78+79 = 157 /2 = 78.5
82.37
72.89

ORACLE 7AM Page 105


power() mod() floor() => 1 arg => returns int
sqrt() log() ceil() => 1 arg => returnn int
sin() ln()
cos() sign() trunc()
tan() abs() round()

Date Functions:
• sysdate
• systimestamp
• add_months()
• last_day()
• next_day()
• months_between()

sysdate:
• is used to get current system date.

Ex:
display current system date:

SELECT sysdate FROM dual;

23-may-22

display current system time:

SELECT to_char(sysdate,HH:MI:SS AM) FROM


dual;

7:29:11 AM

systimestamp:
used to get current system date & time

display system date & time:

SELECT systimestamp FROM dual;

Add_Months():
used to add / subtract months to/from a date.

Syntax:
Add_months(<date>,<no_of_months>)

no_of_months,
+ve adds the months

ORACLE 7AM Page 106


+ve adds the months
-ve subtracts the months

Display tomorrow's date:

SELECT sysdate+1 FROM dual;


24-may-22

Display yesterday's date:


SELECT sysdate-1 FROm dual;
22-may-22

Display the date which falls after 10 days from sysdate:


SELECT sysdate+10 FROM dual;

Adding 2 months to sysdate:


SELECT Add_Months(sysdate,2) FROM dual;
23-jul-22

Subtracting 2 months from sysdate:


SELECT Add_Months(sysdate,-2) FROM dual;
23-mar-22

Adding 1 year to sysdate:


SELECT add_months(sysdate,12) FROM dual;

Subtract 1 year from sysdate:


SELECT add_months(sysdate,-12) FROM dual;

Ex: 60 YEARS
employee
empno ename DOB DOR
1001 A 25-MAY-2000
1002 b 17-DEC-1998

CREATE TABLE employee


(
empno number(4),
ename varchar2(10),
DOB date,
DOR date
);

INSERT INTO employee(empno,ename,DOB)


VALUES(1,'A','25-may-2000');

INSERT INTO employee(empno,ename,DOB)


VALUES(2,'B','17-dec-1998');

ORACLE 7AM Page 107


Calculate Date Of Retirement:

UPDATE employee
SET DOR=Add_Months(DOB,12*60);

Ex:

India_CMs
state_id state_name CM_name start_date end_date
10 TS KCR 15-dec-2018
20 AP YS JAGAN 20-may-2019

UPDATE india_Cms
SET end_date=Add_Months(start_date,12*5);

Ex:

Insert into emp(empno,ename,hiredate)


VALUES(2001,'AA',sysdate);

Insert into emp(empno,ename,hiredate)


VALUES(2002,'BB',sysdate-1);

Insert into emp(empno,ename,hiredate)


VALUES(2003,'CC',Add_Months(sysdate,-1));

Insert into emp(empno,ename,hiredate)


VALUES(2004,'DD',Add_Months(sysdate,-12));

Trunc():
can be used to remove time value
from date value.

SELECT Trunc(sysdate) FROM dual;

SELECT Trunc(systimestamp)
FROM dual;

Display the emp records who joined today:

SELECT * FROM emp


WHERE hiredate = sysdate;
no rows selected

SELECT * FROM emp


WHERE trunc(hiredate) = trunc(sysdate);

Display the emp records who joined yesterday:

SELECT * FROM emp


WHERE trunc(hiredate) = trunc(sysdate-1);

ORACLE 7AM Page 108


WHERE trunc(hiredate) = trunc(sysdate-1);

Display the emp record who joined 1 month ago from sysdate:

SELECT * FROM emp


WHERE trunc(hiredate) = trunc(Add_Months(sysdate,-1));

Display the emp records who joined 1 year ago from sysdate:

SELECT * FROM emp


WHERE Trunc(hiredate) = Trunc(Add_Months(sysdate,-12));

Ex:

Sales
dateid amount
1-jan-2019 30000
2-jan-2019 50000
23-may-22 75000
22-may-22 60000
23-apr-22 80000
23-may21 50000

display today's sales:

SELECT * FROM sales


WHERE trunc(dateid) = truncc(sysdate);

display yesterday's sales:

SELECT * FROM sales


WHERE trunc(dateid) = trunc(sysdate-1);

display 1 month ago sales from sysdate:

SELECT * FROM sales


WHERE trunc(dateid) = trunc(Add_months(sysdate,-1));

display 1 year ago sales from sysdate:

SELECT * FROM sales


WHERE trunc(dateid) = trunc(Add_Months(sysdate,-12));

Last_day():
is used to get last day in the month.

Syntax:
Last_day(<date>)

Exs:

ORACLE 7AM Page 109


Exs:

Display last day in current month:

SELECT last_day(sysdate) FROM dual;

31-may-22

SELECT last_day('25-dec-2018') FROM dual;

31-dec-18

Display next month's first date:

SELECT last_day(sysdate)+1 FROM dual;

Display previous months's first date:

SELECT
Last_day(add_months(sysdate,-2))+1
FROM dual;

Display current month first date:

SELECT
Last_Day(add_months(sysdate,-1))+1
FROM dual;

23-apr-22
30-apr-22 + 1 = 1-may-22

Next_Day():
used to get next date based on weekday.
If we want to find next Sunday date,
next Monday date we can use Next_Day() function.

Syntax:
Next_Day(<date>,<week_Day_name>)
<week_Day_name>
Ex: sun
Sunday
find next Friday's date from sysdate: 1

SELECT next_day(sysdate,'fri') FROM dual;


27-may-22

find next month first Sunday date:

ORACLE 7AM Page 110


find next month first Sunday date:

SELECT Next_day(last_day(sysdate),'sun')
FROM dual;

find current month first Sunday date:

SELECT
Next_day(Last_day(Add_Months(sysdate,-1)),'sun')
FROM dual;

23-apr-22
30-apr-22

Find current month last Sunday date:

SELECT next_day(last_day(sysdate)-7,'sun') FROM


dual;

31-may-22 - 7 = 24-may-22

Months_Between():
used to get months between 2 dates.

Syntax:
Months_Between(date1,date2)

Calculate experience of emps:

SELECT empno,ename,
Round(Months_Between(sysdate,hiredate)/12) as
experience
FROM emp;

Calculate age of SACHIN:


24-APR-1973

SELECT
Months_Between(sysdate,'24-APR-1973')/12 as AGE
FROM dual;

Miscellaneous Functions:

• User
• UID
• Greatest()
• Least()
NVL()
ORACLE 7AM Page 111
• NVL()
• NVL2()
• Rank()
• Dense_Rank()

User:
used to get current user name.

Ex:
SELECT user FROM dual;
c##batch7am

UID:
used to get user ID

Ex:
SELECT UID,USER FROM dual;

Desc All_Users;

to see all usernames & ids:

SELECT username,user_id FROM


all_users;

Max(): used to max value in the column.

GREATEST():
used to find max [greatest] value in
specified list.

Syntax:
GREATEST(<value_list>)

EX:
SELECT
GREATEST(10,20,50,90,40,30)
FROM dual;

90

LEAST():
used to get min [least] value in specified
list.

Syntax:
LEAST(<value_list>)

Ex:
SELECT LEAST(10,90,80,5,80,4)
FROM dual;

ORACLE 7AM Page 112


Max() Greatest()

used to find used to find max value in row


max value in column

can take 1 argument can take variable length arguments

Min() Least()

• used to get min value • used to get min value in the


in column rows.

• can take 1 argument • can take variable length


arguments

NVL():

something+null = null
something-null = null

• Used to replace NULL value with other value.


• When NULL is participated in operation then result
will be NULL.
• To get accurate values we need to replace null value
with other value.

Syntax:
NVL(value1,value2)

Ex:
SELECT NVL(100,200) FROM dual;
100

SELECT NVL(null,200) FROM dual;


200

If first argument is not null, NVL() returns first


argument
If first argument is NULL, NVL() returns 2nd
argument.

Calculate total salary of all emps [sal+comm]:

SELECT empno,ename,sal,comm,
sal+NVL(comm,0) as "total salary"
FROM emp;

Display 'N/A' if comm is null:


ORACLE 7AM Page 113
Display 'N/A' if comm is null:

SELECT empno,ename,
NVL(comm,'N/A') as comm
FROM emp;
ERROR: data type mismatch
comm => number
N/A => string

SELECT empno,ename,
NVL(to_char(comm),'N/A') as comm
FROM emp;

Ex:
student
sid sname M1
101 Ramu 56
102 Kiran
103 AA 45
104 BB

Replace null values with 'AB':

SELECT sid,sname,
NVL(m1,'AB') FROM student;

ERROR: data type mismatch

SELECT sid,sname,
NVL(to_char(m1),'AB') FROM student;

NVL2():
used to replace null and not null values.

Syntax:
NVL2(value1,value2,value3)

Ex:
NVL2(100,200,300) 200
NVL2(null,200,300) 300

If first argument is not null, NVL2() returns 2nd arg


If first argument is null, NVL2() returns 3rd arg

If comm is null replace it with 300.


If comm is not null increase 500 rupees comm:

SELECT empno,ename,comm,
NVL2(comm,comm+500,300) as comm
FROM emp;

ORACLE 7AM Page 114


NVL() used to replace null values
takes 2 args
NVL2() used to replace nulls and not nulls
takes 3 args

Rank():
used to apply ranks to records according specific
column.

Syntax:
Rank() Over(ORDER BY column_name DESC/ASC)

default => ASC

Dense_Rank():
used to apply ranks to records according specific column.

Syntax:
Dense_Rank() Over(ORDER BY column_name DESC/ASC)

default => ASC

Marks Rank Marks Dense_Rank


720 720
850 850
930 930
850 850
640 640
720 720
850 850
930 930
578 578

Give the ranks to emp records according


to salary:

SELECT empno,ename,sal,
Rank() Over(ORDER BY sal DESC) as Rnk
FROM emp;

SELECT empno,ename,sal,
Dense_Rank() Over(ORDER BY sal DESC) as Rnk
FROM emp;

Apply rans to emp records according to salaries in


descending order. If salary is same check with hiredate. If
experience is more give highest rank.
ORACLE 7AM Page 115
experience is more give highest rank.

SELECT empno,ename,sal,hiredate,
Dense_Rank() Over(Order BY sal Desc, hiredate Asc) as Rnk
FROM emp;

ORACLE 7AM Page 116


CASE Expressions
Wednesday, May 25, 2022 7:27 AM

CASE Expression:
• Introduced in Oracle 9i.
• used to implement 'If..Then..Else' in SQL.
• It avoids of writing PL/SQL program.
• can be used in 2 ways:
○ Simple CASE [like switch in C / JAVA]
○ Searched CASE [like if else if in C / JAVA]

Syntax of Simple CASE:

CASE <column_name>
WHEN <value-1> THEN <return_expression>
WHEN <value-2> THEN <return_expression>
..
..
[ELSE <return_expression>]
END

Display emp records along with job titles


as following:
manager => boss
president => big boss
clerk => worker
others => employee

SELECT empno,ename,
CASE job
WHEN 'MANAGER' THEN 'BOSS'
WHEN 'PRESIDENT' THEN 'BIG BOSS'
WHEN 'CLERK' THEN 'WORKER'
ELSE 'EMPLOYEE'
END as JOB
ORACLE 7AM Page 117
END as JOB
FROM emp;

Update emp salaries according to deptno


as following:
deptno=10 => increase 10%
deptno=20 => increase 20%
deptno=30 => increase 15%
others => increase 5%

UPDATE emp SET sal=


CASE deptno
WHEN 10 THEN sal+sal*0.1
WHEN 20 THEN sal+sal*0.2
WHEN 30 THEN sal+sal*0.15
ELSE sal+sal*0.5
END;

SIMPLE CASE It can check equality condition only


SEARCHED CASE It can check any type condition

SEARCHED CASE:

Syntax:

CASE
WHEN <Condition-1> THEN <return_expression>
WHEN <Condition-2> THEN <return_expression>
..
..
[ELSE <return_expression]
END

ORACLE 7AM Page 118


CASE
WHEN <Condition-1> THEN <return_expression>
WHEN <Condition-2> THEN <return_expression>
..
..
[ELSE <return_expression]
END

Display salary ranges as following:


sal>4000 => HiSal
sal<4000 => LoSal
sal=4000 => AvrgSal

SELECT empno,ename,sal,
CASE
WHEN sal>4000 THEN 'HiSal'
WHEN sal<4000 THEN 'LoSal'
WHEN sal=4000 THEN 'AvrgSal'
END as "Salary Range"
FROM emp;

NOTE:
If all conditions are FALSE, if we
don't specify ELSE, by default it
returns NULL.

Find the result of a student: max marks:100


min marks: 40 for pass
STUDENT
sid sname M1 M2 M3
ORACLE 7AM Page 119
sid sname M1 M2 M3
1001 A 60 80 70
1002 B 80 30 50

SELECT sid,sname,
CASE
WHEN m1>=40 AND m2>=40 AND m3>=40 THEN 'PASS'
ELSE 'FAIL'
END as RESULT
FROM student;

alter table student add result varchar2(10);

UPDATE student SET result=


CASE
WHEN m1>=40 AND m2>=40 AND m3>=40 THEN 'PASS'
ELSE 'FAIL'
END;

In ORACLE SQL,
'IF..THEN..ELSE' can be implemented using 2 ways:
• using CASE expression [From Oracle 9i version onwards]
• using Decode() Function [Before Oracle 9i version]

Decode():
• it is used to implement 'IF..THEN..ELSE'.
• It can check equality condition only.
It is same as SIMPLE CASE.
ORACLE 7AM Page 120
• It is same as SIMPLE CASE.

Syntax:

decode(<column_name>,
<value1>,<return_expression>,
<value2>,<return_expression>,
………… , …………………………… ,
<else_Return_expression>)

Display emp records with job titles


as following:
manager => boss
president => big boss
clerk => worker
others => employee

SELECT empno,ename,
decode(job,
'MANAGER','BOSS',
'CLERK','WORKER',
'PRESIDENT','BIG BOSS',
'EMPLOYEE') as JOB
FROM emp;

Update emp salaries as following:


deptno=10 => increase 10%
deptno=20 => increase 20%
deptno=30 => increase 15%
others => increase 5%

UPDATE emp SET sal=


ORACLE 7AM Page 121
UPDATE emp SET sal=
decode(deptno,
10,sal+sal*0.1,
20,sal+sal*0.2,
30,sal+sal*0.15,
sal+sal*0.05);

Decode() CASE expression

• can check equality • SEARCHED CASE can check any


condition only. type of condition.

• It is Not ANSI standard • It is ANSI standard.

• It is not Portable. • It is portable.

ORACLE SQL SERVER

decode() decode()

ORACLE SQL SERVER

CASE CASE

ORACLE 7AM Page 122


Interval Expressions
Thursday, May 26, 2022 7:30 AM

Interval Expression:
• introduced in Oracle 9i.
• using it, we can add/ subtract days, months,
years to/from a date.
• We can also add/subtract hours, minutes and
seconds to/from a time also.

Adding 2 days to sysdate:

SELECT sysdate+interval '2' day FROM dual;

Adding 2 months to sysdate:

SELECT sysdate+interval '2' month FROM dual;

Adding 2 years to sysdate:

SELECT sysdate+interval '2' year FROM dual;

Subtracting 2 days from sysdate:

SELECT sysdate-interval '2' day FROM dual;

Subtracting 2 months from sysdate:

SELECT sysdate-interval '2' month FROM dual;

Subtracting 2 years from sysdate:

SELECT sysdate-interval '2' year FROM dual;

ORACLE 7AM Page 123


Adding 100 days to sysdate:

SELECT sysdate+interval '100' day FROM dual;


ERROR: default precision is 2 => 100 => 3digits

SELECT sysdate+interval '100' day(3) FROM dual;

Adding 1 and half year to sysdate:

SELECT sysdate+interval '1-6' year to month FROM


dual;

Adding 2 hours to system time:

SELECT systimestamp+interval '2' hour from dual;

Adding 30 minutes to system time:

SELECT systimestamp+interval '30' minute from


dual;

Adding 50 seconds to system date:

SELECT systimestamp+interval '50' second from


dual;

Adding 1 and hour to system time:

SELECT systimestamp+interval '1:30' hour to minute


from dual;

ORACLE 7AM Page 124


Adding 2 days 3 hours to system time:

SELECT systimestamp+interval '2 3' day to hour


from dual;

Adding2 days 3 hours 30 minutes to system time:

SELECT systimestamp+interval '2 3:30' day to


minute from dual;

sales
dateid amount
1-jan-2019 60000
2-jan-2019 90000
3-jan-2019 80000
..
..

CREATE TABLE sales


(
dateid date,
amount number(8,2)
);

insert into sales values(sysdate,60000);

insert into sales values(sysdate-1,50000);


ORACLE 7AM Page 125
insert into sales values(sysdate-1,50000);

insert into sales values(sysdate-interval '1' month,80000);

insert into sales values(sysdate-interval '1' year,95000);

Display today's sales:

SELECT * FROM sales


WHERE dateid=sysdate;
no rows selected

SELECT * FROM sales


WHERE trunc(dateid)=trunc(sysdate);

Display yesterday's sales:

SELECT * FROM sales


WHERE trunc(dateid)=trunc(sysdate-1);

Display 1 month ago sales from sysdate:

SELECT * FROM sales


WHERE trunc(dateid)=trunc(sysdate-interval '1' month);

Display 1 year ago sales from sysdate:

SELECT * FROM sales


WHERE trunc(dateid)=trunc(sysdate-interval '1' year);

ORACLE 7AM Page 126


ORACLE 7AM Page 127
Clauses
Thursday, May 26, 2022 8:09 AM

Clauses in SELECT command:

Syntax of SELECT query:

SELECT [DISTINCT/ALL] <column_list / *>


FROM <table_list>
[WHERE <condition>]
[GROUP BY <grouping_column_list>]
[HAVING <group_condition>]
[ORDER BY <column_name> ASC/DESC];

Clauses in SELECT command:

Clause:
• Clause is a part of query.

ENGLISH SQL
Sentences Queries
Words Clauses

Clauses of SELECT query:

• SELECT
• FROM
• WHERE
• DISTINCT
• GROUP BY
• HAVING
• ORDER BY

ORACLE 7AM Page 128


SELECT ename,sal
FROM emp
WHERE sal>3000;

SELECT:
is used to specify the column list.

Ex:
SELECT ename,sal
SELECT sid,sname,scity
SELECT * => * = all columns

FROM:
used to specify table list.

Ex:
FROM emp
FROM emp,dept

WHERE:
• is used to specify the condition.
• this condition will be applied on every row.

Ex:
WHERE job='MANAGER'
WHERE sal>3000

DISTINCT:
is used to avoid duplicate rows.

ORACLE 7AM Page 129


Examples:
Display the job titles offered by the organization:

emp
empno ename job deptno
MANAGER 10
CLERK 30
CLERK 30
MANAGER 10
ANALYST 20
ANALYST 20
CLERK 30

SELECT DISTINCT job FROM emp;

MANAGER
CLERK
ANALYST

Display the deptnos available in organization:

SELECT DISTINCT deptno FROM emp;

Ex:

STUDENT
sid sname course
1001 Ramu JAVA
1002 ORACLE
1003 ORACLE
1004 JAVA
ORACLE 7AM Page 130
1004 JAVA
1005 PYTHON
1006 PYTHON

display the course names offered by institute:

SELECT DISTINCT course FROM student;

JAVA
ORACLE
PYTHON

ORDER BY:
is used to arrange the records in ascending
order or descending order according to
specific column / columns.

Numbers:
1 to 10 => Asc
10 to 1 => Desc

Characters:
A to Z => Asc
Z to A => Desc

Date:
Asc Desc
1-jan-2022 31-dec-2022
2-jan-2022 30-dec-2022
. .
. .
31-dec-2022 1-jan-2022
1-jan-2023 31-dec-2021

Display the emp names in Alphabetical Order:


ORACLE 7AM Page 131
Display the emp names in Alphabetical Order:

SELECT ename,sal,hiredate FROM emp


ORDER BY ename;
(or)
SELECT ename,sal,hiredate FROM emp
ORDER BY ename Asc;

default => Asc

SELECT ename,sal,hiredate FROM emp


ORDER BY 1;

SELECT empno,ename,hiredate FROM emp


ORDER BY 2;

desc emp;
empno
ename
job

SELECT * FROM emp ORDER BY 2;

Display the emp records in descending order


according to salary:

sal desc
----- sal
6000 -------
5000 8000
8000 6000
4000 5000
4000

ORACLE 7AM Page 132


SELECT ename,sal FROM emp
ORDER BY sal DESC;
(or)
SELECT ename,sal FROM emp
ORDER BY 2 DESC;

Ascending Descending
sal
---------------- -----------------
5000 4000 null
8000 5000 null
7000 8000
4000 8000 7000
null 5000
null 4000
7000

Display the emp records in


descending order according to
salary & display nulls in the last:

SELECT ename,sal FROM emp


ORDER BY sal DESC
nulls last;

deptno job
10 clerk
10 clerk
20 clerk
20 clerk

SELECT distinct deptno,job

10 clerk
20 clerk
ORACLE 7AM Page 133
20 clerk

Display the emp records according to deptno:

emp
empno ename deptno sal
1001 A 30 8000 1002 B 10 9000
1002 B 10 9000 1003 C 10 12000
1003 C 10 12000 1006 F 10 6500
1004 D 30 11000 1001 A 30 8000
1005 E 30 7000 1004 D 30 11000
1006 F 10 6500 1005 E 30 7000

SELECT empno,ename,deptno FROM emp


ORDER BY deptno;

Dipslay the emp records in ascending order


according to deptno. Within the dept display
salaries in descending order:

SELECT empno,ename,deptno,sal
FROM emp
ORDER BY deptno Asc,sal desc;

20 10
10 20

10 5000 10 6000
10 6000 10 5000

ORACLE 7AM Page 134


Display the emp records in ascending order according to
deptno. If deptno is same arrange records in descending
order according to sal. if salary is same according to
seniority arrange records in ascending order:

SELECT empno,ename,deptno,sal,hiredate
FROM emp
ORDER BY deptno asc,sal desc,hiredate asc;

GROUP BY:
• used to group the records according to particular
column/columns.
• It is used to get summarized data from detailed data.
• It can be used to apply aggregate functions on group
of records.

emp
empno ename deptno sal deptno sum(sal)
1001 A 30 5000 10 13000
1002 B 30 8000 20 13000
1003 C 10 7000 30 13000
1004 D 10 6000
1005 E 20 9000
1006 F 20 4000

ORACLE 7AM Page 135


Execution Order of Clauses:

FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY

Find 10th dept & 30th dept sum of salaries:

SELECT deptno,sum(Sal)
FROM emp
WHERE deptno IN(10,30)
GROUP BY deptno
ORDER BY deptno;

FROM emp:
selects entire table

emp
empno ename deptno sal
1001 A 30 5000
1002 B 30 8000
1003 C 10 7000
1004 D 10 6000
1005 E 20 9000
1006 F 20 4000

WHERE deptno IN(10,30):


selects 10 & 30 depts records
ORACLE 7AM Page 136
selects 10 & 30 depts records

empno ename deptno sal


1001 A 30 5000
1002 B 30 8000
1003 C 10 7000
1004 D 10 6000

GROUP BY deptno:
groups the records according to deptno

1001 A 30 5000
1002 B 30 8000

1003 C 10 7000
1004 D 10 6000

On group of records aggregate function will be


applied.

SELECT deptno,sum(Sal):
selects deptnos and sum of salaries

deptno sum(sal)
30 13000
10 13000

ORDER BY deptno:
arranges result in ascending order according to
deptno.

deptno sum(sal)
10 13000
ORACLE 7AM Page 137
10 13000
30 13000

Find number of employees in each department:

emp
empno ename deptno sal
1001 A 30 5000
1002 B 30 8000
deptno no_of_emps
1003 C 10 7000
10 2
1004 D 10 6000
20 2
1005 E 20 9000
30 2
1006 F 20 4000

SELECT deptno,count(8)
FROM emp
GROUP BY deptno
ORDER BY 1;

Find dept wise max salary & min salary:

SELECT deptno,max(sal) as max_sal,min(sal) as min_sal


FROM emp
GROUP BY deptno
ORDER BY 1;

Display number of emps joined in different years.


[year wise no of emps]:

year no_of_emps
1980 3
ORACLE 7AM Page 138
1980 3
1981 5
1982 4
1983 7

SELECT to_char(hiredate,'yyyy') as year,


count(8) as no_of_emps
FROM emp
GROUP BY to_char(hiredate,'yyyy')
ORDER BY year;

Can we use alias name in ORDER BY?


Yes. Because, ORDER BY gets executed after
SELECT.

Can we use alias name in GROUP BY?


No. Because, GROUP BY gets executed before
SELECT.

Display the no of emps joined in different quarters.


[quarter wise no of emps]:

quarter no_of_emps
1 3
2 5
3 2
4 6

SELECT to_char(hiredate,'q') as quarter,


count(15) as no_of_emps
FROM emp
GROUP BY to_char(hiredate,'q')

ORACLE 7AM Page 139


GROUP BY to_char(hiredate,'q')
ORDER BY quarter;

aggregate functions:

count(*) counts the records


count(15) counts the 15s => faster

Examples on Group By:

emp
empno ename job deptno sal
clerk 10000
clerk 15000
manager 20000
manager 15000

Display jobwise sum of salaries:

clerk 25000
manager 35000

SELECT job,sum(sal) as sum_of_sal


FROM emp
GROUP BY job;

Display jobwise min salary & max salary:

SELECT job,min(Sal) as min_sal,


max(sal) as max_sal
ORACLE 7AM Page 140
max(sal) as max_sal
FROM emp
GROUP BY job;

Display jobwise avrg salary:

SELECT job,avg(sal)
FROM emp
GROUP BY job;

Display jobwise no of emps:

SELECT job,count(8)
FROM emp
GROUP BY job;

Find salary range wise no of emps:

sal>3000 => hisal


sal<3000 => losal
sal=3000 => avrgsal

sal_range no_of_emps
hisal 3
losal 5
avrgsal 2

SELECT
CASE
WHEN sal>3000 THEN 'hisal'
WHEN sal<3000 THEN 'losal'
WHEN sal=3000 THEN 'avrgsal'
END as "salary range",
count(*) as no_of_emps
ORACLE 7AM Page 141
count(*) as no_of_emps
FROM emp
Group By
CASE
WHEN sal>3000 THEN 'hisal'
WHEN sal<3000 THEN 'losal'
WHEN sal=3000 THEN 'avrgsal'
END;

HAVING clause:
• used to write the conditions on groups.
• We can use aggregate functions in HAVING
clause.
• It cannot be used without GROUP BY.
• On result of GROUP BY, HAVING condition will be
applied.
• After GROUP BY, HAVING will be executed.

Find the deptnos which are spending more than


10000 on their employees:

SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno
HAVING sum(Sal)>10000;

Find the deptnos which sum of salaries value is


equals to 9400:

SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno
ORACLE 7AM Page 142
GROUP BY deptno
HAVING sum(Sal)=9400;

Display the deptnos which are having more than 5


emps:

SELECT deptno,count(*)
FROM emp
GROUP BY deptno
HAVING count(*)>5;

Display the deptnos in which max salaries are


more than 3000:

SELECT deptno,max(Sal)
FROM emp
GROUP BY deptno
HAVING max(sal)>3000;

Find the job titles which are having more than 3


emps:

SELECT job,count(*)
FROM emp
GROUP BY job
HAVING count(*)>3;

Display the job titles which are having 3 emps:

SELECT job,count(*)
FROM emp
GROUP BY job
HAVING count(*)=3;

ORACLE 7AM Page 143


Display the job titles which are spending more than
5000 amount on their employees:

SELECT job,sum(Sal)
FROM emp
GROUP BY job
HAVING sum(Sal)>5000;

Differences b/w WHERE and HAVING:

WHERE HAVING

• used to write the • used to write the conditions on


conditions on rows. groups.

• can be used to without • cannot be used without GROUP


GROUP BY BY

• We cannot use aggregate • We can use aggregate functions


functions in WHERE in having clause
clause

• gets executed before • gets executed after GROUP BY


GROUP BY

Execution Order:

FROM
WHERE
GROUP BY
HAVING
SELECT
ORACLE 7AM Page 144
SELECT
DISTINCT
ORDER BY

Grouping records with multiple columns:

Find deptwise, jobwise sum of salaries:

emp
empno ename job deptno sal
1001 clerk 10 10000
clerk 20 12000
manager 20 8000
clerk 10 7000
salesman 10 15000
salesman 10 20000
manager 10 25000
clerk 20

10 clerk
20 clerk
10 manager
20 manager
10 salesman

SELECT deptno,job,sum(Sal)
FROM emp
GROUP BY deptno,job
ORDER BY deptno;

ORACLE 7AM Page 145


Display yearwise, quarterwise no of emps:

1980 1 3
2 7
3 4
4 9
1981 1 5
2 6
3 2
4 8

break on year skip 1

SELECT to_Char(hiredate,'yyyy') as year,


to_char(hiredate,'q') as quarter,
count(*) as no_of_emps
FROM emp
GROUP BY to_char(hiredate,'yyyy'),
to_char(hiredate,'q')
ORDER BY 1;

Find year wise, quarter wise sales:

SALES
dateid amount
1-jan-2015 50000
2-jan-2015 75000
ORACLE 7AM Page 146
2-jan-2015 75000
..
..
28-MAY-2022 60000

SELECT to_char(dateid,'yyyy') as year,


to_char(dateid,'q') as quarter,
sum(amount) as amount
FROM sales
GROUP BY to_char(dateid,'yyyy'),
to_char(dateid,'q')
ORDER BY year;

Rollup():
• used to calculate sub totals & grand totals
• calculates sub totals & grand total according to
first column in GROUP BY list.

Cube():
• used to calculate sub totals & grand total
• calculates sub totals & grand totals according to
all columns in GROUP BY list.

Calculate dept wise, job wise sum of salaries.


Also calculate subtotal & grand total according to
deptno:

deptno job sum(Sal)


10 CLERK 10000
MANAGER 20000
ORACLE 7AM Page 147
MANAGER 20000
10 dept sub total 30000
20 CLERK 15000
MANAGER 30000
20 dept sub total 45000
GRAND TOTAL 75000

SELECT deptno,job,sum(Sal)
FROM emp
GROUP BY Rollup(deptno,job)
ORDER BY 1;

Display dept wise, job wise sum of salaries.


Calculate subtotals & grand total according to
deptno & job:

deptno job sum(Sal)


10 CLERK 10000
MANAGER 20000
10 dept sub total 30000
20 CLERK 15000
MANAGER 30000
20 dept sub total 45000
CLERK Sub total 25000
MANAGER sub total 50000
GRAND TOTAL 75000

SELECT deptno,job,sum(Sal)
FROM emp
GROUP BY deptno,job
ORDER BY deptno;

ORACLE 7AM Page 148


Display dept wise, job wise no of emps.
Calculate sub totals & grand total according to
deptno:

deptno job no_of_emps


10 CLERK 2
10 MANAGER 3

20 CLERK 8
20 MANAGER 4

SELECT deptno,job,count(2) as no_of_emps


FROM emp
GROUP BY Rollup(deptno,job)
ORDER BY deptno;

Display dept wise, job wise no of emps.


Calculate sub totals & grand total according to deptno and
job:

SELECT deptno,job,count(2) as no_of_emps


FROM emp
GROUP BY Cube(deptno,job)
ORDER BY deptno;

Find year wise, quarter wise sales. Calculate sub totals &
grand total according to year:

ORACLE 7AM Page 149


year quarter sales sales
2017 1 100000
dateid amount
2 300000
1-jan-2017 20000
3 200000
2-jan-2017 30000
4 100000

2018 1 300000
2 100000
3 500000
4 400000

SELECT to_char(dateid,'yyyy') as year,


to_char(dateid,'q') as quarter,
sum(amount) as amount
FROM sales
GROUP BY Rollup(to_char(dateid,'yyyy'),to_char(dateid,'q'))
ORDER BY year;

calculate subtotals & grant total according to year &


quarter:

SELECT to_char(dateid,'yyyy') as year,


to_char(dateid,'q') as quarter,
sum(amount) as amount
FROM sales
GROUP BY Cube(to_char(dateid,'yyyy'),to_char(dateid,'q'))
ORDER BY year;

Person
ORACLE 7AM Page 150
Person
pid pname state gender age aadhar

Find state wise no of wise:

state no_of_people
TS ..
MR ..
AP ..

SELECT state, count(*) as no_of_people


FROM person
GROUP BY state;

Find state wise, gender wise no of people:

STATE GENDER no_of_people


TS M …
F ..
AP M ..
F ..

SELECT state,gender,count(*) as no_of_people


FROM person
GROUP BY state,gender
ORDER BY 1;

Calculate subtotals & grand total according to


state:

SELECT state,gender,count(*) as no_of_people


FROM person
ORACLE 7AM Page 151
FROM person
GROUP BY Rollup(state,gender)
ORDER BY 1;

Calculate subtotals & grand total according to


state & gender:

SELECT state,gender,count(*) as no_of_people


FROM person
GROUP BY Cube(state,gender)
ORDER BY 1;

ORACLE 7AM Page 152


SET OPERATORS
Monday, May 30, 2022 8:17 AM

SETS

A = {1,2,3,4,5}
B = {6,7,1,2,3}

A UB = {1,2,3,4,5,6,7}
A IB = {1,2,3}
A MB = {4,5}
B MA = {6,7}

SET OPERATORS:
• are used to combine the rows from multiple tables.
• ORACLE SQL provides following SET operators:
○ UNION
○ UNION ALL
○ INTERSECT
○ MINUS

Syntax:

<SELECT Query> <SET OPERATOR> <SELECT Query>;

Customer1 Customer2
cid cname cid cname
1001 Ramu 5001 Vijay
1002 Kiran 5002 Sravan
1003 Sai 1002 Kiran

UNION:
is used to get all records from two tables uniquely
ORACLE 7AM Page 153
• is used to get all records from two tables uniquely
[without duplicate records].
• gives result in the order.

SELECT cid,cname FROM customer1


UNION
SELECT cid,cname FROM customer2;

cid cname
1001 Ramu
1002 Kiran
1003 Sai
5001 Vijay
5002 Sravan

UNION ALL:
used to combine the rows from two tables including
duplicates.

SELECT cid,cname FROM customer1


UNION ALL
SELECT cid,cname FROM customer2;

cid cname
1001 Ramu
1002 Kiran
1003 Sai
5001 Vijay
5002 Sravan
1002 Kiran

INTERSECT:
ORACLE 7AM Page 154
INTERSECT:
used to common records from 2 tables.

SELECT cid,cname FROM customer1


INTERSECT
SELECT cid,cname FROM customer2;

cid cname
1002 Kiran

MINUS:
• used to get specific records of a table.
• It gives all records from first table except common
records.

SELECT cid,cname FROM customer1


MINUS
SELECT cid,cname FROM customer2;

Customer1
cid cname
1001 Ramu
1003 Sai

SELECT cid,cname FROM customer2


MINUS
SELECT cid,cname FROM customer1;

Customer2
cid cname
5001 Vijay
ORACLE 7AM Page 155
5001 Vijay
5002 Sravan

Differences b/w UNION & UNION ALL:

UNION UNION ALL

• it gives result without • it gives result with duplicate


duplicate records records

• gives result in order • does not give result in order

• slower than UNION ALL • faster than UNION

Rules:
• Corresponding column data types should be
matched in both SELECT queries.

SELECT cid,cname FROM customer1


UNION
SELECT cname,cid FROM customer2;

ERROR:

• No of columns in both SELECT queries should


be matched.

ORACLE 7AM Page 156


• No of columns in both SELECT queries should
be matched.

SELECT cid,cname FROM customer1


UNION
SELECT cid FROM customer2;

ERROR:

Display the job titles offered by deptno 10 & 20:

SELECT job FROM emp WHERE deptno=10;

JOB
---------
MANAGER
PRESIDENT
CLERK

SELECT job FROM emp WHERE deptno=20;

JOB
---------
CLERK
MANAGER
ANALYST
CLERK
ANALYST

SELECT job FROM emp WHERE deptno=10


ORACLE 7AM Page 157
SELECT job FROM emp WHERE deptno=10
UNION
SELECT job FROM emp WHERE deptno=20;

job
-----------
ANALYST
CLERK
MANAGER
PRESIDENT

Display common job titles offered by deptno 10 & 20:

SELECT job FROM emp WHERE deptno=10


INTERSECT
SELECT job FROm emp WHERE deptno=20;

Display the specific job designations of deptno 10:

SELECT job FROM emp WHERE deptno=10


MINUS
SELECT job FROM emp WHERE deptno=20;

PRESIDENT

Display the specific job designations of deptno 20:

SELECT job FROM emp WHERE deptno=20


MINUS
SELECT job FROM emp WHERE deptno=10;

ANALYST

ORACLE 7AM Page 158


Cust1 UNION Cust2 = Cust2 UNION Cust1
Cust1 INTERSECT Cust2 = Cust2 INTERSECT Cust1
Cust1 UA Cust2 = Cust2 UA Cust1
Cust1 MINUS Cust2 != Cust2 MINUS Cust1

ORACLE 7AM Page 159


JOINS
Tuesday, May 31, 2022 7:45 AM

College DB

STUDENT
MARKS
FEE
STAFF
LIBRARY

STUDENT MARKS
sid sname scity sid Maths Phy Che

sid sname Maths

JOINS:
• Join => Connect / Link / Combine
• Joins concept is used to retrieve the data from
multiple tables.
• JOIN is an operation that combines one table
records with another based on JOIN CONDITION.
• JOIN CONDITION decides which record one table
should be joined with which record in another
table.

STUDENT MARKS
sid sname scity sid Maths Phy Che
1001 A Hyd 1001 50 80 60
1002 B Delhi 1002 40 60 30
1003 C Mumbai 1003 55 78 36

sid sname Maths


1001 A 50
1002 B 40
1003 C 55

ORACLE 7AM Page 160


Types of Joins:
• Equi Join / Inner Join
• Outer Join
○ Left Outer Join
○ Right Outer Join
○ Full Outer Join
• Non-Equi Join
• Self Join
• Cross Join / Product Join / Cartesian Join

Equi Join / Inner Join:


• If Join Operation is performed based on equality
condition then it is called "Equi Join".

emp dept
empno ename job sal deptno deptno dname loc

ename sal dname loc

Display emp details along with dept details:

SELECT ename,sal,dname,loc
FROM emp, dept
WHERE emp.deptno=dept.deptno;
(or)
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;

emp dept
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30

ORACLE 7AM Page 161


Join Query can be written in 2 style:
• ORACLE style / Native Style
• ANSI style

ORACLE SQL SERVER

Join query [oracle style] Join query [oracle style]

ORACLE SQL SERVER

join query [ANSI style] join query [ANSI style]

Display emp details along with dept details:

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno;

Note:

• In ANSI style, to separate two tables use KEYWORD


Whereas in ORACLE style we use comma.
• In ANSI style, write join condition in ON clause or USING
clause whereas in ORACLE style we write join condition in
WHERE clause.

ANSI style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno;
ORACLE 7AM Page 162
ON e.deptno=d.deptno;
(or)
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
USING(deptno);

Display the emp records along with


dept details.d isplay the emps who
are working in CHICAGO:

emp e dept d
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30

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';

Display BLAKE record along with dept details:

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
ORACLE 7AM Page 163
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';

emp e
dept d
empno ename sal deptno
deptno dname loc
1001 A .. 20
10 ACCOUNT NEW YORK
1002 B .. 20
20 RESEARCH DALLAS
1003 BLAKE .. 30
30 SALES CHICAGO
1004 D 10
40 OPERATIONs BOSTON
1005 E 10
1006 F 30

to retrieve data from 2 tables, we write 1 JOIN CONDITION


to retrieve data from 5 tables, we write 4 JOIN CONDITIONS
to retrieve data from 10 tables, we write 9 JOIN CONDITIONS
.
.
to retrieve data from n tables, we write n-1 JOIN CONDITIONS

emp1 dept1 Location1 Country1

empno deptno LocID cid


ename dname Lname cname
deptno LocId CID

ename dname Lname cname

ORACLE style:

SELECT e.ename, d.dname, l.lname, c.cname


FROM emp1 e,dept1 d,location1 l,country1 c
ORACLE 7AM Page 164
FROM emp1 e,dept1 d,location1 l,country1 c
WHERE e.deptno=d.deptno AND
d.locid=l.locid AND
l.cid=c.cid;

ANSI style:

SELECT e.ename,d.dname,l.lname,c.cname
FROM emp1 e INNER JOIN dept1 d
ON e.deptno=d.deptno
INNER JOIN location1 l
ON d.locid=l.locid
INNER JOIN country1 c
ON l.cid=c.cid;

Outer Join:
• Inner Join can give matched records only. It
cannot give unmatched records.
• Outer Join is used to get matched & unmatched
records.
• For outer join we use Outer Join Operator in
ORACLE style.
• Outer Join Operator symbol: (+)
• There are 3 sub types in Outer Join:
○ Left Outer Join
○ Right Outer Join
○ Full Outer Join

Left Outer Join:

Left Outer = matched + unmatched records from left

• Left Outer Join is used to get matched records and


unmatched records from left side table.

emp dept
empno ename sal deptno dept dname loc
1001 A .. 20 no
1002 B .. 20 10 ACCOUNT NEW
1003 C .. 30 YORK

1004 D 10 20 RESEARCH DALLAS

1005 E 10 30 SALES CHICAG

ORACLE 7AM Page 165


1003 C .. 30 YORK

1004 D 10 20 RESEARCH DALLAS

1005 E 10 30 SALES CHICAG


O
1006 F 30
40 OPERATIONs BOSTO
1007 G
N
1008 H

Display emp records along with dept details. Also


display the emp records to whom dept is not assigned
[Left Outer Join]:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno(+);

Note:
For left outer join write (+) symbol at right side

In ANSI style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno=d.deptno;

In oracle style, join condition decides left table


and right table
emp.deptno=dept.deptno
emp => left table
dept => right table

dept.deptno=emp.deptno
dept => left table
emp => right table

In ANSI style, keyword decides left table right table

emp e LEFT OUTER JOIN dept d


emp => left table
dept => right table

dept d LEFT OUTER JOIN emp e


ORACLE 7AM Page 166
dept d LEFT OUTER JOIN emp e
dept => left table
emp => right table

Display emp records along with dept details.


Also display the dept names which are not
having emps
[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;

FULL OUTER JOIN:

Full Outer = matched + unmatched from left + unmatched from right

e.deptno=d.deptno matched records


e.deptno=d.deptno(+) left outer
e.deptno(+)=d.deptno right outer
e.deptno(+)=d.deptno(+) ERROR
left outer Full outer
UNION
right outer

Display emp records along with dept details. Also


display the emp records to whom dept is not assigned.
Also display the dept names which are not having
emps.

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d

ORACLE 7AM Page 167


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;

Display the emp records to whom dept is not assigned:


[unmatched from left table]
Left outer => matched +unmatched from left
Left Outer + Condition => unmatched from left table

emp dept
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30
1007 G

ename sal dname loc


G 4000

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;

ANSI style:

ORACLE 7AM Page 168


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;

Display the dept names which are not having emps:


[unmatched from right table]
Right Outer => matched + unmatched from right
Right Outer + Condition => unmatched from right

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:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename IS null;

Display the emp records to whom dept is not assigned.


Also display dept names which are not having emps:
{unmatched from left & right}
Full Outer => matched + unmatched from left & right
Full outer+Condition => unmatched from left & right

Full outer+conditions =
left outer + condition
UNION
right outer + condition

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
ORACLE 7AM Page 169
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 => Join operation will be performed based


on equality condition
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:
e.deptno>d.deptno
e.deptno<d.deptno

Display the emp records with salary grades:

emp salgrade
empno ename sal grade losal hisal
1234 5000 1 700 1200
1235 2000 2 1201 1400
1236 1200 3 1401 2000
1237 1800 4 2001 3000
1238 3000 5 3001 5000

empno ename sal grade

display emp records with salary grades:

ORACLE style:

SELECT e.empno,e.ename,e.sal,s.grade
ORACLE 7AM Page 170
SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e,salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;

ANSI style:

SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e INNER JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;

inner => matched


outer => unmatched

Self Join:
• If a table is joined to itself then it is called "Self Join".
• It can be also called as "Recursive Join".
• a record in one table joined with another record in same
table here.

emp emp
empno ename job sal mgr empno ename job sal mgr
1001 A manager 1001 A manager
1002 B clerk 1001 1002 B clerk 1001
1003 C SALESMAN 1001 1003 C SALESMAN 1001
1004 d MANAGER 1004 d MANAGER
1005 E CLERK 1004 1005 E CLERK 1004
1006 f analyst 1004 1006 f analyst 1004

ename sal manager_name sal


B A
C A
E D
F D

ORACLE style:

SELECT e.ename as emp_name, e.sal as


emp_Sal,
m.ename as mgr_name,
m.sal as mgr_sal
FROM emp e,emp m
WHERE e.mgr=m.empno;

ANSI style:
ORACLE 7AM Page 171
ANSI style:

SELECT e.ename as emp_name,


e.sal as emp_Sal,
m.ename as mgr_name,
m.sal as mgr_sal
FROM emp e INNER JOIN emp m
ON e.mgr=m.empno;

Display the emp records who are earning


more than their manager:

ORACLE style:

SELECT e.ename as emp_name,


e.sal as emp_Sal,
m.ename as mgr_name,
m.sal as mgr_sal
FROM emp e,emp m
WHERE e.mgr=m.empno
AND e.sal>m.sal;

ANSI style:

SELECT e.ename as emp_name,


e.sal as emp_Sal,
m.ename as mgr_name,
m.sal as mgr_sal
FROM emp e INNER JOIN emp m
ON e.mgr=m.empno
WHERE e.sal>m.sal;

CROSS JOIN / Cartesian Join / Product Join:

A = {1,2,3}
B = {4,5}

AXB =

ORACLE 7AM Page 172


CROSS JOIN is used to combine each record in
one table with every record in another table.

GroupA GroupB
cid cname cid cname
10 IND 40 PAK
20 AUS 50 ENG
30 WIN 60 NZ

3X3=9
IND PAK
IND ENG 10 X 5 = 50
IND NZ
AUS PAK
AUS ENG
AUS NZ
WIN PAK
WIN ENG
WIN NZ

ORACLE style:

SELECT a.cname,b.cname
FROM groupA a,groupB b;

ANSI style:

SELECT a.cname,b.cname
FROM groupA a CROSS JOIN groupB b;

Equi Join / join operation performed based


Inner Join on equality condn
Outer matched + unmatched
Left Outer matched + unmatched from left
Right Outer matched + unmtched from right
Full Outer matched + unmatched from left
& right

ORACLE 7AM Page 173


& right
Self Join table will be joined to itself.
one table record will be joined
with another record in same
table.
Cross join each record in one table will be
joined with every record in
another
Non-Equi join operation performed based
Join on other than =

ORACLE 7AM Page 174


Wednesday, June 1, 2022 7:39 AM

emp dept
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30
1007 G

ORACLE 7AM Page 175


Sub Queries
Friday, June 3, 2022 7:45 AM

Sub Queries / Nested Queries:


• Writing query in another query is called "Sub Query /
Nested Query".

Syntax:

SELECT <column_list>
FROM <table_list>
WHERE <column_name> <operator> (<SELECT query>);

SELECT
• Inside query is called "inner query / sub query / child
WHERE .. (SELECT …
query".
(SELECT …
• Outside query is called "outer query / main query / parent
(SELECT …
query"
• Normally, first inner query gets executed. Then outer
255 levels
query will be executed.
• The result of inner query becomes input for the outer
query.
• Normally, when WHERE condition value is unknown then
write Sub Query.
• We can write maximum of 255 sub queries in WHERE
clause.
• Sub query must be written in parenthesis. [ (<sub
query>) ].
• Sub Query must be SELECT query only.
• Sub Query cannot be INSERT / UPDATE / DELETE
• Main query can be INSERT / UPDATE / DELETE / SELECT.

Types of Sub Queries:


• Single Row Sub Query
• Multi Row Sub Query
• Correlated Sub Query
• Inline View
• Scalar Sub Query

Single Row Sub Query:


• if sub query returns one value then it is called
"Single Row Sub Query".

Display the emp records whose salary is greater


than BLAKE's Salary:

BLAKE 5000
ORACLE 7AM Page 176
BLAKE 5000

SELECT empno,ename,sal FROM emp


WHERE sal>(SELECT sal FROM emp WHERE
ename='BLAKE');

Find 2nd max salary:

SELECT max(sal) FROM emp


sal
WHERE sal<(SELECT max(Sal)
----
FROM emp);
5000
7000
4000 5000
8000 7000
6000 4000
6000

Find 3rd max salary:

sal
----
5000 SELECT sal FROM emp
7000 WHERE sal<7000;
4000
8000 5000
6000 4000
6000

SELECT max(sal) FROM emp


WHERE sal<(SELECT max(sal) FROM emp
WHERE sal<(SELECT max(Sal) FROM emp);

Display the emp name who is earning max salary:

SELECT ename FROM emp


WHERE sal=(SELECT max(Sal) FROM emp);

Display the emp name who earning 2nd max salary:

SELECT ename FROM emp


WHERE sal=(SELECT max(Sal) FROM emp
WHERE sal<(SELECT max(Sal) FROM emp);

Display the ename who is earning 3rd max salary:

ORACLE 7AM Page 177


Display the emp records who are juniors of FORD:

SELECT ename,sal,hiredate FROM emp


WHERE hiredate>(SELECT hiredate FROM emp
WHERE ename='FORD');

Display the emp records who are senior to FORD:

SELECT ename,sal,hiredate FROM emp


WHERE hiredate<(SELECT hiredate FROM emp
WHERE ename='FORD');

Display the emp records who joined on same


hiredate of FORD:

SELECT ename,sal,hiredate FROM emp


WHERE hiredate=(SELECT hiredate FROM emp
WHERE ename='FORD');

Update 7499 empno's sal as 30th dept max salary:

UPDATE emp SET sal=(SELECT max(Sal)


FROM emp WHERE deptno=30)
WHERE empno=7499;

Delete an emp record who is having max experience:

DELETE FROM emp


WHERE hiredate=(SELECT min(hiredate) FROM emp);

Swapping 2 salaries:

7369 SMITH 800


7499 ALLEN 1600

UPDATE emp SET sal=


CASE empno
WHEN 7369 THEN (SELECT sal FROM emp WHERE empno=7499)
WHEN 7499 THEN (SELECT sal FROM emp WHERE empno=7369)
END
WHERE empno IN(7369,7499);

ORACLE 7AM Page 178


Find the deptno which is spending maximum
amount on their emps:

emp
empno ename deptno sal
deptno sum(Sal)
10 10000
10 25000
10 15000
20 15000
20 5000
30 35000
20 10000
30 20000
30000 15000

30 35000

SELECT deptno FROM emp


GROUP BY deptno
HAVING sum(sal)=(SELECT max(sum(Sal))
FROM emp
GROUP BY deptno);

30

Display the dept name which spending max


amount on their emps:

SELECT dname FROM dept


WHERE deptno = (SELECT deptno
FROM emp
GROUP BY deptno
HAVING sum(sal) = (SELECT max(sum(Sal))
FROM emp
GROUP BY deptno));

Find deptno which is having maximum no of emps:

SELECT deptno FROM emp


GROUP BY deptno
HAVING count(*)=(SELECT max(count(*))
FROM emp
GROUP BY deptno);

Find the dept name which is having max no of


emps:

SELECT dname FROM dept


WHERE deptno = (SELECT deptno
FROM emp
GROUP BY deptno
ORACLE 7AM Page 179
GROUP BY deptno
HAVING count(*) = (SELECT max(count(*))
FROM emp
GROUP BY deptno));

Single Row Sub Query


Multi Row Sub Query
Correlated Sub Query
Inline View
Scalar Sub Query

Multi Row Sub Query:


If sub query returns multiple values then it is called
"Multi Row Sub Query".

Examples:

Display the emp records whose job designations are


equal to SMITH and BLAKE:

SELECT empno,ename,job FROM emp


WHERE job IN('CLERK','MANAGER');

SELECT job FROM emp


WHERE ename IN('SMITH','ALLEN');

Display the emp names who are earning max sal in their
dept:

SELECT empno,ename,deptno,sal FROM emp


WHERE(deptno,sal) IN(SELECT deptno,max(Sal)
FROM emp GROUP BY deptno);

Display the emp names who are senior in each dept:

SELECT empno,ename,deptno,hiredate FROM emp


WHERE(Deptno,hiredate) IN(SELECT deptno,min(hiredate)
FROM emp
GROUP BY deptno);

ORACLE 7AM Page 180


Correlated Sub Query:
• If outer query passes value to inner query then it is
called "Correlated Sub Query".
• Normally in Sub Queries, first inner query gets
executed. Then outer query gets executed. And
Inner query gets executed only once.
Ex:
SELECT ename FROM emp
WHERE sal=(SELECT max(Sal) FROM emp);

• In Correlated sub query, first outer query gets


executed. It passes value to inner query. Then
inner query gets executed. Inner query passes
value to outer query. Outer query condition will be
tested. If condition is TRUE, row will be selected.
Above process will be performed for every row.
So, inner query gets executed multiple times.

no of execution times of inner query = number of


rows passed by the outer query.

Execution Process:
• Outer query gets executed. It selects the row.
• Outer query passes value to inner query.
• Inner query gets executed.
• Inner query passes value to outer query.
• Outer query condition will be tested. If condition
is TRUE, row will be selected.
• Above process will be executed repeatedly for
every row.

Display the emp records who are earning more


than their dept's avrg salary:

emp e
empno ename sal deptno deptno avg_sal
1 A 10000 20 10 15000
2 B 15000 20 20 12500
3 C 20000 10
4 D 10000 10

SELECT empno,ename,sal,deptno
FROM emp e
WHERE sal>(SELECT avg(sal) FROM emp
WHERE deptno=e.deptno);

empno ename sal deptno


2 B 15000 20
3 C 20000 10

ORACLE 7AM Page 181


Find 3rd max salary:

emp

empno ename sal deptno no of emps>emp sal 0 max sal


1 A 10000 20 no of emps>emp sal 1 2nd max sal
2 B 15000 20 no of emps>emp sal 2 3rd max sal
3 C 20000 10 no of emps>emp sal 3 4th max sal
4 D 12000 10

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 2 = (SELECT count(DISTINCT sal)
FROM emp WHERE sal>e.sal);

4 D 12000 10

Find 4th max salary:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 3 = (SELECT
count(DISTINCT sal)
FROM emp WHERE sal>e.sal);

Find 5th max salary:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 4 = (SELECT
count(DISTINCT sal)
FROM emp WHERE sal>e.sal);

Find nth max salary:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE &n-1 = (SELECT
count(DISTINCT sal)
FROM emp WHERE sal>e.sal);

enter value for n: 5


5th max sal

enter value for n: 10


10th max sal

ORACLE 7AM Page 182


Find top 3 salaries:

emp
empno ename sal deptno no_of_sals>emp sal 0 max sal
1 A 10000 20 no_of_sals>emp sal 1 2nd max sal
2 B 15000 20 no_of_sals>emp sal 2 3rd max sal
3 C 20000 10 no_of_sals>emp sal 3 4th max sal
4 D 12000 10 no_of_sals>emp sal 4 5th max sal

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 3 > (SELECT count(distinct sal)
FROM emp WHERE sal>e.sal);

find top 5 salaries:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 5 > (SELECT count(distinct sal)
FROM emp WHERE sal>e.sal);

find top n salaries:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE &n > (SELECT count(distinct sal)
FROM emp WHERE sal>e.sal);

Exists & Not Exists:

Exists returns TRUE if record is existed


returns FALSE if record is not existed
Not Exists returns TRUE if record is not existed
returns FALSE if record is existed

Display the dept names which are having emps:

SELECT dname FROM dept d


WHERE exists(SELECT * FROM emp
WHERE deptno=d.deptno);

dept emp
deptno dname empno ename sal deptno
10 Accounting 1 A 10000 20
20 Research 2 B 15000 20
30 Sales 3 C 20000 10
4 D 12000 10

ORACLE 7AM Page 183


Find the dept names which are not having emps:

SELECT dname FROM dept d


WHERE not exists(SELECT * FROM emp
WHERE deptno=d.deptno);

Single Row Sub Query


Multi Row Sub Query
Correlated Sub Query
Inline View
Scalar Sub Query

Inline View:
• Writing sub query in FROM clause is In WHERE clause, we can write
called "Inline View". maximum of 255 sub queries
• It acts like table. In FROM clause, no limit is there.
• Used to change the execution order.

FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY

Display the emp records whose annual salary is


more than 30000:

SELECT empno,ename,sal,sal*12 as an_sal


FROM emp
WHERE an_Sal>30000;
ERROR: an_sal invalid identifier

SELECT * FROM (SELECT empno,ename,sal,sal*12


as an_sal
FROM emp)
WHERE an_sal>30000;

Display top 3 salaried emps records:

SELECT * FROM (SELECT empno,ename,sal,


Dense_Rank() Over(order by sal desc) as rnk
FROM emp)
WHERE rnk<=3;

Find 3rd max salary:

ORACLE 7AM Page 184


SELECT * FROM (SELECT empno,ename,sal,
Dense_Rank() Over(Order BY sal Desc) as rnk
FROM emp)
WHERE rnk=3;

pseudo => false

RowNum:
• is a pseudo column.
• It is used to get record numbers.
• Row number will be applied on result of
SELECT query.

Display 3rd row:

SELECT * FROM (SELECT rownum as rn,empno,ename,sal


FROM emp)
WHERE rn=3;

Display 3rd, 5th and 11th rows:

SELECT * FROM (SELECT rownum as rn,empno,ename,sal


FROM emp)
WHERE rn IN(3,5,11);

Display even rows: 2,4,6,8.. => divide with 2 => remainder 0


SELECT * FROM (SELECT rownum as rn, 1,3,5,7.. => divide with 2 => remainder 1
empno,ename,sal FROM emp)
WHERE mod(rn,2)=0;

Display odd rows:


SELECT * FROM (SELECT rownum as rn,
empno,ename,sal FROM emp)
WHERE mod(rn,2)=1;

Scalar Sub Query:


• Writing sub query in SELECT clause is called
"Scalar Sub Query".
• It acts like column.

Find no of records in emp table & dept table:


emp dept
-------- ----------
16 4

SELECT (SELECT count(*) FROM emp) as emp,

ORACLE 7AM Page 185


SELECT (SELECT count(*) FROM emp) as emp,
(SELECT count(*) FROM dept) as dept
FROM dual;

emp dept
------- ------
16 4

Calculate share of each dept:

deptno per
10 30
20 50
30 20

SELECT deptno,sum(Sal) dept_sal,


(SELECT sum(Sal)
FROM emp) as total_Salary,
Round((sum(Sal)/(SELECT sum(Sal) FROM emp))*100) as
percentage
FROM emp
GROUP BY deptno
ORDER BY 1;

Single Row Sub query


Multi Row Sub query
Correlated sub query
Inline view => FROM
Scalar sub query => SELECT

ORACLE
Database
Tables

SQL
PL/SQL

SQL => query lang => used to write queries


5 sub languages:
DDL DRL DML DCL TCL
C S I G C
A U R R
D D S
T IA
R M
F
ORACLE 7AM Page 186
D D S
T IA
R M
F
P

Built-in functions Clauses Joins


String
Aggregate SELECT Equi Join / Inner Join
Conversion FROM Non-Equi
Date WHERE Outer => matched + unmatched
Math GROUP BY left outer => matched + unmatched from left
Miscellaneous HAVING right outer => matched + unmatched from right
DISTINCT full outer => matched + unmatched from L & R
ORDER BY Self Join
Cross Join

ORACLE 7AM Page 187


Views
Wednesday, June 8, 2022 7:31 AM

Views:
Virtual => not real
• View is a DB Object.
• View is a Virtual Table.
• Virtual Table means, it does not contain
physical data & does not occupy the memory.
• View holds SELECT query.
• When we retrieve data through VIEW, implicitly
ORACLE runs SELECT query & retrieve data
from table.
• A VIEW is created on table. This table is called
"Base Table".
• Without Table we cannot create the VIEW.
• Some views can be updated. These are called
"Updatable views / simple views".
• Some views cannot be updated. These are
called "Read-Only views / Complex Views".

Syntax to create VIEW:

CREATE VIEW <view_name>


AS
<SELECT QUERY>;

Ex:
emp
empno ename job sal comm deptno hiredate mgr

V1
empno ename job

By default user has no permission for


creating the VIEW. DBA gives permission as
follows:

Log In as DBA:
username: system
password: nareshit

GRANT create view TO c##batch7am;

Advantages:
• provides security for the data.
• reduces the complexity & simplifies queries.

SECURITY can be implemented in


c##batch7am
3 levels:
emp
• DB level => Schema [User]
• Table level => GRANT, REVOKE
c##ramu
ORACLE 7AM Page 188
c##batch7am
3 levels:
emp
• DB level => Schema [User]
• Table level => GRANT, REVOKE
c##ramu
• Data level => VIEW

• VIEW is used to implement data level security.


• Data Level Security can be implemented in 2
levels:
○ Column Level
○ Row Level

Column Level Security:

emp
empno ename job sal mgr comm hiredate deptno

V1
empno ename job

On this VIEW, we give permission to other user. That user


works with emp table through the VIEW. Only specific
columns will be displayed to that user.

Row Level Security:

emp
empno ename job sal mgr comm hiredate deptno
1001 10
1002 10
1003 10
1004 20
1005 20
1006 20

deptno 10 manager => can access only 10th dept records


deptno 20 manager => can access only 20th dept records

To retrieve data from 2 tables we write 1 Join Condition


To retrieve data from 5 tables we write 4 Join Conditions
To retrieve data from 10 tables we write 9 Join Conditions

CREATE VIEW v2
ORACLE 7AM Page 189
CREATE VIEW v2
AS
Join query

SELECT * FROM v2;

Disadvantage:
• Less Performance

Example on implementing Column Level Security:

Log in as DBA:
username: system
password: nareshit

CREATING USER:

CREATE USER c##ramu


IDENTIFIED by ramu
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO c##ramu;

Log in as c##oracle7am:

CREATE VIEW v2
AS
SELECT empno,ename,job FROM emp;

GRANT all ON v2 TO c##ramu;

Log in as c##ramu:
username: c##ramu
password: ramu

SELECT * FROM c##batch7am.v2;


empno ename job
.. .. ..

INSERT INTO c##batch7am.v2 VALUES(1,'A','CLERK');


1 row created

If data is inserted through VIEW, this data will be


inserted in base table.

UPDATE c##batch7am.v2 SET job='MANAGER'


WHERE empno=1;
1 row updated

ORACLE 7AM Page 190


If data is updated through VIEW, this data will be
updated in base table.

DELETE FROM c##batch7am.v2


WHERE empno=1;
1 row deleted

If data is deleted through VIEW, this data will be


deleted from base table.

If DML operations like


INSERT/UPDATE/DELETE are performed
through view, it will be applied on base
table.

Types of Views:

2 types:
• Simple VIEW
• Complex VIEW

Simple VIEW:

• If view is created based on one table it is called


"Simple View".
• It can be also called as "Updatable view".
• DML operations can be performed on Simple View.

Ex on implementing row level security:

emp
empno ename job sal comm mgr hiredate deptno
10
10
20
20
emp
30
empno ename sal gender
30

c##batch7am:

CREATE VIEW v3
AS
SELECT * FROM emp WHERE deptno=20;

ORACLE 7AM Page 191


GRANT all ON v3 TO c##ramu;

Log in as c##Ramu:

SELECT * FROM c##batch7am.v3;

INSERT INTO c##batch7am.v3(empno,ename,deptno)


VALUES(5678,'Sai',20);

INSERT INTO c##batch7am.v3(empno,ename,deptno)


VALUES(5679,'Srinu',30);
1 row created.

SELECT * FROM c##batch7am.v3;


--this view can display 20 dept records only
--this cannot display 30th dept record

WITH CHECK OPTION clause:


• If view is created using 'WITH CHECK OPTION'
clause, This view does not allow the records which
cannot be displayed the view.
• WHERE condition violated records will not be
accepted in this view.

Note:
• We cannot use ALTER command on View.
• To make changes in existing view, we use
CREATE OR REPLACE

c##batch7am:

CREATE OR REPLACE VIEW v3


AS
SELECT * FROM emp WHERE deptno=20
WITH CHECK OPTION;

c##ramu:

INSERT INTO c##batch7am.v3(empno,ename,deptno)


VALUES(5679,'Srinu',30);
ERROR: WHERE condition violated

Complex View:
• If view is created based on multiple tables
(joins) or group by or having or set operators
or sub queries or group functions or
expressions then it is called "Complex View"

ORACLE 7AM Page 192


expressions then it is called "Complex View"
• It can be also called as "Read-Only View".
• We cannot perform DML operations on
Complex View.

CREATE VIEW v4
AS
SELECT deptno,sum(Sal) as sum_of_sal
FROM emp
GROUP BY deptno
ORDER BY 1;

CREATE VIEW v5
AS
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno;

Differences b/w Simple View & Complex View:

Simple View Complex View

• It is created based on • It is created based on joins /


one table. group by / set operators …etc

• Updatable View • Read-Only View

• We can perform • We cannot perform DML


DML operations through operations through this view
this view

• it performs simple • it performs complex operations


operations like join operations, group by,
group functions ..etc

After creating view, if we add a column to base


table does it reflect to view?
No. Because, view holds select query. when we
CREATE VIEW v6
retrieve data through view, it runs SELECT query.
AS
In SELECT clause column list new column name is
SELECT * FROM emp WHERE deptno=20;
not there.

After creating view, if we add the record to base


table does it reflect to view?
Yes. Because, When we retrieve data through view,
ORACLE 7AM Page 193
Yes. Because, When we retrieve data through view,
it runs SELECT query. So it selects from base table.
View gives recent data [committed data].

Can we create a view without table?


No.

FORCE VIEW:
If view is created forcibly with some errors then it is
called "FORCE VIEW".

Ex:
• If we want to create view without base table then
use FORCE VIEW.
• This view will not work until we create the base
table.

Can we create a view from another view?


Yes.

If we drop the base table does it drop the view?


No. This view will not work because of base table
dropped. After creating base table again it will work.

Can we use ALTER or TRUNCATE on view?


NO.

How can we make changes in existing view?


CREATE OR REPLACE

Dropping View:

Syntax:
DROP VIEW <view_name>;

Ex:
DROP VIEW v9;

User_views:
It maintains all views information of specific user.

SELECT view_name,text FROM user_Views;

View:
Virtual does not contain physical data & does not
Table occupy the memory.
View holds SELECT query

ORACLE 7AM Page 194


2 types: Simple => DMLS allowed
Complex => DMLS not allowed

ORACLE 7AM Page 195


Indexes
Friday, June 10, 2022 7:29 AM

ORACLE
Indexes:
• Index is a DB Object.
• Index is used to improve the performance INDEX
of data retrieval.
• To refer a chapter in book, we use index. Chapter Name Page Num
With this, we can refer the chapter quickly.
DDL 5
• If index is created on column of table, we
DML 10
can retrieve the record quickly.
• Index will be created on column. Built-in fun 20
• The columns which are frequently in WHERE Joins 50
condition or Join Condition, on them create
the Index to improve the performance.

Syntax to create the Index:

CREATE INDEX <index_name>


ON <table_name>(<column>/columns>);

Advantage:
• It improves performance of data retrieval.

SELECT * FROM emp Table Scan


WHERE sal>3000; (or)
Index Scan

When we submit to ORACLE, it may


perform any one of the 2 scans:
• Table Scan
• Index Scan

Table Scan:
If Index is not created, ORACLE performs Table Scan.
It is slower than Index scan

Index Scan:
If index is created, ORACLE performs Index Scan.
It is faster than table scan.

ORACLE 7AM Page 196


SET autotrace ON explain

SELECT * FROM emp WHERE sal>3000; -- Table Scan

CREATE INDEX i1 ON emp(sal);

SELECT * FROM emp WHERE sal>3000; -- Index Scan

CREATE INDEX i1 ON emp(sal);

When we create index on specific column, implicitly


B-Tree [Balanced Tree] will be created.

Tree => collection of nodes

If value is less than or equals to root node,


place it at left side.
If value is greater than root node, place it at
right side.

1000+5000 = 6000 /2 = 3000 1000+3000 = 4000 /2 = 2000


sal 5000+3000 = 8000 /2 = 4000
---------
3000 3000
4500
5000
1200 2000 4000
4500
1500
1000 1000 * 3000 ** 3500 * 4500 **
3000 1200 * 3800 * 5000 *
1500 1500 **
1800 1800 *
3500
3800

Table scan

sal WHERE sal>3500


---------
3000
4500
5000
ORACLE 7AM Page 197
---------
3000
4500
5000
1200
4500
1500
1000
3000
1500
1800
3500
3800

Types of Indexes:

2 Types:

• B-Tree Index / Normal Index


○ Simple Index
○ Composite Index
○ Unique Index
○ Function-Based Index
• Bitmap Index

B-Tree Index / Normal Index:


If B-Tree is created when we create the index
then it is called "B-Tree Index".

It has 4 sub types:


• Simple Index
• Composite Index
• Unique Index
• Function-Based Index

Simple Index:
If index is created on one column then it is
called "Simple Index".

Ex:

CREATE TABLE emp1


AS
SELECT * FROM emp;

ORACLE 7AM Page 198


SELECT * FROM emp;

Create an index on salary column of emp1 table:

CREATE INDEX i2 ON emp1(Sal);

Composite Index:
If index is created on multiple columns then it is called
"Composite Index".

SELECT * FROM emp1


WHERE deptno=20 AND job='MANAGER'; --Table Scan

CReate index on deptno & job columns of emp1 table:

CREATE INDEX i3 ON emp1(deptno,job);

Before Oracle 9i:

SELECT * FROM emp1


WHERE deptno=20 AND job='MANAGER'; --Index Scan

SELECT * FROM emp1


WHERE deptno=20; -- Index Scan

SELECT * FROM emp1


WHERE job='MANAGER' ; --Table scan

From Oracle 9i version onwards:

SELECT * FROM emp1


WHERE deptno=20 AND job='MANAGER'; --Index Range Scan

SELECT * FROM emp1


WHERE deptno=20; -- Index Range Scan

SELECT * FROM emp1


WHERE job='MANAGER' ; -- Index skip scan

deptno job
10 clerk
20 manager

ORACLE 7AM Page 199


deptno job
10 clerk
20 manager
10 clerk
10 manager
20 clerk
30 clerk
30 manager

Unique Index:
If index is created on the column which is having
unique values then it is called "Unique Index".

Create an index on dept name of dept table:

CREATE UNIQUE INDEX i4 ON dept(dname);

We can create unique values in a column using


3 ways:
• Primary Key
• Unique
• Unique Index

When we create the table using Primary Key, implicitly


one index will be created on primary key column.

create table idemo


(
f1 number(4) constraint it1 primary key,
f2 varchar2(10)
);

Function-Based Index:
If index is created based on function (or) expression
then it is called "Function-Based Index".

SELECT * FROM emp1


WHERE ename = 'SMITH'; --Table scan

CREATE INDEX i5 ON emp1(ename);

SELECT * FROM emp1


ORACLE 7AM Page 200
SELECT * FROM emp1
WHERE ename = 'SMITH'; --Index scan

SELECT * FROM emp1


WHERE ename = 'smith';
no rows selected

SELECT * FROM emp1


WHERE lower(ename) = 'smith'; --Table Scan

CREATE INDEX i6 ON emp1(lower(ename));

SELECT * FROM emp1


WHERE lower(ename) = 'smith'; --Index Scan

SELECT ename,sal,sal*12 FROM emp1


WHERE sal*12>30000; --Table Scan

CREATE INDEX i7 ON emp1(sal*12);

SELECT ename,sal,sal*12 FROM emp1


WHERE sal*12>30000; --Index Scan

B-TREE INDEX:
• In this, B-TREE will be created.
• It stores data & rowids.
○ Ex: sal => 3000 * *
5000 *

BITMAP INDEX:
• In this B-TREE will not be created.
• It stores the bits => 0s and 1s.
• Every bit is associated with Row IDs. Bit will be
converted to Row ID, goes to that Row ID & picks
the record.
• On low cardinality columns create bitmap index.

Low cardinality column:


If column has less distinct values then it is called
"Low Cardinality Column"

Ex:

Gender
------------
ORACLE 7AM Page 201
------------
M
M
F
F
F
M
M
F
M
M
M
F

deptno
-----------
10
30 10
30 20
20 30
20
10
10
20
30

emp2

Gender CREATE BITMAP INDEX bi1


------------ ON emp2(gender);
M
F M F
F 1 0
M 0 1
M 0 1
F
1 0
M
1 0
M
M 0 1
F 1 0
1 0
1 0
0 1

SELECT * FROM emp2 WHERE gender='M';

ORACLE 7AM Page 202


In Table scan, No of comparisons are equal to no of rows.
IN Bitmap Index scan, No of comparisons are equal to no of
rows. The how bitmap index improves the performance?

Bit comparison is faster than value comparison.

CREATE TABLE emp2


(
empno number(4),
ename varchar2(10),
gender char
);

INSERT INTO emp2 VALUES(1,'A','M');


INSERT INTO emp2 VALUES(2,'B','F');
INSERT INTO emp2 VALUES(3,'C','M');
INSERT INTO emp2 VALUES(4,'D','M');
INSERT INTO emp2 VALUES(5,'E','F');
INSERT INTO emp2 VALUES(6,'F','F');

SELECT * FROM emp2 WHERE gender='M'; --Table Scan

CREATE BITMAP INDEX bi1 ON emp2(gender);

SELECT * FROM emp2 WHERE gender='M'; --Index Scan

ORACLE 7AM Page 203


B-TREE INDEX BITMAP INDEX

• It creates B-TREE • It does not create B-TREE.

• It stores data & row ids. • stores bits => 0s and 1s


bits will be converted to row ids.

• On high cardinality • On low cardinality columns


columns create it create it.

Ex: empno,ename,sal Ex: gender, deptno, job

When we drop the table does it drop rows & columns?

Yes

When we drop the base table does it drop the view?

No

When we drop the table does it drop the index?

Yes

User_indexes:

"User_indexes" maintain all indexes information.

Desc user_indexes;

SELECT index_name,index_type FROM user_indexes;

Dropping Index:

Syntax:
DROP INDEX <index_name>;

EX:
DROP INDEX i1;

ORACLE 7AM Page 204


Index it is a db object.
it is created on column
it improves the performance of data
retrieval.
2 types B-Tree Index
Bitmap Index

ORACLE 7AM Page 205


SEQUENCES
Saturday, June 11, 2022 8:28 AM

SEQUENCES:
• SEQUENCE is a DB Object.
• It is used to create sequential integers.
• It is independent of the table.
Ex:
Order_id cust_id Transaction_id
------------- ------------ -----------------------------
12345678 123456 1234567890
12345679 123457 1234567891
12345680 123458

Syntax:

CREATE SEQUENCE <sequence_name>


[START WITH <value>]
[INCREMENT BY <value>]
[MAXVALUE <value>]
[MINVALUE <value>]
[cycle/nocycle]
[cache <size> / nocache];

CREATE SEQUNCE s1;

CLAUSE Default value


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10 power 28
CYCLE NOCYCLE
CACHE 20
ORACLE 7AM Page 206
CACHE 20

Sequence provides 2 pseudo columns:

NEXTVAL it returns next value in the sequence


CURRVAL it returns current value in the sequence

Syntax:
sequence_name.pseudo_column
Ex:
s1.nextval
s1.currval

SELECT s1.currval FROM dual;


ERROR

SELECT s1.nextval FROM dual;


1

SELECT s1.currval FROM dual;


1

SELECT s1.nextval FROM dual;


2

SELECT s1.nextval FROM dual;


3

SELECT s1.nextval FROM dual;


4

SELECT s1.nextval FROM dual;


5

ORACLE 7AM Page 207


CREATE SEQUENCE s2
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 5;

CUSTOMER
cid cname
1 A
2 B

CREATE TABLE customer


(
cid number(4),
cname varchar2(10)
);

INSERT INTO customer VALUES(s2.nextval,'&cname);


enter value for cname: A

/
enter value for cname: B

/
enter value for cname: C

/
enter value for cname: D

/
ORACLE 7AM Page 208
/
enter value for cname: E

/
enter value for cname: F
ERROR: sequence reached max value

Assignment:

course
CREATE SEQUENCE s3
cid cname START WITH 10
10 Java INCREMENT BY 10
20 C# MINVALUE 10
30 Python MAXVALUE 50;
40 C
50 Oracle

Cycle / NoCycle:
• Default => NoCycle

NoCycle:
When we create a sequence with nocycle,
When we call the sequence, it can generate next
value up to max value. After reaching max value, it
will be stopped.

ORACLE 7AM Page 209


CREATE SEQUENCE s5
START WITH 300
INCREMENT BY 1
MINVALUE 100
MAXVALUE 500
NoCycle;

Cycle:
If sequence is created with Cycle,
Sequence will be started with START WITH value,
generates next value up to max value. After
reaching max value, it will be reset to min value.

CREATE SEQUENCE s6
START WITH 300
INCREMENT BY 1
MINVALUE 100
MAXVALUE 500
Cycle;

CREATE SEQUENCE s5

ORACLE 7AM Page 210


CREATE SEQUENCE s5
START WITH 5
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
NoCycle;

CREATE SEQUENCE s6
START WITH 5
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
Cycle
Cache 9;

Cache <size> / NoCache:

NoCache:
If sequence is created with NoCache,
When we call the sequence, ORACLE goes to
DB, identifies current value, adss increment
by value, returns sequential number.

CREATE SEQUENCE s8
ORACLE 7AM Page 211
CREATE SEQUENCE s8
START WITH 300
MINVALUE 100
MAXVALUE 500
INCREMENT BY 1
NoCache;

Cache <size>:
• If sequence is created using cache, every time it
will not go to database. Sequential Values will be
preloaded into cache memory. When we call the
sequence, sequential number will be returned
from cache.
• It improves the performance.
• Cache size must be less than one cycle.
• Default Cache size: 20

CREATE SEQUENCE s8
START WITH 300
MINVALUE 100
MAXVALUE 500
INCREMENT BY 1
Cache 100;

CREATE SEQUENCE s11


START WITH 5
INCREMENT BY 1

ORACLE 7AM Page 212


START WITH 5
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
Cycle; --ERROR

CREATE SEQUENCE s11


START WITH 5
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
Cycle
Cache 9;

Can we call the sequence from UPDATE command?


Yes

CREATE SEQUENCE s12


START WITH 1001
INCREMENT BY 1
MAXVALUE 2000
MINVALUE 1001;

ORACLE 7AM Page 213


Make empnos in sequential order:

UPDATE emp SET empno=s12.nextval;

Can we call the sequence from CREATE command?


From Oracle 12c version onwards we can call the
sequence from CREATE command also.

CREATE SEQUENCE s13


START WITH 101
MAXVALUE 200
MINVALUE 101
INCREMENT BY 1;

CREATE TABLE student13


(
sid number(4) default s13.nextval,
sname varchar2(10)
);

From Oracle 12c version onwards, we can


generate sequential nums in 2 ways:
• using Sequence
• using Identity

CREATE TABLE student14


ORACLE 7AM Page 214
CREATE TABLE student14
(
sid number(4) generated always as identity,
sname varchar2(10)
);

insert into student14(sname) values('A');


insert into student14(sname) values('B');
insert into student14(sname) values('C');
insert into student14(sname) values('D');
insert into student14(sname) values('E');
commit;

SELECT * FROM student14;

ALTERING SEQUENCE:

CREATE SEQUENCE s15


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 5;

ALTER SEQUENCE s15 MAXVALUE 10;

50 CREATE SEQUENCE s16


49 START WITH 50
48 INCREMENT BY -1
47 MINVALUE 1
. MAXVALUE 50;
ORACLE 7AM Page 215
48 INCREMENT BY -1
47 MINVALUE 1
. MAXVALUE 50;
.
1

Dropping the sequence:

Syntax:
DROP SEQUENCE <seq_name>;

Ex:
DROP SEQUENCE s1;

user_sequences:
• It maintains all sequences information.

Desc user_sequences;

SELECT * FROM user_sequences;

ORACLE 7AM Page 216


Materialized View
Monday, June 13, 2022 8:31 AM

Materialized View:
• Materialized View is a DB object.
• M.View is not Virtual Table. It contains physical
data. It occupies the memory.
• M.VIEW holds result of SELECT query Whereas
VIEW holds SELECT query.
• It is used to improve the performance.
• It holds precomputed result.
• In DWH (DataWare Housing), to maintain
summarized tables physically, we use M.VIEW.
• VIEW gives recent data. Because, It holds
SELECT query. Materialized View gives
precomputed result. M.View does not give
recent data. That's why we need to refresh
M.View.

VIEW
Disadvantage:
• Less Performance

PERSON

pid pname state gender aadhar

Calculate state wise no of people:

CREATE VIEW v1
AS
SELECT state,count(*) FROM person
GROUP BY state;

v1

SELECT state,count(*) FROM person


GROUP BY state;

SELECT * FROM v1;

Advantages of M.View:
• Improves the performance.
• We can maintain a local copy of remote database.

ORACLE 7AM Page 217


Syntax:

CREATE MATERIALIZED VIEW <m.view_name> Log in as DBA:


AS
<SELECT query>; GRANT create materialized view
TO c##batch7am;

ORACLE 7AM Page 218


CREATE VIEW v1 CREATE MATERIALIZED VIEW mv1
AS AS
SELECT deptno,sum(sal) SELECT deptno,sum(sal)
FROM emp FROM emp
GROUP BY deptno; GROUP BY deptno;
O/P: view created O/P: m.view created

V1 MV1

SELECT deptno, deptno sum(sal)


sum(sal) as sum_sal 10 10000
FROM emp GROUP BY deptno 20 30000
30 15000

SELECT * FROM v1;


SELECT * FROM v1; First time calculated & result of
SELECT * FROM v1; SELECT query stored in m.view.
SELECT * FROM v1;
SELECT * FROM v1; SELECT * FROM mv1;
--retrieves from m.view

SELECT * FROM v1;


--retrieves from m.view

SELECT * FROM mv1;


--retrieves from m.view

Only one calculation will be done.


5 times calculation will be
done.

It improves the performance


When large amounts of data
is there, performance
will be degraded

UPDATE emp SET sal=sal+1000; UPDATE emp SET sal=sal+1000;

SELECT * FROM v1; SELECT * FROM mv1;


--changes will be applied to view --changes will not be applied to
m.view
--we need to refresh the m.view
to get recent data.

Refreshing Materialized View:

• Applying the changes of base table to materialized


view is called "Refreshing Materialized View".
M.View can be refreshed in 3 ways:
ORACLE 7AM Page 219
• M.View can be refreshed in 3 ways:
○ On Demand [Default]
○ On Commit
○ On regular interval of time

On DEMAND:
In this way, we need to call "refresh()" procedure
explicitly to refresh the m.view.
"refresh()" procedure defined in"dbms_mview" package.

Syntax for calling packaged procedure:


exec package_name.procedure_name

Ex:
exec dbms_mview.refresh('MV2');

"exec / execute" command is used to call the


procedure.

CREATE MATERIALIZED VIEW mv2


REFRESH ON demand
AS
SELECT deptno,sum(sal) FROM emp
GROUP BY deptno;

SELECT * FROM mv2;

UPDATE emp SET sal=sal+1000;


COMMIT;

SELECT * FROM mv2;

exec dbms_mview.refresh('MV2');

SELECT * FROM mv2;


-- gives refreshed data

On COMMIT:
• In this way, when COMMIT is executed Materialized
view will be refreshed.

CREATE MATERIALIZED VIEW mv3


REFRESH ON COMMIT
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

SELECT * FROM mv3;

ORACLE 7AM Page 220


SELECT * FROM mv3;

UPDATE emp SET sal=sal+1000;

SELECT * FROM mv3; --changes not reflected

COMMIT; --m.view will be refreshed

SELECT * FROM mv3; --changes reflected

On regular interval of time:


In this way, materialized view can be
refreshed in a regular interval of time like:
daily sales => refresh per every day
weekly sales => refresh per every week
monthly sales => refresh per every month

CREATE MATERIALIZED VIEW mv4


REFRESH force
START WITH sysdate NEXT sysdate+interval '2' day
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

-- for every 2 days m.view will be refreshed

CREATE MATERIALIZED VIEW mv4


REFRESH force
START WITH sysdate NEXT sysdate+interval '2' minute
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

SELECT * FROM mv4;

UPDATE emp SET sal=sal+1000;


COMMIT;

SELECT * FROM mv4;

After 2 minutes:
SELECT * FROM mv4; --gives refreshed data

ORACLE 7AM Page 221


Refresh Types:

3 Refresh Types:

• Complete
• Fast
• Force

Complete:

CREATE MATERIALIZED VIEW mv2


REFRESH complete ON commit
AS
SELECT deptno,sum(sal) FROM
emp
GROUP BY deptno;

Complete Truncates complete data from m.view.


It runs SELECT query.
Result will be loaded in m.view.

deptno sum(sal)
10 10000
20 30000
30 15000

Fast:
• Only recent changes of base table will be
applied to m.view.

emp
mv2
empno ename deptno sal
10 6000 deptno sum(sal)
10 4000 10 10000
20 20000 20 30000
20 10000 30 15000
30 10000
30 5000 fast
10 20000 materialized view log
20 10000

ORACLE 7AM Page 222


30 5000 fast
10 20000 materialized view log
20 10000
10 20000
20 10000

• In FAST refresh, The changes recorded in


materialized view log file will be applied to
materialized view.
• Only recent changes will be applied here. So, it
is faster than COMPLETE refresh.
• If materialized view log file is not there, it will
be failed.

FORCE [best way]:


• In FORCE refresh, refresh type will be selected by
ORACLE implicitly.
• ORACLE gives first priority for FAST refresh. If
materialized view log file is not available, ORACLE
performs COMPLETE refresh.

COMPLETE truncates complete data from m.view.


again runs SELECT query
fills the result
FAST only recent changes will be applied to
m.view.
If m.view log file is not there it will be failed
FORCE ORACLE gives first priority for FAST refresh.
If m.view log file is not there, it performs
COMPLETE refresh

user_mviews:
It maintains all materialized view
info.

DESC user_mviews;

SELECT MVIEW_NAME FROM


user_mviews;

Dropping materialized view:

DROP MATERIALIZED VIEW mv1;

ORACLE 7AM Page 223


DROP MATERIALIZED VIEW mv1;

"Enable Query Rewrite" clause:

When we create materialized view using 'ENABLE


QUERY REWRITE'clause, even if user submits normal
query, ORACLE retrieves data from m.view only.
Thus, it improves the performance.

CREATE MATERIALIZED VIEW mv7


REFRESH ON COMMIT
ENABLE QUERY REWRITE
AS
SELECT deptno,sum(sal)
FROM emp
GROUP BY deptno;

Java Developer:

frequently work with dept wise sum of salaries

SELECT deptno,sum(Sal) FROM emp


GROUP BY deptno;

ORACLE 7AM Page 224


Synonyms
Wednesday, June 15, 2022 7:44 AM

Synonyms:
• Synonym is a DB Object.
• Synonym is used to give alias name (alternative
name) to the database object.
• Synonym is permanent whereas Table alias or
column alias are temporary. Scope of Table alias or
column alias is limited to that query only. In another
query we cannot use those names.

Advantages:
• It makes table name short.
• It avoids of writing schema name.

Syntax:

CREATE SYNONYM <syn_name> FOR <db_object>;

By default, user has no permission for creating


synonym.

DBA gives permission to create the synonym as


following:

Login as DBA:

GRANT create synonym TO c##batch7am;

Ex:
CREATE SYNONYM e FOR emp;

SELECT * FROM e;

ORACLE 7AM Page 225


INSERT INTO e(empno,ename)
VALUES(1001,'A');

Types of Synonyms:

2 Types:

• Private Synonym
• Public Synonym

Private Synonym:
Private Synonym is created by the user.

Syntax:

CREATE SYNONYM <syn_name> FOR <db_object>;

Ex:
CREATE SYNONYM d FOR dept;

Public Synonym:
It is created by DBA [DataBase Administrator]

Syntax:

ORACLE 7AM Page 226


Syntax:

CREATE PUBLIC SYNONYM <syn_name> FOR <db_object>;

c##batch7am => owner


emp

c##batch7am user is giving permission on emp


table to c##batch2pm, c##batch6pm, c##ramu

c##batch2pm:
SELECT * FROM c##batch7am.emp;

CREATE SYNONYM x FOR c##batch7am.emp;

c##batch6pm:
SELECT * FROM c##batch7am.emp;

CREATE SYNONYM y FOR c##batch7am.emp;

c##ramu:

SELECT * FROM c##batch7am.emp;

CREATE SYNONYM z FOR c##batch7am.emp;

DBA:

CREATE PUBLIC SYNONYM ee FOR c##batch7am.emp;

GRANT all ON ee TO c##ramu, c##batch2pm,


c##batch6pm;

ORACLE 7AM Page 227


c##ramu:

SELECT * FROM ee;

Dropping private synonym:

DROP SYNONYM e;

Dropping public synonym:

DROP PUBLIC SYNONYM ee;

user_synonyms:
It maintains all synonyms information

SELECT synonym_name FROM user_synonyms;

SQL

Tables
Views
Indexes
Sequences
Materialized Views
Synonyms

ORACLE 7AM Page 228

You might also like