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

R SQL

The document discusses Oracle database installation and demo classes. It provides links to video tutorials for installing Oracle 19c and for Oracle SQL and PL/SQL demo classes being conducted from January 24th to January 26th. It also includes summaries of key concepts related to databases, such as the difference between data and information, different types of databases, DBMS, RDBMS, and SQL.

Uploaded by

Avulaiah G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views

R SQL

The document discusses Oracle database installation and demo classes. It provides links to video tutorials for installing Oracle 19c and for Oracle SQL and PL/SQL demo classes being conducted from January 24th to January 26th. It also includes summaries of key concepts related to databases, such as the difference between data and information, different types of databases, DBMS, RDBMS, and SQL.

Uploaded by

Avulaiah G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

Wednesday, January 26, 2022 11:36 PM

Manoj Sir, WhatsApp Number:


Notes Link: 9010980818
https://bit.ly/oracle6pm
Software installation doubts:
Suresh sir - 8328182606

Note: Oracle DB 19c installation process


Day-9 https://youtu.be/UQl3D_XtJVs

DEMO Classes Links:


ORACLE (SQL & PL/SQL) @ 6:00 PM
(IST) by Mr.Shiva Chaitanya from 24th
January
Day-1 https://youtu.be/f4qmrlLptpk
Day-2 https://youtu.be/A_GCgMRjG6M
Day-3 https://youtu.be/LjNhcwnUSys
Day-4 https://youtu.be/GnYz6mOAVeQ
Day-5 https://youtu.be/HbSyQIVdGDY
Day-6 https://youtu.be/QR0W9rODecM
Day-7 https://youtu.be/e6ig1T8wX4A
Day-8 https://youtu.be/lKZrg9iot8w
Day-9 https://youtu.be/UQl3D_XtJVs

Oracle 6 PM Page 1
ORACLE
Monday, January 24, 2022 6:20 PM

ORACLE 19c

SQL
PL/SQL

Data
Information
Database
DBMS
RDBMS
Metadata

Data:
is a raw collection of facts about people or
places or things.

Person Place thing

nareshit smartphone
1234
4 samsung
Ravi
2nd floor 20000
500
2 room no
100

raw => unordered

raw material

engine Bike
seat Connecting
handle

Information
Data
sid sname marks
1234
Ravi Data Processing 1234 Ravi 500
500

processed one
unprocessed one
is in meaningful form
not in meaningful form
increases knowledge
does not increase knowledge of
of person
person

Micro Processor
Mother board Computer
Hard disk
RAM
.
.

Types of Data:

2 Types:
• Structured Data
• Unstructured Data

Structured Data:
data is made up of with letters, digits & special symbols

Oracle 6 PM Page 2
data is made up of with letters, digits & special symbols
Ex: 1234 Kiran Clerk 6000.00 H.NO.1-2-123

Unstructured Data:
data is in the form of audios, videos, images or documents
Ex: emp_photo emp_voice

Information:
If data is arranged in meaningful form then it is called
"Information"

Database:
• is a collection of interrelated data in an organized
form.
• Complete details about an organization.

College DB Bank DB Online shopping DB

Student Customer Products


Marks Transaction Customers
Fee Employees Orders
Employee Branches
Library Loans

College DB
Student
sid sname scity mobile
101 Srinu Hyd …

Marks
sid M1 M2 M3 tot avrg result
101 70 80 60 .. .. ..

Fee
sid total paid balanc
fee amount e
101 15000 10000 5000

Two types of databases:


• OLTP
• OLAP

OLTP OLAP [DWH / DSS]

• OnLine Transaction Processing • OnLine Analytical Processing


DWH => DataWare Housing
DSS => Decision Support System

• is used to perform day-to-day • used for data analysis. historical


operations data will be maintained
Ex: 2021-22 current DB • Ex: 2017 2018 2019 2020

• CRUD operations are performed. • R => Read operation only


○ C => Create/Insert => opening
a/c
○ R => Read => check balance
○ U => Update => withdraw
○ D => Delete => closing a/c

DBMS:
• DataBase Management System/ Software.
• is a software that is used to create &
maintain the database.

Oracle 6 PM Page 3
maintain the database.
• allows us to store, manipulate & retrieve the
data of database.
• manipulate => INSERT / UPDATE / DELETE
• emp is joining in organization => INSERT
• emp got promotion => UPDATE [modify]
• emp left the organization => DELETE
• Retrieve => opening existing data [Read]

6PM to 7.30 PM ORACLE 19c Duration: 3 Months

SQL PL/SQL

SQL Basics
=> DDL DML DCL Control Structures
TCL DRL Cursors
Operators Functions
Built-In Functions Procedures
Clauses in SQL Packages
SET Operators Triggers
Joins Exception Handling
Sub Queries Dynamic SQL
Views Collections
Indexes Working with LOBs
Synonyms
Sequences
Materialized views

RDBMS:
• Relational DataBase Management System / Software.
Before 1960s => manually in the books [papers]
• It is the software which is used to create & maintain
the database.
1960s => FMS => data in files
• Relation => Table 1976 => E.F.Codd
• We create & maintain database in the form of tables.
1970s => HDBMS [Hierarchical]
• Table => is a collection of rows & columns. RDBMS
NDBMS [Network]
Relation => Table
12 Rules

Oracle => 1979


Customer => Table / Relation / Entity
cid cname ccity
1001 Ravi Hyd column / field / attribute / property
1002 Srinu Mumbai
1003 Kiran Chennai row / record / entity instance /
tuple

field => holds individual values


record => collection of field values

Examples:
Oracle, SQL Server, My SQL, DB2, Postgre SQL

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

Marks

Oracle 6 PM Page 4
Marks

sid sname marks String


25 Kiran 456 int

Ex:
Table Name => Marks Varchar2
Field Name => sid, sname, marks Number
Data Type => 25 => Number
kiran => varchar2
Field Size => Number(4) => max 4 digits => 9999
4 => field size
Varchar2(20) => max 20 chars
20 => field size

ORACLE:
• is a Relational DataBase Management Software
[RDBMS].
• Using Oracle database software, we create &
maintain the database in the form of tables. Oracle company established in
• It allows us to store, manipulate & retrieve the 1977 with the name "Software Development
data of database. Laboratories".
• manipulate => add / delete / modify
• retrieve => opening existing data [read] Larry Ellison => 1977
• second version introduced in 1979. 1977 => Software Development Laboratories
• latest version is Oracle 21c. 1979 => Relational Software Inc.
1983 => Oracle Corp.

To work with Oracle Database we can use 2


Languages. They are:

• SQL [Structured Query Language]


• PL/SQL [Procedural Language]

SQL:
• Structured Query Language.
• we write the queries.
• we write these queries to communicate
with the database.
• query => is a request that is sent to DB C
Server. Java => Programming Languages
• Non-Procedural Language. It means, we
will not write any set of statements Software =>
here. Just we write the queries. => programs
• is a 4GL [4th generation language]. => instructions
In 4GLs, we much concentrate on what
to do rather than how to do.
• is a Unified Language. It means, it is
common for many relational database
management softwares.

ORACLE SQL SERVER MY SQL DB2

-SQL -SQL -SQL -SQL

• SQL provides operators to perform operations like


arithmetic or relational operations.
Ex: + - * > < and or not

• SQL provides built-in functions. Every function


defined to perform particular task.
Ex: min() max() avg() sum()

• SQL provides JOINS concept to retrieve the data


from multiple tables.

• SQL provides SUB QUERIES / NESTED QUERIES


concept.

Oracle 6 PM Page 5
SQL provides 5 sub languages. They are:

DDL Create
[Data Definition Language] Alter
Drop
Truncate
Rename

Flashback [Oracle 10g]


Purge [Oracle 10g]
DRL / DQL
[Data Retrieval language / Select
Data Query Language]
DML Insert
[Data Manipulation Language] Update
Delete

Insert All [Oracle 9i]


Merge [Oracle 9i]
DCL / ACL Grant
[Data Control Language / Revoke
Accessing Control Language]
TCL Commit
[Transaction Control Language] Rollback
Savepoint

DDL:
• Data Definition Language.
• It deals with metadata. customer
cid cname cust_city
Create
1001
Alter
1002
Drop
Truncate
Rename cid => number

add one column => mobilenum


Flashback [Oracle 10g]
delete the column
Purge [Oracle 10g]

DRL / DQL:
• Data Retrieval Language
• Data Query Language
• Retrieval => opening existing data [read]
• Query => request
• It deals with data retrievals

SELECT

DML:
• Data Manipulation Language.
• deal with data manipulations
• Manipulation = add / delete / modify opening account => INSERT
• emp joined => add {INSERT} closing account => DELETE
• emp left => delete {DELETE} withdraw / deposit => UPDATE
• emp got promotion => modify {UPDATE}

Insert
Delete
Update

Insert All
Merge

Oracle 6 PM Page 6
Merge

DCL / ACL :
• Data Control Language
• Accessing Control language
• It deals with data accessibility.

GRANT => is used to give permission to other users


REVOKE => is used to cancel the permissions from other users

Example:

manager

user: ravi
emp
empno ename job sal clerk

5001
user: kiran
5002

after getting permission


kiran can access emp table
ravi is owner of emp table data

GRANT Select,insert,delete,update on kiran can use SELECT only


emp to kiran; he can read the data

Revoke all on emp from kiran;

TCL:
• Transaction Control language.
• It deals with transactions.
• Transaction => is a series of commands
• series of SELECT commands
• series of INSERT / UPDATE / DELETE commands

CHECKING BALANCE => TRANSACTION

READS card info


PIN NUMBER matched with BANK DB PIN
READS BALANCE & displays to u

Every Transaction must be successfully completed


or aborted [canceled]

Withdraw => TRANSACTION

Reads card info


pin valid or not
withdraw
entering amount
sufficient amount is there in account or not
balance updated

COMMIT [Save] => save the transaction

ROLLBACK [Undo All] => cancels the transaction

Oracle 6 PM Page 7
DDL:
• Data Definition Language.
• It deals with the metadata.

SQL provides following DDL Commands:


• Create
• Alter
• Drop
• Truncate
• Rename
• Flashback
• Purge

Create:
• is used to create the database objects like tables,
view, indexes …etc.

Oracle Server
Schema [User]
Tables
Views
Indexes
Sequences
Synonyms
Materialized views
Procedures
Functions
Packages
Triggers

< > => Any


Syntax to create the Table: [ ] => Optional

Create Table <Table_Name>


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

student
sid sname Number(4) => 9999
1001 Ravi 10000 => 5digits ERROR

Create Table student


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

Oracle 6 PM Page 8
Data Types in SQL:
• Data Type tells the type of data colln of facts
which a column can hold.
• It also tells the valid range. 25
Ravi
A
67.89

SQL provides following data types:

Number Related Number(p)


int
integer

Number(p,s)
float
binary_float
binary_double
Character Related char(n)
varchar2(n)
long Raju
CLOB mobile
clerk
nChar(n)
nVarchar2(n)
nCLOB
Date & time Related Date
Timestamp
Binary Related BFILE
BLOB

Number Related Data Types:

Number(p) Number(p,s)
int float
integer binary_float
binary_double

Integer Types Floating Point Types

Number(p):
• It is Integer related data type.
• It is used to hold integers.
• p => precision => max no of digits
• valid range of p: 1 to 38
• max value: 99999…..999 [9 38digits]
• min value: -99999…..999 [-9 38digits]

cid
--------
Example: 123456
rno Number(2) => -99 to 99 123457
123458
sub1_marks Number(3) => -999 to 999

empno Number(4) => -9999 to 9999

cid Number(6) => -999999 to 999999

Mobilenum Number(10)

creditcard_num Number(16)

aadhar_num Number(12)

Oracle 6 PM Page 9
Number(p,s):
• used to hold floating point values.
• p => precision => max no of digits
• s => scale => max number of decimal places
• p => valid range => 1 to 38
• s => valid range => -84 to 127

Examples: sal avrg


----- --------
avrg Number(5,2) =>-999.99 to 999.99 12000.00 67.89
25000.00 54.52
salary Number(8,2) => 18000.00 78.91
-999999.99 to 999999.99
100000.00 100.00

p=8 p=5
s=2 s=2

Character Related Data Types:

char(n)
varchar2(n)
long
CLOB

nchar(n)
nvarchar2(n)
nCLOB => N => National

Char(n):
• it is used to hold a set of characters.
• It is fixed length char data type.
• n => max no of chars

Varchar2(n):
• it is used to hold a set of characters.
• it is variable length char data type.
• n => max no of chars

CharDemo
f1 char(10) f2 varchar2(10)
sai7spaces sai
arun6spaces arun
naresh4spaces naresh

Oracle 6 PM Page 10
Gender char(1) ename varchar2(10)
---------- -----------
M sai
F vijay
ramu

STATE_CODE char(2)
--------------------- job varchar2(20)
AP -----------
TS programmer
WB DBA
UP team leader
manager
Country_code char(3) CEO
------------------------
IND
AUS prod_name
USA ----------------
hard disk
VEHICLE_NUM char(10) RAM
------------------------ keyboard
TS09EY1234 mouse

PAN_CARD_NUM char(10)
----------------------
ABC 56 WE123

Char(n):
• it is used to hold a set of characters.
• It is fixed length char data type.
• n => max no of chars
• max size: 2000 Bytes
• Default size: 1
• Ex: Gender char => char(1)
• Ex: state_Code country_Code gender
pan_num veh_num

Varchar2(n):
• it is used to hold a set of characters.
• it is variable length char data type.
• n => max no of chars
• max size: 4000 Bytes
• Default size: no default size
• Ex: Gender varchar2 => ERROR
• Gender varchar2(1) => valid
• Exs: ename job product_name cust_name

Differences b/w char & varchar2:

Char Varchar2

• Fixed length char data type • variable length char data type

• max size: 2000 Bytes • max size: 4000 bytes

• default size: 1 • default size: no default size

• when fixed length chars are • when variable length characters


required then use it are required then use it
Ex: gender state_Code Ex: ename prod_name job

Why Varchar2?

Oracle 6 PM Page 11
Oracle 2, 3, 4, 5, 6 => Varchar Data type
There was no Varchar2 data type in above
versions.

Varchar data type has some draw backs. It was


not following one of the E.F.Codd Rules.

According to E.F.Codd,
there should be difference b/w null and space
This rule not followed by varchar data type

eid comm
------ -----
1234 2000
1235 0
1236 null

In Oracle 7 version, introduced Varchar2 Data type.


Later, oracle developers modified the varchar data
type behavior also.
In Latest versions, varchar & varchar2 both acts as
same.
Oracle company convention is:
don't use varchar data type. in future versions we
may change the behavior of varchar data type.
That is why we are using varchar2 instead of
varchar.
Note: varchar is deprecated data type.
deprecated means, in future versions they may
remove this data type or they may change the
behavior of data type.

Long:
• is used to hold a set of characters. char(n)
• max size: 2 GB 2000 bytes
• It's better to avoid of using Long data type.
Because some restrictions are there on
Long data type. varchar2(n)
• We can create only one column as long 4000 bytes
type for a table. We cannot take many
columns as long type for a table.
• We cannot use built-in functions on Long
type

Example:
Cust_Feedback
Experience_summary
Complaints

CLOB:
• Character Large Object
• It is used to hold large amounts of text.
• max size: 4GB
• We can create many columns as CLOB type
in a table
• We can use built-in functions on CLOB type.

Examples:
Cust_Feedback
Complaints
Experience_summary

Oracle 6 PM Page 12
char(n) => 2000 bytes Single Byte Char Data types
varchar2(n) => 4000 bytes ASCII Code Char data types
long => 2GB English only
clob => 4GB

nChar(n) => 2000 bytes Multi Byte Char Data Types


nVarchar2(n) => 4000 bytes UNI code char data types
nCLOB => 4 GB English + other lang chars

n => National

In C In Java

char => 1 Byte char => 2 Bytes


ASCII coding system UNI coding system
256 chars 0 to 65535
0 to 255 English + other language chars
English only

A to Z
a to z
, @ #$

Date &Time Related data types:

Date
Timestamp [Oracle 9i]

Date:
• is used to hold date values.
• default date format: DD-MON-RR
• it can hold date, month, year, hour, minute and
second
• Fixed length data type.
• memory: 7 Bytes
• default time value: 12:00:00 AM [mid night time]

Examples:
Date_Of_Bith
Date_Of_Joining
Order_date
Deliver_date

Timestamp:
• can hold date, month, year, hour, minute,
second and fractional seconds.
• fixed length data type
• memory: 11 bytes

Ex:
Transaction_date_time

Binary Related Data Types: Structured data

Oracle 6 PM Page 13
Binary Related Data Types: Structured data

letters
BFILE
digits
BLOB
symbols
These 2 data types are used to maintain
multimedia objects like audios, videos, images …etc. Unstructured Data
audios
videos
BFILE: images
• Binary File Large Object data type.
• It maintains the path of the file.
• External Large Object.
• It is not secured one. Because multimedia object
will be stored out of the database.
• bfilename() function is used to maintain the file
path.

BFILE

Screen clipping taken: 2/2/2022 6:33 PM

BLOB:
• Binary Large Object.
• Multimedia Object will be stored
inside of the database.
• Internal Large Object.
• we need to write PL/SQL program
to store binary data.

Database

empno ename ephoto [BLOB]


AB100EF2312

4 categories: 100.00

Number(p) => Number(4)

Number(p,s) => Number(5,2)

char(n) => char(1)

varchar2(n) => varchar2(15)

CLOB

Date => 23-feb-22

Timestamp

BFILE => path


BLOB => stores object

Create:

Syntax:

Create Table <name>

Oracle 6 PM Page 14
Syntax:

Create Table <name>


(
<field_name> <data_type> [constraint <con_name> <con_type>,
<fn> <dt> ………..,
…..]
);

Insert:

Syntax:

Insert into <table_name>[(<column_list>)]


values(<value_list>);

Examples on creating tables:

EX-1:

student
sid sname marks
1001 Ramu 75
1002 Kiran 56
max marks: 100

Creating table:

Create Table student


(
Oracle DB
sid number(4),
Schema [User]
sname varchar2(10),
DB Objects
marks number(3)
);
Table
View
Index

To see structure of table:

desc student; desc / describe

Output:
sid number(4)
sname varchar(10)
marks number(3)

To see tables list:

"user_tables" maintain all tables information


which are created by one user.

select table_name from user_tables;

output:
Table_name
-----------------
student
emp
dept
..

Oracle 6 PM Page 15
Inserting records: 1001 Ramu 75
1002 Kiran 56
Insert into student
values(1001,'Ramu',75);

output:
1 row created.

Insert into student


values(1002,'Kiran',56);

Inserting records using parameters:


parameter
&sid
Insert into student
&sname
values(&sid,'&sname',&marks);
&marks

output:
enter value for sid:1003
enter value for sname: vijay
run (or) / => runs recent command
enter value for marks: 55

Insert into student


values(1003,'vijay',55)

1 row created

/
enter value for sid:1004
enter value for sname: sai
enter value for marks: 88

/
enter value for sid:1005
enter value for sname: sravan
enter value for marks: 67

Downloading & Installing software:

Open SQL PLUS:

windows + R => sqlplus

Log in as DBA:
user name: system
password: nareshit
[during s/w installation u have
given password. i.e DBA password]

Syntax to create the user [schema]:

Create User <user_name>


identified by <password>
default tablespace <tablespace_name>
quota <memory> on <tablespace_name>;

Oracle 6 PM Page 16
c## => common user

Create user c##batch6pm


identified by nareshit
default tablespace users
quota unlimited on users;

Grant connect,resource to c##batch6pm;

Ex on creating table:

employee
empno ename job sal doj
1001 Ravi clerk 8000 23-nov-2019

Create table employee 100000.00


(
empno number(4),
ename varchar2(10),
job varchar2(10),
sal number(8,2),
doj date
);

Insert into employee


values(1001,'Ravi','Clerk',8000,'23-nov-2019');

Insert into employee


values(1002,'Kiran','Clerk',8000,to_date('23-nov-2019'));

Inserting records using parameters:

Insert into employee


values(&empno,'&ename','&job',&sal,'&doj');

enter value for empno: 1003


enter value for ename:Srinu
enter value for job: salesman
enter value for sal: 7000
enter value for doj: 17-aug-2020

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

..

Inserting limited column values:

Oracle 6 PM Page 17
Inserting limited column values:

Insert into
employee(empno,ename,job)
values(1006,'A','manager');

Inserting limited column values by


changing the order:

Insert into
employee(ename,job,empno)
values('B','clerk',1007);

Null:
• Null value means empty / blank.
• Null is not equals to 0 or space.
• When the value is unknown we insert null value.

emp
empno ename job sal
1001 AA CLERK
1002 BB manager 12000

student
sid sname M1
1001 AA 70
1002 BB
1003 CC 0

Null:
• Null value means empty / blank.
• Null is not equals to 0 or space.
• When the value is unknown we
insert null value.
• when null is participated in
expression then result will be
null only.
• Ex:
set pages 200 lines 200
○ 10+20 = 30
○ 10 + null = null
pages 200:
○ 10-null = null
in one page it
• Null comparison is not possible
can display 200 records
using = [equals to] operator.
• "IS NULL" operator is used
lines 200:
to compare with null value.
in one line it
Ex:
can display 200 chars
comm=300 //valid
comm=1400 //valid
comm=null //invalid => no rows
selected empno Number(4) ename doj
comm is null //valid => null -----------
comparing comm value with null 1234 => valid
value A-1234
• Null can be accepted by any data null
type column. number data type can accept only
digits

Inserting NULL value:

NULL value can be inserted using


2 ways:
• by inserting limited column values [IMPLICIT]
• using NULL [EXPLICIT]

Oracle 6 PM Page 18
Example:

Customer
cid cname ccity mobile
1001 A Hyd 90123……..
1002 B null null

Create Table Customer


(
cid number(4), 1001 A Hyd 90123…
cname varchar2(10),
ccity varchar2(10),
mobile number(10)
);

Insert into customer


values(1001,'A','Hyd',9012345678);

IMPLICIT:
1002 B

insert into customer


values(1002,'B');
error => NOT ENOUGH VALUES
WE need to insert 4. but we are passing 2

To insert limited column values:

Insert into customer(cid,cname)


values(1002,'B');

total 4 values
we are passing 2 values
remaining 2 values will be inserted as NULL implicitly

inserting limited column values by changing order:

insert into customer(cname,cid)


values('C',1003);

1004 D 9012389764

Insert into
customer(cid,cname,mobile)
values(1004,'D',9045678923);

2nd way:
1005 E

insert into customer


values(1005,'E',null,null);

insert into customer


values(1006,'F',null,9098765432);

insert into customer


values(1006,'F','null',9098765432); //wrong result

city name will be taken as null.


don't use single quotes when insert null value in the
string related data type.

Oracle 6 PM Page 19
Constraints:

Syntax to create the table:

Create Table <name>


(
<f_name> <data_type> [constraint <con_name> <con_type>,
……,
….
);

<f_name> <data_type> [constraint <con_name> <con_type>

Field Definition

Constraints:
• Constraint is a rule that is applied on a column.
• It restricts the user from entering invalid data. Ex:
• It is used to maintain data integrity. max marks: 100
• Data Integrity means, maintaining accurate & student
quality data. sid sname M1 min=> 0
1 A 56 max => 100
Oracle SQL provides following constraints:
2 B 786
• Primary Key
• Unique
500 seats
• Not Null
flight
• Check
• Default pid pname seatnum
• References [Foreign Key] 101 Ravi 754

Gender
------------
Primary Key:
M
• should not accept duplicate values.
F
• should not accept null values.

Ex:
student
customer
sid sname M1
1001 Ravi 56 cid cname ccity
1002 Raju 78 Ravi Hyd
Vijay 93 Raju Hyd
1003 Ravi 78 Ravi Mumbai
1001 Kiran 66 Raju Mumbai
Duplicate

Unique:
• It does not accept duplicate values.
• It accepts the null values.
• to maintain null or unique values, use it

Example:

Customer

cid cname mobile mailid aadhar_num


1001 Ravi 90123… [email protected] 1234…..
1002 Srinu qwer@gmail
1003 Ramu 89123… [email protected]

Oracle 6 PM Page 20
1001 Ravi 90123… [email protected] 1234…..
1002 Srinu qwer@gmail
1003 Ramu 89123… [email protected]

Not Null:
• should not accept null values.
• it accepts duplicate values.
• when we want to demand for a
value & accept the duplicate the
value, use it.

Ex:

emp

empno ename job sal


1234 Raju clerk 7000
1235 manager 12000
1236 Raju salesman 9000

constraint null duplicate


Primary Key No No
Unique Yes No
Not Null No Yes

UNIQUE + Not Null = PK

[no duplicate] [no null]

Check:
• is used to apply our own rules on a column.

Ex:
Max Marks: 100

sid sname M1
min marks: 0
1 A 78 max marks: 100
2 B 123

emp

empno ename Gender


1001 A M
1002 B F
1003 C Z

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

student FEE => 15000


colg_name => XYZ
sid sname FEE Colg_name Ccity Ccity => Hyd
101 A 15000 XYZ Hyd Nationality => INDIAN

102 B 15000 XYZ Hyd


103 C 5000 XYZ Hyd

Oracle 6 PM Page 21
103 C 5000 XYZ Hyd

References [Foreign Key]:

Foreign Key refers to Primary key values of another table.

Ex:
course student

cid cname sid sname cid


10 Java 5001 A 20
20 Python 5002 B 30
30 C# 5003 C 80

Dept emp

deptno dname empno ename deptno


10 Accounts 7001 A 10
20 Sales 7002 B 30
30 Research 7003 C 90

Syntax to create the table:

Create Table <Name>


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

Examples on constraints:

Ex-1:

student1
sid sname M1

sid => PK
sname => Not Null
M1 => b/w 0 to 100

Create Table Student1


(
sid Number(4) Primary Key,
sname Varchar2(10) Not Null,
M1 number(3) Check(M1>=0 and M1<=100)
);

Insert into Student1 values(101,'A',68);

Insert into Student1 values(null,'B',55); --ERROR

Oracle 6 PM Page 22
Insert into Student1 values(null,'B',55); --ERROR

Insert into Student1 values(101,'B',55); --ERROR

Note:
When we define the constraint we have to give
constraint name. If we don't give constraint
name ORACLE gives constraint name implicitly
by prefixing it with "sys_c"

Ex: sys_c001234

Insert into Student1 values(102,'B',567); -- ERROR

check constraint violated

Insert into student1 values(103,null,45); --ERROR

Insert into student1 values(104,'A',77);

Ex-2:
Student2
sid sname FEE cname ccity

sid => Unique


sname => Not Null
FEE => default 15000
cname => default XYZ
ccity => dafault Hyd

Create Table Student2


(
sid Number(4) Unique,
sname Varchar2(10) Not Null,
fee Number(7,2) Default 15000,
cname Varchar2(10) Default 'XYZ',
ccity Varchar2(10) Default 'HYD'
);

Insert into Student2(sid,sname)


values(5001,'A');

Insert into Student2(sid,sname)


values(null,'B');

Insert into Student2(sid,sname)


values(5001,'C'); --ERROR

Select * from Student2;

Ex on Foreign Key:

Course Student3

Oracle 6 PM Page 23
Ex on Foreign Key:

Course Student3
PK
cid cname sid sname cid
10 Python 5001 A 30
20 Java 5002 B 20
30 C# 5003 C 70

Create Table Course(


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

Insert into Course values(10,'Python');

Insert into Course values(20,'Java');

Insert into Course values(30,'C#');

Create Table Student3


(
sid Number(4),
sname Varchar2(10),
cid Number(2) References Course(cid)
);

Insert into Student3 values(8001,'A',30);

Insert into Student3 values(8002,'B',20);

Insert into Student3 values(8003,'C',80); --ERROR

Assignment:

Dept Emp
deptno dname empno ename deptno
10 HR 1001 A 30
20 Sales 1002 B 10
30 Accounts 1003 C 90

Naming Constraints:

• We can give names to the constraints in column


definition. It is called "Naming Constraint".
• When we create field with constraint type we
must specify constraint name. If we don't give
constraint name ORACLE gives a name
implicitly by prefixing it with "sys_c".
• Ex: sys_c004567

Oracle 6 PM Page 24
Ex on naming constraints:

Student5

sid sname M1

sid => PK => constraint name c1


sname => Not Null => constraint name c2
M1 => Check => constraint name c3

Create Table Student5


(
sid Number(4) constraint c1 Primary Key,
sname Varchar2(10) constraint c2 Not Null,
M1 Number(3) constraint c3 Check(M1>=0 and M1<=100)
);

User_Constraints:
It maintains all constraints information.

Desc User_Constraints;

Select Constraint_Name, Constraint_Type,


Table_Name From User_Constraints;

Constraints can be applied in 2 styles:


• Column Level Constraints [Inline Constraints]
• Table Level Constraints [Out of Line Constraints]

Column Level Constraints [Inline Constraints]:


If we define the constraint in column definition then
it is called "Column Level Constraint".

Column definition:

<col_name> <data_type> constraint <con_name> <con_type>

All 6 constraints can be applied at column level.

Create table student6


(
sid number(4) constraint cc1 primary key,
sname varchar2(10) constraint cc2 not null,
m1 number(3) constraint cc3 check(m1>=0 and m1<=
100)
);

Table Level Constraints [Out of line constraints]:


After defining all columns, if we define the
constraints these constraints are called
"Table Level Constraints".
We can apply 4 constraints at table level:
Primary Key
Unique
Check
References

Oracle 6 PM Page 25
References

Not Null & Default Constraints cannot be applied at


Table Level.

PK => sid
Check => M1
Create Table student7
(
sid number(4),
sname Varchar2(10),
M1 Number(3),
constraint ccc1 Primary Key(sid),
constraint ccc2 Check(M1>=0 and M1<=100)
);

Dept1 Emp1
deptno dname empno ename deptno
10 Sales 1001 A 30
20 HR 1002 B 10
30 Research 1003 C 90

Create Table Dept1


(
deptno Number(2),
dname Varchar2(10),
constraint dept_pk Primary Key(deptno)
);

Create Table Emp1


(
empno Number(4),
ename Varchar2(10),
deptno Number(2),
constraint emp_pk Primary Key(empno),
constraint emp_fk Foreign Key(deptno) References Dept1(deptno)
);

DDL Commands:

Create
Alter
Drop
Truncate
Rename

Flashback
Purge

Alter:
• Alter => Change
is used to change the structure of table.

Oracle 6 PM Page 26
• is used to change the structure of table.

Using this command we can:


○ Add the Columns
○ Modify The Field Sizes
○ Modify the Data types
○ Rename the columns
○ Drop the Columns
○ Add the Constraints
○ Disable the Constraints
○ Enable the Constraints
○ Rename The Constraints
○ Drop The Constraints

Syntax of Alter Command:

Alter Table <Table_Name> add


modify
drop column
rename column
drop
add constraint
disable constraint
enable constraint
rename constraint
drop constraint

add:
is used to add the columns

Ex:
student8
sid sname
sid sname M1
adding a column [M1]:
Alter Table student8 add M1 Number(3);

desc student8;
sid
sname
M1

Adding 2 Columns [M2, M3]:

Alter Table student8 add(m2 number(3),m3 number(4));

Rename Column:
[rename m3 column to maths]

sid sname M1 M2 M3

Alter Table student8 rename column M3 to Maths;

Dropping [deleting] a Column:


[Delete MATHS column]

student8
sid sname M1 M2 Maths

Alter table student8 drop column Maths;


(or)
Alter table student8 drop(Maths);

Oracle 6 PM Page 27
Alter table student8 drop(Maths);

drop column => used to drop a column


drop => used to drop one or more columns

Dropping Multiple Columns:


Delete M1 & M2 Columns

student8
sid sname M1 M2

Alter Table student8 drop(m1,m2);

modify:
is used to modify the field sizes or data types.

student8
sid sname

Alter table student8 modify sname varchar2(20);

sname
-----------
Raju
Kiran
Vijay
Naresh

Ca we decrease the size of data type?


Yes. But we can decrease up to max no of chars in
the column data.

Alter table student8 modify sname varchar2(15);

Modifying the data type:

sid
--------

Alter Table student8 modify sid Varchar2(10);

Example on Alter:

emp11
empno ename

Create Table emp11


(
empno number(4),
ename varchar2(10)
);

100000.00

Add job & sal columns:

Oracle 6 PM Page 28
Add job & sal columns:

Alter Table emp11 add(job varchar2(10),


sal number(8,2));

rename sal column to salary:

Alter Table emp11 rename column


sal to salary;

Dropping salary & job columns:

Alter Table emp11 drop(job,salary);

Add primary key constraint to empno column:

Alter Table emp11 add constraint xyz


Primary Key(empno);

Disabling constraint:

Alter Table emp11 disable constraint xyz;

Enabling Constraint:

Alter Table emp11 enable constraint xyz;

Renaming Constraint:

Alter Table emp11 rename constraint xyz to abc;

Dropping Constraint:

Alter Table emp11 drop constraint abc;

ADD CONSTRAINT:
• we can add table level constraints only.
• table level constraints => 4
○ Primary Key
○ Unique
○ Check
○ References [Foreign Key]

To add Not Null or Default use "MODIFY" keyword

Customer

cid cname Aadhar State

Add Unique Constraint to Aadhar field:

Alter Table Customer add constraint cc1


Unique(Aadhar);

Adding NOT NULL to cname:

Alter Table Customer


modify cname varchar2(10) constraint cc2 Not Null;

Oracle 6 PM Page 29
Adding default constraint to State column:

Alter Table customer


modify State Varchar2(10) constraint cc3
default 'Telangana';

std
sid sname M1

Adding check constraint to M1:

Alter Table std add constraint cc4 check(m1>=0


and m1<=100);

Course Student
cid cname sid sname cid

Adding Primary Key:


Alter Table Course add constraint cc5
Primary Key(cid);

Adding Foreign Key:

Alter Table Student add constraint cc6


Foreign Key(cid) References Course(cid);

DDL Commands:

Create
Alter

Truncate

Drop
Flashback
Purge

Rename

TRUNCATE:
• is used to delete all records from
the table.
• It clears the memory.

customer
cid cname ccity
5001 A Hyd
5002 B Chennai

Syntax:

Truncate Table <table_name>;

Oracle 6 PM Page 30
Truncate Table <table_name>;

Example:
Truncate table emp11;

It deletes all records from


table.
It will not delete the table
structure.
table structure will be existed.

DROP
FLASHBACK => Oracle 10g
PURGE => Oracle 10g

DROP:
• is used to drop the tables.
• Dropped tables will be stored in recycle
bin.
• If we want to recollect it in future, we can
recollect it from recycle bin
• Before Oracle 10g version "RecycleBin"
concept was not available.
• "RecycleBin" concept introduced in Oracle
10g version

Syntax:

Drop Table <Table_Name> [Purge];

Dropping a Table:

Drop Table student1;

show recyclebin;

Flashback:
• used to recollect the dropped tables from recycle
bin.

Syntax:

Flashback Table <Table_name>


to before drop [rename to <new_name>];

Flashback Table student1 to before drop;

For Ex:

• student1 is existing table


• dropping the table
• dropped table will be moved to recyclebin
• we are creating another table with the
name "student1"

Oracle 6 PM Page 31
name "student1"
• Now, we are Flashbacking the table
"student1". It will give ERROR
• Within the schema, table name must be
unique. That's why it gives ERROR
• In this situation, recollect dropped table
with new name. For this we use
"RENAME TO <NEW_NAME>".

Flashback Table student1


to before drop
rename to student_old;

Purge:
is used to delete the dropped table
from recycle bin.

Syntax:

Purge Table <Table_name>;

Drop Table student_old;


-- table will be dropped & placed in recyclebin

Purge Table student_old;


-- table will be deleted from recyclebin.
-- Permanently table will be deleted

(OR)

Drop Table student_old Purge;


-- Dropped table will not be placed in Recycle Bin.
-- Permanently it wll be deleted

Emptying Recyclebin:

Purge Recyclebin; -- It clears the recyclebin

DDL Commands:

Create
Alter
Truncate
Drop
Flashback
Purge
Rename

Rename:
used to rename the database objects

Syntax:

Rename <OLD_NAME> to <NEW_NAME>;

Rename student8 to abcd;

SQL:

5 sub languages:

Oracle 6 PM Page 32
DDL Create
Alter
Drop
Truncate
Flashback
Purge
Rename
DRL / DQL SELECT
DML
DCL
TCL

DRL / DQL :
• DRL => Data Retrieval Language
• DQL => Data Query Language
• Retrieval => opening existing data
• Query => is a request that is sent to DB Server
• SELECT command comes under DRL.
• It is used to retrieve the data from the table.

Syntax of SELECT:
Select ename,sal
From emp
SELECT [DISTINCT] <column_list> / *
Where sal>3000;
FROM <table_list>
[WHERE <condition>]
[GROUP BY <grouping_column_list>]
[HAVING <group_condition>]
[ORDER BY <column_list> Asc / Desc] ;

ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES - are part of query

SELECT => is used to specify Column List


FROM => is used to specify table list
WHERE => is used to specify condition on rows

Using SELECT command, we can display


• all records & all columns
• limited columns
• limited rows
• limited rows and columns

all records & all columns:

SELECT * FROM emp;

limited rows:

SELECT * FROM emp WHERE job='MANAGER';

limited columns:

SELECT ename,job,sal FROM emp;

limited rows & columns:

SELECT ename,job,sal FROM emp


WHERE sal>2000;

Oracle 6 PM Page 33
OPERATORS in SQL:

Operator:
is a symbol that is used to perform operations
like arithmetic or logical operations.
Ex: sal*12 sal>5000

ORACLE SQL provides following operators:

Arithmetic + - * /
Relational (or) < <= > >= = <> (or) != (or) ^=
Comparison equals not equals
Logical And Or Not
Special IN NOT IN
BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL
SET UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||
Miscellaneous EXISTS
ANY
ALL

PIVOT
UNPIVOT

Arithmetic Operators:
Arithmetic operators are used to perform
Arithmetic Operations.

+ Addition 5+2 = 7
- Subtraction 5-2 = 3
* Multiplication 5*2 = 10
/ Division 5/2 = 2.5

DUAL:
• is a dummy table.
• It is used to work with non-database
values temporarily.

Calculate 2+3+4:

SELECT 2+3+4 FROM dual;

2+3+4
------------
9

SELECT 2+3+4 as total FROM dual;

TOTAL
----------
9

SELECT 2+3+4 total FROM dual;

TOTAL
----------
9

SELECT 2+3+4 as total value FROM dual; --ERROR

Oracle 6 PM Page 34
SELECT 2+3+4 as total value FROM dual; --ERROR

SELECT 2+3+4 as "total value" FROM dual;

total value
-----------------
9

Column Alias [another name / alternative name]:


• Column alias is used to display alternative column
heading in the result of SELECT query.
• "as" keyword is used to give column alias.
• Using "as" keyword is optional.
• To maintain case & to accept space in the column
alias specify alias name in double quotes.
• Ex: 2+3+4 as "total value"

Calculate Annual Salary:

SELECT ename, sal,


sal*12 as "Annual Salary"
FROM emp;

Calculate TA, DA, HRA, TAX & GROSS salary of


employees:
10% on sal as TA
20% on sal as HRA
15% on sal as DA
5% on sal as TAX
GROSS => sal+TA+HRA+DA-TAX

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

student
sid sname M1 M2 M3
1 A 50 80 70
2 B 70 30 90

Create Table student


(
sid number(4),
sname varchar2(10),
m1 number(3),
m2 number(3),
m3 number(3)
);

Insert into student values(1,'A',50,80,70);

Insert into student values(2,'B',70,30,90);

Calculate total and average:

SELECT sname,
M1+M2+M3 as TOTAL,
(M1+M2+M3)/3 as AVRG

Oracle 6 PM Page 35
(M1+M2+M3)/3 as AVRG
FROM student;

Relational Operators / Comparison Operators:

are used to compare 2 values.

< less than


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

Display the emp records whose sal is greater than


2500:

SELECT empno,ename,sal FROM emp


WHERE sal>2500;

Display the emp records whose salary is 3000 or


greater:

SELECT * FROM emp


WHERE sal>=3000;

Display the emp records whose sal is less than


1500:

SELECT * FROM emp


WHERE sal<1500;

Display the emp records whose salary is 1100 or


less:

SELECT * FROM emp


WHERE sal<=1100;

Display the emp record whose empno is 7900:

SELECT * FROM emp


WHERE empno=7900;

Display the emp record whose name is 'BLAKE':

SELECT * FROM emp


WHERE ename='blake';

no rows seleted => 'BLAKE' = 'blake'

NOTE:
SQL not case sensitive language. But for string
comparison, it is case sensitive.

Display all managers records:

SELECT * FROM emp


WHERE job='manager';

Display all employees records except


SALESMAN:

SELECT * FROM emp


WHERE job<>'SALESMAN';

Oracle 6 PM Page 36
Display the emp records who are working in deptno 20:

SELECT * FROM emp


WHERE deptno=20;

Display the emp records who are not working in deptno 30:

SELECT * FROM emp


WHERE deptno!=30;

Display the emp records who joined after 1981:

SELECT ename,hiredate FROM emp


WHERE hiredate>'31-DEC-1981';

Display the emp records who joined before 1982:

SELECT ename,hiredate FROM emp


WHERE hiredate<'1-JAN-1982';

Asc Asc Date


1 A 1-JAN-2022
2 B 2-JAN-2022
3 C 3-JAN-2022
4 D
5

Logical Operators:
are used to perform logical operations

And is used to perform Logical AND operations


Or is used to perform Logical Or operations
Not is used to perform Logical Not operations

condition1 condition2 condn and condn2 condn1 or condn2


T T T T
T F F T
F T F T
F F F F

And, Or operators are used to write multiple conditions.

And All conditions should be satisfied


Or At least one condition to be satisfied

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

Max marks: 100


Min Marks: 40 => in each sub => pass

Display the passed student records:

SELECT * FROM student


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

Oracle 6 PM Page 37
WHERE M1>=40 and M2>=40 and M3>=40;

Display the failed students records:

SELECT * FROM student


WHERE m1<40 or m2<40 or m3<40;

Display all managers and clerks records:

SELECT * FROM emp


WHERE job='MANAGER' OR job='CLERK';

Display the manager records whose sal is greater


than 2500:

SELECT * FROM emp


WHERE job='MANAGER' AND sal>2500;

Display the all managers records whose sal is > 2500


and joined after apr 1981:

SELECT * FROM emp


WHERE job='MANAGER' AND sal>2500
AND hiredate>'30-APR-1981';

Display the emp records whose empnos are


7369,7499,7900:

SELECT * FROM emp


WHERE empno=7369 or empno=7499 or empno=7900;

Display all emps records except clerks:

SELECT ename,job FROM emp NOT


WHERE not(job='CLERK'); condition Not(condition)
T F
(or)
F T
SELECT ename,job FROM emp
WHERE job!='CLERK';

Display all emps records except clerks and managers:

SELECT ename,job FROM emp


WHERE not(job='MANAGER' or job='CLERK');

Display the emp records who are


working in 10 and 20:

SELECT * FROM emp


WHERE deptno=10 OR deptno=20;

Display the emp records whose


names are 'ALLEN', 'BLAKE' and
'SCOTT':

SELECT * FROM emp


WHERE ename='ALLEN' Or
ename='BLAKE' Or
ename='SCOTT';

Display the emp records who are


not working in deptno 30:

SELECT * FROM emp


WHERE deptno!=30;

(or)

SELECT * FROM emp


WHERE deptno!=30;

Oracle 6 PM Page 38
WHERE deptno!=30;

Special Operators:
• are also comparison operators

IN NOT IN
BETWEEN AND NOT BETWEEN AND
IS NULL IS NOT NULL
LIKE NOT LIKE

IN:

Syntax:

<column_name> IN(<val1>,<val2>,………);

• It is used to compare column value with a list of


values.
• If column value existed in list of values, it returns
true. Otherwise, it returns false.
• It avoids of writing multiple conditions using OR.

Display the emp records whose empnos are 7369, 7900,


7902,7499:

SELECT * FROM emp


WHERE empno=7369 Or empno=7900 Or empno=7902
or empno=7499;

(or)

SELECT * FROM emp


WHERE empno IN(7369,7900,7902,7499);

Display the emp records who are working in 10th dept


& 30th dept:

SELECT * FROM emp


WHERE deptno IN(10,30);

Display the emp records who are not working in deptno


30:

SELECT * FROM emp


WHERE deptno NOT IN(30);

Display all managers and clerks records:

SELECT * FROM emp


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

Display all emps records except managers and


salesman:

SELECT * FROM emp


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

Display the emp records whose names are


SMITH, ALLEN, SCOTT and WARD:

SELECT * FROM emp


WHERE ename IN('SMITH','ALLEN','SCOTT','WARD');

Oracle 6 PM Page 39
Display all emps records except SCOTT and WARD:

SELECT * FROM emp


WHERE ename NOT IN('SCOTT','WARD');

BETWEEN AND:

Syntax:

<column_name> BETWEEN <lower_value> AND <higher_value>

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


• It is suitable when we want to compare a value with a range of
values.
• If column value falls under the range, it returns TRUE. Otherwise,
it returns FALSE.

Display the emp records whose sal is between 2000 and 3000:

SELECT * FROM emp


WHERE sal>=2000 AND sal<=3000;
(OR)
SELECT * FROM emp
WHERE sal BETWEEN 2000 AND 3000;

Display the emp records whose sal is less than 2000 or


greater than 3000:

SELECT * FROM emp


WHERE sal<2000 OR sal>3000;
[OR]
SELECT * FROM emp
WHERE sal NOT BETWEEN 2000 and 3000;

Display the emp records who joined in 1981:

SELECT * FROM emp


WHERE hiredate>='1-JAN-1981' AND hiredate<='31-DEC-1981';

[OR]

SELECT * FROM emp


WHERE hiredate BETWEEN '1-JAN-1981' AND '31-DEC-1981';

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

SELECT * FROM emp


WHERE hiredate BETWEEN '1-JAN-1982' AND '31-DEC-1984';

IS NULL:
• It is used for null comparison.
• To compare a column value with NULL, use IS NULL.
We cannot use = [equals operator] for null comparison.

Oracle 6 PM Page 40
• We cannot use = [equals operator] for null comparison.

Syntax:
<column_name> IS NULL

Display the emp records whose comm is null:

SELECT * FROM emp


WHERE comm IS Null:

Display the emp records who are getting commission:

SELECT * FROM emp


WHERE comm IS NOT NULL;

Like Operator:
• used to compare column value with text pattern.

SQL provides 2 wild card characters. They are:

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

Syntax:

<column_name> LIKE <text_pattern>

If column value matches with text pattern, it


returns TRUE. otherwise, it returns FALSE.

Display the employee records whose names


SMITH
are started with 'S':
ALLEN
SCOTT
SELECT * FROM emp
WHERE ename like 'S%';

Display the emp records whose names are


ended with S:

SELECT * FROM emp


WHERE ename LIKE '%S';

Display the emp records whose name's


middle character is 'A':

SELECT * FROM emp


WHERE ename LIKE '%A%';

Display the emp records whose name ended


with 'RD':

SELECT * FROM emp


WHERE ename LIKE '%RD';

Display the emp records whose names


second character is 'A':

SELECT * FROM emp


WHERE ename LIKE '_A%';

Display the emp records whose names


starting letter and ending letter are 'D':

SELECT * FROM emp


WHERE ename LIKE 'D%D';

Display the emp records whose is having


4 chars:

Oracle 6 PM Page 41
4 chars:
SMITH
SELECT * FROM emp WARD
WHERE ename LIKE '____';

Display the emp records whose name is


having 'AM' characters:

SELECT * FROM emp


WHERE ename LIKE '%AM%';

Display the emp records whose names third


character is 'L':

SELECT * FROM emp


WHERE ename LIKE '__L%';

Display the emp records whose name is


having 5 chars only:

SELECT * FROM emp


WHERE ename LIKE '_____';

Display the emp records who joined in 1982:

SELECT * FROM emp


WHERE hiredate LIKE '%82'; 23-DEC-83
12-JAN-82
18-FEB-82
17-OCT-83

Display the emp records who


joined in 1980 or 1983:

SELECT empno,ename,hiredate
FROM emp
WHERE
hiredate LIKE '%80'
Or
hiredate LIKE '%83';

Display the emp records who joined in DECEMBER


month:
23-DEC-83
12-JAN-82
SELECT empno,ename,hiredate 18-FEB-82
FROM emp 17-OCT-83
WHERE hiredate LIKE '%DEC%';

Display the emp records whose salary is in 4 digits:

SELECT ename,sal FROM emp


WHERE sal LIKE '____';

Display the emp records who joined in first 9 days in


the month:

SELECT ename,hiredate FROM emp


WHERE hiredate LIKE '0%';

Display all emps whose names are not started


with 'S':

SELECT * FROM emp


WHERE ename NOT LIKE 'S%';

Oracle 6 PM Page 42
mail_id
-----------
[email protected]
[email protected]

Display the emp records whose name is having


'_':

SELECT * FROM emp


WHERE ename LIKE '%\_%' ESCAPE '\';

Display the emp records whose name is


having %:

SELECT * FROM emp


WHERE ename LIKE '%\%%' ESCAPE '\';

Concatenation Operator ( || ):
• concatenate => combine
• is used to combine the strings.

Syntax:
string1 || string2 || string3

SELECT 'raj' || ' ' || 'kumar' FROM dual;

SELECT empno || ' ' || ename || ' ' || sal


FROM emp;

Oracle 6 PM Page 43
DML
Thursday, February 17, 2022 6:24 PM

DML Commands:
• Data Manipulation Language.
• Manipulation = INSERT + UPDATE[modify] +DELETE
• For Ex, emp joined in Organization => INSERT
• emp got promotion => UPDATE
• emp left from org => DELETE
• DML deals with data.
• All DML commands are not auto-committed. Where as
DDL commands are auto-committed.
• After using DML command to save the transaction use
COMMIT command.
• After using DML command to cancel the transaction use
ROLLBACK command.

TCL [Transaction Control Language]:

COMMIT
ROLLBACK
SAVEPOINT

COMMIT [SAVE]:
• is used to make the changes the permanent.
It means, it is used to save the transactions.
• When COMMIT command is executed, All the
changes of Oracle Instance [RAM] will be
applied to Oracle Database [Hard Disk].

Rollback [ UNDO ALL ]:


• Rollback cancels all previous transactions.
It means, All uncommitted transactions
will be cancelled when ROLLBACK is
executed.

• All DDL commands are auto-committed.


All DML commands are not auto-committed.
Oracle 6 PM Page 44
• All DML commands are not auto-committed.

DDL Command = DDL command + COMMIT

create table tt1


create table tt2
INSERT
INSERT
INSERT
INSERT
INSERT
Create Table tt3
INSERT
INSERT
ROLLBACK => 4 actions
INSERT
cancelled
ROLLBACK => 2
actions cancelled

INSERT:
• used to insert the records.
• Using INSERT command, we can
○ insert single record
○ insert the record using parameter
○ insert limited column values
○ insert limited column values by changing order
○ insert the records from existing table [copying records]

Syntax:

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


VALUES(<value_list>);

Example:

Customer
cid cname ccity

Oracle 6 PM Page 45
Create Table Customer
(
cid number(4),
cname varchar2(10),
ccity varchar2(10)
);

Inserting a record:

INSERT into customer values(1001,'A','Hyd');

Inserting records using parameters:

Insert into customer values(&cid,'&cname','&ccity');

enter value for cid:


enter value for cname:
enter value for ccity:

/
enter value for cid:
enter value for cname:
enter value for ccity:

Inserting limited column values:

INSERT into customer values(1005,'E'); --ERROR

INSERT into customer(cid,cname) values(1005,'E');

Inserting limited column values by changing the


order:

INSERT into customer(cname,cid) values('F',1008);

Oracle 6 PM Page 46
Inserting records from existing table:
[Copying the records from one table to another]

Customer Emp
cid cname ccity empno ename job sal
1001 5001 ..
1002 5002 ..
5003 ..
5004 ..

Syntax:

INSERT into <Table_Name>[(<column_list>)]


<SELECT query>;

SELECT query result will be inserted into table.

Ex:
INSERT INTO customer(cid,cname)
SELECT empno,ename FROM emp;

--All EMP table records will be copied into CUSTOMER table

Update Command:
• is used to modify [update] the data.
• Using this command we can:
○ update single column value of single record
○ update multiple column values of single record
○ update a set of records
○ update all records
○ update the records using parameters

Oracle 6 PM Page 47
Syntax:

UPDATE <table_name>
SET <column1>=<value1>[,<column2>=<value2>,….]
[WHERE <condition>];

○ updating single column value of single record:

Ex:
Increase 2000 rupees salary to the emp whose
empno is 7499:

UPDATE emp
SET sal=sal+2000
WHERE empno=7499;

Updating a set of records:

Exs:
Set sal value as 4000 to the employees whose sal is
null:
UPDATE emp
SET sal=4000
WHERE sal IS NULL;

Increase 2000 rupees salary to all clerks:

UPDATE emp
SET sal=sal+2000
WHERE job='CLERK';

○ updating multiple column values of single record:

Ex:
Update job value as manager and salary value as
5000 to the emp whose empno is 7369:

Oracle 6 PM Page 48
UPDATE emp
SET job='MANAGER', sal=5000
WHERE empno=7369;

Updating all records:

Increase 1000 rs salary to all employees:

UPDATE emp SET sal=sal+1000;

Updating records using parameters:

Ex:
Increase sal as following:
7369 => increase 1500
7499 => increase 2000
7900 => increase 1000

UPDATE emp
SET sal=sal+&amount
WHERE empno=&empno;

Enter amount: 1500


Enter empno: 7369

/
Enter amount: 2000
Enter empno: 7499

Increase 10% sal to all managers and clerks:

UPDATE emp
SET sal=sal+sal*0.1
WHERE job IN('MANAGER','CLERK');

Oracle 6 PM Page 49
WHERE job IN('MANAGER','CLERK');

Increase 20% sal to the emps who are getting


commission:

UPDATE emp
SET sal=sal+sal*0.2
WHERE comm is not null;

Increase 15% sal to the emps who are having


more than 40 years experience:

UPDATE emp
SET sal=sal+sal*0.15
WHERE (sysdate-hiredate)/365>40;

Increase 20% sal, 10% comm to the emps who


are getting commission:

UPDATE emp
SET sal=sal+sal*0.2, comm=comm+comm*0.1
WHERE comm is not null;

Transfer all deptno 20 emps to 10 dept:

UPDATE emp
SET deptno=10
WHERE deptno=20;

Update comm value as null to the employees


who are getting the commission:

UPDATE emp
SET comm=null
WHERE comm is null;

Oracle 6 PM Page 50
IN C, JAVA: IN SQL:

== equals = equals
= Assignment
= Assignment

WHERE <condition>
x=50
WHERE sal=3000 => comparison
x==50
SET sal=3000 => Assignment

UPDATE emp
SET comm=null
WHERE comm is not null;

comm=null => valid for null assignment


comm=null => invalid for null comparison

WHERE comm=null => invalid => comparison


SET comm=null => valid => assignment

Note:
FOR null comparison use "IS NULL"
FOR null null assignment use " = " [Assignment operator]

Increase 10% sal to all employees & set comm


value as 500 to all employees:

UPDATE emp
SET sal=sal+sal*0.1, comm=500;

Oracle 6 PM Page 51
SET sal=sal+sal*0.1, comm=500;

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

Syntax:
Delete From <table_name> [WHERE <condition>];

Deleting single Record:

Ex:
Delete the emp record whose empno is 7902:

DELETE FROM emp WHERE empno=7902;

Deleting a set of records:

Ex:
Delete the emp records whose job title is
'SALESMAN':

DELETE FROM emp WHERE job='SALESMAN';

Delete the emp records whose job title is null:

DELETE FROM emp WHERE job IS NULL;

DELETE the emp records who are having more


than 40 years experience:

Oracle 6 PM Page 52
DELETE FROM emp
WHERE (sysdate-hiredate)/365 > 40;

DELETE the emp records who are working in 10th


dept & 30th dept:

DELETE FROM emp


WHERE deptno IN(10,30);

Deleting all records:

Ex:
Delete all emp records from emp table:

DELETE FROM emp;


(or)
DELETE emp;

Deleting records using parameters:

DELETE FROM emp WHERE empno=&empno;


enter value for empno: 7900

/
enter value fro empno: 7499

DDL DRL DML TCL DCL


Create SELECT INSERT COMMIT GRANT
Alter UPDATE ROLLBACK REVOKE
Drop DELETE
Truncate SAVEPOINT
Rename INSERT ALL
Flashback MERGE
Purge

Oracle 6 PM Page 53
DELETE FROM emp;
(or)
TRUNCATE TABLE emp;

DELETE TRUNCATE

• DML command • DDL command

• It can be used to delete • It can be used to delete all


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

• We can use WHERE • We cannot use WHERE clause


clause in DELETE in TRUNCATE
command

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

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

• does not clear the • clears the memory.


memory.

• Deletes row-by row • Deletes page by page [block by


block]

• it is slower than truncate • it works faster

ORACLE SERVER = INSTANCE {RAM} + DB {Hard Disk}

ORACLE SERVER

INSTANCE DB

Oracle 6 PM Page 54
Block => default size => 8KB

Extent => is a collection of Blocks

1 Block = 8 KB
1 Extent = 8 Blocks (64 KB)

DB
TABLESPACE [USERS]
SCHEMA [USER => c##batch6pm]
Segments
Extents
Blocks [pages]
Data

TRUNCATE VS DROP:

TRUNCATE =>
deletes entire table data. But does not delete the
structure of table

Oracle 6 PM Page 55
DROP =>
deletes entire table. It deletes table data & table
structure also.

SQL:

DDL
DRL
DML
TCL
DCL

DCL:
• Data Control Language.
• It deals with Data Accessibility.
• SQL provides 2 DCL commands:
○ Grant
○ Revoke

Grant:
• is used to give permissions on DB Objects
[Tables,Views] to other users.
• Owner of DB Object Or DBA can grant the
permissions to other users.

Syntax:

GRANT <privileges_list> ON <DB_Object_Name>


TO <user_name>;

Oracle 6 PM Page 56
c##raju c##ravi

emp
empno ename job sal
1001 A
1002 B

GRANT

Revoke:
• is used to cancel the permissions on DB objects from
users.

Syntax:

REVOKE <privileges_list> ON <DB_Object_Name>


FROM <user_name>;

Example on Grant & Revoke:

Creating common user => [C##UserA]:

Log In as DBA:
username: system
password: nareshit

Create User c##usera identified by usera


default tablespace users
quota unlimited on users;

Oracle 6 PM Page 57
Grant connect,resource to c##usera;

Note:
connect => is permission for logging in
resource => is permission for creating table

Creating common user => c##userB:

Create user c##userb identified by userb


default tablespace users
quota unlimited on users;

Grant connect,resource to c##userb;

c##userA c##userB

Create Table std:

std
sid sname
1 A
2 B

SELECT * FROM c##userA.std;


ERROR:

GRANT select ON std


to c##userB;

SELECT * FROM c##userA.std;


displays records

INSERT INTO c##usera.std


values(5,'E');
ERROR: insufficient privileges

DELETE FROM c##userA.std


WHERE sid=1;
ERROR: insufficient privileges

Oracle 6 PM Page 58
WHERE sid=1;
ERROR: insufficient privileges

UPDATE c##userA.std SET


sname='SAI' where sid=1;
ERROR: insufficient privileges

GRANT insert,update
ON std to c##userB;

SELECT * FROM c##userA.std;


displays records

INSERT INTO c##usera.std


values(5,'E');
1 row created

UPDATE c##userA.std SET


sname='SAI' where sid=1;
1 row updated

DELETE FROM c##userA.std


WHERE sid=1;
ERROR: insufficient privileges

Granting all permissions:

GRANT All ON std


to c##userB;

DELETE FROM c##userA.std


WHERE sid=1;
1 row deleted

GRANT select ON
c##userA.std TO c##batch6pm;
Allowing the user to grant
ERROR
permissions to other users:

GRANT All ON std


TO c##userB
WITH GRANT OPTION;

Now userB can Grant permission


Oracle 6 PM Page 59
Now userB can Grant permission
on std table to other users GRANT select ON
c##userA.std TO c##batch6pm;

Cancelling permissions from


c##userB:

REVOKE All ON std


FROM c##userB;
SELECT => ERROR
INSERT => ERROR

Creating table from existing table:


[Copying Table]

Syntax:

Create Table <Table_Name>


AS
<SELECT query>;

emp
empno ename job sal mgr comm deptno hiredate
1001
1002

employee
empno ename job sal
1001
1002

CREATE TABLE employee


AS
Oracle 6 PM Page 60
AS
SELECT empno, ename, job, sal
FROM emp;

Creating a table from existing table with all


managers records:

CREATE TABLE employee1


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

Creating Table From Existing Table Without


Records [Copy structure only. Not records]:

emp
empno ename job sal comm hiredate deptno
1001
1002

employee2
empno ename job sal

CREATE TABLE employee2


1=2
AS
'a' = 'b'
SELECT empno,ename,job,sal
FROM emp
WHERE 1=2; --write any false condition

INSERT ALL & MERGE Commands [DML


Commands]:

INSERT ALL:
• introduced in Oracle 9i version
• Used to insert multiple records in multiple
tables or in single table

Oracle 6 PM Page 61
emp1
emp
empno ename job sal
empno ename job sal deptno
1001 ..
1002 emp2
.. empno ename job sal
1010
emp3
empno ename job sal

emp employee3
empno ename job sal deptno empno ename job sal
1001
1002

INSERT INTO employee3 employee4


SELECT empno, ename, job, sal
FROM emp;
employee5
INSERT INTO employee4
SELECT empno, ename, job, sal
FROM emp;

INSERT INTO employee5


SELECT empno, ename, job, sal
FROM emp;

• INSERT ALL command is used to insert multiple


records into multiple records or single table.

Oracle 6 PM Page 62
records into multiple records or single table.
• It avoids of writing multiple INSERT commands.

INSERT ALL can be used in 2 ways:


• Unconditional INSERT ALL
• Conditional INSERT ALL

Unconditional INSERT ALL:

Syntax:

INSERT ALL
into <table-1>(<column_list>) values(<value_list>)
into <table-2>(<column_list>) values(<value_list>)
into <table-3>(<column_list>) values(<value_list>)
….
….
<SELECT query>;

emp emp1
empno ename job sal deptno empno ename job sal
1001
1002
emp2
empno ename job sal

emp3
empno ename job sal

CREATING emp1 TABLE:

CREATE TABLE emp1


AS
Oracle 6 PM Page 63
AS
SELECT empno,ename,job,sal FROM emp
WHERE 1=2;

CREATING emp2 TABLE:

CREATE TABLE emp2


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

CREATING emp3 TABLE:

CREATE TABLE emp3


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

Copying emp table records into emp1, emp2, emp3:

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 4 columns data will be copied


-- into emp1,emp2, emp3

Conditional INSERT ALL:

Syntax:

INSERT ALL
When <condition-1> Then
into <table-1>(<column_list>) values(<value_list>)
When <condition-2> Then
Oracle 6 PM Page 64
When <condition-1> Then
into <table-1>(<column_list>) values(<value_list>)
When <condition-2> Then
into <table-2>(<column_list>) values(<value_list>)
When <condition-3> Then
into <table-3>(<column_list>) values(<value_list>)
..
..
ELSE
into <table-n>(column_list>) values(<value_list>)
<SELECT query>;

dept10
emp
empno ename job sal deptno
empno ename job sal deptno
1001 10
1002 10 dept20
1003 20 empno ename job sal deptno
1004 20
1005 30
1006 40 dept_others
empno ename job sal deptno

CREATE TABLE dept10


AS
SELECT empno,ename,deptno FROM emp
WHERE 3=4;

CREATE TABLE dept20


AS
SELECT empno,ename,deptno FROM emp
WHERE 3=4;

CREATE TABLE dept_others


AS
SELECT empno,ename,deptno FROM emp
WHERE 3=4;

Oracle 6 PM Page 65
Copy deptno 10 emps into dept10,
deptno 20 emps into dept20
other depts emps into dept_others:

INSERT ALL
WHEN deptno=10 THEN
into dept10 values(empno,ename,deptno)
WHEN deptno=20 THEN
into dept20 values(empno,ename,deptno)
ELSE
into dept_others values(empno,ename,deptno)
SELECT empno,ename,deptno FROM emp;

Assignment:
emp_clerk
emp empno ename job
empno ename job
CLERK
CLERK emp_manager
MANAGER empno ename job
MANAGER
SALESMAN
emp_others
ANALYST
empno ename job

INSERT ALL
WHEN job='CLERK' THEN
into emp_clerk

emp
emp1980
empno ename hiredate
empno ename hiredate
Oracle 6 PM Page 66
emp
emp1980
empno ename hiredate
empno ename hiredate
17-JAN-80
13-OCT-80
emp1981
25-DEC-81 empno ename hiredate
12-FEB-81
17-MAR-82
28-APR-83 emp_others
empno ename hiredate

INSERT ALL
WHEN hiredate like '%80' THEN
into emp1980

MERGE:
• is introduced in Oracle 9i version.
• MERGE = UPDATE + INSERT
• MERGE is a combination of UPDATE & INSERT
commands.
• It can be also called as "UPSERT" Command.
• This command used to apply changes of a table
to its replica [duplicate copy].

Replication:
The process of making duplicate copies.

Replica: Duplicate copy is called "Replica".

Oracle 6 PM Page 67
OLTP OLAP [DWH]

day-to-day operations used for data analysis

Cust2
Cust1
cid cname ccity
cid cname ccity
1 A Hyd
1 A Bangalore
2 B Chennai
2 B Chennai
3 C Delhi
3 C Delhi
4 D Bangalore
5 E Kolkata

Syntax:

MERGE INTO <target_table_name> <alias>


USING <source_table_name> <alias>
ON(<condition>)
WHEN matched THEN
UPDATE query
WHEN unmatched THEN
INSERT query ;

MERGE INTO Cust2 T


USING Cust1 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) ;

Cust1 Cust2
Oracle 6 PM Page 68
Cust1 Cust2
cid cname ccity cid cname ccity
1 A Bangalore 1 A Hyd
2 B Chennai 2 B Chennai
3 C Delhi 3 C Delhi
4 D Bangalore
5 E Kolkata

SAVEPOINT: [TCL Commnad]

• It is used to set margin for rollback.

INSERT
UPDATE
DELETE
Rollback;

SavePoint aaa;
INSERT
Savepoint bbb;
INSERT
Savepoint ccc;
INSERT
Rollback to ccc; --1 action will be cancelled

Rollback to bbb; --2 actions will be cancelled

Oracle 6 PM Page 69
Rollback to bbb; --2 actions will be cancelled

Rollback to aaa; --3 actions will be cancelled

SQL =>
• query language
• used to write the queries
• By writing queries we can communicate with
oracle DB

5 Sub Languages

DDL Create => create the tables


Alter => for structural changes
Drop => to drop the table
Truncate => to delete all records
Rename => to rename db objects
Flashback => to recollect from bin
Purge => delete from bin

DML INSERT
UPDATE
DELETE

INSERT ALL
MERGE

DRL SELECT
TCL COMMIT [SAVE]
ROLLBACK [ROLLBACK]
SAVEPOINT [to set margin for rollback
DCL GRANT
REVOKE

Oracle 6 PM Page 70
Built-In Functions
Thursday, February 24, 2022 7:21 PM

Built-In Functions:
• SQL provides several built-in functions to make
our tasks easier.
• Function => Task / Action
• Every function is defined to perform particular
task. power(2,3) => 8
• Oracle developers already defined some functions
& placed in Oracle Database. These functions are 2,3 => arguments
called "Built-In Functions / Predefined Functions". Function performs process
• Function can take Arguments [Input] & returns 8 => returned value [result]
the result.

SQL provides following Built-In Functions:


• String Functions [Text Functions]
• Aggregate Functions [Group Functions]
• Numeric Functions [Math Functions]
• Conversion Functions
• Date Functions
• Miscellaneous Functions

String Functions [Text Functions]:

Lower()
Upper()
Initcap()
length()
concat()

reverse()
ASCII()
Chr()

substr()
instr()

lpad()
rpad()

ltrim()
rtrim()
trim()

replace()
translate()
soundex()

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

Syntax:
Lower(<string>)

Ex:
Lower('RAJU') => raju

UPPER():
used to convert the string to upper case.

Syntax:
UPPER(<string>)

Ex:
UPPER('raju') => RAJU

Oracle 6 PM Page 71
Initcap():
used to get each word's starting letter as capital.

Syntax:
Initcap(<string>)

Exs:
Initcap('RAJU') => Raju
Initcap('RAJ KUMAR') => Raj Kumar

Concat():
concatenate => combine
used to combine 2 strings

Syntax:
Concat(<string1>,<string2>)

Ex:
Concat('Raj','Kumar') => RajKumar

Length():
used to find length of the string. It means, number
of chars in string.

Syntax:
Length(<string>)

Exs:
Length('Sai') => 3
Length('Ramu') => 4
Length('Ravi Teja') => 9

SELECT lower('RAMU') FROM DUAL;

DUAL:
• is a table created in oracle database.
• created in 'SYS' user.
• It can be used by any user.
• It is created with 1 column. that column
name is 'dummy'.
• Dummy column can hold only one char i.e. X
• Only one row is available in 'dual' table.
• To get one value from the expressions or
built-in functions we use it.

DUAL
DUMMY
-------------
X

SELECT lower('RAMU') FROM DUAL;


ramu

SELECT upper('ramu') FROM DUAL;


RAMU

SELECT initcap('RAMU') FROM dual;


Ramu

SELECT initcap('RAVI TEJA') FROM dual;


Ravi Teja

SELECT concat('raj','kumar') FROM dual;


rajkumar

SELECT concat('raj','kumar','varma') FROM dual;


--ERROR: invalid number of arguments

SELECT concat(concat('raj',' '),'kumar') FROM dual;


raj kumar

Oracle 6 PM Page 72
concatenation operator:
Symbol: ||

SELECT 'raj' || ' ' || 'kumar' || ' ' || 'varma'


FROM dual;

SELECT length('RAVI') FROM dual;


4

Display emp names in lower case:

SELECT lower(ename) ename, job, sal FROM emp;

UPDATING emp names in lower case:

UPDATE emp SET ename=lower(ename);

Display the emp record whose name is blake even if don't


know the exact case:

SELECT ename,sal FROM emp


WHERE lower(ename)='blake';

Display length of each emp name:

SELECT ename, length(ename) as "no of chars"


FROM emp;

Display the emp records whose name is having


4 characters:

_ 1 char
% any no of chars

SELECT ename,sal FROM emp


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

Display the emp names whose name is having


more than 4 chars:

SELECT ename,sal FROM emp


WHERE length(ename)>4;

Player
pid fname lname
1001 sachin tendulkar
1002 rahul dravid
1003 rohit sharma
1004 virat kohli

CREATE TABLE player


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

INSERT INTO player


values(1001,'SACHIN','TENDULKAR');

INSERT INTO player


values(1002,'RAHUL','DRAVID');

Oracle 6 PM Page 73
INSERT INTO player
values(1003,'ROHIT','SHARMA');

INSERT INTO player values(1004,'VIRAT','KOHLI');

Adding a column pname:

ALTER TABLE player add(pname varchar2(25));

UPDATE player
SET pname = Initcap(fname || ' ' || lname);

drop fname,lname:

ALTER TABLE player drop(fname, lname);

Display the player records whose names are having


12 chars:

SELECT * FROM player


WHERE length(pname) = 12;

Display the emp records whose names are having


more than 12 chars:

SELECT * FROM player


WHERE length(pname)>12;

Reverse():
is used to get reverse string

Syntax:
Reverse(<string>)

Ex:
A=65
Reverse('raju') => ujar
B=66
.
.
ASCII():
Z=90
Used to get ASCII value of specified char.

Syntax: a=97
ASCII(<char>) b=98
.
Ex: .
ASCII('A') => 65 z=122
ASCII('a') => 97

SELECT
ASCII('A'), ASCII('a'),ASCII('1'),ASCII('#')
FROM dual;

CHR():
used to get character of specified ASCII value.

Syntax:
CHR(<ascii_value>)

Ex:
CHR(65) => A
CHR(97) => a

SELECT chr(65), chr(97) FROM dual;

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

Syntax:
substr(<string>,<position>[,<no_of_chars])

Oracle 6 PM Page 74
substr(<string>,<position>[,<no_of_chars])

Exs:

R a j K u m a r

substr('Raj Kumar',5) => Kumar


substr('Raj Kumar',1,3) => Raj
substr('Raj Kumar',6) => umar
substr('Raj Kumar',6,3) => uma
substr('Raj Kumar',1,5) => Raj K

"position" value can be +ve (or) -ve

+ve position => FROM left side position number


-ve position => FROM right side position number

R A V I T E J A

substr('RAVI TEJA',-4) => TEJA


substr('RAVI TEJA',-4,3) => TEJ

emp
empno ename job sal mailid
7369 SMITH .. .. [email protected]
7499 ALLEN .. .. [email protected]

ALTER TABLE emp add(mailid varchar2(50));

UPDATE emp
SET mailid=substr(ename,1,3) || substr(empno,-3,3)
|| '@nareshit.com';

Display the emp records whose name is


started with 'S':

SELECT * FROM emp


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

Display the emp records whose names are


ended with 'S':

SELECT * FROM emp


WHERE substr(ename,-1,1)='s';
(or)
SELECT * FROM emp
WHERE ename like '%s';

Display the emp names whose name's starting


letter & ending letter are same:

SELECT * FROM emp


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

Display the emp names whose names are ended


with 'RD':

SELECT * FROM emp


WHERE substr(ename,-2,2) = 'RD';

Oracle 6 PM Page 75
Display the emp records whose name's second
char is 'A':

SELECT * FROM emp


WHERE substr(ename,2,1) = 'A';

instr():
• used to get position of sub string.
• if sub string is existed in string, it returns sub string
position value.
• if sub string is not existed in string , it returns 0.

Syntax:
instr(<string>,<sub_string>
[,<search_position>,<occurrence>])

default search position => 1


default occurrence => 1

Exs:

t h i s i s h i s w i s h

instr('this is his wish','is',-1) => 14 instr('this is his wish','is') => 3


instr('this is his wish','is',-1,2) => 10 instr('this is his wish','is',1,2) => 6
instr('this is his wish','is',-4,2) => 6 instr('this is his wish','is',4,2) => 10

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','naresh') => 0

Display the emp records whose name is


having 'AM' chars:

ename
-----------
ALLEN
JAMES
SMITH

SELECT * FROM emp


WHERE instr(ename,'AM')>0;

Soundex:
• This Function is used to retrieve the data
based on pronunciation.
• When we don't know exact spelling of string
we can search with the sound.

Syntax:
Soundex(string)

Display the emp record whose name is scott:

SELECT * FROM emp


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

substr()
instr()
soundex()

Lpad() & Rpad() Functions:

Lpad():

Oracle 6 PM Page 76
Lpad():
• pad => fill
• used to fill specified char set from left side.
• Default char is 'space'.

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

Ex:
Lpad('raju',10,'*') => ******raju
Lpad('naresh',10,'#') => ####naresh
Lpad('sai',10,'#$') => #$#$#$#sai
Lpad('sai',10) => 7spacessai

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

number of chars to be filled = max size- string lenth

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

EX:
Rpad('Ravi',10,'*') => Ravi******
Rpad('Sai',10) => Sai7spaces

LPAD('*',10,'*') => **********

LPAD('X',6,'X') => XXXXXX

account num: 10 digits


1234567890

SELECT 'amount dedited from ' ||


LPAD('X',6,'X') ||
substr('1234567890',-4,4)
FROM dual;

amount debited from XXXXXX7890

Ltrim(), Rtrim(), Trim() Functions:

Ltrim():
• trim => remove
• used to remove unwanted chars from left side.

Syntax:
Ltrim(<string>[,<char/chars>])

Rtrim():
• used to remove unwanted chars from right side.

Syntax:
Rtrim(<string>[,<char/chars>])

default char is space

Exs:
Ltrim('*****RAJU*****','*') => RAJU*****
Rtrim('*****RAJU*****','*') => *****RAJU

Ltrim(' RAVI ') =>

Oracle 6 PM Page 77
mailid
------------
[email protected]
[email protected]
[email protected]

SELECT Rtrim(mailid,'@nareshit.com')
FROM emp;

Model
-------------
OPPO-A72
OPPO-A12
OPPO-A51

SELECT Ltrim(Model,'OPPO-') FROM product;

SELECT Ltrim('OPPO-A72','OPPO-') FROM dual;


A72

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

Syntax:
Trim(leading / trailing / both <char> FROM <string>)

leading => left side unwanted chars


trailing => right side unwanted chars
both => both side unwanted chars [default]

Ex:
Trim(Leading '@' FROM '@@@raju@@@') => raju@@@
Trim(Trailing '@' FROM '@@@raju@@@') => @@@raju
Trim(Both '@' FROM '@@@raju@@@') => raju

gmail.com

username ravi

password

SELECT Trim(' RAVI ') FROM dual;

it trims left side & right side spaces

Replace & Translate() Functions:

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

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

Ex:
Replace('sai krishna','sai','rama') => rama krishna
Replace('sai krishna','krishna','teja') => sai teja

Translate():

Oracle 6 PM Page 78
Translate():
used to translate corresponding chars

Syntax:
Translate(<string>,<char_set1>,<char_set2>)

Translate('hello','leo','xyz') =>

REPLACE('abcaabbccabcabcaabbcc','abc','XYZ')

Conversion Functions:

SELECT 100+200 FROM dual;


300

SELECT '100' + '200' FROM dual;


300

SELECT * FROM emp WHERE empno=7900;

displays 7900 emp's record

SELECT * FROM emp WHERE empno='7900';

displays 7900 emp's record

INSERT INTO emp(empno,ename,hiredate)


values(1234,'ABC','23-JAN-2020');

There are 2 types of conversions. They are:


• Implicit Conversion
• Explicit Conversion

Implicit Conversion:
This conversion will be done implicitly by the ORACLE
Ex:
SELECT '100' + '200' FROM dual;
300

Explicit Conversion:
This conversion will be done explicitly by using
built-in function.

SQL provides following conversion functions:


• to_char()
• to_date()
• to_number()

CHAR

Oracle 6 PM Page 79
CHAR

DATE
NUMBER

to_char() [Date to String]:


• used to convert date value to string value.
• using this function we can display date value in different formats like
US DATE FORMAT [ mm/dd/yyyy ],
IND DATE FORMAT [dd/mm/yyyy].

FORMAT purpose / Ex Result


yyyy to_char(sysdate,'yyyy') 2022
3-mar-22
yyy to_char(sysdate,'yyy') 022
yy to_char(sysdate,'yy') 22
y to_char(sysdate,'y') 2
year / YEAR to_char(sysdate,'year') twenty twenty-two
to_char(sysdate,'YEAR') TWENTY TWENTY-TWO
mon / MON to_char(sysdate,'mon') mar
to_char(sysdate,'MON') MAR
mm to_char(sysdate,'mm') 03
month / MONTH to_char(sysdate,'month') march
to_char(sysdate,'MONTH') MARCH
dd day num in the month 03
to_char(sysdate,'dd')
d day num in the week 5
to_char(sysdate,'d')

ddd day num in the year 062


to_char(sysdate,'ddd')
dy / DY short weekday name
to_char(sysdate,'dy') thu
to_char(sysdate,'DY') THU
day / DAY full weekday name
to_char(sysdate,'day') thursday
to_char(sysdate,'DAY') THURSDAY
q quarter num
1st quarter => jan-mar
2nd => apr-jun
3rd => jul-sep
4th => oct-dec

to_char(sysdate,'q') 1

cc century num
to_char(sysdate,'cc') 21
AD / BC to_char(sysdate,'BC') AD

w week num in the month 01

ww week num in the year


to_char(sysdate,'ww') 09

hh / hh12 to_char(sysdate,'hh') 07
to_char(sysdate,'hh12') 07
hh24 to_char(sysdate,'hh24') 19
mi to_char(sysdate,'mi') 10
ss seconds value
ff fractional seconds value
AM / PM AM / PM format

SELECT to_char(sysdate,'HH:MI AM') FROM dual;

7:11 PM

SELECT to_char(sysdate,'HH24:MI:SS') FROM dual;

Oracle 6 PM Page 80
19:11:15

SELECT to_char(systimestamp,'ff') FROM dual;

displays fractional seconds

Display emp records with hiredates. Display hiredate in


US DATE FORMAT:

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

Display emp records with hiredates. Display hiredate in


IND DATE FORMAT:

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

Display the emp records who joined in 1982:

SELECT * FROM emp


WHERE to_char(hiredate,'yyyy') = 1982;

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

SELECT * FROM emp


WHERE to_char(hiredate,'yyyy') IN(1980,1982,1983);

Display the emp records who joined in oct,nov,dec[4th


quarter]:

SELECT * FROM emp


WHERE to_char(hiredate,'q') = 4;

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

SELECT * FROM emp


WHERE to_char(hiredate,'q') IN(1,4);

Display the emp records who joined in dec month:

SELECT * FROM emp


WHERE to_char(hiredate,'mm')= 12;

Display the emp records who joined in jan,jun & dec:

SELECT * FROM emp


WHERE to_char(hiredate,'mm') IN(1,6,12);

ASSIGNMENT:

Display the emp records who joined on Sunday using d, dy &


day formats:

SELECT * FROM emp


WHERE to_char(hiredate,'d')=1;
(or)
SELECT * FROM emp
WHERE to_char(hiredate,'dy')='sun'; sun=1
(or) mon=2
SELECT * FROM emp
WHERE to_char(hiredate,'day')='sunday';
no rows selected

'sunday3spaces' = 'sunday' => both are not equal


So, it displays no rows selected

Oracle 6 PM Page 81
So, it displays no rows selected
To remove unwanted spaces from right side use Rtrim()

SELECT * FROM emp


WHERE Rtrim(to_char(hiredate,'day'))='sunday';

to_char() [number to string]:


• using to_char() function, we can convert
number to string.
It can be used to apply currency formats like
currency symbol, currency name

Ex:
sal
------
5000 $5,000.00
5000 USD5,000.00

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

Format Purpose
L Currency Symbol ($)
C Currency name (USD)
9 digit
, thousand separator
. decimal point

Exs:
to_char(123) => 123

to_char(123.45) => 123.45

to_char(5000,'L9999.99) => $5000.00

to_char(5000,'C9,999.99') => USD5,000.00

We can change currency symbols.


For this we need to modify 2 parameters.
They are: NLS_TERRITORY, NLS_CURRENCY
Only DBA can modify the currency symbols.

Log in as DBA:

username: system
password: nareshit

Alter Session Set NLS_TERRITORY='UNITED KINGDOM';

Alter Session Set NLS_CURRENCY='£';

to_char() convert date to string


to_char() convert number to string

to_date():

Oracle 6 PM Page 82
to_date():
• used to convert string to date.

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

Exs:
to_date('22 DEC 2019') => 22-DEC-19
to_Date('22-DEC-2019') =>
to_date('22 DECEMBER, 2019') => 22-DEC-19

to_date('22/12/2019') => ERROR


to_date('22/12/2019','dd/mm/yyyy') => 22-DEC-19

insert into emp(empno,ename,hiredate)


values(2346,'XYZ',to_date('25-AUG-2020'));

display today's date:


SELECT sysdate FROM dual;
4-MAR-22

display year 4 digits from today's date:


SELECT to_char(sysdate,'yyyy') FROM dual;
2022

display year 4 digits from specific date:


[25-SEP-2018]

to_char(sysdate,'yyyy') => 2022

to_char('25-SEP-2018','yyyy') => ERROR

SELECT to_char(to_date('25-SEP-2018'),'yyyy')
FROM dual;
2018

SELECT to_char(to_date('25-SEP-2018'),'mm')
FROM dual;
09

On which weekday india got independence?

to_char(sysdate,'dy') => fri

15-AUG-1947

to_char('15-AUG-1947','dy') => ERROR


SELECT to_char(to_date('15-AUG-1947'),'dy')
FROM dual;

find weekday name of sachin's birthday:


[24-APR-1973]

SELECT
to_char(to_date('24-APR-1973'),'day')
FROm dual;

to_number():
• used to convert string to number.
• string must be numeric string.

'123' => 123


'123.45' => 123.45

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

Ex:

Oracle 6 PM Page 83
Ex:
to_number('123') => 123
to_number('123.45') => 123.45

to_number('USD5000') => ERROR


to_number('USD5000','C9999') => 5000
to_number('$8,000.00','L9,999.99') => 8000

Display sal column values of emp


table with currency symbol:

SELECT ename,
to_char(sal,'L99,999.99') as salary desc emp;
FROM emp;
sal number(7,2)

SELECT ename,
to_char(sal,'C99,999.99') as salary
FROM emp;

to_char()
to_date()
to_number()

String Functions
Conversion Functions => Single Row Functions

Aggregate Functions => Multi Row Functions

Aggregate [Group] Functions:


• Aggregate => single value is formed using a set of values

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

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

Syntax:
sum(<column_name>)

Ex:
sum(sal)

Find sum of salaries of all employees:

SELECT sum(sal) as "sum of salaries"


FROM emp;

Find sum of salaries of employees who are


working in 10th dept:

SELECT sum(sal) FROM emp


WHERE deptno=10;

Oracle 6 PM Page 84
Find sum of salaries of all clerks:

SELECT sum(Sal) FROM emp


WHERE job='CLERK';

Find sum of salaries of 10 & 20 depts:

SELECT sum(sal) FROM emp


WHERE deptno IN(10,20);

Find sum of salaries of clerks & managers:

SELECT sum(Sal) FROM emp


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

avg():
This function is used to average of a set of values.

Syntax:
avg(<column_name>)

Ex:
avg(sal)
avg(runs)

Find avrg salary of all employees:

SELECT avg(Sal) FROM emp;

Find average salary of 10th dept:

SELECT avg(Sal) FROM emp

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

Syntax:
max(<column_name>

Ex:
max(sal)
max(marks)

Find the max salary:

SELECT max(sal) FROM emp;

Find max salary in all managers:

SELECT max(Sal) FROm emp


WHERE job='MANAGER';

Find max salary in deptno 20:

SELECT max(Sal) FROM emp


WHERE deptno=20;

Min():
This function is used to find
minimum value in a set of numbers.

Syntax:
min(<column_name>)

Ex:
min(sal)
min(marks)

Find min salary in all employees:

Oracle 6 PM Page 85
Find min salary in all employees:

SELECT min(sal) FROM emp;

Find min salary in deptno 10:

SELECT min(Sal) FROM emp


WHERE deptno=10;

Find min sal in all slaesmen:

SELECT min(Sal) FROM emp


WHERE job='SALESMAN';

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

Syntax:
count(<column_name>/*)

Ex:
count(Sal)
count(comm)
count(*) => counts number of records

Find the number of employees who are getting


commission:

SELECT count(comm) FROM emp;

Note:
count(comm) => it will not count null values

Find number of records in emp table:

SELECT count(*) FROM emp;


(or)
SELECT count(8) from emp; --count(<any_value>)

count(8) & count(*):


count(8) works faster than count(*)

Find number of clerks in emp table:

SELECT count(*) FROM emp


WHERE job='CLERK';

Find number of emps in deptno 10:

SELECT count(*) FROM emp


WHERE deptno=10;

Sub Queries / Nested Queries:


• Writing query in another query is called
"Sub Query / Nested Query"
• Sub Query must be written in parenthesis
[ (sub query) ]
• Sub query must be SELECT query only. It cannot be
INSERT / UPDATE / DELETE
• First inner query gets executed. Then outer query
gets executed.
• The result of inner query becomes input for the
outer query
• Inner query => Sub query / Child Query
• Outer query => main query / Parent Query
• We can write maximum of 255 sub queries.

Oracle 6 PM Page 86
Find second max salary:

SELECT max(sal) FROM emp


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

1. finds max salary


2. finds all salary values except max sal
3. finds max value in the above list

Find the emp name who is getting max salary:

SELECT ename FROM emp


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

Find the emp name whose salary is second


maximum:

SELECT ename FROM emp


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

Assignment:

• Find third max salary


• Find second min salary
• Find the ename whose salary is minimum
• Find the ename whose salary is 2nd minimum

Number Functions [Math Functions]:

sqrt()
power()
mod()
sin()
cos()
tan()

abs()
sign()
log()
ln()

ceil()
floor()

trunc()
round()

sqrt():
used to find square root value

Syntax:
sqrt(<number>)

Ex:
sqrt(100) => 10

power():
used to find power value

Oracle 6 PM Page 87
Syntax:
power(number,power)

Ex:

power(2,3) => 8

mod():
used to get remainder value.

Syntax:
mod(<number>,<divisor>)

Ex:
mod(5,2) => 1

sin():
used to find sine values

Syntax:
sin(angle)

cos():
used to find cosine values

Syntax:
cos(angle)

tan():
used to tangent values

Syntax:
tan(angle)

Note:
specify angle value in the form of
radians

Ex:
sin 90 => sin(90*3.14/180) => 1
cos 0 => cos(0*3.14/180) => 1
tan 45 => tan(45*3.14/180) => 1

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 a number is +ve
or -ve or zero.
it returns 1 when number is +ve
it returns -1 when number is -ve
it returns 0 when number is ZERO

Syntax:
sign(<number>)

Ex:
sign(8) => 1
sign(-8) => -1
sign(0) => 0

log():
used to find logarithmic values

Syntax:
log(number,base)

Oracle 6 PM Page 88
Ex:

log(10,10) => 1

ln():
used to get natural logarithmic values

Syntax:
ln(<number>)

Ex:
ln(7)

ceil():
used to get upper integer value

Syntax:
ceil(<number>) 123 => 123.4567 => 124

Ex:
ceil(123.4567) => 124
ceil(167.8923) => 168

floor():
used to get lower integer value.

Syntax:
floor(<number>)
123 => 123.4567 => 124
Ex:
floor(123.4567) => 123
floor(167.8923) => 167

trunc():
it truncates [removes] decimal places

Syntax:
trunc(<number>[,<decimal_places>])

Ex:
trunc(123.45678) => 123
trunc(123.45678,2) => 123.45

trunc(678.78953) => 678


trunc(678.78953,2) => 678.78
trunc(678.78953,3) => 678.789

-1 => rounds in the 10s


-2 => rounds in the 100s
-3 => rounds in the 1000s

Note:
Always it takes lower integer value

trunc(123.45678,-1) => 120


100, 110, 120,130,140

120 => 123.45678 => 130

trunc(567.89234,-1) => 560


560 => 567.89234 => 570

trunc(123.45678,-2) => 100


100, 200, 300, ….

100 => 123.45678 => 200

trunc(567.89234,-2) => 500

trunc(4567.23456,-3) => 4000

Oracle 6 PM Page 89
Round():
used to get rounded values.
if value is .5 or > .5 => it takes upper value
if value is <.5 => it takes lower value

Syntax:
Round(<number>,<decimal_places>) percentage
-------------
Ex: 56.78 => 57
Round(123.45678) => 123 78.34 => 78
Round(123.7896) => 124 67.53 => 68
Round(123.54321) => 124

Round(123.45678,2) => 123.46


Round(123.45478,2) => 123.45

Round(456.78234,2) => 456.78


Round(456.78834,2) => 456.79
Round(456.78534,2) => 456.79

Round(834.456789,3) => 834.457


Round(834.456489,3) => 834.456

-1 => rounds in 10s


-2 => rounds in 100s

if value is avrg or above avrg, it takes upper


if value is < avrg, it takes lower value

Round(123.45678,-1) => 120


120,130 => 120+130 = 250 /2 = 125
123.45678 < 125

Round(128.45678,-1) => 130


120,130 => avrg = 125
128.45678>125

Round(123.45678,-2) => 100


100 => 123.45678 => 150 => 200

Round(153.45678,-2) => 200


100 => 150 => 153.45678 => 200

Date Functions:

• sysdate
• systimestamp
• add_months()
• last_day()
• next_day()
• months_between()

sysdate:
• used to current system date
• Date value also contains time value.

Display the current system date:

SELECT sysdate FROM dual;


8-mar-22

Display current system time:

SELECT to_char(sysdate,'HH:MI AM') FROM dual;


6:20 PM hh
mi
am
systimestamp:
It returns current system date & time

Display current system date & time:

Oracle 6 PM Page 90
SELECT systimestamp FROM dual;

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

Syntax:
Add_Months(<date>,<number_of_months>)

Display tomorrow's date:

SELECT sysdate+1 FROM dual;

Display yeterday's date:

SELECT sysdate-1 FROM dual;

Add 2 days to the sysdate:

SELECT sysdate+2 FROM dual;

Add 2 months to the sysdate:

SELECT Add_Months(sysdate,2) FROM dual;

Add 2 years to the sysdate:

SELECT Add_Months(sysdate,12*2) FROM dual;

display 1 month ago date from sysdate:

SELECT Add_Months(sysdate,-1) FROM dual;

display 1 year ago date from sysdate:

SELECT Add_Months(sysdate,-12) FROM dual;

Ex:

SALES
DateId Amount
1-JAN-2018 25000
2-JAN-2018 35000
.
.

Create Sales Table:

Create Table Sales


(
DateId Date, 100000.00
Amount Number(8,2)
);

INSERT INTO sales VALUES(sysdate,20000);

INSERT INTO sales VALUES(sysdate-1,25000);

INSERT INTO sales


VALUES(Add_Months(sysdate,-1),30000);

INSERT INTO sales


VALUES(Add_Months(sysdate,-12),10000);

Display today's sales amount:

SELECT * FROM sales


WHERE dateid = sysdate;

Oracle 6 PM Page 91
WHERE dateid = sysdate;

no rows selected

SELECT * FROM sales


WHERE trunc(dateid) = trunc(sysdate);

Display yesterday's sales amount:

SELECT * FROM sales


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

Display 1 month ago sales amount:

SELECT * FROM sales


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

Display 1 year ago sales amount:

SELECT * FROM sales


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

Employee
60 years age

empno ename DOB DOR


1001 A 23-DEC-2000
1002 B 17-OCT-1995

CREATE TABLE employee


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

INSERT INTO employee(empno,ename,DOB)


values(1001,'A','23-DEC-2000');

INSERT INTO employee(empno,ename,DOB)


values(1002,'B','17-OCT-1995');

Calculate DOR [Date Of Retirement]:

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

IndiaCMs
State CM_NAME B_O_TERM_DATE E_O_TERM_date
TS .. 23-MAY-2018 After 5 years?
AP .. 15-OCT-2019 After 5 years?

Last_Day():
It is used to get last day in the specified month.

Syntax:
Last_day(<date>)

Ex:

Display last day in current month:

Oracle 6 PM Page 92
SELECT last_day(sysdate) FROM dual;

Display last day in next month:

SELECT last_day(add_months(sysdate,1))
FROM dual;

Display last day in previous month:

SELECT last_day(add_months(sysdate,-1))
FROM dual;

Display next month first day:

SELECT last_day(sysdate) FROM dual;

Display current month first day:

SELECT Last_day(Add_Months(sysdate,-1))+1 FROM


dual;

Next_day():
Used to coming date based on weekday.

Syntax:
Next_day(<date>,<weekday_format>) weekday_format:
d
dy
day
Find next Friday's date:

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

Find next month first Sunday date:

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

Find current month first Sunday:


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

Find last Sunday in current month:

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

Months_Between():
used to find months b/w two dates.

Syntax:
Months_Between(<date-1>,<date-2>)

Calculate experience of emps in the form of years:

SELECT ename, (sysdate-hiredate)/365 experience


FROM emp;
(or)

SELECT ename,
trunc(Months_Between(sysdate,hiredate)/12) experience
FROM emp;

Miscellaneous Functions:

Greatest()

Oracle 6 PM Page 93
Greatest()
Least()

NVL()
NVL2()

Rank()
Dense_Rank()

User
UID

Greatest():
is used to get maximum value in the specified values.

Syntax:
Greatest(<value1>,<value2>,……<value-n>)

Ex:
Greatest(500,400,800,300,600) => 800

Max() => is used to get max value

SELECT max(Sal) FROM emp;

STUDENT

SID SNAME M1 M2 M3
1001 A 60 50 90
1002 B 70 80 40

SELECT greatest(m1,m2,m3) SELECT max(m1)


FROM student; FROM student;

90 70
80

Functions
greatest() max()

• Single row function • Multi-Row Function


single row multi-row
functions functions
• used to find max value in • used to find max value
row in column
String functions Aggregate Functions
Date Functions max()
• can take variable length • can take one argument
Conversion min()
arguments only
Number Functions sum()
avg()
count()
Least():
• used to get minimum value in specified values

Syntax:
Least(<val1>,<val2>,……,<val-n>)

EX:
Least(50,70,30,80,75) => 30

NVL():
• used to replace NULL value with some other value.
• Something + NULL = NULL
• Something - NULL = NULL

emp Calculate total salary:


empno ename sal comm
1001 A 5000 500 total salary = sal+comm

1002 B 8000
1003 C 6000 300
1004 D 4000

Oracle 6 PM Page 94
1004 D 4000
1005 E 7000

Syntax:
NVL(<first>,<second>)

If first value is not null => returns first value


If first value is null => returns second value

EX:
NVL(600,700) => 600
NVL(null,700) => 700

Calculating total salary:

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

Replace null value with N/A in "comm" column of


"emp" table:

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

to_char(123) => 123 number


to_number('123') => 123 number
to_number('N/A') => ERROR

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

Ex:

STUDENT
SELECT sname,
sid sname M1 M2 M3
NVL(M1,'AB')
1001 A 60 80 70
FROM student;
1002 B 55 90 ERROR
1003 C 70 66 44
1004 D 35 82 SELECT sname,
NVL(to_char(M1),'AB') as M1
FROM student;

NVL2():
is used to replace NULL values and NOT NULL values.
Whereas NVL() Function can replace only NULL values.

Syntax:
NVL2(<first>,<second>,<third>)

If first value is not null => it returns second value


If first value is null => it returns third value

Ex:
NVL2(500,600,700) => 600
NVL2(null,600,700) => 700

Update comm values as follows:


If emp is getting commission then increase rs250 commission
If emp is not getting commission then set comm as 750

comm
-----------
null => 750

Oracle 6 PM Page 95
null => 750
1000 => 1250 => comm+250

UPDATE emp
SET comm = NVL2(comm,comm+250,750);

NVL() NVL2()

• can replace null values • can replace null values


only and not null values

• can take 2 arguments • can take 3 arguments.


only

USER:
used to get current user name

UID:
used to get current user ID

Ex:
SELECT user FROM dual; (or) show user
--gives current user name

SELECT uid FROM dual; -- current user ID

All_Users:
It maintains all users information

SELECT username, user_id


FROM all_users;

SELECT username, user_id


FROM all_users
WHERE username='C##BATCH6PM';

Rank():
• Used to apply ranks to records according to specific
column or columns.
• does not follow the sequence

Syntax:
Rank() over(order by <column> Asc/Desc)

Dense_Rank():
• Used to apply ranks to records according to specific
column or columns.
• follows the sequence.

Syntax:
Dense_Rank() over(order by <column> Asc/Desc)

Marks Rank Dense_Rank


700 8 5
750 7 4
950 1 1
900 2 2
850 4 3
900 2 2
850 4 3
700 8 5
850 4 3

Apply the ranks according to sal. Give 1st rank for


highest salary:

SELECT ename,sal,

Oracle 6 PM Page 96
SELECT ename,sal,
Rank() Over(Order BY sal Desc) as "RANK"
FROM emp;

SELECT ename,sal,
Dense_Rank() Over(Order BY sal Desc) as "RANK"
FROM emp;

Apply ranks to emp records according to sal in descending


order. If sal is same, give ranking according to experience:

SELECT ename,sal,hiredate,
DENSE_RANK() Over(Order By sal Desc, hiredate Asc) as RANK
FROM emp;

Oracle 6 PM Page 97
Case Expressions
Thursday, March 10, 2022 6:52 PM

Case Expressions:
• This concept introduced in Oracle 9i version.
• used to implement "If..Then..Else" in
Oracle SQL.
It avoids of writing a separate PL/SQL program
or Procedure.

IN Oracle SQL, we can implement "IF..THEN..ELSE"


using 2 concepts:
• CASE Expression [Oracle 9i] => Best way
• Decode() Function

CASE Expression can be used in 2


ways:
• Simple CASE
• Searched CASE

Simple Case:
can check equality condition only.

Syntax: switch(exprn)
{
CASE <expression> case <const>:
WHEN <value> THEN <return_value> …
WHEN <value> THEN <return_value> break;
. case <const>:
. ….
[Else <return_value>] break;
End .
.
default:
..
}
Increase the salary to the employees as
following:
If deptno is 10 => Increase 10% sal
Oracle 6 PM Page 98
If deptno is 10 => Increase 10% sal
If deptno is 20 => Increase 20% sal
If deptno is 30 => Increase 15% sal
Others => Increase 5% sal

Update emp SET sal= deptno sal


CASE deptno 10 5000
WHEN 10 THEN sal+sal*0.1
30 6000
WHEN 20 THEN sal+Sal*0.2
20 4000
WHEN 30 THEN sal+sal*0.15
ELSE sal+sal*0.05 40 7000
END;

Display
CLERK as WORKER
MANAGER as BOSS
PRESIDENT as BIG BOSS
OTHERS as EMPLOYEE
in job column:

SELECT ename,sal,
CASE job
WHEN 'CLERK' THEN 'WORKER'
WHEN 'MANAGER' THEN 'BOSS'
WHEN 'PRESIDENT' THEN 'BIG BOSS'
ELSE 'EMPLOYEE'
END AS JOB
FROM emp;

Oracle 6 PM Page 99
Simple CASE [like switch]:
can check equality condition only

Searched CASE [like if else if]:


can check any type of condition like < > = >= <=

Syntax:
CASE
WHEN <condition-1> THEN <return_value>
WHEN <condition-2> THEN <return_value>
.
.
ELSE <return_value>
END

Display salary ranges of employees


as following:
If sal>3000 then HiSal
If sal<3000 then LoSal
If sal=3000 then AvrgSal

column "salary range" format a20

SELECT empno,ename,sal,
CASE
WHEN sal>3000 THEN 'HiSal'
WHEN sal<3000 THEN 'LoSal'
WHEN sal=3000 THEN 'AvrgSal'
END as "salary range"
FROM emp;

Ex:

Oracle 6 PM Page 100


STUDENT
SID SNAME M1 M2 M3
1001 A 60 80 70
1002 B 60 30 45

Find the result of student:


Max Marks: 100
Min Marks: 40 in every subject for pass

column result format a6

SELECT sname,M1,M2,M3,
CASE
WHEN m1>=40 AND m2>=40 AND m3>=40 THEN 'PASS'
ELSE 'FAIL'
END as Result
FROM student;

CASE expressions can be used in 2 styles:


• Simple CASE => equality condn only
• Searched CASE => any condition can be checked

Decode():
• is used implement 'IF..THEN..ELSE' in
SQL.
• It can check equality condition only. It
cannot check other conditions like > <

Update emp salaries as following:


Deptno 10 => increase 10%
Deptno 20 => Increase 20%
Deptno 30 => Increase 15%
Others => Increse 5%

Oracle 6 PM Page 101


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);

Ex:
Display job titles as following:
PRESIDENT as Big Boss
CLERK as Worker
MANAGER as Boss
Others as Employee;

SELECT ename,
DECODE(Job,
'PRESIDENT','Big Boss',
'CLERK', 'Worker',
'MANAGER','Boss',
'Employee') as Job
FROM emp;

In SQL,
we can implement IF..THEN..ELSE
using 2 ways:
• CASE Expression
• Decode() Function

Oracle 6 PM Page 102


CASE Expression Decode() Function

• Searched case can check • can check equality


any type of condition condition only.

• Oracle 9i • beginning version onwards


it is available.

• It is ANSI standard
• It is portable

Oracle SQL SERVER

CASE CASE

Oracle SQL SERVER

Decode Decode

Oracle 6 PM Page 103


Interval Expressions
Saturday, March 12, 2022 6:21 PM

Interval Expressions:
• introduced in Oracle 9i version.
• used to add or subtract days, months or years
to particular date or from particular date.
• can be also used to add or subtract hours,
minutes or seconds to a time or from a time.

Add 2 days to sysdate:

SELECT sysdate+interval '2' day FROM dual;

Add 2 months to sysdate:

SELECT sysdate+interval '2' month FROM dual;

Add 2 years to sysdate:

SELECT sysdate+interval '2' year FROM dual;

Subtract 2 days from sysdate:

SELECT sysdate-interval '2' day FROM dual;

Subtract 2 months from sysdate:

SELECT sysdate-interval '2' month FROM dual;

Subtract 2 years from sysdate:

SELECT sysdate-interval '2' year FROM dual;

Add 1 and hour year to sysdate:

SELECT sysdate+interval '1-6' YEAR TO MONTH


Oracle 6 PM Page 104
SELECT sysdate+interval '1-6' YEAR TO MONTH
FROM dual;

Add 150 years to sysdate:

SELECT sysdate+interval '150' YEAR FROM dual; --ERROR

default precision for year is: 2


150 is having 3 digits

SELECT sysdate+interval '150' YEAR(3) FROM dual;

Add 2 hours to system time:

SELECT systimestamp+interval '2' hour FROM dual;

Add 30 minutes to system time:

SELECT systimestamp+interval '30' minute FROM dual;

Add 1 and hour time to system time:

SELECT systimestamp+interval '1:30' HOUR TO MINUTE


FROM dual;

Oracle 6 PM Page 105


Add 5 days 2 hours to system date & time:

SELECT systimestamp+interval '5 2' day to hour


FROM dual;

Add 5 days 2 hours and 30 minutes to system date &


time:

SELECT systimestamp+interval '5 2:30' day to minute


FROM dual;

Add 1 year 10 days to system date:

SELECT sysdate+interval '1' year+interval '10' day


FROM dual;

SALES
dateid amount
1-jan-2018 25000
2-jan-2018 30000

Insert into sales values(sysdate,30000);

Insert into sales


values(sysdate-interval '1' day,25000);

Insert into sales


values(sysdate-interval '1' month,35000);

Oracle 6 PM Page 106


values(sysdate-interval '1' month,35000);

Insert into sales


values(sysdate-interval '1' year,25000);

Display today's sales amount:

SELECT * FROM sales


WHERE trunc(dateid) = trunc(sysdate);

Display yesterday's sales amount:

SELECT * FROM sales


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

Display 1 month ago sales amount from sysdate:

SELECT * FROM sales


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

Display 1 year ago sales amount from sysdate:

SELECT * FROM sales


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

Flashbacking Data:
• Flashback concept in Oracle 10g version.
• Before Oracle 10g,
○ If we delete all records from table &
committed then we cannot recollect it.
To recollect the data they were using backup
Oracle 6 PM Page 107
To recollect the data they were using backup
copies.
• From Oracle 10g version onwards.
○ If we delete all records from table &
committed then also we can recollect it by
using the "FLASHBACK query".
• By default we can recollect upto 15 minutes
[900 seconds].
• We can change this time using the parameter
"undo_retention".

• Flashback query is used to recollect the data


which was existed some time ago.
• "AS OF" clause is used to write the FLASKBACK
query.

Syntax:

SELECT <column_list> FROM <table_name>


AS OF TIMESTAMP <interval_Expression>;

SELECT * FROM sales


AS OF TIMESTAMP sysdate-interval '10' minute;

10 minutes ago data will be displayed

INSERT INTO sales


SELECT * FROM sales
AS OF TIMESTAMP sysdate-interval '15' minute;

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

Oracle 6 PM Page 108


show parameters
undo_retention => 900 [seconds]

ALTER system SET undo_retention=3600;

Oracle 6 PM Page 109


Clauses in SQL
Monday, March 14, 2022 6:21 PM

Clauses in SELECT query:

Syntax:

SELECT [DISTINCT] <column_list / *>


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

SQL English
Queries Sentences
Clauses Words

Clauses:
• Clause is a part of query.

Following clauses can be used in


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

SELECT ename,sal
FROM emp
WHERE sal>2500;

• SELECT:
SELECT clause is used to specify
the column list.

Ex:
SELECT ename,sal

• FROM clause:
FROM clause is used to specify the table list.

Ex:
FROM emp
FROM emp,dept

• WHERE clause:
○ WHERE clause is used to write the
conditions on rows.
○ This condition is applied on every row.

Ex:
WHERE sal>3000
WHERE sal between 3000 and 5000

ORDER BY:
• ORDER BY clause is used to arrange the
records in ascending or descending
according to specific column / columns.
• Default Order is Ascending Order. We have
no need to specify "Asc". By default it will be
taken.
• For Descending Order we must write "DESC".

1 to 10 => Ascending
10 to 1 => Descending

A to Z => Ascending
Z to A => Descending

1-jan-2022 to 31-dec-2022 => Asc

Oracle 6 PM Page 110


1-jan-2022 to 31-dec-2022 => Asc
31-dec-2022 to 1-jan 2022 => Desc

Display the emp records in alphabetical


order according to emp names:

SELECT ename,sal
FROM emp
ORDER BY ename;

(or)

SELECT ename,sal
FROM emp
ORDER BY ename Asc;

Display the salaries in Descending Order:

SELECT ename,sal
FROM emp
ORDER BY sal DESC;

Display the salaries in Descending Order. If


salary is same arrange those records in
alphabetical order according emp name:

SELECT ename,sal
FROM emp
ORDER BY sal DESC, ename ;

(or)

SELECT ename,sal
FROM emp
ORDER BY sal DESC, ename Asc;

Arrange the emp records in Descending Order according


to salary. If salary is same arange them in alphabetical
order according emp name. If name is also same then
arrange the in ascending order according to empno:

SELECT empno,ename,sal FROM emp


ORDER BY sal DESC, ename Asc,empno Asc;

Display the emp records in Ascending


order according to deptno:

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

Display the emp records in Ascending order


according to deptno. If deptno is same
arrange them in descending order according
to sal.

SELECT ename,sal,deptno FROM emp


ORDER BY deptno Asc, sal Desc;

Display the emp records in Ascending order


according to deptno. With in dept display
senior emp records first.
1981
SELECT ename,sal,deptno,hiredate 1982
FROM emp 1983
ORDER BY deptno Asc, Hiredate Asc;

Oracle 6 PM Page 111


ORDER BY deptno Asc, Hiredate Asc;

Display the enames in alphabetical


order:

SELECT ename,sal FROM emp


ORDER BY 1;

Display the salaries in descending


order. Display nulls in the last:
emp
SELECT ename,sal FROM emp
DESC
ORDER BY 2 DESC nulls last; sal
---------
2500 5000
null
5000 4500
null
4200
3000 5000
3800
4500 4500
3000
4200
2500
3800
4200 null
3000
null
2500
3800

GROUP BY clause:
• is used group the records according to
specific column or columns.

SELECT sum(Sal)
emp
FROM emp
empno ename job sal deptno GROPU BY deptno;
1001 A CLERK 3000 20 10 13000
1002 B MANAGER 5000 20 20 8000
1003 C MANAGER 4000 30 30 10000
1004 D CLERK 6000 30
1005 E MANAGER 8000 10 SELECT sum(Sal)
1006 F CLERK 5000 10 FROM emp
GROPU BY job;
CLERK 14000
MANAGER 17000

GROUP BY:
• It is used to group the records according to specific
column / columns.
○ GROUP BY deptno => 10, 20, 30
○ GROUP BY Job => CLERK, MANAGER
○ GROUP BY deptno,job => 10 MANAGER, 10 CLERK
• When column values are same it will be treated as one
group.

• GROUP BY can be used to get summarized


data from detailed data.
• It can be used for Data Analysis.
• We can apply aggregate (group) functions on
group of records.

Display dept wise sum of salaries:

empno ename job sal deptno


1001 A CLERK 3000 20 deptno sum(Sal)
1002 B MANAGER 5000 20 20 8000
1003 C MANAGER 4000 30 30 10000
1004 D CLERK 6000 30 10 13000
1005 E MANAGER 8000 10
1006 F CLERK 5000 10

SELECT deptno,sum(Sal)

Oracle 6 PM Page 112


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

Display deptno 10 & 30 sum of salaries.


Arrange the result in Ascending order
according to deptno:

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

Execution Order in SELECT query:

1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. DISTINCT
7. ORDER BY

empno ename job sal deptno


1001 A CLERK 3000 20
1002 B MANAGER 5000 20
1003 C MANAGER 4000 30
1004 D CLERK 6000 30
1005 E MANAGER 8000 10
1006 F CLERK 5000 10

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

FROM emp:

empno ename job sal deptno


1001 A CLERK 3000 20
1002 B MANAGER 5000 20
1003 C MANAGER 4000 30
1004 D CLERK 6000 30
1005 E MANAGER 8000 10
1006 F CLERK 5000 10

WHERE deptno IN(10,30):

1003 C MANAGER 4000 30


1004 D CLERK 6000 30
1005 E MANAGER 8000 10
1006 F CLERK 5000 10

GROUP BY deptno:

1003 C MANAGER 4000 30


1004 D CLERK 6000 30

1005 E MANAGER 8000 10


1006 F CLERK 5000 10

SELECT deptno,sum(Sal):

Oracle 6 PM Page 113


SELECT deptno,sum(Sal):

deptno sum(Sal)
30 10000
10 13000

ORDER BY deptno:

deptno sum(Sal)
10 13000
30 10000

Display number of employees in each


dept:

deptno num_of_emps
sum()
10 5
avg()
20 7 count()
30 6 max()
min()
SELECT deptno, count(*) no_of_emps
FROM emp
GROUP BY deptno
ORDER BY deptno;

Dept wise maximum salary &


minimum salary:

deptno max_sal min_sal


10 5000 800
20 3000 1200

SELECT deptno,
max(Sal) max_Sal,
min(Sal) min_Sal
FROM emp
GROUP BY deptno
ORDER BY 1;

Display year wise number of emps joined


the organization:

Year No_Of_Emps
1980 2
1981 5
1982 3
1983 4

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


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

Note:
Can we use alias name in GROUP BY?
No. Because After GROUP BY, SELECT
will be executed. GROUP BY cannot
identify alias name.

Can we use alias name in ORDER BY?


Yes. We can use. After SELECT, ORDER
BY gets executed.

Oracle 6 PM Page 114


Display quarter wise number of employees
joined in the organization:

quarter no_of_emps
1 5
2 3
3 7
4 4

SELECT to_char(hiredate,'q') quarter,


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

Display number of emps according


to salary range:
If sal>3000 => Hisal
If sal<3000 => Losal
If sal=3000 => AvrgSal

sal_range no_of_emps
Hisal 1
LoSal 5
AvrgSal 8

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"
FROM emp
GROUP BY
CASE
WHEN sal>3000 THEN 'HiSal'
WHEN sal<3000 THEN 'LoSal'
WHEN sal=3000 THEN 'AvrgSal'
End;

Display job wise sum of salaries:

job sum(sal)
CLERK …
ANALYST …

SELECT job, Sum(Sal) FROM emp


GROUP BY job;

Display job wise max sal & min sal:

Job Min(Sal) Max(Sal)


CLERK .. ..
MANAGER .. ..

SELECT job, Min(Sal), Max(Sal)


FROM emp
GROUP BY job;

Display job wise number of emps:

Job no_of_emps
CLERK 3
MANAGER 2

SELECT job, count(*) FROM emp


GROUP BY job;

Oracle 6 PM Page 115


GROUP BY job;

HAVING clause:
• HAVING clause is used to write the conditions
on Groups [Group of records]. Display dept wise no of emps:
• It will be applied on result of GROUP BY. Display the depts which are having
• It cannot be used without GROUP BY. more than 5 emps:
SELECT deptno,count(*)
• It filters the groups. FROM emp
SELECT deptno,count(*)
GROUP BY deptno;
Display the deptnos which are spending more FROM emp
than 10000 amount on their employees: GROUP BY deptno
deptno count(*)
HAVING count(*)>5;
10 3
SELECT deptno,Sum(Sal) FROM emp
20 6 deptno count(*)
GROUP BY deptno
HAVING sum(sal)>10000; 30 8 20 6
40 4 30 8

Display the deptnos which are having more than


5 employees:

SELECT deptno, count(*) FROM emp


GROUP BY deptno
HAVING count(*)>5;

Display the job titles which are spending more


than 6000 amount on the emps:

SELECT job, sum(Sal) FROM emp


GROUP BY job
HAVING sum(Sal)>6000;

Display the jobs which are having more than 3


employees:

SELECT job, count(*) FROM emp


GROUP BY job
HAVING count(*)>3;

WHERE => used to write conditions


HAVING => used to write conditions

WHERE HAVING

• used to apply the • used to apply the condition on


condition on row. group

• It can be used without • It cannot be used without


GROUP BY GROUP BY. Because it filters the
groups.

• We cannot use • We can use aggregate functions


aggregate functions in HAVING clause.
in WHERE clause

• It will be executed • It will be executed after GROUP


before GROUP BY BY

Note:
When we use GROUP BY or Aggregate Functions,
In SELECT clause we can write group column or
group function.
We cannot write single row column.

SELECT deptno,ename,sum(Sal)

Oracle 6 PM Page 116


We cannot write single row column.

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

ERROR:
ename is not GROUP BY expression

SQL> SELECT ename,sum(Sal) FROM emp;


SELECT ename,sum(Sal) FROM emp
*
ERROR at line 1:
ORA-00937: not a single-group group function

SELECT used to specify column list


FROM used to specify table list
WHERE used to write the conditions on rows
GROUP BY used to group the records according
specific column / columns
HAVING used to conditions on groups
ORDER By used to arrange the records in
Ascending or Descending Order
DISTINCT avoids duplicate rows

Grouping the records according to


multiple columns:

emp

empno ename job sal deptno


1001 A CLERK 3000 20
1002 B MANAGER 5000 20
1003 C MANAGER 4000 30
1004 D CLERK 6000 30
1007 G CLERK 7000 20
1008 AA MANAGER 12000 20
1009 CC MANAGER 4000 30
1010 DD CLERK 6000 30

Display Dept wise, Job wise sum of salaries:

break on deptno skip 1

SELECT deptno, job, sum(Sal) FROM emp


GROUP BY deptno,job
ORDER BY 1;

Calculating sub totals & grand total:

We can use 2 functions to calculate sub totals


& grand total. They are:
• Rollup()
• Cube()

Rollup():
Syntax:
Rollup(grouping_column_list)
Ex:
Rollup(deptno,job)
It calculates sub totals & grand total
according to "deptno"

Oracle 6 PM Page 117


Cube():
Syntax:
Cube(grouping_column_list)
Ex:
Cube(deptno,job)

Calculates sub totals & grand total


according to deptno & job.

Rollup() calculates subtotals & grand total


according to first column in the list
Cube() calculates sub totals & grand total
according to all columns specified in the
list

Display dept wise, job wise sum of salaries. Calculate


sub totals & grand total according to deptno:

SELECT deptno, job, sum(Sal)


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

Display dept wise, job wise sum of salaries. Calculate


sub totals & grand total according to deptno & job:

SELECT deptno, job, sum(Sal) FROM emp


GROUP BY Cube(deptno,job)
ORDER BY 1;

Display Year wise, Quarter wise number of


emps joined in organization:

Year Quarter no_of_emps


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

SELECT to_char(hiredate,'yyyy') year,


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

Display year wise, quarter wise number of emps joined in


organization. Calculate sub totals & grand total according to year:
SELECT to_char(hiredate,'yyyy') year,
to_char(hiredate,'q') quarter,
count(*) no_of_emps
FROM emp
GROUP BY Rollup(to_char(hiredate,'yyyy'), to_char(hiredate,'q'))
ORDER BY year;

calculate subtotals & grand total according to year & quarter:

SELECT to_char(hiredate,'yyyy') year,


to_char(hiredate,'q') quarter,
count(*) no_of_emps

Oracle 6 PM Page 118


count(*) no_of_emps
FROM emp
GROUP BY Cube(to_char(hiredate,'yyyy'), to_char(hiredate,'q'))
ORDER BY year;

SALES
dateid amount
Year quarter amount
1-JAN-2017 20000
2017 1 100000
2-JAN-2017 30000
2 2000000
.
3 …
.
4 …
.
2017 sub total
.
2018 1
2
3
4
2018 sub total
grand total

SELECT to_char(dateid,'yyyy') year,


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

Person
pid pname state gender age aadhar

Display state wise, gender wise number of


people:
State Gender No_of_People
Telangana M ….
F …
AP M …
F …

SELECT State, Gender, Count(*) No_of_People


FROM Person
GROUP BY state,gender
ORDER BY 1;

SELECT State, Gender, Count(*) No_of_People


FROM Person
GROUP BY Rollup(state,gender)
ORDER BY 1;

SELECT State, Gender, Count(*) No_of_People


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

Display state wise, age range wise, gender wise


no of people:

STATE age_range gender no_of_people


Telangana Minors M ..
F ..
s.CITIZEN M ..

Oracle 6 PM Page 119


s.CITIZEN M ..
F ..
MidAge M ..
F ..
Gujarat Minors M
F
s.CITIZEN M ..
F ..
MidAge M ..
F ..

break on state on age_group skip 1

SELECT state,
CASE
WHEN age<18 THEN 'MINOR'
WHEN age between 18 and 60 THEN 'MidAge'
WHEN age>60 THEN 'S.CITIZEN'
END as age_group,
gender,
count(*) no_of_people
FROM person
GROUP BY state,
CASE
WHEN age<18 THEN 'MINOR'
WHEN age between 18 and 60 THEN 'MidAge'
WHEN age>60 THEN 'S.CITIZEN'
END,
gender
ORDER BY 1;

DISTINCT:
used to avoid the duplicate rows

empno ename job


MANAGER
CLERK
CLERK
MANAGER
SALESMAN
SALESMAN

Display the job titles offered by the company:

SELECT DISTINCT job FROM emp;

job Job
MANAGER ---------
CLERK MANAGER
CLERK CLERK
SALESMAN
MANAGER
SALESMAN
SALESMAN

Display the deptnos existed in the


company:

SELECT deptno FROM emp;

SELECT DISTINCT deptno FROM emp;


deptno
--------------- deptno
10 -------------
30
30
10

Oracle 6 PM Page 120


10 -------------
30
30
10
20
20
30
10
20

Clauses in Select query:

SELECT used to specify column list


Ex: SELECT ename,sal
FROM used to write the table names
Ex: FROM emp
WHERE used to write the conditions on rows.
It filters the records.
Ex: WHERE sal>3000

GROUP used to group the records according to


BY specific column/columns

Ex:
GROUP BY deptno => 10 20 30
GROUP BY job => CLERK MANAGER
GROUP BY deptno,job => 10 MANAGER
10 CLERK
20 MANAGER
20 CLERK

HAVING used to write the conditions on groups


used to filter the groups
Ex:
GROUP BY deptno
HAVING sum(sal)>10000
DISTINCT used to avoid duplicate rows
Ex:
distinct job => CLERK MANAGER
distinct deptno => 10 20 30
ORDER BY used to arrange the records in Ascending
or descending order
Ex:
Order By ename => A B
Order By sal desc => 10000 9000 8000

Execution Order:

FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY

Oracle 6 PM Page 121


SET OPERATORS
Saturday, March 19, 2022 7:13 PM

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

A U B = {1,2,3,4,5,6,7,8}
A I B = {2,3,4}
A M B = {1,5,6}
B M A = {7,8}

Syntax:
SELECT query
SET OPERATOR
SELECT query;

SQL provides 4 SET OPERATORS:


• UNION
• UNION ALL
• INTERSECT
• MINUS

UNION:
• used to combine records from multiple
tables without duplicates.

cust1 cust2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E

Display all customer records from cust1 & cust2:

SELECT cid,cname FROM cust1


UNION
SELECT cid,cname FROM cust2;

cid cname
1001 A
1002 B
1003 C
5001 D
5003 E

Oracle 6 PM Page 122


UNION:
• used to combine records from multiple
tables without duplicates.
• It gives result in the order according to first
column.

UNION ALL:
• used to combine records from 2 tables
including duplicates.

cust1 cust2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E

SELECT cid,cname FROM cust1


UNION ALL
SELECT cid,cname FROM cust2;

cid cname
1001 A
1002 B
1003 C
5001 D
1002 B
5003 E

INTERSECT:
used to common records from multiple tables.

cust1 cust2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E

cid cname
1002 B

SET Operators:
cust1 [Branch1] cust2 [Branch2]
UNION cid cname cid cname
UNION ALL 1001 A 5001 D
INTERSECT
1002 B 1002 B
MINUS
1003 C 5003 E

Oracle 6 PM Page 123


Display specific customers of Branch1:

SELECT cid,cname FROM cust1


MINUS
SELECT cid,cname FROM cust2;

cid cname
1001 A
1003 C

Minus:
It is used to get specific records
from first table.
It gives all records from first table
except common records.

Differences b/w UNION & UNION ALL:

UNION UNION ALL

• It will not give • gives duplicate records


duplicate records

• Always gives result • It will not give result in the


in order order

• Union is slower • Union All is faster than Union


than Union All.

cust1 U cust2 = cust2 U cust1


cust1 UA cust2 = cust2 UA cust1
cust1 I cust2 = cust2 I cust1

cust1 M cust2 != cust2 M cust1

cust1 M cust2 => specific records of cust1


cust2 M cust1 > specific records of cust2

display specific records of branch1:

SELECT * FROM cust1


MINUS

Oracle 6 PM Page 124


MINUS
SELECT * FROM cust2;

CID CNAME
---------- ----------
1001 A
1003 C

Display specific records of branch2:

SELECT * FROM cust2


MINUS
SELECT * FROM cust1;

CID CNAME
---------- ----------
5001 D
5003 E

SELECT query1
SET OPERATOR
SELECT query1

Rules:
• Corresponding columns data types in both
SELECT queries should be matched.
Ex:
SELECT cid,cname FROM cust1
UNION
SELECT cname,cid FROM cust2;
Output:
ERROR at line 1:
ORA-01790: expression must have same
datatype as corresponding expression

• Number of Columns in both SELECT queries


should be same.
Ex:
SELECT cid FROM cust1
UNION
SELECT cid,cname FROM cust2;
Output:
ERROR at line 1:
ORA-01789: query block has incorrect
number of result columns

• Corresponding column names need not to be


same.
Ex:
cust2 [Branch2]
Oracle 6 PM Page 125
• Corresponding column names need not to be
same.
Ex:
cust1 [Branch1] cust2 [Branch2]
custid cust_name cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E

SELECT custid,cust_name FROM cust1


UNION
SELECT cid,cname FROM cust2;

cust_id cust_name
1001 A
1002 B
1003 C
5001 D
5003 E

Display the common designations in deptno 10 & deptno20:

SELECT distinct job FROM emp


WHERE deptno=20;

JOB
---------
CLERK
ANALYST
MANAGER

SQL> SELECT distinct job FROM


emp WHERE deptno=10;

JOB
---------
CLERK
MANAGER
PRESIDENT

JOB JOB
--------- ---------
CLERK CLERK
ANALYST MANAGER
MANAGER PRESIDENT

SELECT Job FROM emp WHERE deptno=10


INTERSECT
SELECT job FROM emp WHERE deptno=20;
Oracle 6 PM Page 126
SELECT job FROM emp WHERE deptno=20;

CLERK
MANAGER

Display specific designations of deptno 10:

SELECT Job FROM emp WHERE deptno=10


MINUS
SELECT job FROM emp WHERE deptno=20;

PRESIDENT

Display specific designations of deptno 20:

SELECT job FROM emp WHERE deptno=20


MINUS
SELECT job FROM emp WHERE deptno=10;

ANALYST

Display all job designations of deptno 10 & 20:

SELECT job FROM emp WHERE deptno=10


UNION
SELECT job FROM emp WHERE deptno=20;

ANALYST
CLERK
MANAGER
PRESIDENT

emp_us
empno ename job sal
5001 Display all emp records who are working
5002 in india & us.

5003
Display common emps who are working
5004
for india & us.
5005
Display the emp records who are
emp_ind working only for us.
empno ename job sal
2001 Display the emp records who are
2002 working only for ind.

5002
5004
2003
2004
Oracle 6 PM Page 127
2004

Oracle 6 PM Page 128


Joins
Monday, March 21, 2022 7:15 PM

Joins:
Goal => Retrieve data from multiple tables

College DB
Student

Student sid sname city mobile


Marks
Fee Marks
Employee sid Maths Phy Che
Library
.
sid sname Maths
Student Marks

sid sname maths phy che

Orders
Orderid Ord_Date Cid Del_date Pid Qty Price
1001 15-FEB-22 2001 20-FEB-22 3001 2 5000

Customers
cid cname ccity

Products
pid pname cid cname pid pname orderid ord_Date del_Date

Joins:
• Join => Connect / Link / Combine College DB
• Join is an operation that is used to combine
one table records with another based on Student
Join Condition. Marks
• Join condition decides one record in one table Fee
should be joined with which record in another Staff
table.
• Goal: Joins are used to retrieve the data from
multiple tables.
STUDENT.sid = MARKS.sid Join Condition
• Normally, for Join operation common column is
required.
• Common column names need not to be same. STUDENT MARKS
• Ex: STUDENT.stdid = MARKS.sid sid sname scity sid M1 M2 M3
1001 A Hyd 1001 60 90 70
1002 B Mumbai 1002 66 88 44
1003 C Pune 1003 45 72 49
Types of Joins:
• Equi Join / Inner Join

Oracle 6 PM Page 129


1002 B Mumbai 1002 66 88 44
1003 C Pune 1003 45 72 49
Types of Joins:
• Equi Join / Inner Join
• Outer Join
○ Left Outer Join sid sname M1
○ Right Outer Join 1001 A 60
○ Full Outer Join 1002 B 66
• Non-Equi Join 1003 C 45
• Self Join
• Cross Join / Cartesian Join / Product Join
• Natural Join

Equi Join / Inner Join:


If Join Operation is performed based on Equality
Condition then it is called "Equi Join / Inner Join".

e.Deptno = d.Deptno Join COndition

Emp e
empno ename sal deptno Dept d

1001 A 20 Deptno Dname Loc

1002 B 30 10 Accounting DALLAS

1003 10 20 Research CHICAGO

1004 10 30 SALES BOSTON

1005 20 40 OPERATIONS NEW YORK

1006 30

Display employee details along


with dept details:

ename sal dname loc


emp dept

SELECT ename, sal, dname, loc


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

Table Alias:
• We can give alias(alternative)
names to tables.

Advantages:
• It makes table name short.
• improves the performance.

ORACLE Style:

SELECT e.ename, e.sal, d.dname, d.loc


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

We can write a Join Query in 2 styles:


• Oracle Style [Native Style]
• ANSI Style [introduced in Oracle 9i version]

Oracle 6 PM Page 130


We can write a Join Query in 2 styles:
• Oracle Style [Native Style]
• ANSI Style [introduced in Oracle 9i version]

ORACLE SQL SERVER

Join QUERY [ANSI] Join QUERY [ANSI]

ANSI STYLE:
• To separate two table names we use comma
[,] in Oracle Style. In ANSI style, to separate
two table names use keyword.

• We write Join Condition in WHERE clause in


ORACLE style. In ANSI style, write join condition
in ON clause Or USING clause.

ORACLE Style:
SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;

ANSI STYLE:
SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno;

In ANSI style, Join condition can be written


using 2 clauses. They are:
• ON clause [Best way]
• USING clause

e.deptno=d.deptno
SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e INNER JOIN dept d
USING(deptno);

• implicitly USING clause will be


converted to ON clause only. ON clause
gets executed faster than USING.
• In case of USING clause common
column name must be same.
• Ex:
ON e.dno = d.deptno => valid
Above join condition is not possible with
"USING" clause.

ON e.deptno=d.deptno
(or)
USING(deptno)

e.deptno = d.deptno
Oracle 6 PM Page 131
e.deptno = d.deptno

emp e dept d
empno ename sal deptno deptno dname loc

ename sal dname loc


emp dept

To retrieve data from 2 tables write => 1 Join Condition


To retrieve data from 5 tables write => 4 Join conditions
To retrieve data from 10 tables write => 9 Join conditions
.
.
To retrieve data from n tables write => n-1 Join Conditions

e.deptno = d.deptno d.locid=l.locid l.cid=c.cid

emp1 e dept1 d location1 l Country1 c

empno deptno LocId cid


ename dname Lname cname
deptno locid Cid

ename dname lname cname


emp1 dept1 location1 country1

ORACLE STYLE:

SELECT e.ename, d.dname, l.lname, c.cname


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:
• Equi Join [Inner Join] can display matching records
only. Outer Join is used to get matching records &
unmatching records.
• Equi Join / Inner Join = matching records only

• Outer Join = matching records + unmatching records

• Join Operator : (+)

Oracle 6 PM Page 132


There are 3 sub types:
• Left Outer Join
• Right Outer Join
• Full Outer Join

Left Outer Join:

Emp Dept
empno ename sal deptno Deptno Dname Loc
1001 A 20 10 Accounting DALLAS
1002 B 30 20 Research CHICAGO
1003 C 10 30 SALES BOSTON
1004 D 10 40 OPERATIONS NEW YORK
1005 E 20
1006 F 30
1007 G
1008 H

Display the emp details along with dept details.


Also display the employees to whom dept is
not assigned:

Left Outer Join:


• It displays matching records and unmatching records
from left table

Left Outer = matching recs + unmatching from left table

Equi Join e.deptno = d.deptno


Left Outer e.deptno = d.deptno(+)
Right Outer e.deptno(+) = d.deptno

Display the emp details along with dept details.


Also display the employees to whom dept is
not assigned:

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d
WHERE e.deptno = d.deptno(+);

ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e LEFT OUTER JOIN dept d
ON e.deptno=d.deptno;

Note:
IN ANSI STYLE , based on table list in
FROM clause which one left & right will
be decided.
Ex:
FROM emp e LEFT OUTER JOIN dept d

left table => emp

Oracle 6 PM Page 133


left table => emp
right table => dept

In ORACLE style based on join condition


which one left or which one right will be
decided.
Ex:
emp.deptno = dept.deptno(+)

left table => emp


right table => dept

Display the emp records along with dept details.


Also display the emp records to whom deptno is
not assigned:
Left 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 LEFT OUTER JOIN dept d
ON e.deptno = d.deptno;

Left Outer Join = matching recs + unmatching from left table

Right Outer Join:

Right Outer = matching recs + unmatching from right table

• It gives all matching records and unmatching


records from right table

Display the emp records along with dept details.


display the depts in which employees are not
existed:
[Right Outer Join]:

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d
WHERE e.deptno(+) = d.deptno;

ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e RIGHT OUTER JOIN dept d

Oracle 6 PM Page 134


FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno;

FULL OUTER JOIN:

FULL OUTER = matching recs + unmatching from left


+ unmatching from right

It gives matching records, unmatching records


from left & right tables

Inner Join matching records e.deptno = d.deptno


Left Outer matching +
unmatching from e.deptno = d.deptno(+)
left
Right Outer matching +
unmatching from e.deptno(+) = d.deptno;
right
Full Outer matching + e.deptno(+) = d.deptno(+) --ERROR
unmatching from
left + unmatching left outer join
from right union
right outer join

Display the emp records along with dept details. Also


display the employees to whom dept is not assigned. Also
display the dept names which are not having employees:

FULL OUTER JOIN:

ORACLE STYLE:

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 deptno is not


assigned:

Left Outer Join + Condition

ORACLE STYLE:

Oracle 6 PM Page 135


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:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e LEFT JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname IS null;

Display the dept details which are not having emps:

RIGHT OUTER JOIN +CONDITION:

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 JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename IS null;

Display the employee records to whom dept is not


assigned. Also display the dept details which are not
having emps:

FULL OUTER JOIN + 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
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno and e.ename is null;

ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname IS null or e.ename IS null;

Equi Join:
If join operation is performed based on equality condition
then it is called "Equi Join".

Non-Equi Join:
If join operation is performed based on other than equality

Oracle 6 PM Page 136


If join operation is performed based on other than equality
condition then it is called "Non-Equi Join".

e.deptno = d.deptno => Equi Join

e.deptno != d.deptno => Non-Equi Join


e.deptno > d.deptno => Non-Equi Join

Display the emp salaries with salary grades:

emp salgrade
empno ename sal
1001 5000 grade losal hisal
1002 8000 1 700 1200
1003 4000 2 1201 1400
1004 1800 3 1401 2000
4 2001 3000
5 3001 6000
6 6001 9000

ORACLE STYLE:

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 JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;

Self Join:
• Self Join can be also called as "Recursive Join".
• If a table is joined to itself then it is called "Self Join"

Emp e1 [employee]
Emp e2 [manager]
empno ename job sal mgr
empno ename job sal mgr
1001 A clerk 5000 1003
1001 A clerk 5000 1003
1002 B analyst 7000 1003
1002 B analyst 7000 1003
1003 C manager 10000
1003 C manager 10000
1004 D clerk 6000 1005
1004 D clerk 6000 1005
1005 E manager 12000
1005 E manager 12000

Display employee details along with their


manager's details:

SELECT e1.ename employee, e2.ename manager


FROM emp e1, emp e2
WHERE e1.mgr=e2.empno;

Display the emp records who are earning more


than their manager's salary:

SELECT e1.ename employee, e1.sal emp_Sal,


e2.ename manager, e2.sal mgr_sal
FROM emp e1, emp e2

Oracle 6 PM Page 137


FROM emp e1, emp e2
WHERE e1.mgr=e2.empno;

Cross Join / Cartesian / Product Join:

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

Each record in one table will be combined


with each record in another table.

GROUPA GROUPB
----------------- ----------------
IND NZ
AUS ENG
WI PAK

3 3 9

SELECT a.cname AGroup, b.cname Bgroup


FROM groupA a, groupb b;

Natural Join:

emp
empno ename job sal hiredate comm mgr deptno

dept
deptno dname loc

SELECT * FROM emp Natural Join dept;

empno ename job sal hiredate comm mgr deptno dname loc

• In natural join we will not write join condition.


• Implicitly join condition will be written by the oracle.
• It performs equi join & displays columns without duplicate
columns.
• Natural join equi join without duplicate columns.

Equi Join:
SELECT * FROM emp e, dept d
WHERE e.deptno=d.deptno;

Natural join:
ORACLE STYLE:
SELECT e.*,d.dname,d.loc FROM emp e, dept d
WHERE e.deptno=d.deptno;

Oracle 6 PM Page 138


WHERE e.deptno=d.deptno;

ANSI style:
SELECT * FROM emp Natural Join dept;

Join:
• Join => connect / link / combine
• used to combine one table records with another
based on join condition.
• join condition decides which record in one table
should be joined with which record in another table
• used to retrieve the data from multiple tables

Types of joins:

Equi / gives matching records only


Inner based on equality condition join operation
will be performed
Ex: e.deptno = d.deptno
Outer matching & unmatching records
Left Outer matching + unmatching from left table
Ex: e.deptno = d.deptno(+)
Right matching + unmatching from rght table
Outer Ex: e.deptno(+) = d.deptno

Full Outer matching + unmatching from left table &


right table
Left Outer UNION Right OUTER

Non-Equi based on other than equality condition


join operation will be performed
> < !=
Self If a table is joined to itself
Product / each record in one table will be joined with
Cross each record in another table
natural equi join without duplicate columns

student course
sid sname cid cid cname
101 A 20 10 Java
102 B 30 20 Python
103 C 30 30 HTML
104 D 10 40 CPP
105 E

sid sname cname

Oracle 6 PM Page 139


Sub Queries
Saturday, March 26, 2022 6:22 PM

Sub Queries / Nested Queries:


• Writing query in another query is called "Sub Query /
Nested Query".

SELECT ………
……..(SELECT ……
(SELECT …. ) );

Outer query/ Main query / Parent query


Syntax:

SELECT <column_list>
FROM <table_name>
WHERE <column_name> <operator> (SELECT query);

Inner Query /
Sub Query /
Child Query

• Inside query is called "Inner query / Sub Query / Child


Query"
• Outside query can be called as "Outer Query /
Main Query / Parent Query".
• Normally in sub queries, first inner query gets executed.
The result of inner query becomes input for the outer
query. Then outer query gets executed.
• INNER QUERY must be SELECT query only. It cannot be
INSERT / UPDATE / DELETE.
• OUTER QUERY can be SELECT / INSERT / UPDATE /
DELETE .
• Inner query must be written in parenthesis [ (inner_query) ]
• In WHERE clause, we can write up to 255 levels of sub
queries.

Types of Sub Queries:

• Single Row Sub Queries


• Multi Row Sub Queries
• Correlated Sub Queries
• Inline View
• Scalar Sub Queries

Single Row Sub Queries:

• If sub query returns single row then it is


called "Single Row Sub Query".

Examples on Single Row Sub Queries:

1. Display the emp records who are earning more


than BLAKE:
BLAKE 3000

SELECT * FROM emp SELECT sal FROM emp


WHERE sal>(SELECT sal FROM emp WHERE ename='BLAKE';
WHERE ename='BLAKE'); 3000

Note:
When value is unknown in WHERE clause

Oracle 6 PM Page 140


When value is unknown in WHERE clause
condition then write subquery.

Display the emp records who


joined after 'FORD' [OR]
FORD 23-NOV-1981
Display the juniors of 'FORD':

ALLEN 25-DEC-1983
SMITH 17-oct-1980
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate > '23-NOV-1981';

25-MAR-2022
24-NOV-1981 onwards => juniors
26-MAR-2022

1
SELECT hiredate FROM emp 1-jan-2022
2
WHERE ename='FORD'; 2-jan-2022
3
.
4
.
5
SELECT empno, ename, hiredate 31-jan-2022
6
FROM emp
7
WHERE hiredate > (SELECT hiredate
8
FROM emp
9
WHERE ename='FORD');
10

Display the emp records who joined before FORD [OR]


Display the emp records who are senior to FORD:

SELECT empno,ename,hiredate FROM emp


WHERE hiredate<(SELECT hiredate FROM emp
WHERE ename='FORD');

Display the emp records who joined on FORD's joining date:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate = (SELECT hiredate FROM emp
WHERE ename='FORD');

Update 7369 empno salary with deptno 30's max salary:

UPDATE emp SET sal=(SELECT max(Sal) FROM emp


WHERE deptno=30)
WHERE empno=7369;

Write a query to swap two salries:


7369 SMITH 2850
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

Oracle 6 PM Page 141


END
WHERE empno IN(7369,7499);

Find most senior's hiredate:

SELECT min(hiredate) FROM emp;

Find the emp name who is most senior in all


employees:

SELECT * FROM emp


WHERE hiredate = (SELECT min(hiredate)
FROM emp);

Find most junior's hiredate:

SELECT max(hiredate) FROM emp;

Find the emp name who is most junior in all


emps:

SELECT * FROM emp


WHERE hiredate = (SELECT max(hiredate)
FROM emp);

Find max Sal in all employees:

SELECT max(Sal) FROM emp;

Find the emp name who is earning maximum


salary:

SELECT * FROM emp


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

Find the min salary in all employees:

SELECT min(Sal) FROM emp;

Find the emp name who is earning min salary


in all emps:

SELECT ename FROM emp


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

Find 2nd max salary:

• find salary values < max sal


• From that list find max value

SELECT max(sal) FROM emp


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

Find 3rd maximum salary:

• Find sal <second max salary


• From this list find max value

SELECT max(sal) FROM emp


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

Oracle 6 PM Page 142


Find the emp name who is earning second max salary:

SELECT ename FROM emp


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

Find the emp name who is earning 3rd max salary:

SELECT ename FROM emp


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

Find the emp name who is earning min salary:

Find 2nd min salary:

Find 3rd min salary:

Find the ename who earning 2nd min salary:

Find the ename who is earning 3rd min salary:

sal
--------
select min(sal) from emp
4000
where sal>(select min(Sal) from
5000
emp);
2000
3000
select ename FROM emp
WHERE sal = (
select min(sal) from emp
where sal>(select min(Sal) from
emp)
);

Find the maximum sum of amount in all depts:

Dept wise sum of salaries:

SELECT deptno,sum(sal) FROM


emp GROUP BY deptno;

10 10000
20 15000
30 12000

Find the maximum sum of amount in all


depts:

SELECT max(sum(Sal)) FROM emp


GROUP BY deptno;

Find the deptno which is spending max


amount on their employees:

SELECT deptno FROM emp

Oracle 6 PM Page 143


SELECT deptno FROM emp
GROUP BY deptno
HAVING sum(sal) = (SELECT max(sum(sal))
FROM emp
GROUP BY deptno);

Find the dept name which is spending max


amount on their employees:

SELECT dname FROM dept


WHERE deptno=20;

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 dept wise number of employees:

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

Find the deptno which is having maximum


number 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
HAVING count(*) = (SELECT max(count(*))
FROM emp
GROUP BY deptno));

Multi Row Sub Queries:


• If sub query returns multiple rows then it is
called "Multi Row Sub Query".

Display all managers & clerks records:

SELECT empno,ename,job,sal,deptno
FROM emp
WHERE job IN('MANAGER','CLERK');

Display all emps records whose job title is


equals to BLAKE & JAMES:

SELECT * FROM emp


WHERE job IN(SELECT job FROM emp
WHERE ename IN('BLAKE','JAMES') );

Oracle 6 PM Page 144


Display the emp records who are earning
1250 & 3000:

SELECT * FROM emp


WHERE sal IN(1250,3000);

Display the emp records whose salary is


equals to WARD's salary & FORD's salary:

SELECT empno,ename,sal
FROM emp WHERE sal IN(SELECT sal
FROM emp
WHERE ename IN('WARD','FORD') );

Any multi greater condition (or) multi less


condition [with OR]
All multi greater condition (or) multi less
condition [with AND]
IN multi equality condition [with OR]

TURNER => 1500


BLAKE => 2850

Display all emp records who are earning more


than 1500 or more than 2850:

sal>1500 or sal>2850

SELECT empno,ename,sal sal>ANY(1500,2850)


FROM emp
WHERE sal>ANY(1500,2850);

Display the emp records whose sal sal>1500 and sal>2850


is greater than 1500 and also
greater than 2850:
sal>ALL(1500,2850)
SELECT empno,ename,sal
FROM emp
WHERE sal>ALL(1500,2850);

Display the emp records whose sal is greater


than TURNER(1500) and BLAKE(2850):

SELECT empno,ename,sal
FROM emp
WHERE sal>ALL(SELECT sal
FROM emp
WHERE ename IN('TURNER','BLAKE'));

Display the emp records whose salary is greater


than TURNER's salary or greater than BLAKE's
salary:

Oracle 6 PM Page 145


salary:

SELECT empno,ename,sal
FROM emp
WHERE sal>ANY(SELECT sal
FROM emp
WHERE ename IN('TURNER','BLAKE'));

Display the emp records who are max salary in their depts:

Find dept wise max salary:

SELECT deptno,max(Sal) FROM emp


GROUP BY deptno;

SELECT empno,ename,sal,deptno
FROM emp
WHERE (deptno,sal) IN(
SELECT deptno,max(Sal) FROM emp
GROUP BY deptno);

Display the emp records who are senior in their dept:

10 senior hiredate
20 senior hiredate
30 senior hiredate

SELECT deptno,min(hiredate)
FROM emp
GROUP BY deptno;

SELECT empno,ename,hiredate,deptno
FROM emp
WHERE (deptno,hiredate) IN(SELECT deptno,min(hiredate)
FROM emp
GROUP BY deptno);

Correlated Sub Queries:


• If outer query passes value to inner query
then it is called "Correlated Sub Query".
• In Correlated Sub query, first outer query display the emp records whose
gets executed then inner query gets salary is > blake's sal:
executed.

SELECT * FROM emp


WHERE sal>(SELECT sal FROM
emp WHERE ename='BLAKE');

Execution Order of Correlated Sub Query:


• Outer query gets executed. It returns a row.
• Outer query passes value to inner query.
• Inner query gets executed.
• Inner query returns value to Outer query.
• Outer query condition will be executed. based
on condition Selects the row.
Above steps will be executed repeatedly for all

Oracle 6 PM Page 146


• Above steps will be executed repeatedly for all
rows.

Display the emp records whose salary is


greater than their dept's average salary:

emp
deptno avrg_sal
empno ename sal deptno
10 6000
1001 A 4000 10
20 8000
1002 B 8000 10
1003 C 6000 20
1004 D 10000 20

1002 B 8000 10
1004 D 10000 20

SELECT empno,ename,sal,deptno
FROM emp e
WHERE sal>(SELECT avg(Sal) FROM emp
WHERE deptno=e.deptno);

emp
deptno avrg_sal
empno ename sal deptno
10 6000
1001 A 4000 10
20 8000
1002 B 8000 10
1003 C 6000 20
1004 D 10000 20

1002 B 8000 10
1004 D 10000 20

Display the emp records who are earning max


salary in their depts:

emp
empno ename sal deptno
deptno max(Sal)
1001 A 4000 10
10 8000
1002 B 8000 10
20 10000
1003 C 6000 20
1004 D 10000 20

SELECT empno,ename,sal,deptno
FROM emp e
WHERE sal = (SELECT max(Sal) FROM emp
WHERE deptno=e.deptno);

1002 B 8000 10
1004 D 10000 20

Find third max salary using correlated sub query:

Oracle 6 PM Page 147


Find third max salary using correlated sub query:

how many salary values > sal

highest sal 0
2nd max sal 1
3rd max sal 2
4th max sal 3

3rd max sal:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 2 = (SELECT count(sal)
FROM emp WHERE sal>e.sal);

emp
empno ename job sal
1001 5000
1002 8000
1003 6000
1004 7000

find highest salaried emp record:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 0 = (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);

Find 2nd highest salary:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 1= (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);

Find 3rd highest salary:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 2 = (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);

Find 4th highest salary:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE 3 = (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);

Find nth highest salary:

SELECT empno,ename,sal,deptno
FROM emp e
WHERE &n-1 = (SELECT count(distinct sal)
FROM emp WHERE sal>e.sal);

Exists & Not Exists:

Oracle 6 PM Page 148


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 employees:

SELECT dname FROM dept d


WHERE exists(SELECT * FROM emp
WHERE deptno=d.deptno);

10 ACCOUNTING NEW YORK


20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Display the dept names which are


not having employees:

SELECT dname FROM dept d


WHERE not exists(SELECT * FROM
emp WHERE deptno=d.deptno);

Types of Sub Queries:

Single Row sub query returns


Sub Query single row
Multi Row sub query returns
Sub Query multiple rows
Correlated outer query passes
Sub Query value to inner query
Inline view
Scalar Sub Query

Inline View:
• If sub query is written in FROM clause then FROM
it is called "Inline View". WHERE
• This sub query acts like Table. GROUP BY
• It is used to change execution order of HAVING
clauses. SELECT
DISTINCT
ORDER BY

Display the emp records whose annual


salary is > 30000:

SELECT * FROM
(SELECT empno,ename,sal,sal*12 An_Sal
FROM emp)
WHERE An_Sal>30000;

Oracle 6 PM Page 149


Display top 3 salaried emps records:

SELECT * FROM
(SELECT empno,ename,sal,
Dense_Rank() over(order by sal desc) Rnk
FROM emp)
WHERE Rnk<=3;

Rownum & RowID:


• These are called pseudo columns

Rownum:
• It is a pseudo column. pseudo => false
• It is used to apply row numbers to the
result of select query.

SELECT rownum, empno,ename,job


FROM emp;

SELECT rownum, empno,ename,job


FROM emp WHERE deptno=30;

Display the 3rd record:

SELECT * FROM
(SELECT rownum rn,
empno,ename,sal
FROM emp)
WHERE rn=3;

Display even number records:

2,4,6,8 …… => even => divide with 2 => remainder 0


1,3,5,7 …… => odd => divide with 2 => remainder 1

mod(6,2) => 0
mod(7,2) => 1

WHERE mod(rn,2)=0 => even number row


WHERE mod(rn,2)=1 => odd number

SELECT * FROM
(SELECT rownum rn,empno,ename,sal
FROM emp)
WHERE mod(rn,2)=0;

Oracle 6 PM Page 150


WHERE mod(rn,2)=0;

Display the odd number records:

SELECT * FROM
(SELECT rownum
rn,empno,ename,sal
FROM emp)
WHERE mod(rn,2)=1;

Display the row numbers b/w 6 to 10:

SELECT * FROM
(SELECT rownum rn,empno,ename,sal
FROM emp)
WHERE rn BETWEEN 6 AND 10;

Display 3rd,7th,12th & 14th records:

SELECT * FROM
(SELECT rownum rn,empno,ename,sal
FROM emp)
WHERE rn IN(3,7,12,14);

ROWID:
• ROWID is a pseudo column.
• It displays row address.

SELECT rowid, e.* FROM emp e;

Create Table demo


(
id number(4),
name varchar2(10)
);

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


INSERT INTO demo VALUES(2,'B');
INSERT INTO demo VALUES(1,'A');
INSERT INTO demo VALUES(2,'B');

Delete last record whose id is 2:

DELETE FROM demo


WHERE rowid='AAAWy0AAHAAAB/XAAF';

Scalar Sub Query:


• A Sub Query which is written in SELECT clause
is called "Scalar Sub Query".
• This sub query acts like column.

Display number of records in emp & dept table:

SELECT count(*) FROM emp;

SELECT count(*) FROM dept;


Oracle 6 PM Page 151
SELECT count(*) FROM dept;

SELECT (SELECT count(*) FROM emp) emp,


(SELECT count(*) FROM dept) dept
FROM dual;

emp dept
-------- ……….
14 4

Display the share of each dept:


[each dept spending how much % of amount in
total amount]:

10 30
20 50
30 20

SELECT deptno,sum(Sal) dept_sum_of_Sal,


(SELECT sum(Sal) FROM emp) tot_Amount,
round((sum(sal)*100)/(SELECT sum(Sal) FROM emp)) perc
FROM emp
GROUP BY deptno;

deptno dept_sum_sal tot_amount perc

Sub Queries
writing query in another query

Types of Sub Queries:


single row sub if sub query returns 1 row
query
multi row sub if sub query returns multiple
query rows
correlated sub outer query passes value to inner

query query
inline view if we write sub query in FROM
clause
scalar sub query if we write sub query in SELECT
clause

SQL
Table
5 sub languages => DDL DML DRL DCL TCL
Built-In Functions
Clauses => SELECT FROM WHERE GB H D OB
Joins => Equi, Outer => LO, RO, FO Non-equi self cross natural
Sub Queries
SET operators

Oracle 6 PM Page 152


Tuesday, March 22, 2022 7:04 PM

Emp
empno ename sal deptno
Dept
1001 A 20
Deptno Dname Loc
1002 B 30
10 Accounting DALLAS
1003 C 10
20 Research CHICAGO
1004 D 10
30 SALES BOSTON
1005 E 20
40 OPERATIONS NEW YORK
1006 F 30
1007 G
1008 H

Oracle 6 PM Page 153


Views
Friday, April 1, 2022 6:24 PM

View:
• is a Database Object.
• View is a Virtual table.
• It means, View does not contain physical data & it does
not occupy the memory.
• VIEW holds SELECT query. It does not hold result of
query.
• When we retrieve data through view, implicitly oracle runs
SELECT query.
• A view is created on Table. Without Table we cannot
create the view.
• A table on which view is created is called "Base Table".
• View always gives recent data [committed data].
• Some views can be updated. These are called "Updatable
Views / Simple Views".
• Some view cannot be updated. These are called "Read-
Only Views / Complex Views".

Advantages:
• Provides Security
• Reduces Complexity & Simplifies queries

Disadvantages:
• Low performance

Syntax to create view:

CREATE VIEW <view_name> emp


AS empno ename job sal deptno mgr hiredate comm
<SELECT query>;

CREATE VIEW v1
AS
SELECT empno eno,ename en,job ejob FROM
emp;

• Security can be implemented in 3 levels:


○ DB Level Security => Schema [User]
○ Table Level Security => Grant, Revoke
○ Data Level Security => View
▪ Column Level Security
▪ Row Level Security

Oracle 6 PM Page 154


▪ Column Level Security:

emp table
empno ename job sal deptno mgr comm hiredate

v1 View
empno ename job hiredate

User can see 4 columns only out of 8 columns

Row Level Security:

emp Table
empno ename job sal comm deptno hiredate mgr
1001 A .. .. .. 10 .. ..
1002 10 .. ..
1003 10
1004 20
1005 20

Joins => Join Conditions

5 tables => 4 Join Conditions

SELECT ………………….
FROM …………….
………………….
………………..

CREATE VIEW v1
AS
SELECT deptno, sum(Sal) FROM
emp
GROUP BY deptno;

Oracle 6 PM Page 155


Log in as DBA:
username: system
password: nareshit

CREATE USER c##ramu IDENTIFIED BY ramu


default tablespace users
quota unlimited on users;

GRANT connect, resource TO c##ramu;

Implementing Column Level Security:

emp => 8 columns => empno,ename,job,hiredate, sal, comm, mgr, deptno


v1 => 4 columns => empno,ename,job,hiredate

Create view on 4 columns & give permission on this


view to c##ramu user:

Log in as c##batch6pm:
username: c##batch6pm
password: nareshit

CREATE VIEW v1
AS
SELECT empno,ename,job,hiredate FROM emp;

ERROR: Insufficient privileges

Log in as DBA:
username: system
password: nareshit

GRANT create view TO c##batch6pm;

Log in as c##batch6pm:

CREATE VIEW v1
AS
SELECT empno,ename,job,hiredate FROM emp;

Grant permission on v1 to c##ramu:

GRANT all ON v1 TO c##ramu;

Log in as c##ramu:

Oracle 6 PM Page 156


SELECT * FROM c##batch6pm.v1;

INSERT INTO c##batch6pm.v1


VALUES(5678,'ABCD','CLERK',sysdate);

Types of Views:
2 types:

• Simple View / Updatable View


• Complex View / Read-Only View

Simple View / Updatable View:


• A view which is created based on one table is
called "Simple View".
• We can perform DML operations like INSERT,
UPDATE & DELETE through this view. That’s why it
can be also called as "Updatable View".

Ex: CREATE VIEW v1


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

Row Level Security:

emp
empno ename job sal hiredate mgr comm deptno
1001 A .. .. .. .. .. 10
1002 10
1003 20
1004 20
1005 20
1006 30
1007 30

Log in as c##batch6pm:

CREATE VIEW v2
AS
SELECT * FROM emp WHERE deptno=20;

Oracle 6 PM Page 157


Grant all on v2 to c##ramu;

log in as c##ramu:

INSERT INTO
c##batch6pm.v2(empno,ename,deptno)
VALUES(2345,'A',20);

UPDATE c##batch6pm.v2 SET sal=sal+1000


WHERE empno=2345;

DELETE FROM c##batch6pm.v2


WHERE empno=2345;

SIMPLE VIEW • If view is created based on 1 table then


it is called simple view
• we can perform DML operations on
simple view
• When perform DML operations through
view, these changes will be applied to
base table only. Because, view does
not contain physical data.

insert into v2(empno,ename,deptno)


values(9999,'AA',30);

"v2" created on deptno 20.


Still we can insert other dept records through
"v2" view.
To prevent the user from other than 20 dept
records, use 'WITH CHECK OPTION' clause.

WITH CHECK OPTION clause:


• If view is created using WITH CHECK OPTION clause,
it does not allow the records which cannot be
displayed by the view later.
• The records which are violating WHERE clause in the
view will not be accepted.

CREATE VIEW v3
AS
SELECT * FROM emp WHERE deptno=20
WITH CHECK OPTION;

Oracle 6 PM Page 158


Using v3, user can insert 20 dept records
only. He cannot insert other dept records.

INSERT INTO v3(empno,ename,deptno)


VALUES(1111,'A',10);

ERROR:
ORA-01402: view WITH CHECK OPTION
where-clause violation

INSERT INTO v3(empno,ename,deptno)


VALUES(1111,'A',20);

1 row created

Complex View:
• If a view is created based on multiple tables then it
is called "Complex View".
• If a view is created based on joins (or) group by (or)
having (or) sub queries (or) set operators (or)
group functions (or) expressions then it is called
"Complex View".
• We cannot perform DML operations on complex view.
• Just we can read the data. That's why it can be also
called as "Read-Only View".

Example on Complex View:

CREATE VIEW v5
AS
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;

SELECT * FROM v5;

Oracle 6 PM Page 159


SIMPLE VIEW COMPLEX VIEW

it is created based on It is created based on multiple


one table tables

updatable view read-only view

DML operations can be DML operations cannot be


performed using SIMPLE VIEW performed using COMPLEX VIEW

performs complex operations like


It performs simple
joins, group by, sub queries ..etc
operations

Can we create a view without table?


No. We cannot.

FORCE VIEW:
A view which is created forcibly with some
errors is called "FORCE VIEW".
Ex: without base table existence we can
create FORCE VIEW. This view will not work
until we create the base table.

Can we create a view from another view?


Yes. We can.

CREATE VIEW v8
AS
SELECT empno,ename,job FROM emp;

CREATE VIEW v9
AS
SELECT * FROM v8;

After creating the view, if we add a column


to base table does it reflect to view?
No.

CREATE VIEW v10


AS
SELECT * FROM emp;

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

Oracle 6 PM Page 160


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

Alter Table emp add gender char;

SELECT * FROM v10;


empno ename job sal hiredate comm mgr deptno

How can we make changes in table


structure?
ALTER

How can we make changes in view


structure?
CREATE OR REPLACE

CREATE OR REPLACE VIEW v10


AS
SELECT * FROM emp;

After creating view, if we add rows to base table


does it reflect to view?
Yes.

Can we use ALTER or TRUNCATE command on


View?
NO.

User_Views:
• "User_Views" maintains all views information.

SELECT view_name FROM user_views;

Dropping views:

Syntax:
Drop View <view_name>;

Ex:
Drop View v10;

If we drop the table does it delete all rows &


columns?
Yes

If we drop base table does it drop the view?

Oracle 6 PM Page 161


If we drop base table does it drop the view?
No. This view will not work until we create
base table again.

CREATE VIEW v11


AS
SELECT * FROM salgrade;

DROP TABLE salgrade;

View:
Virtual Table
SELECT query

Advantages:
• SECURITY
• REDUCES COMPLEXITY

Disadvantage:
• Low performance

2 types of views:

Simple view view created based on 1 table


we can perform DMLs
Updatable View
complex view created based on multiple
view tables
we cannot perform DMLs
Read-Only View

Oracle 6 PM Page 162


SEQUENCES
Tuesday, April 5, 2022 7:02 PM

SEQUENCE:
• SEQUENCE is a DB Object.
• SEQUENCE is independent from the table.
• It is used to generate sequential integers.

Ex:

Transaction_ID ORDER_ID empid


------------------------ ---------------- ----------
123456 100001 7001
123457 100002 7002
123458 100003 7003
123459 7004

cid productid
------- ------------
10 1000
20 1100
30 1200
40 1300
50

Syntax to create the Sequence:

CREATE SEQUENCE <sequence_name>


[START WITH <value>]
[INCREMENT BY <value>]
[MINVALUE <value>]
[MAXVALUE <value>]
[cycle / nocycle]
[cache <size> / nocache];

Example:

CREATE SEQUENCE s1;

Clause Default
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10 power 28
Cycle NoCycle
Cache 20

Pseudo Columns in SEQUENCE:

2 Pseudo Columns can be used in the SEQUENCE:


• NEXTVAL
• CURRVAL

Oracle 6 PM Page 163


NEXTVAL It returns next value in the sequence
CURRVAL It returns current value in the sequence

Syntax:
<seq_name>.<pseudo_column>

Ex:
s1.NEXTVAL
s1.CURRVAL

Example:

Customer CREATE TABLE Customer


cid cname (
1 cid number(4),
2 cname varchar2(10)
);
3
4
CREATE SEQUENCE s2
5 START WITH 1
INCREMENT BY 1
MINVALUE 1
MAX VALUE 5;

INSERT INTO Customer


VALUES(s2.nextval,'&cname');
enter value for cname:Ramu

1 row inserted

/
enter value for cname:Vijay

Assignment:

Course
cid cname
10 JAVA CREATE SEQUENCE s3
20 PYTHON START WITH 10
30 C# INCREMENT BY 10
MINVALUE 10
40 ORACLE
MAXVALUE 50;
50 C

CREATE TABLE course


(
cid number(2),
cname varchar2(10)
);

INSERT INTO course VALUES(s3.nextval,'&cname');


Enter value for cname:

/
Enter value for cname:
Oracle 6 PM Page 164
Enter value for cname:

START WITH to specify starting value in


sequence
INCREMENT BY to specify step value
MINVALUE to specify min value
MAXVALUE to specify max value

Calling Sequence from UPDATE:

CREATE SEQUENCE s4
START WITH 1001
INCREMENT BY 1
MINVALUE 1001
MAXVALUE 1020;

UPDATE emp SET empno=s4.nextval;

Can we call SEQUENCE from CREATE command?


Yes.
From Oracle 12c Version onwards we can call the
sequence from CREATE command.
From default constraint call the sequence.

CREATE SEQUENCE s5
START WITH 101
INCREMENT BY 1
MINVALUE 101
MAXVALUE 500;

CREATE TABLE student


(
sid number(4) default s5.nextval,
sname varchar2(10)
);

cycle / nocycle:
• default => nocycle

cycle:

CREATE SEQUENCE s6
START WITH 300 s6.nextval 300
INCREMENT BY 1 301
MAXVALUE 310 302
MINVALUE 100
cycle;
310
100

Oracle 6 PM Page 165


100
101

310
100

CREATE SEQUENCE s7
START WITH 300
INCREMENT BY 1
MAXVALUE 500
MINVALUE 100
cycle;

If sequence is created with CYCLE,


sequence starts from START WITH value.
Generates NEXTVALUE upto MAXVALUE.
After reaching maximum value it will reset to MINVALUE.
It generates next value up to MAXVALUE. Again it will reset
to MINVALUE

CREATE SEQUENCE s7
START WITH 300
INCREMENT BY 1
MAXVALUE 500
MINVALUE 100
nocycle;

If sequence is created with nocycle,


Sequence starts from START WITH value.
Generates next value up to MAXVALUE.
After reaching MAXVALUE it will be stopped. Next
number will not be generated.

cache <size> / nocache:

CREATE SEQUENCE s9
START WITH 301

Oracle 6 PM Page 166


START WITH 301
INCREMENT BY 1
MINVALUE 300
MAXVALUE 500
nocache;

s9.nextval =>
• goes to DB.
• identifies current value
• to the current value increment by value will added
• returns sequence number

If sequence is created with nocache, for every


sequence call, it goes to DB, identify current value,
adds increment by value & returns sequence number

Ex: if we call 10 times => 10 times it goes to DB.


Performance will be degraded.

To improve the performance use cache

cache 100:

CREATE SEQUENCE s9
START WITH 301
INCREMENT BY 1
MINVALUE 300
MAXVALUE 500
cache 100;

s9.nextval =>

100 values in the sequence will


be loaded into CACHE memory

s9.nextval =>
it collects next value from CACHE
memory

cache:
• Default size: 20
• It improves the performance.
• When we call the sequence, next number
will be collected from cache.
• Cache holds preloaded values.
• Cache size must be < one cycle.

CREATE SEQUENCE s11

Oracle 6 PM Page 167


CREATE SEQUENCE s11
INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
cycle;

ERROR: cache size must be less


than one cycle

CREATE SEQUENCE s11


INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
cycle
cache 9;

Altering Sequence:

CREATE SEQUENCE s12


START WITH 1
INCREMENT BY 1
MAXVALUE 5
MINVALUE 1;

ALTER SEQUENCE s12 MAXVALUE 50;

ALTER SEQUENCE s12 INCREMENT BY 2 cycle;

From ORACLE 12c version onwards,


we can generate sequential numbers using 2
ways:
• using SEQUENCE
• using IDENTITY

using IDENTITY:
• Introduced in Oracle 12c version.
• It is used to generate sequential integers.
• Always it starts from 1 only.
• "GENERATED ALWAYS AS IDENTITY" keyword is
used to generate sequential integers for a column.

Generating sequential integers using Identity:

CREATE TABLE iddemo


(
sid number(4) generated always as identity,
sname varchar2(10)
);

INSERT INTO iddemo(sname)


VALUES('&sname');

Oracle 6 PM Page 168


Using IDENTITY,
always starts from 1 only
we cannot know current value.
It is not that much flexible when we compare
with the sequence.

Dropping SEQUENCE:

Syntax:
Drop Sequence <seq_name>;

Ex:
Drop Sequence s1;

USER_SEQUENCES:
It maintains all sequences information

SELECT sequence_name FROM user_sequences;

Oracle 6 PM Page 169


MATERIALIZED VIEW
Thursday, April 7, 2022 6:41 PM

PERSON

pid pname state aadhar_num gender age

Display state wise number of people:


state no_of_people
CREATE VIEW v1 TS ..
AS AP ..
SELECT state,count(*)
FROM person
GROUP BY state;

SELECT * FROM v1; 15 mins

SELECT * FROM v1;

SELECT * FROM v1;

SELECT * FROM v1;

Disadvantage of VIEW:
• Less Performance

To improve the performance, we use


'MATERIALIZED VIEW'.

VIEW VIRTUAL does not contain physical data


MATERIALIZED VIEW: TABLE & does not occupy memory
• It is a DB Object. M.VIEW NOT It contains physical data.
• It is not virtual table. VIRTUAL It occupies memory.
• It contains physical data. TABLE
• It occupies memory.
• It holds result of SELECT query whereas VIEW
holds SELECT query
• It is mainly used in DWH [DataWare Housing].
To maintain summarized data physically, we use
it.
• It holds precomputed result.
• It must be refreshed to get recent data.

Advantages:
• It improves performance.
• We can maintain local copy physically of remote
database.

Syntax to create Materialized View:


Oracle 6 PM Page 170
Syntax to create Materialized View:

CREATE MATERIALIZED VIEW <m_view_name>


AS
<SELECT query>;

VIEW MATERIALIZED VIEW

emp emp
empno ename job sal deptno empno ename job sal deptno
1001 10 1001 10
1002 10 1002 10
.. 20 .. 20
1005 30 1005 30

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;

v1 mv1
deptno sum(Sal)
SELECT ..
10 50000
20 100000

SELECT * FROM v1; //calculates


SELECT * FROM mv1; //retrieves from mv1
SELECT * FROM v1; //calculates
SELECT * FROM mv1; //retrieves from mv1
SELECT * FROM v1; //calculates
SELECT * FROM mv1; //retrieves from mv1
SELECT * FROM v1; //calculates
SELECT * FROM mv1; //retrieves from mv1
SELECT * FROM v1; //calculates
SELECT * FROM mv1; //retrieves from mv1

If we write above query for


5 times, 5times it calculates In this, dept wise sum of salaries
dept wise sum of salaries. will be calculated for first time.
Second time onwards, it retrieves
Performance will be precomputed result from the
degraded materialized view.
So, performance will be improved.

emp
empno ename job sal deptno
Oracle 6 PM Page 171
empno ename job sal deptno
1001 10
1002 10
.. 20
1005 30
2001 A 20000 10

insert deptno 10 employee record:


INSERT INTO emp(empno,ename,sal,deptno)
values(2001,'A',20000,10);

SELECT * FROM v1; SELECT * FROM mv1;

mv1
deptno sum(Sal)
deptno sum(Sal)
10 70000
10 50000
20 100000
20 100000

refresh materialized view

mv1
deptno sum(Sal)
10 70000
20 100000

Refreshing Materialized View:

• Applying the changes of base table to materialized


view is called "Refreshing Materialized View".
• After creating materialized view if we make any
changes in base table it will not applied to
materialized view. That's why we need refresh
Materialized View.

Materialized view can be refreshed in 3 ways:


• On Demand [default]
• On Commit
• On regular interval of time

Log in as DBA:
GRANT create materialized view TO c##batch6pm;

CREATE MATERIALIZED VIEW mv1


Oracle 6 PM Page 172
CREATE MATERIALIZED VIEW mv1
REFRESH ON DEMAND
AS
SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno;

ON DEMAND:

• to refresh materialized view, call stdio.h


the procedure "refresh()" which package dbms_mview
printf()
is already defined in package
"dbms_mview". PROCEDURE refresh()
java.lang

String
….
Syntax:
execute dbms_refresh(mview_name);

Ex:
SQL> Execute dbms_mview.refresh('MV1');

CREATE MATERIALIZED VIEW mv3


REFRESH ON DEMAND
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

insert into emp(empno,sal,deptno)


values(6789,3000,20);

Execute dbms_mview.refresh('MV3');

On commit:

In this way, when "commit" command is


executed materialized view will be refreshed.

CREATE materialized view mv4


refresh ON COMMIT
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

INSERT INTO emp(empno,sal,deptno)


VALUES(1235,3000,20);

Oracle 6 PM Page 173


COMMiT; //m.view will be refreshed

On regular interval of time:

In this way, materialized view will


be refreshed in a regular interval of
time

Ex:
weekly collection on every week
monthly collection on every month
year collection on every year

CREATE MATERIALIZED VIEW mv5 CREATE MATERIALIZED VIEW mv5


refresh force refresh force
START WITH sysdate START WITH sysdate
NEXT sysdate+interval '2' day NEXT sysdate+interval '1' minute
AS AS
SELECT deptno, sum(Sal) FROM emp SELECT deptno, sum(Sal) FROM emp
GROUP BY deptno; GROUP BY deptno;

INSERT INTO emp(empno,sal,deptno)


Materialized view will be refreshed for every 2 days VALUES(1236,3000,20);

Refresh Types:

3 refresh types:

• Complete
• Fast
• Force

Complete refresh:
• In "complete" refresh, truncates complete data
from materialized view. Again it calculates &
fills the result in materialized view.

BASE TABLE
MV6
emp
deptno sum(sal)
empno ename deptno sal
10 7000
1001 10 3000
20 15000
1002 10 4000
1003 20 6000
1004 20 5000
1005 20 4000

Oracle 6 PM Page 174


COMPLETE refresh

FAST refresh:
• In fast refresh, only recent changes made on base
table will be applied to materialized view.
• For FAST refresh, "materialized view log" file is
required. In this file, recent changes of base table
will be recorded here.

BASE TABLE

emp
MV6
empno ename deptno sal
deptno sum(sal)
1001 10 3000
10 7000
1002 10 4000
20 11000
1003 20 6000
1004 20 5000
1005 20 4000
1006 10 2000

1005 20 4000
1006 10 2000

MATERIALIZED VIEW LOG FILE

Note:
If materialized view log file is not there, FAST refresh
will be failed.

FORCE refresh:
• IN FORCE refresh, ORACLE gives first
priority for FAST refresh. If "materialized
view log" file is not available, then ORACLE
performs COMPLETE refresh.

COMPLETE truncates complete data from m.view. Again


calculates & fills in m.view
FAST only recent changes will be applied to
m.view. If m.view log file not there it will be
failed.
FORCE ORACLE gives first priority for FAST refresh.
If m.view log file not available, then it
performs COMPLETE refresh.

Oracle 6 PM Page 175


CREATE MATERIALIZED VIEW mv6
REFRESH complete ON COMMIT
AS
SELECT deptno,sum(sal) FROM emp
GROUP BY deptno;

CREATE MATERIALIZED VIEW mv7


REFRESH fast ON commit
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno; //ERROR

Creating Materialized view log file:

Note:
to create m.view log file, the table must have primary key

DBA creates it

Log in as DBA:

CREATE MATERIALIZED VIEW LOG ON c##batch6pm.emp;


//ERROR - Primary Key not there in emp

CREATE TABLE student


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

CREATE MATERIALIZED VIEW LOG ON student;

CREATE MATERIALIZED VIEW mv7


REFRESH fast ON commit
AS
SELECT * FROM student;

CREATE MATERIALIZED VIEW mv8


REFRESH force ON demand
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

Oracle 6 PM Page 176


Enable Query Rewrite clause:
If we create materialized view using "ENABLE
QUERY REWRITE" clause, even if we write normal
SELECT query data will be retrieved from
materialized view.

improves performance

frequently , he wants dept wise sum of salaries

CREATE MATERIALIZED VIEW mv9


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

Java Developer:

SELECT * FROM mv9; //improves performance

SELECT deptno,sum(Sal) FROM emp


GROUP BY deptno; //every time it will be calculated
//performance will be degraded

CREATE MATERIALIZED VIEW mv9


REFRESH ON commit
ENABLE QUERY REWRITE
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

To see execution plan:


SQL> SET AUTOTRACE ON EXPLAIN

Select * from mv9; //retrieves from mv9

SELECT deptno,sum(Sal) FROM emp


GROUP BY deptno; //retrieves from mv9

user_mviews:
It maintains all m.views information

Oracle 6 PM Page 177


It maintains all m.views information

SELECT mview_name FROM user_mviews;

Dropping materialized view:

Drop materialized view mv1;

Oracle 6 PM Page 178


Indexes
Saturday, April 9, 2022 6:23 PM

ORACLE

Index:
Joins
• Index is DB Object.
• Index improves the performance
of data retrieval. INDEX
• To refer particular topic in BOOK, we
use INDEX. With this quickly we can DDL
refer particular topic. DML
• If index is created on column quickly
access the records. Joins 50
• Index will be created on columns.
• Index will be created on the columns
which are frequently used in WHERE
clause Or in JOIN condition.

Syntax to create the INDEX:

CREATE INDEX <index_name>


ON <table_name>(<column_list>);

Advantage:
• improves performance of data retrieval.

SELECT * FROM emp WHERE sal>2800;

When we submit a query to ORACLE,


ORACLE performs any of the 2 scans:
• Table Scan
• Index Scan [Faster]

Table Scan:
If index is not created "TABLE SCAN" will be
performed.

Index Scan:
If index is created "INDEX SCAN" will be
performed

Oracle 6 PM Page 179


SET AUTOTRACE ON EXPLAIN;

SELECT * FROM emp WHERE sal>2500; --Table Scan

CREATE INDEX I1 ON emp(sal);

SELECT * FROM emp WHERE sal>2500; --Index Scan

When we create the index "B-TREE


[Balanced Tree] will be created.

TREE => collection of nodes

If value is less than or equals to ROOT value


place it at left side.
If value is greater than ROOT value place it at
right side

sal
------- 3000
3000
5000
1500
1800 2000 4000
4000
4000
1200 1000 * 2500 * 4000 ** 5000 *
1000 1200 * 3000 **
3000 1500 *
2500 1800 *

sal
------- SELECT * FROM emp WHERE sal>3500;
3000
5000 If index is not created 10 comparisons
1500 will be done
1800
4000
Oracle 6 PM Page 180
5000 If index is not created 10 comparisons
1500 will be done
1800
4000
4000
1200
1000
3000
2500

Types of Indexes:

2 Types:

• B-TREE INDEX [Normal Index]


▪ Simple Index
▪ Composite Index
▪ Unique Index
▪ Function-Based Index
• BITMAP INDEX

B-TREE Index:
If B-TREE is created when we create the INDEX then it
is called "B-TREE INDEX"

It has 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 INDEX i1 ON emp(sal);

Oracle 6 PM Page 181


Composite Index:
If index is created on multiple columns then
it is called "Composite Index".

CREATE INDEX i2 ON emp(deptno,job);

According to deptno B-TREE will be created

Before Oracle 9i:

SELECT * FROM emp


WHERE deptno=10 and job='MANAGER'; --INDEX SCAN

SELECT * FROM emp


WHERE deptno=10; --INDEX SCAN

SELECT * FROM emp


WHERE job='MANAGER'; --TABLE SCAN

From Oracle 9i version onwards:

SELECT * FROM emp


WHERE deptno=10 and job='MANAGER'; --INDEX RANGE SCAN

SELECT * FROM emp


WHERE deptno=10; --INDEX RANGE SCAN

SELECT * FROM emp


WHERE job='MANAGER'; -- INDEX SKIP SCAN

emp
empno ename deptno job
10 MANAGER 20
10 CLERK
20 MANAGER 10 30
10 CLERK
20 CLERK
10 man * 20 man * 30 man *
30 MANAGER
10 cler ** 20 cle 8 30 cl *
30 CLERK

Oracle 6 PM Page 182


Unique Index:
• An Index which is created on a column which is
having unique values is called "Unique Index"

dept
deptno dname
10 sales
20 accounts
30 research
40 operations

CREATE UNIQUE INDEX i3 ON dept(dname);

Note:
When we create a table with primary key an index will be
created implicitly on primary key column.

We can Implement "UNIQUE" constraint in 3 ways:

• Primary Key [UNIQUE + NOT NULL]


• UNIQUE
• INDEX

Function-Based Index:
If index is created based on function or expression
then it is called "Function-Based Index".

CREATE INDEX i4 ON emp(ename);

SELECT * FROM emp WHERE ename='BLAKE'; --Index Scan

SELECT * FROM emp WHERE lower(ename)='blake'; --Table Scan

CREATE INDEX i5 ON emp(lower(ename)); --Function-Based Index

Oracle 6 PM Page 183


CREATE INDEX i5 ON emp(lower(ename)); --Function-Based Index

SELECT * FROM emp WHERE lower(ename)='blake'; --Index Scan

Expression = column names+ operators+ numbers

Ex:
sal*12 (sysdate-hiredare)/365

SELECT * FROM emp WHERE sal*12>30000; --Table Scan

CREATE INDEX i6 ON emp(sal*12); --Function-Based Index

SELECT * FROM emp WHERE sal*12>30000; --Index Scan

BITMAP INDEX:
• 0,1 are the bits. B-TREE INDEX value, row iid
• An Index which can store bits only is called
Bitmap Index bits
"Bitmap Index".
• For this B-Tree will not be created.
1 Row ID
• Every bit is associated with row id.
• In this, bits will be converted to ROW IDs.
• Low Cardinality => A column which is having
less distinct values
• Create Bit map index on low cardinality Low Cardinality:
columns
deptno
-----------
10
20 10
job
10 20
------
CLERK 10 30
CLERK 20
MANAGER 20
SALESMAN 30
MANAGER 30
CLERK 20
SALESMAN 30
10

Gender
-----------
M
Oracle 6 PM Page 184
M
M M
F F
F
F
M
F
M
F

High Cardinality COlumn

ename
------------
SMITH
ALLEN
BLAKE
SMITH
JOHN
MILLER
.

CREATE TABLE stddemo


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

INSERT INTO stddemo VALUES(1,'A','M');


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

CREATE BITMAP INDEX bi1 ON stddemo(gender);

gender
Oracle 6 PM Page 185
gender
-----------
M M F
F 1 0
F 0 1
M 0 1
M 1 0
F
1 0
0 1

In Table Scan 6 comparisons.


In Bitmap Index, 6 comparisons

No of comparisons in Table Scan & Bitmap Scan are


same. The how bitmap index is faster than table
scan?

Bit comparison is FASTER THAN value comparison

User_Indexes:
• "User_Indexes" maintains all indexes information.

SELECT index_name, index_type FROM user_indexes;

Differences b/w B-Tree Index & Bitmap Index:

B-Tree Index Bitmap Index

• B-Tree will be created • B-Tree will not be created.

• on high cardinality columns • on low cardinality columns


create B-Tree Index. create Bitmap Index

• It contains, values & row ids • It contains 0s & 1s


These bits will be converted to
row ids

Oracle 6 PM Page 186


When we drop the table does it drop the rows
& columns?
Yes

When we drop the base table does it drop the


view?
No. This view will not work until we create
the table with base table name.

When we drop the table does it drop the


Index?
Yes.

Oracle 6 PM Page 187

You might also like