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

SQL Notes

This document provides information about an Oracle SQL and PL/SQL training session happening at 7:00 AM. It includes links to video recordings of previous training sessions. It also provides background information about data, databases, DBMS, RDBMS, metadata, Oracle, SQL and PL/SQL.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
161 views

SQL Notes

This document provides information about an Oracle SQL and PL/SQL training session happening at 7:00 AM. It includes links to video recordings of previous training sessions. It also provides background information about data, databases, DBMS, RDBMS, metadata, Oracle, SQL and PL/SQL.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 222

Tuesday, December 28, 2021 6:44 AM

Notes Link:
https://bit.ly/oracle7am

Mahesh:
Whatsapp num: 81436 16558

gmail id, batch details & fee reciept

Oracle (SQL & PL/SQL) @ 7:00 AM


by Mr. Shiva Chaitanya
Day-1
https://youtu.be/05uEoFz70wk
Day-2 https://youtu.be/d8ic2u_8hOo
Day-3-1
https://youtu.be/pIgb4GD0LOE
Day-3-2
https://youtu.be/RHL6FRtNKqE
Day-4
https://youtu.be/-8FJBmKeGCg
Day-5
https://youtu.be/ZmegWfpuDSQ
Day-6:
https://youtu.be/XOReEOaafNo
Day-7:
https://youtu.be/MJMt5oxlXO8
Day-8:
Oracle7AM Page 1
Day-8:
https://youtu.be/NLU8VejnZo4

Oracle7AM Page 2
Oracle
Wednesday, December 22, 2021 7:21 AM

Oracle:

SQL
PL/SQL

Data
Information
Database
DBMS
RDBMS
Metadata

Data:
• Data is a raw collection of facts about
people, places & things …etc.
• Raw => unordered [Not in Order]

Engine
Tyres
Connecting Bike
Seat
..
..

• Data is a raw collection of facts about people,


places & things …etc.

4567
1234
Srinu
Ravi
8000
500
MANAGER

Smartphone
nareshit
20000
floor 3
Samsung
room no 1
30.5
20.4

Data:
• Data is a raw collection of facts about people,
places & things …etc.
• Data is unprocessed one.
• Data is not in meaningful form.

25 rno sname marks


Ravi Data Processing 25 Ravi 500
500

Information
Data

Information:

Oracle7AM Page 3
Information:
If data is arranged in meaningful form then it is
called "information".

Data Information

• Unprocessed one. • Processed one.


• It is not in meaningful • It is in meaningful form.
form.
• It does not increase • It increases knowledge of a
knowledge of a person person.

Types of Data:

2 Types:

• Structured Data
• Unstructured Data

• Structured Data:
If data is in the form of letters, digits & special
symbols.

Ex: 1234 Ramu H.NO.1-2-3/A/C

• Unstructured Data:
• Multimedia objects are comes under unstructured Data.

Ex: Images, audios, videos, documents

Database:
• Database is a collection of interrelated data in an
organized form.
• You can understand like complete details about
an organization.

Ex:

College DB

Student
sid sname city

Marks
sid M1 M2 M3 Tot Avrg Result

Fee
sid Fee Balance Total Fee

Amazon DB

Oracle7AM Page 4
Amazon DB

Customer
cid cname ccity mobile

Product
pid pname QIH Price

Orders
cid pid qty amount orddate deldate

Types of databases:

2 Types:

• OLTP
• OLAP

OLTP OLAP [DWH / DSS]

• OnLine Transaction processing • OnLine Analytical Processing

• used for day-to-day operations • used for data analysis. Historical


data is maintained here.

• In this, we perform • We perform Read operations


CRUD operations only.
• Create
• Read
• Update
• Delete

DBMS:
• DataBase Management System / Software.
• It is a software that is used to create &
maintain the Database.
• It allows us to store, manipulate & retrieve
the data of Database.
○ Manipulate = Insert + Update + Delete
○ Retrieve => Opening existing data

RDBMS:
• Relational DataBase management System
• Relation => Table FMS / FPS => 1960s
• In RDBMS, we maintain database in the form
of tables. Hierarchical => 1970s
Network
Ex:
Oracle => Oracle RDBMS => 1976 => E.F.Codd
SQL Server => Microsoft
Postgre SQL => PostGre 1979 => Oracle
DB2 => IBM
MySQL => Oracle

• We maintain Database in the form of


tables.

Oracle7AM Page 5
tables.
• Relation => Table

Table:
Table is a collection of rows & columns
where rows are the records & columns are
the fields.

Customer
cid cname ccity Table => Relation / Entity
1001 Raju Hyd
1002 Kiran Mumbai row => record / entity instance / tuple

column => field / attribute / Property

field => holds individual values

record => is a collection of field


values

Metadata:

Marks

sid sname marks


25 Ramu 456
26 Charan 678

Table Name => Marks


Column Names => sid, sname, marks
Data Type => Number(4), varchar2(20)
Field Size => 4, 20

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

Ex:
Table Name
Field Name
Data Type
Field Size

Data
Information
Database
DBMS
RDBMS
Metadata

Oracle7AM Page 6
Metadata

ORACLE:
• is a Relational Database Management Software.
• Relation => Table
• In this, we create & maintain database in the form of
tables.
• It allows us to store, manipulate & retrieve the data of Larry Ellison
database.
• Manipulate = Insert + Update + Delete 1977 => Software Development Laboratories
• Retrieval => Opening existing data [Reading data] 1979 => Relational Software Inc.
• Oracle Database software's second version introduced in 1983 => Oracle Corp.
1979.
• Oracle Database latest version is Oracle 21C.

To work with ORACLE database we use 2 Languages:


• SQL
• PL/SQL

SQL => Structured Query Language


PL/SQL => Procedural Language

SQL:
• SQL stands for Structured Query Language.

Java Python C# C C++ => Programming Languages


In Programming Language we write programs

a=10 fact
b=5
power
print a+b
print a-b sqrt
print a*b

SQL => Query Language

SQL:
SQL stands for Structured Query Language.

Oracle7AM Page 7
• SQL stands for Structured Query Language.
• It is a Query Language. Oracle Server
• It is used to write the queries.
• Query is a request which is sent to Database
Server. request Instance DB

select
emp
empno,ename response
from emp; [query]
RAM Hard Disk
Client

SQLPLUS Oracle Server = Instance + DB


TOAD
SQL DEVELOPER

SQL:
• Structured Query Language.
• It is a query language that is used to write the queries.
• Query is a request that is sent to DB Server.
• Ex: Select empno, ename from emp;
• Queries are written to communicate with Database. Procedure
• SQL is a Non-Procedural Language. We will not write any
set of statements. In C =>
• SQL is a 4GL [Generation Language]. We much Function => is a set of statements
concentrate on what to do rather than how to do.
• Ex: sqrt(100) In Java:
• SQL is a unified language. It is common for many Method => is a set of statements
relational databases like SQL Server, Postgre SQL,
MySQL ..etc.
• Ex:
SQL Server MYSQL Postgre SQL Oracle
+ >
SQL SQL SQL SQL
- >=
• SQL provides built-in [predefined] functions.
* <
• SQL provides operators to perform operations.
<=
• SQL provides Joins to work with multiple tables
• SQL provides Sub Queries.

• SQL provides 5 sub languages:

DDL Data Definition Language Create


Alter
Drop
Truncate
Rename
Flashback
Purge
DML Data Manipulation Language Insert
Oracle7AM Page 8
DML Data Manipulation Language Insert
Update
Delete
Insert All
Merge
TCL Transaction Control Language Commit
Rollback
Savepoint
DCL/ACL Data Control Language / Grant
Accessing Control Language Revoke
DRL/DQL Data Retrieval Language / Select
Data Query Language

SQL:
DDL
DML
DCL
TCL
DRL

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

Create
Alter
Drop
Truncate
Rename
Flashback [Oracle 10g]
Purge [Oracle 10g]

metadata:
data about the data
emp
Ex: empno ename sal job
Table name 1234 Ravi 8000 manager
Field name
Data Type
Field size

Create Table emp


(
emp => table name
empno number(4),
empno => field name
number => data type
4 => field size

Oracle7AM Page 9
Alter : change the structure of table

emp
empno ENAME job sal

Add one column => mobileno

DML:
• stands for Data Manipulation Language.
• Manipulation = Insert + Update +Delete
• It deals with the data.

emp
empno ename job sal
1001 Raju manager 10000

Insert
Update
Delete
Insert All [Oracle 9i]
Merge [Oracle 9i]

DRL / DQL:
• Data Retrieval Language / Data Query Language
• It deals with data retrievals
• Retrieval = opening existing data [reading the data]

SELECT

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

Grant
Revoke

userA [owner of emp] userB


emp
empno ename job sal
1001
..
1010

GRANT
REVOKE

Oracle7AM Page 10
REVOKE

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

Ex:
Transaction => a series of actions

Withdraw =>
read pin
check validity
sufficient bal
read amount
update bal

Deposit
Order

COMMIT
ROLLBACK
SAVEPOINT

DDL Commands:

Create:
• is used to create the database Database
objects like tables, views, Schema [user]
indexes ..etc. DB Objects
Table
View
Index
Sequence
Synonym
materialized view
< > => Any
function
[ ] => Optional
procedure
trigger
package

Syntax to create the table:

Create Table <table_name>


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

Data Types in SQL:


• Data Type tells the type of data a column can
hold.
• It also tells the range of values.

Oracle7AM Page 11
SQL provides following data types:
Number Related number(p) [Integer] Ex: 123
int
integer

number(p,s) [Floating Point]


Ex: 123.45
float
real
binary_float
binary_double
Character Related char(n)
varchar2(n)
long
CLOB

nChar(n)
nVarchar2(n)
nCLOB
Date & Time related Date
Timestamp [Oracle 9i]
Binary related BFILE
BLOB

Number related Data Types:

Number(p):
• It is used to hold integer type data.
• p => precision => Max number of digits
• p => valid range => 1 to 38

age empno
Examples:
------ -------------
17 1001
age Number(2) => -99 to 99 23 1002
18 1003
m1 Number(3) => -999 to 999

empno Number(4) => -9999 to 9999 m1


--------
cust_id Number(6) 100
45
Mobile_num Number(10) 78
61
debit_Card_num Number(16)

f1 number(38) =>
-999….99 [38digits] to 99999…99 [38 digits]

f2 number(39) => ERROR

f3 Number => default size => 38

Number(p,s):
• used to hold floating point type data.
• p => precision => Total Number of Digits
• s => scale => Number of decimal places
• p => 1 to 38
• s => -84 to 127

Oracle7AM Page 12
avrg sal
Example: ---------- ----------
67.89 15000.00
avrg Number(5,2) => -999.99 to 999.99 54.23 12000.00
sal Number(8,2) => -999999.99 to 999999.99 89.61 100000.00
100.00

100000.00

Character Related data types:

char(n)
varchar2(n)
long
clob

nchar(n)
nvarchar2(n)
nclob

char(n):
• n => max number of characters
• used to hold a set of characters [strings].
• Fixed length data type

gender country_code State_Code PAN_CARD_NUM


------------ -------------------- ------------------- --------------------------
M IND AP AXY2L 23456
F AUS TS
PAK WB
UP

varchar2(n):
• n => max number of characters
• used to hold a set of characters [strings]
• Variable length data type

ename
---------
sai
arun
10 chardemo 3
10 4
10 f1 char(10) f2 varchar2(10) 6
sai7spaces sai
Ravi6spaces Ravi
Charan4spaces Charan

char(n):
• n => max number of characters
• used to hold a set of characters [strings].
• Fixed length data type
• default size: 1
• max memory: 2000 Bytes

Ex:
state_code char(2)
coutry_Code char(3)
section char

Oracle7AM Page 13
section char

varchar2(n):
• n => max number of characters
• used to hold a set of characters [strings]
• Variable length data type
• default size => no default size. we must specify
the size
• max memory => 4000 Bytes

gender char => default size => 1


gender varchar2 => ERROR
ename varchar2(10)

char varchar2(n)

• fixed length data type • variable length data type.

• default size => 1 • default size => no default size

• max size => 2000 Bytes • max size => 4000 Bytes

• it is suitable for fixed • it is suitable for variable length


length charcters chars
• Ex: state_Code Ex:
gender emp_name
section cust_name
country_Code std_name
pan_num course_name

Oracle 2 => 1979 => varchar


3,4,5,6
Oracle 7 version => varchar2 data type introduced

''
E.F.Codd => RDBMS
null
12 Rules
0 => value
null => unknown => empty / blank

Note:
There should be difference between null and
' ' [space]
varchar data type was not following this
rule.
Oracle 7 version varchar2 data type
introduced. It treats null and ' ' [space] as
different.
In later versions, they changed meaning
varchar also.
In current versions, varchar and varchar2

Oracle7AM Page 14
In current versions, varchar and varchar2
both acts as same.
Oracle is suggesting that don't use "varchar"
data type. in future versions they may
change the meaning of varchar or they may
remove varchar type. It means, it is
deprecated data type.

long:
• it is used to hold a set of characters [string].
• max size: 2 GB
• It is outdated. Its better to avoid of using
long.
• We can take one field as a long type for a
table. we cannot take more than one field as
long type.
• We can use string functions on long data
type.

CLOB:
• Character Large Object.
• It is used to hold a set of chars [string].
• max size: 4GB

Ex: 2012-15
experience_summary 2015-17
Feedback
Complaints

single byte char types


char(n) 2000 Bytes ASCII code char types
varchar2(n) 4000 Bytes ENGLISH chars only
CLOB 4 GB
nchar(n) 2000 Bytes
nvarchar2(n) 4000 Bytes multi byte char types
nCLOB 4 GB UNI code char types
ENGLISH chars + other language
n => National character set chars

ASCII => 256 chars => 0 to 255 =>


A=65 B=66 … Z=90
a=97 b=98 … z=122

UNI => ENGLISH + other language chars

Date:
• It is used to hold date values.
• It is fixed length data type. DOB
• default date format: dd-mon-rr. -----------
• It can hold date, month, year, hours, 23-dec-04

Oracle7AM Page 15
• It is used to hold date values.
• It is fixed length data type. DOB
• default date format: dd-mon-rr. -----------
• It can hold date, month, year, hours, 23-dec-04
minutes and seconds.
• default time values is 12.00.00 AM
[mid night]. hiredate
• It cannot hold milli seconds. -------------
• size: 7 Bytes

Ex:
DOB date
DOJ date
DOR date
Transaction_date date

RR

0 to 49 => current year 2021 => current year => 2070

if value falls under 0 to 49, it takes 2000s year 50-99 =>


if year falls user this range, it takes
50 to 99 => as 2000s year
if value falls under 50 to 99, it takes 1900s year
0-49 =>
if year falls under this range, it
takes as 2100s year

default date format: dd-mon-rr

Changing date format:

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

Timestamp:
• introduced in Oracle 9i version.
• It is an extension of date data type.
• date, month, year, hours, minutes, seconds &
milli seconds.
• size: 11 Bytes

Oracle7AM Page 16
Date Timestamp

7 Bytes 11 Bytes

day, month, year, day, month, year,


hours, minutes & hours, minutes,
seconds seconds & milli seconds

to maintain date values to maintain time values use it


use it

Binary Related Data Types:

BFILE
BLOB

Text File [Flat File] Binary File

SQL is a query 0111010010001110


language. 1010100101

Ex: .txt Ex: .mp3 .mp4


.exe .jpg .gif

BFILE, BLOB are used to maintain multimedia


objects like audios, videos, images, documents ..etc.

BFILE:
• External Large Object.
• it maintains path only.
• Object will be stored out of the database.
• It is not secured.

BLOB [Binary Large Object]:


• Internal Large Object.
• It stores binary data.
• Object will be stored inside of database.
• it is secured.

D:
Oracle Database
emp_photos folder
1001.jpg file
emp
ephoto => BFILE
----------

Oracle DB

Oracle7AM Page 17
Oracle DB

emp
ephoto => BLOB
----------
12AB676C35556DA

Log in as DBA:
username: system
password: nareshit [password given at the time
of installation of oracle]

Creating common user [schema]:

Common user name must be prefixed with c##

Create user c##batch7am


identified by nareshit
default tablespace users
quota unlimited on users;

Grant connect,resource to c##batch7am;

Syntax to create the table:

Create Table <Table_Name>


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

Syntax of Insert Command:

Insert into <table_name>[(column_list)]


values(<value_list>);

Examples on Creating Tables & Inserting the records:

Ex-1:
Student
sid sname Marks Max marks: 1000
1001 Ravi 678
1002 Vijay 789
1003 Sravan 567

Creating Table:

Create Table Student


(
sid Number(4),
sname Varchar2(20),
Oracle7AM Page 18
sname Varchar2(20),
Marks Number(4)
);

Inserting Records:

Insert into Student Values(1001,'Ravi',678);

Insert into Student Values(1002,'Vijay',789);

Inserting records using parameters:

SQL> Insert into Student values(&sid,'&sname',&marks);


Enter value for sid:1003
Enter value for sname:Arun
Enter value for marks:456

1 row created

SQL> /
Enter value for sid:1004
Enter value for sname:sai
Enter value for marks:867

SQL> / / (or) run => It runs above [recent]


Enter value for sid:1005 command
Enter value for sname:Srinu
Enter value for marks:657

Inserting record by changing the order:

Insert into student(sname,sid,marks)


values('Ramu',1008,666);

Inserting limited column values:

Insert into student(sid,sname)


values(1009,'Raju');

Display all columns & all records of student table:

Select * from student;

Ex-2:
Create table with following structure:

Employee
empid ename job sal doj
5001 Ramu clerk 7000 23-oct-20
5002 Srinu manager 12000 18-aug-18

Create Table Employee


(
empid Number(4),
ename Varchar2(15),
job Varchar2(10),

Oracle7AM Page 19
job Varchar2(10),
sal Number(8,2),
doj Date
);

Insert into employee


values(5001,'Ramu','CLERK',7000,'23-oct-2021');

Note:
To insert date value, we use to_Date() function.
to_Date function converts string to date value.
It is called "Explicit Conversion".
If we don't use to_Date() function implicit
conversion will be done.

SQL> Insert into employee


values(5002,'Srinu','MANAGER',12000,
to_date('18-aug-2019'));

Select * from employee;

Constraint:
• Constraint is a rule applied on a column.
• It restricts the user from entering invalid data.

sid sname M1
1234 Ravi

Gender
--------------
M
F
Z => invalid

Constraint:
Online Bus Ticket Reservation
• Constraint is a rule applied on a column.
system
• It restricts the user from entering invalid data.
• Constraint is used to maintain data integrity.
seatnum
• Data Integrity means, maintaining accurate
----------------
& quality data.
51 => invalid

Constraints in SQL:

Oracle7AM Page 20
Constraints in SQL:

SQL provides following constraints:

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

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

student

sid sname scity


5001 Ravi Hyd
5002 Kiran Delhi
5001 Srinu Hyd
Sai Chennai

Unique:
• it should not accept duplicate values.
• it accepts the null values.

Customer
cid cname mail_id mobile_num aadhar_nu
m
1001 Ramu 90123 45678
1002 Srinu [email protected] 90123 45678
1003 Vijay [email protected] ……

Not Null:
• should not accept null values.
• accepts duplicate values.

emp
PK
empno ename
1001 Ravi
1002
1003 Ravi

Constraint Duplicate Null


Primary Key NO NO
Unique NO YES

Oracle7AM Page 21
Constraint Duplicate Null
Primary Key NO NO
Unique NO YES
Not Null YES NO

Primary Key = Unique + Not Null

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

marks Max marks: 100


sid sname M1 0 to 100
101 A 56
102 B 48
103 C 123

empno ename gender


M
F
Z

Default:
• it is used to give default value to a column.
• When we don't give the value, this default
value will be taken.
• When all column values are same, it's better
to give default value.

emp
empno ename company_name company_Address nationality
1001 A nareshit ameerpet India
1002 B nareshit ameerpet India

student
sid sname group
EEE
EEE
EEE

References [Foreign Key]:


Foreign key refers to Primary Key values of
another table.

Oracle7AM Page 22
Course
cid cname
10 Java
20 Python Student
30 HTML sid sname cid
40 C#.net 4001 A 30
4002 B 20
4003 C 40
4004 D 80

DEPT

deptno dname
10 SALES
20 ACCOUNTS
30 RESEARCH Emp
empno ename deptno
3001 A 20
3002 B 30
3003 C 30
3004 D 70

Examples on Constraints:

Std
sid sname M1

sid => Number(4) => Primary Key


sname => Varchar2(10) => Not Null
M1 => Number(3) => Check => b/w 0 to 100

SQL> Create Table Std


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

Null:
• Null is a value.
• It means empty or blank.
• When the value is unknown, then insert null
value.
• It is not equals to zero or space

Null value can be inserted in 2 ways:


• Explicit [use null keyword
Implicit [insert limited column values]

Oracle7AM Page 23
• Implicit [insert limited column values]

Insert into std values(1001,'A',56);

Inserting nulls using Explicit:


Insert into std values(1002,'B',null);

Inserting nulls using Implicit:


Insert into std(sid,sname)
values(1003,'C');

Example on constraints:

emp1
empno ename sal aadhar cname ccity
6001 Ravi 7000 1234 nareshit hyd
6002 nareshit hyd
6003 nareshit hyd

empno => PK
ename => not null
sal => min 5000 max 100000.00
aadhar => unique
cname => default nareshit
ccity => default hyd

Create Table emp1


(
empno number(4) primary key,
ename varchar2(10) not null,
sal number(8,2) check(Sal>=5000 and sal<=100000),
aadhar_num number(12) unique,
cname varchar2(10) default 'nareshit',
ccity varchar2(10) default 'hyd'
);

Insert into emp1(empno,ename,sal,aadhar_num)


values(6001,'A',7000,5678);

Insert into emp1(empno,ename,sal,aadhar_num)


values(6001,'B',9000,9876);
Error: unique constraint violated

Insert into emp1(empno,ename,sal,aadhar_num)


values(null,'B',9000,9876);
Error: cannot insert null

Insert into emp1(empno,ename,sal,aadhar_num)


values(6002,'B',9000,9876);

Insert into emp1(empno,ename,sal,aadhar_num)


values(6003,'A',8000,2345);

Insert into emp1(empno,ename,sal,aadhar_num)


values(6004,null,7500,2346);
Error: cannot insert null into ename

Insert into emp1(empno,ename,sal,aadhar_num)


values(6004,'D',3000,2346);
Error: check constraint violated

Oracle7AM Page 24
Error: check constraint violated

Insert into emp1(empno,ename,sal,aadhar_num)


values(6008,'E',12000,2345);
Error: Unique constraint violated

Insert into emp1(empno,ename,sal,aadhar_num)


values(6008,'E',12000,null);

Select * from emp1;

References [Foreign Key]:

It refers to PK values of another table.

Course
cid cname Std
10 Python sid sname cid
20 Java 1001 Ravi 20
30 Oracle 1002 Srinu 30
1003 Charan 90 Invalid

Create Table Course


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

Create Table Std


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

SQL> Insert into Course values(&cid,'&cname');


Enter value for cid: 10
Enter value for cname: Python

SQL> /
Enter value for cid: 20
Enter value for cname: Java

SQL> /
Enter value for cid: 30
Enter value for cname: Oracle

SQL> select * from course;

CID CNAME
---------- ----------
10 Python
20 Java
30 Oracle

SQL> Insert into std values(2001,'A',20);

SQL> Insert into std values(2002,'B',30);

SQL> Insert into std values(2003,'C',90);

Oracle7AM Page 25
SQL> Insert into std values(2003,'C',90);
Error: Integrity constraint violated

Exaple on Foreign Key:

dept emp2
deptno dname empno ename deptno
10 Sales 1234 A 10
20 Accounts 1235 B 30
30 Research 1236 C 80 invalid

Create Table Dept


(
deptno Number(2) primary key,
dname Varchar2(10)
);

Create Table emp2


(
empno Number(4) Primary Key,
ename Varchar2(10),
Deptno Number(2) References Dept(deptno)
);

Insert into Dept values(&deptno,'&dname');

Insert into EMp2 values(1234,'A',20);

Insert into EMp2 values(1235,'B',30);

Insert into EMp2 values(1236,'C',80);


ERROR: Integrity constraint violated

Naming Constraints:
• Giving names to the constraints is called "Named
Constraints".
• If we don't give name to the constraint by default
oracle gives constraint name by prefixing a random
number with 'sys_c'.
• If we give constraint names oracle will not give
constraint names.

Ex:
Create table t1(f1 number(4) primary key);

sys_c4567893 => constraint name

User_Constraints:
All constraints information of user stored in
"User_Constraints".

SQL> select constraint_name, constraint_type,


table_name from user_Constraints;

Oracle7AM Page 26
Example on Naming Constraints:

student1
sid sname m1

sid => primary key => constraint name c1


sname => not null => constraint name c2
m1 => check => 0 to 100 => constraint name c3

Create Table Student1


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

select constraint_name, constraint_type


from user_Constraints where
table_name='STUDENT1';

• to disable the constraint or enable the constraint or


drop the constraint this name is useful.

Syntax to create the table:

Create Table <name>


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

DDL Commands:

Create
Alter
Drop
Truncate
Rename
Flashback
Purge

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

sid sname

add one more column m1

Alter

sid sname m1

Oracle7AM Page 27
Alter:
• Alter => Change
• It is used to change structure of the table.
• Using "Alter" Command we can
○ Add the columns
○ Rename The Columns
○ Drop the Columns
○ modify the data types
○ modify the field sizes
○ add the constraints
○ rename the constraints
○ disable the constraints
○ enable the constraints
○ drop the constraints

Syntax of "Alter" the Table:

Alter Table <Table_Name> add


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

add:
is used to add the columns.

Ex:
emp
empno ename sal

add a column job

Syntax:
Alter tabe <name> add(field_Definitions);

Examples:
Adding one column:
Alter table emp add job varchar2(10);

Adding multiple columns [gender,city]:


Alter Table emp add(gender char, city varchar2(10));

rename column:
used to change name of existing column.

emp
empno ename Date_of_Joining

Syntax:
Alter Table emp rename column <old_name> to <new_name>;

Ex:
Alter Table emp rename column date_of_joining to doj;

Oracle7AM Page 28
drop column:
is used to drop (Delete) one column from existing table.

Syntax:
Alter Table <name> drop column <column_name>;

emp
empno ename job sal gender city

Alter Table emp drop column city;

empno ename job sal gender

drop:
is used to drop one or multiple columns

Syntax:
Alter table <name> drop(<column_list>);

emp
empno ename job sal gender

Alter table emp drop(sal,gender);

emp
empno ename job

modify:
it can be used to change field size or data type.

empno [ Number(4) ]
--------------
hyd_1234
del_1235
mum_1236

Syntax:
Alter table <name> modify(<field_definitions>);

Ex: [modifying data type]


Alter table emp modify empno varchar2(10);

ename
-----------

Alter table emp modify ename varchar2(30);

can we decrease the field size?


Yes. we can decrease up to maximum no of chars in
the existing string.

ename
-------------
sai
raju
naresh
ravi

Alter table emp modify ename varchar(6);

Alter table emp modify ename varchar(5); //ERROR

Oracle7AM Page 29
Add Constraint:
used to add the constraint to existing field.

emp
empno ename

Syntax:
Alter table <name> add constraint <con_name> <con_type>(<field_name>);

Adding PK constraint to empno:


Alter table emp add constraint con1 Primary Key(empno);

Rename Constraint:
used to change name of the constraint

con1 => emp_pk

Syntax:
Alter table <name> rename constraint <old_name> to
<new_name>;

Ex:
Alter table emp rename constraint con1 to emp_pk;

Disable Constraint:
used to disable the constraint. It means, temporarily
constraint will not work.

Syntax:
Alter table <name> disable constraint <con_name>;

Ex:
Alter table emp disable constraint emp_pk;

Enable Constraint:
used to enable the disabled constraints. It means,
again constraint will work. To enable it, data must
follow the properties of that constraint type.

Ex: PK => should not duplicate & null

Syntax:
Alter table <name> enable constraint <con_name>;

Ex:
Alter table emp enable constraint emp_pk;

Drop Constraint:
To drop [delete] the constraint permanently use it.

Syntax:
Alter table <name> drop constraint <con_name>;

Oracle7AM Page 30
Alter table <name> drop constraint <con_name>;

Ex:
Alter table emp drop constraint emp_pk;

Primary Key
Unique
Check
References [Foreign Key]

Default
Not Null

Constraints can be categorized as 2 types:


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

• Column Level Constraints [Inline Constraints]:


• If constraint is defined in column definition then
it is called "Column Level Constraint".
• All 6 constraints [PK, U, NN, C, R, D] are comes
under Column level Constraints.

Ex:
create table customer
(
cid number(4) constraint cc1 Primary Key,
cname Varchar2(10) constraint cc2 not null
);

Table Level Constraints [Out of line constraints]:


• If constraint is defined after defining all columns
then it is called "Table Level Constraint".
• Primary Key, Unique, Check & References
[Foreign Key] are comes under table constraints.

Ex:

std11
sid sname
sid => PK

Create Table std11


(
sid Number(4),
sname Varchar2(10),
M1 Number(3),
aadhar Number(12),
constraint cc1 primary key(sid),
constraint cc2 Check(M1>=0 and M1<=100),
constraint cc3 Unique(aadhar)
);

Oracle7AM Page 31
Course12
Std12
cid cname
sid sname cid
10 Java
2001 A 20
20 Python
2002 B 30
30 C#
2003 C 50

Create Table Course12


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

Create Table Std12


(
sid Number(4),
sname Varchar2(10),
cid Number(2),
constraint ccc2 Foreign Key(cid)
References Course12(cid)
);

Ex on Alter:

std13
sid sname

Create Table std13(


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

Adding a Column [m1 column]:

Alter Table std13 add m1 number(3);


o/p: table altered

Desc std13;
o/p:
sid
sname
m1

Adding multiple columns [m2,m3 columns]:

Alter Table Std13 add(m2 number(3), m3 number(3));

Renaming a Column:

Alter Table std13 rename column m3 to maths;

Oracle7AM Page 32
Dropping a Column:

Alter table std13 drop column maths;


(or)
Alter table std13 drop(maths);

Dropping multiple columns:

Alter table std13 drop(m1,m2);

Adding Constraint:

Alter Table Std13 add constraint con1 Primary Key(sid);

Note:
Using "add constraint", we can add table level
constraints [PK, U, C, R].
"modify" is used to add not null and default constraints

Renaming the constraint:

Alter Table std13 rename constraint con1 to std_pk;

Disabling Constraint:

Alter table std13 disable constraint std_pk;

Enabling Constraint:

Alter table std13 enable constraint std_pk;

Dropping Constraint:

Alter table std13 drop constraint std_pk;

Modifying field size:

Alter Table std13 modify sname Varchar2(20);

Modifying the data type:

Alter table std13 modify sid Varchar2(10);

DDL Commands: DRL => Select

Create
Alter
Truncate

Oracle7AM Page 33
Truncate
Drop
Rename
Flashback
Purge

Truncate:
• is used to delete all records from table.
• It releases the memory.

Table = Table Structure + Table Data


emp
empno ename job sal
1001 Ravi clerk 8000
1002 Srinu manager 12000

Oracle DB
Tablespaces [DB File]
Segments
Extents => Extent = 8 Blocks [64KB]
Blocks [Pages] => 8KB
Data

Syntax:

Truncate Table <table_name>;

Example:
Truncate table employee;

All records of employee table will be deleted

Drop
Flashback
Purge

Drop:
• used to drop [delete] the tables.
• When we delete the table it will be stored in
"recyclebin".
• "Recyclebin" concept introduced in Oracle 10g
version.

Syntax:

Drop Table <Table_name> [Purge];

Oracle7AM Page 34
version.

Syntax:

Drop Table <Table_name> [Purge];

Ex:
Drop Table employee;

show recyclebin => it displays dropped tables

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

Syntax:

Flashback Table <Table_Name> to before drop


[rename to <new_table_name>];

Ex:
Flashback Table employee to before drop;

before dropping the table, if table has 5


records now table will be recollected with 5
records.

Example:
employee
drop table employee;

show recyclebin

create table employee

Flashback table employee to before drop


rename to employee_old;

Purge:
• is used to delete the table from recyclebin.

Syntax:

Purge Table <table_name>;

Ex:
Drop Table employee_old;
Purge Table employee_old;

[or]

Drop table employee_old purge;

Now, dropped object will not be

Oracle7AM Page 35
Now, dropped object will not be
stored in recyclebin. It will be
dropped permanently.

To clear the recyclebin:

Purge recyclebin;

Create
Alter
Truncate
Drop
Flashback
Purge
Rename

Rename:
is used to rename the database objects like
tables, vies ..etc

Syntax:

Rename <old_name> To <new_name>;

Rename student To nareshit;

DDL
DRL => SELECT => Operators
DML
DCL
TCL

Create table t1(f1 number(4));

Drop Table t1; --recyclebin

Create table t1(f1 varchar2(10));

Drop Table t1; --recyclebin

Flashback Table t1 to before drop; //recent one will be


recollected

SQL
DDL
DRL / DQL
DML
DCL / ACL

Oracle7AM Page 36
DCL / ACL
TCL

DRL Command [DQL]:


• DRL => Data Retrieval Language
• DQL => Data Query Language
• It deals with retrievals.
• Retrieval => opening existing data [reading the data]

Oracle SQL provides only one DRL Command i.e


SELECT

Syntax of SELECT query:

SELECT [DISTINCT] <column_list>


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

Clauses in SELECT query:

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
DISTINCT

emp
empno ename job sal doj
1001 A .. 15000 ..
102 B 8000
1010 C 12000

SELECT empno,ename,sal
FROM emp
WHERE sal>10000;

SELECT:
this clause is used to specify column list

FROM:
this clause is used to specify table list

Oracle7AM Page 37
WHERE:
this clause is used to write the conditions on rows

SELECT empno,ename,sal
FROM emp
WHERE sal>10000;

FROM emp:

emp
empno ename job sal doj
1001 A .. 15000 ..
1002 B 8000
1003 C 12000

WHERE sal>10000:

empno ename job sal doj


1001 A .. 15000 ..
1003 C 12000

SELECT empno,ename,sal:

empno ename sal


1001 A 15000
1003 C 12000

Examples on SELECT:

Display all records & all columns:

SELECT *
FROM emp; -- * => All Columns

For our convenience purpose we write *.


Implicitly * will be replaced with all column names
* = empno,ename,job,sal,mgr,comm,deptno,hiredate

Display limited columns:

SELECT empno,ename,sal
FROM emp;

Display limited rows:

SELECT *
FROM emp
WHERE sal=3000;

Display limited rows & columns:

SELECT empno,ename,sal
FROM emp
WHERE sal<1300;

Oracle7AM Page 38
WHERE sal<1300;

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

SQL provides following Operators:

Arithmetic + - * /
Relational / < > <= >= = != / <> / ^=
Comparison
Logical And Or Not
Special IN NOT IN
BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL

ANY
ALL
EXISTS

PIVOT
UNPIVOT
SET UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||

DUAL:
• is a dummy table created in the oracle database.
• it is used to work with non-database values.

Calculating 2+3:

SELECT 2+3 FROM dual;

2+3
-------
5

SELECT 2+3 as total from dual;


(or)
SELECT 2+3 total from dual;

SELECT 2+3 as total value from dual; //ERROR

SELECT 2+3 as "total value" from dual;

total value
--------------------
5

SELECT 2+3 as "TOTAL VALUE" from dual;

TOTAL VALUE
---------------------
5

" " =>


it maintains case
to use multiple words as alias

Oracle7AM Page 39
to use multiple words as alias

Examples on Arithmetic Operators:

student
sid sname M1 M2 M3
1 A 50 80 60
2 B 45 78 62

create table student(


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

Calculate total marks:

Select sid,sname,M1+M2+M3 from student;

sid sname M1+M2+M3


-------- --------------- ---------------------
1 A 190

Select sid,sname,M1+M2+M3 as TOTAL from student;

sid sname TOTAL


-------- --------------- ---------------------
1 A 190

Select sid,sname,M1+M2+M3 as "TOTAL MARKS" from


student;

sid sname TOTAL MARKS


-------- --------------- ---------------------
1 A 190

Calculating Avrg Marks:

Select sid, sname, (M1+M2+M3)/3 as avrg from student;

sid sname avrg


------- ………….. --------

Calculating total and average:

Select sid, sname, M1+M2+M3 as total,


(M1+M2+M3)/3 as avrg from student;

Calculating TA, HRA, DA, ITAX and GROSS Salary:

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

Oracle7AM Page 40
7369 SMITH CLERK 800

TA => 10% on sal => sal*10/100 => sal*0.1


HRA => 20% on sal => sal*20/100 => sal*0.2
DA => 15% on sal => sal*15/100 => sal*0.15
ITAX => 5% on sal => sal*5/100 => sal*0.05
GROSS => sal+TA+HRA+DA-ITAX

Select empno,ename,
sal*0.1 as TA,
sal*0.2 as HRA,
sal*0.15 as DA,
sal*0.05 as ITAX,
sal+sal*0.1+sal*0.2+sal*0.15-sal*0.05 as GROSS
from emp;

Fee
sid sname total_fee paid_fee
101 A 15000 5000

calculate the balance:

Select sid,sname, total_fee-paid_fee as balance


from fee;

Arithmetic: + - * /

Relational Operators / Comparison Operators:

are used to compare 2 values

< less than


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

Examples on Relational Operators:

Display the emp record whose name is SMITH:

Select * from emp where ename='SMITH';

display SMITH record

select empno,ename from emp where


ename='smith';

no rows selected

string comparison is case sensitive

Oracle7AM Page 41
string comparison is case sensitive

display the emp record whose empno is 7499:

Select * from emp where empno=7499;

display the emp records who are working in 20


dept:

Select * from emp where deptno=20;

Display all employee records except deptno 20 employees:

Select * from emp where deptno!=20;

Display all managers records:

Select * from emp where job='manager';

no rows selected => string comparison case sensitive

Select * from emp where job='MANAGER';

displays all managers records

Display all emp records except clerks:

Select * from emp where job<>'CLERK';

Display the emp records whose sal is greater than 2800:

Select * from emp where sal>2800;

Display the emp records whose sal is 3000 or greater:

Select * from emp where sal>=3000;

Display the emp record whose sal is less than 1500:

Select * from emp where sal<1500;

Display the emp records whose sal is less than or equals to


1100:

Select * from emp where sal<=1100;

Display the emp records who joined after 1982:

Select * from emp where hiredate>'31-DEC-1982';

Display the emp records who joined before 1981:

Select * from emp where hiredate<'1-JAN-1981';

Logical Operators:
are used to perform logical operations like logical and,
logical or and logical not operations.

Oracle SQL provides following Logical operators:


And
Or
Not

Oracle7AM Page 42
Not

And , Or are used to write multiple conditions.

Truth Table of And, Or:

condn1 condn2 condn1 and condn2 condn1 or condn2


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

And => should satisfy all conditions


Or => should satisfy at least one condition

Student
sid sname M1 M2 M3
1234 Ravi 60 90 70
1235 Kiran 70 30 50

In each subject student must get min 40 marks => PASS

Display the passed students records:

Select * from student


where M1>=40 And M2>=40 And M3>=40;
M1
----
80
Display the failed students records:
40
37
Select * from student
where m1<40 or m2<40 or m3<40;

Display all managers and clerks records:

Select * from emp


where job='MANAGER' and job='CLERK';

gender
check(gender='M' OR gender='F')
-----------
M
F

Display all mangers records whose sal is less than 2800:

Select * from emp


where job='MANAGER' And sal<2800;

Display all managers records who is earning more than 2800 and
who joined after apr 1981:

Oracle7AM Page 43
who joined after apr 1981:

Select * from emp


where job='MANAGER' and sal>2800 and hiredate>'30-APR-1981';

Display the emp records who are working in deptno 10 and 20:

Select * from emp


where deptno=10 Or deptno=20;

Display the emp records whose empnos are 7499, 7521, 7788:

Select * from emp


where empno=7499 Or empno=7521 Or empno=7788;

Display the emp records whose names are ALLEN,BLAKE, SCOTT:

Select * from emp


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

Condn Not
T F
F T

Display all managers records:


job
-------
Select * from emp
CLERK
where job='MANAGER';
MANAGER
CLERK
Display all emp records except managers:
MANAGER
SALESMAN
Select * from emp
MANAGER
where not(job='MANAGER');
MANAGER

Display all emp records except managers and clerks:

Select * from emp


where not(job='MANAGER' Or job='CLERK');

Special Operators:

IN:
• used to compare column value with a list of values
• If column value existed in list of values then record
will be retrieved.
• it avoids of writing multiple equality conditions
using or.

Syntax:
column_name IN(value_list);

Ex:
Deptno IN(10,30);

Display the emp records who are working in


10,20,50,60,80 depts:

Select * from emp deptno

Oracle7AM Page 44
Display the emp records who are working in
10,20,50,60,80 depts:

Select * from emp deptno


where deptno=10 or deptno=20 or deptno=50 or ----------
deptno=60 or deptno=80; 40
(or) 50
Select * from emp 55
where deptno IN(10,20,50,60,80); 80
20
25

Display the emp records who are not working in


deptnos 20 and 30:

Select * from emp


where deptno NOT IN(20,30);

Dipslay the emp records whose empnos are 7499,


7521, 7369:

Select * from emp


where empno=7499 or empno=7521 or empno=7369;
(or)
Select * from emp
where empno IN(7499,7521,7369);

Between And:
• It is used to compare column value with a range of values
• If column value falls under the range then record will be
retrieved.

Syntax:
column_name Between min_value And max_value

Ex:
sal BETWEEN 1000 and 2000

Display the emp records whose sal is 1000 or greater or sal is


2000 or less [display emp records whose sal is between 1000
to 2000]:

Select * from emp


where sal>=1000 and sal<=2000;
(or)
Select * from emp
where sal BETWEEN 1000 and 2000;

Display the emp records who joined in 1982:

Select * from emp


where hiredate between '1-JAN-1982' and '31-DEC-1982';

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

Select * from emp


where hiredate between '1-JAN-1982' and '31-DEC-1984';

Display the emp records who are not joined from 1982 to
1984:
Select * from emp
where hiredate not between '1-JAN-1982' and '31-DEC-1984';
Oracle7AM Page 45
where hiredate not between '1-JAN-1982' and '31-DEC-1984';

Arithmet + - * /
ic
Relation > >= < <= = <>
al
Logical And Or Not
Special IN NOT IN
Between And
IS NULL IS NOT NULL

IS NULL:
• is used to compare column value with null value
• For Null comparison we cannot use comparison
operator ( = ).

= comparison operator

Syntax:

column_name IS NULL

Display the emp records whose salary is 3000:

Select * from emp where sal=3000;

Display the emp records whose comm is null:

Select * from emp where comm=null;


//no rows selected

Select * from emp where comm is null;

Display the emp records who are getting the


commission:

Select * from emp where comm is not null;

Like & Not Like:

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

d: wildcard characters:
all jpg images
* 0 or any number of chars
*.jpg
? replaces 1 char
*.*

Oracle7AM Page 46
all jpg images
* 0 or any number of chars
*.jpg
? replaces 1 char
*.*
s*.jpg
?a*.jpg

SQL provides following wildcard


characters:
% replaces 0 or any no of chars
_ replaces 1 character

Syntax:
column_name like text_pattern

Display the employee records whose name is


started with 'S':

Select * from emp


where ename like 'S%';

Display the emp records whose ne is ended


with 'S':

Select * from emp


where ename like '%S';

Display the emp records whose name is ended


with 'RD':

Select * from emp


where ename like '%RD';

Display the emp records whose name is started


with 'A':

Select * from emp


where ename like 'A%';

Display the emp records whose name's second


char must be 'A':

Select * from emp


where ename like '_A%';

Display the emp records whose name's third


char is 'M':

Select * from emp


where ename like '__M%';

Disply the emp records whose name has 'A'


alphabet:

Select * from emp


where ename like '%A%';

JAMES
ALLEN

Oracle7AM Page 47
Display the emp records whose names are having 4 chars:

Select * from emp


where ename like '____';

Display the emp records whose


names are not having 4 chars:

Select * from emp


where ename not like '____';

Display the emp records whose names are not started


with 'S':

Select * from emp


where ename not like 'S%';

Display the emp records who joined in 1982:

Select * from emp


where hiredate like '%82';

Display the emp records who joined in April month:

Select * from emp


where hiredate like '%APR%';

Display the emp records who joined in 1981 and 1983:

Select * from emp


where hiredate like '%81' or hiredate like '%83';

Display the emp records who is getting 3 digit salary:

Select * from emp


where sal like '___';

Display the emp records who joined in the month first


9 days:

Select * from emp


where hiredate like '0%';

Display the emp records whose names are having 6


chars:

Select * from emp


where ename like '______';

mailid
------------
[email protected]
[email protected]

Oracle7AM Page 48
Display the emp records whose names are
having _:
Select * from emp
where ename like '%\_%' ESCAPE '\';

Display the emp records whose names are


having A:

Select * from emp


where ename like '%A%';

Display the emp names which are having %:

Select * from emp printf(" \"steve\" ");


where ename like '%\%%' escape '\';
\n

"steve" \\ \
\" "

Concatenation Operator :

Symbol => ||

used to concatenate (combine) 2 strings

Ex:

Select 'Raj' || ' Kumar' from dual;

Raj Kumar

Customer
Cid Fname Lname
1234 Sai Kumar
1235 Ravi Teja
1236 Sravan Kumar

Select fname || ' ' || lname as name


from Customer;

name
……
Sai Kumar
Ravi Teja

Oracle7AM Page 49
DML Commands
Wednesday, January 19, 2022 7:23 AM

SQL:
5 sub languages:

DDL => C A D T R F P
DRL => SELECT
DML
DCL
TCL

• All DDL Commands are auto-committed.

TCL Commands:
• Transaction Control Language
• COMMIT
• ROLLBACK
• SAVEPOINT

COMMIT [SAVE]:
• used to save the transaction.

DDL Commands are auto-committed.


DML Commands are not auto-committed.

DDL Command = DDL + Commit

insert
insert
rollback => used to cancel the previous actions

COMMIT => SAVE


ROLLBACK => [UNDO ALL]

create => t2 create => t2


insert insert
insert insert
insert create => t3
insert insert
rollback => 4 actions will insert
be canceled rollback => 2 actions will
be cancelled

Note:
DDL commands are auto-committed
DML commands are not auto-committed

Oracle7AM Page 50
DML Commands:
• Data Manipulation Language
• Manipulation = Insert or Delete or Update
• Ex:
• emp joined => INSERT
• emp left => DELETE
• emp got promotion => UPDATE [modify]
• DML commands deal with data.
• DML commands are used to manipulate the data.
• DML commands are not auto-committed.
• After using DML command
○ to save the transaction we use "COMMIT"
○ to cancel the transaction we use "ROLLBACK"

COMMIT [SAVE]:
• is used to save the transactions.
• when commit is executed, the changes of oracle
instance [RAM] will be applied to Oracle Database
[Hard Disk].
• After commit, we cannot use rollback.
• Rollback is applied on Oracle Instance. Not on
Database.

Rollback [Undo All]:


• is used to cancel the previous actions.
• It cancels uncommitted data.

SQL provides following DML commands:

• INSERT
• DELETE
• UPDATE
• INSERT ALL
• MERGE

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

Syntax:

Insert into <table_name>[<column_list>]


values(<value_list>);

Example:

Customer
cid cname ccity
101 Ravi Hyd
102 Kiran Chennai

CReate table Customer


(
cid number(4),
cname varchar2(10),
ccity varchar2(10)
);

Oracle7AM Page 51
);

Inserting single record:

Insert into customer values(101,'Ravi','Hyd');

Inserting records using parameters:

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

Enter value for cid: 102


Enter value for cname: Vamshi
Enter value for ccity: Chennai

/
Enter value for cid:
Enter value for cname:
Enter value for ccity:

Inserting limited column values:

Insert into customer(cid,cname)


values(104,'Raju');

cid cname ccity


104 Raju

Inserting records by changing the order of columns:

Insert into customer(cname,cid)


values('Krishna',105);

Copying records from existing table:

Syntax:
Insert into table_name(column_list)
select query;

Insert into customer(cid,cname)


select empno,ename from emp;

Insert into customer(cid,cname)


select empno,ename from emp
where job='MANAGER';

Insert into customer(Cid,cname)


select empno,ename from emp
where deptno=10;

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:

Oracle7AM Page 52
Syntax:
Delete from <table_name>
[WHERE <condition>];

EMP
empno ename job sal
7900 … .. …

Delete the emp record whose empno is 7900:

Delete from emp where empno=7900;

Delete all CLERKs records:

Delete from emp where job='CLERK';

Delete all records:

Delete from emp;


(or)
Delete emp;

Deleting records using parameters:

Delete from emp where empno=&empno;


Enter value for empno:7369

/
Enter value for empno:7521

Delete emp records who are working in 10th dept & 3oth
dept:

Delete from emp where deptno=10 OR deptno=30;


(or)
Delete from emp where deptno IN(10,30);

Delete all emps records except deptno 30 emps:

Delete from emp where deptno<>30;


(or)
Delete from emp where deptno not in(30);

Delete the emp records who joined in 1982:

Delete from emp where hiredate like '%82';


(or)
Delete from emp where
hiredate between '1-jan-1982' and '31-dec-1982';

Delete the emp records who joined before 1982:

Delete from emp where hiredate<'1-jan-1982';

Delete the emps who are having more than 40 years


experience:

Delete from emp


where (sysdate-hiredate)/365>40;

UPDATE:

Oracle7AM Page 53
UPDATE:
• 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

Syntax:

Update <table_name>
Set <column_name>=<value>[,<col>=<value>,…….]
[Where <condition>];

Increase 2000 rupees salary to the emp whose


empno is 7698:

Update emp
Set sal=sal+2000
where empno=7698;

Increase 20% sal to the emp whose empno is 7876 &


also modify job value as manager:

Update emp
set job='MANAGER', sal=sal+sal*0.2
where empno=7876;

Increae 15% sal to the employees who are working


in 20th dept:

Update emp set sal=sal+sal*0.15


where deptno=20;

transfer all deptno 10 emps to 30:

Update emp set deptno=30 where deptno=10;

Increase 20% sal and 15% comm to the emps who


are getting the commission:

Update emp
set sal=sal+sal*0.2, comm=comm+comm*0.15
where comm is not null;

Update comm value as null to the emps who are


getting the comm:

Update emp set comm=null


where comm is not null;

where comm=null => no rows selected


don't use = for null comparison

where comm is null =>


"is null" is used for null comparison

for null assignment write: comm=null

Set comm as 500 to all employees:

Update emp set comm=500;

Increase 20% sal to all employees:

Update emp set sal=sal+sal*0.2;

Oracle7AM Page 54
Updating records using parameters:

Increase the sal as following:


7369 => increase 2000
7902 => increase 3000
7521 => increase 1000
.
.

Update emp set sal=sal+&amt where empno=&eno;


Enter value for amt: 2000
Enter value for empno: 7369

/
Enter value for amt:3000
Enter value for empno:7902

Exs on performing calculations:

student
sid sname M1 M2 M3 Total Avrg
5001 A 60 50 80
5002 B 75 40 39

Create table student


(
sid number(4),
sname varchar2(10),
m1 number(3), 300/3 = 100.00
m2 number(3),
m3 number(3),
total number(3),
avrg number(5,2)
);

Insert into student(sid,sname,m1,m2,m3)


values(&sid,'&sname',&m1,&m2,&m3);

Calculating total and avrg:

Update student set


total=m1+m2+m3,
avrg=(m1+m2+m3)/3;

Emp1
empno ename job sal TA HRA DA TAX GROSS
1001 A clerk 5000
1002 B manager 10000

calculate TA, HRA, DA, TAX and GROSS salary:

20% on sal => TA


15% on sal => HRA
10% on sal => DA
5% on sal => TAX
GROSS => sal+ta+hra+da-tax

Create table emp1

Oracle7AM Page 55
Create table emp1
(
empno number(4),
ename varchar2(10),
job varchar2(10),
sal number(8,2),
ta number(8,2),
hra number(8,2),
da number(8,2),
tax number(8,2),
gross number(10,2)
);

Insert into emp1(empno,ename,job,sal)


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

update emp1 set


ta=sal*0.2,
hra=sal*0.15,
da=sal*0.1,
tax=sal*0.05,
gross=sal+sal*0.2+sal*0.15+sal*0.1-sal*0.05;

DML DDL
----- -----------
INSERT Create
DELETE Alter
UPDATE Drop
Truncate
INSERT ALL Rename
MERGE Flashback
Purge

Differences b/w Delete & Truncate:

Oracle7AM Page 56
DELETE TRUNCATE

• DML command • DDL Command

• Using this, we can delete • It cannot delete single record or


single record or a set of a set of records. Always it
records or all records. deletes all records.

• It does not clear the memory • Clears the memory

• It is not auto-committed • it is auto-committed

• Where clause can be used in • Where clause cannot be


DELETE command used in TRUNCATE command

• Delete is slower than truncate • Truncate is faster than Dleete

• deletes row by row • deletes page by page

Difference b/w drop & truncate:

std
sid sname scity
1001 A Hyd
1002 B Chennai

Truncate: deletes all records. It will not delete table structure


Drop: It deletes entire table(structure+data)

SQL
DDL C A D T R F P
DRL SELECT
DML I D U IA M
TCL Rollback Commit Savepoint
DCL Grant Revoke

TCL Commands:
• Transaction Control Language
• It deals with transactions.
• Transaction => is a series of commands
• Ex: withdraw deposit placing order

withdraw :
• read card info
• pin valid or not
• display the menu
• selecting withdraw
• entering amount
• checks sufficient balance is there
updaes ur account balance

Oracle7AM Page 57
• updaes ur account balance

Rollback [Undo All]:


• used to cancel the previous actions.
• After commit we cannot use rollback. Because, it
will be applied on oracle instance.

Commit [Save]:
• used to apply the changes to oracle database.
• to make changes permanent, use it.

SavePoint:
• is used to set margin for the rollback.

Syntax:
Savepoint <savepoint_name>;

EMP

INSERT => 1234 emp record


Savepoint aaa; Savepoint aaa; Savepoint aaa;
UPDATE => increase 2000 sal
INSERT INSERT INSERT
DELETE => delete 1234 record
SavePoint bbb; SavePoint bbb; SavePoint bbb;
UPDATE UPDATE UPDATE
Rollback;
SAvePoint ccc; SAvePoint ccc; SAvePoint ccc;
DELETE DELETE DELETE
all previous 3 actions will be
canceled
Rollback to ccc; Rollback to bbb; Rollback to aaa;

DELETE action will be DELETE & UPDATE DELETE, UPDATE &


canceled actions will be INSERT actions will be
canceled canceled

SQL
DDL
DRL
DML
TCL rollback commit savepoint

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

c##ravi => owner c##kiran

emp select => ERROR

GRANT
select => displays

REVOKE

select => ERROR

Oracle7AM Page 58
SQL provides 2 DCL commands. They are:
• GRANT
• REVOKE

• GRANT:
• is used to give [grant] permission to other users on
DB objects like tables, views …etc.

Syntax:
Grant <priviliges_list> ON <table_name>
to <users_list>;

Ex:
privileges GRANT select, insert, update
SELECT ON emp
INSERT TO c##ravi;
DELETE
UPDATE
ALL

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

Syntax:
Revoke <privileges_list> ON <table_name>
FROM <user_list>;

REVOKE update, insert


ON emp
FROM c##ravi;

Creating user:
there are 2 types of users:
• common user => can access any DB data
• to create common user, user name must be prefixed
with 'c##' [c => common user]
• Ex: c##raju

• local user => can access only local data


• Ex: ravi

Creating user:

"system" tablespace
Log in as DBA:
username: system
Every table space is a file
password: nareshit
file extension is ".DBF"
Create user c##usera
identified by nareshit
default tablespace users
quota unlimited on users;

Grant connect,resource to c##usera;

Oracle7AM Page 59
Grant connect,resource to c##usera;

Create user c##userb


identified by nareshit
default tablespace users
quota unlimited on users;

Grant connect,resource to c##userb;

c##usera c##userb

std
Select * from c##usera.std;
sid sname
1 A ERROR: Insufficient privileges
2 B

Create table std(sid number(4),


sname varchar2(10));

Insert into std values(1,'A');


Insert into std values(2,'B');

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

Update c##userb.std set sname='Z'


where sid=1;
ERROR: Insufficient privileges

Delete from c##usera.std 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');


row will be inserted

Update c##userb.std set sname='Z'


where sid=1;
row will be updated

Delete from c##usera.std where sid=1;


ERROR: Insufficient privileges

Grant all on std to c##userb;

SELECT
INSERT
DELETE
UPDATE

Oracle7AM Page 60
USERA USERB
Batch7AM
Create std

Grant all on std


to c##userb;
can access
he cannot
give permission
to other users

Grant all on std


to c##userb
with grant option;
Grant select on c##usera.std
to c##batch7am;

with grant option:


this is used to allow the user to grant the
permissions to other users.

c##usera:
Grant all on std
to c##userb
with grant option;

usera is allowing userb to grant permission to


other users

Granting permission on std table to c##userb,


c##batch7am,c##raju;

Grant select on std


to c##userb,c##batch7am.c##raju;

Granting permission to all users:

Grant select on std to public;

cancelling all permissions on std table from


c##userb:

Revoke all on std from c##userb;

Insert All
Merge => Oracle 9i

Insert All:
• used to insert multiple records in multiple
tables or in single table using one query.
• it avoids of writing multiple insert commands.

It can be used in 2 ways:


• unconditional insert all
• conditional insert all

Oracle7AM Page 61
• unconditional insert all:
• Syntax:
insert all
into <table_name>[(<column_list>)] values(<value_list>)
into <table_name>[(<column_list>)] values(<value_list>)
..
..
<Select query>;

Inserting multiple records in one table:

Insert All
into emp(empno,ename) values(1,'A')
into emp(empno,ename) values(2,'B')
into emp(empno,ename) values(3,'C')
Select * from dual;

emp empdemo
empno ename job sal empno ename job sal
1001
1002

1010
Insert into empdemo
select empno,ename,job,sal from emp;

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

emp3
empno ename job sal

Insert All
into emp1(empno,ename,job,sal) values(empno,ename,job,sal)
into emp2(empno,ename,job,sal) values(empno,ename,job,sal)
into emp3(empno,ename,job,sal) values(empno,ename,job,sal)
Select empno,ename,job,sal from emp;

Creating table from existing table:

Syntax:
Create table <table_name>
As
<Select query>;

case-1 [copying table] :


Creating table from existing table with records:
emp => is existed table with 10 records

Oracle7AM Page 62
emp => is existed table with 10 records
create "empdemo" table with records =>

Create table empdemo


As
Select * from emp;

now empdemo table will be created with emp table


structure & data.

Create empcopy1 table with empno,ename,job,sal


columns:

Create table empcopy1


As
Select empno,ename,job,sal from emp;

Case-2:
Creating table from existing table without records:

Create table empcopy2


As
Select * from emp
where 1=2;
[1=2 => false condition. any false condition we can
write here]

a new table will be created with emp table structure


without records.
Only structure is copied. Not data.

Ex on Insert All:

emp => is existed table

Create emp1,emp2,emp3 tables from existing table


emp without records:

Create table emp1


As
Select empno,ename,job,sal from emp where 1=2;

Create table emp2


As
Select empno,ename,job,sal from emp where 1=2;

Create table emp3


As
Select empno,ename,job,sal from emp where 1=2;

Copy emp table's 4 columns empno,ename,job,sal data


into emp1, emp2 and 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;

Replication:

Oracle7AM Page 63
Replication:
is the process of making multiple copies of db
objects like tables.

Replica:
Duplicate copy is called "Replica".

OLTP OLAP [DWH/DSS]

for day to day operations for data analysis


historical data.
By recording OLTP this will be
created

Conditional Insert All:

Syntax:
Insert All
When <condition-1> Then
into <table_name>[(<column_list>)] values(<value_list>)
When <condition-2> Then
into <table_name>[(<column_list>)] values(<value_list>)
.
.
Else
into <table_name>[(<column_list>)] values(<value_list>)
<Select query>;

Emp emp_Clerk
empno ename job sal empno ename job sal
clerk
manager
clerk emp_mgr

salesman empno ename job sal

manager
analyst
emp_others
empno ename job sal

Create table emp_clerk


As
Select empno,ename,job,sal from emp where 1=2;

Create table emp_mgr


As
Select empno,ename,job,sal from emp where 1=2;

Create table emp_others


As
Select empno,ename,job,sal from emp where 1=2;

Insert All
When job='CLERK' Then
into emp_clerk values(empno,ename,job,sal)
When job='MANAGER' Then
into emp_mgr values(empno,ename,job,sal)
Else
into emp_others values(empno,ename,job,sal)
Select empno,ename,job,sal from emp;

Oracle7AM Page 64
Assignment:

Copy deptno 10 emps to dept10 table


Copy deptno 20 emps to dept20 table
Copy other depts to dept_others table

Assignment:
Copy the emps who joined in 1981 to emp1981 table
Copy the emps who joined in 1982 to emp1982 table
Copy other than 1981,1982 to emp_other table

Merge:
Merge => Combine
• is a combination of Update & Insert
Commands.
• It can be also called as "UPSERT"
command.
• is used to apply the changes of a
table to its replica [duplicate copy]

OLTP OLAP

Customer1 Customer2
cid cname ccity cid cname ccity
1 A Bangalore [Update] 1 A Hyd
2 B Mumbai 2 B Mumbai
3 C Delhi 3 C Delhi
4 D Kolkata [Insert]

Syntax:
Merge into <target_table_name> <alias>
Using <source_table_name> <alias>
On(<condition>)
When MATCHED Then
UPDATE query
When NOT MATCHED Then
INSERT query ;

Ex on "MERGE":

Customer1
Customer2
cid cname ccity
cid cname ccity
1 A Hyd
1 A Hyd
2 B Mumbai
2 B Mumbai
3 C Delhi
3 C Delhi

Create Table Customer1


(
cid number(4),
cname varchar2(10),

Oracle7AM Page 65
cname varchar2(10),
ccity varchar2(10)
);

Insert into Customer1 values(1,'A','Hyd');

Insert into Customer1 values(2,'B','Mumbai');

Insert into Customer1 values(3,'C','Delhi');

Creating replica [duplicate copy]:

Create Table customer2


As
Select * from customer1;

Insert into customer1 values(4,'D','Chennai');

Update customer1 set ccity='Bangalore'


where cid=1;

Merge into Customer2 t


Using Customer1 s
On(s.cid=t.cid)
When MATCHED Then
Update Set t.cname=s.cname, t.ccity=s.ccity
When NOT MATCHED Then
Insert values(s.cid,s.cname,s.ccity);

SQL:

DDL Create
Alter
Truncate
Drop
Rename
Flashback [10g]
Purge [10g]
DRL Select
DML INSERT
UPDATE
DELETE

INSERT ALL [9i]


MERGE [9i]
DCL Grant
Revoke
TCL Commit
Rollback
Savepoint

Oracle7AM Page 66
Built-in Functions
Tuesday, January 25, 2022 8:01 AM

Function => Task / Action / Job

Built-In Functions:
• Function is a set of statements that gets
executed on calling.
• Oracle developers already defined some functions
and placed them in oracle database. These are
called "Built-In Functions / Predefined Functions".
• A function can take arguments & return the value.
• Every function is defined to perform particular
task.

SQL provides following functions:

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

• String Functions:

lower()
upper()
initcap()
length()
concat()

substr()
raj kumar
instr()

ltrim()
rtrim()
trim()

lpad()
rpad()

replace()
translate()

reverse()
soundex()
Oracle7AM Page 67
soundex()
ascii()
chr()

Lower():
returns string in lower case [small letters]

Syntax:
Lower(<string>)

Ex:
Lower('RAMU') => ramu

Upper():
reruns string in upper case[all capital letters]

Syntax:
Upper(<string>)

Ex:
Upper('ramu') => RAMU

Initcap():

returns every word's starting letter as capital


& remaining letters as small.

Syntax:
Initcap(<string>) Intial letter capital

Ex:
Initcap('RAMU') => Ramu
Initcap('RAVI TEJA') => Ravi Teja

Oracle7AM Page 68
length():
returns length (no of chars) of the
string.

Syntax:
length(<string>)

Ex:
length('ramu') => 4
length('sai') => 3
length('ravi teja') => 9

Display the emp records whose names are


having 4 chars:

Select * from emp _ 1 char


where ename like '____'; % 0 or any
(or);
Select * from emp
where length(ename)=4;

Concat():
used to concatenate [combine] 2 strings.

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

Ex:
Concat('ravi','teja') => raviteja
Concat(Concat('ravi',' '),'teja') => ravi teja

Oracle7AM Page 69
Ex:
Concat('ravi','teja') => raviteja
Concat(Concat('ravi',' '),'teja') => ravi teja

Display the emp record when we don't know the


exact case:

Select * from emp where lower(ename)='blake';

ename
-----------
WARD
ALLEN
BLAKE

Ex:

Player
pid fname lname PName
5001 sachin tendulkar Sachin Tendulkar
5002 rahul dravid
5003 virat kohli
5004 rohit sharma

Create Table Player


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

Insert into player values(5001,'sachin','tendulkar');

Insert into player values(5002,'rahul','dravid');

Insert into player values(5003,'virat','kohli');

Insert into player values(5004,'rohit','sharma');

Oracle7AM Page 70
Alter table player add pname varchar2(20);

Update player set pname=initcap(concat(concat(fname,' '),lname));

Alter table player drop(fname,lname);

display the player records whose name is having 12 chars:

Select * from player where length(pname)=12;

display the player records whose names are having more than 12
chars:

Select * from player where length(pname)>12;

substr():
is used to get substring from the string.

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

Examples:
1 2 3 4 5 6 7 8 9
r a v i t e j a
-9 -8 -7 -6 -5 -4 -3 -2 -1

-ve => position from right side


+ve => position from left side

substr('ravi teja',6) => teja


substr('ravi teja',6,3) => tej
substr('ravi teja',1,4) => ravi
substr('ravi teja',1,6) => ravi t

substr('ravi teja',-4) => teja


substr('ravi teja',-4,3) => tej
substr('ravi teja',-9,4) => ravi

aadhar card:

in name first 4 chars, in dob year 4 chars

Oracle7AM Page 71
in name first 4 chars, in dob year 4 chars

aadhar
name dob password
--------------------- ------------ ----------------
ravi teja 23-oct-1998 ravi1998

update aadhar set


password=substr(name,1,4) || substr(dob,-4,4);

add emailid column in Player table:

Alter table Player add mailid varchar2(100);

generate email ids for all players with their name's first 5
chars & their id's last 3 chars:

Update Player set


mailid=substr(pname,1,5) || substr(pid,-3,3) || '@bcci.com';

Display the emp records whose names are


started with 'S':

Select * from emp


where ename like 'S%'; SMITH
(or) S
Select * from emp
where substr(ename,1,1)='S'; ALLEN
A

Display the emp records whose names are


ended with 'S':

Select * from emp


where ename like '%S';
(or)
Select * from emp
where substr(ename,-1,1)='S';

Oracle7AM Page 72
Instr():
used to search for sub string in the string.
Default position value : 1
Default occurrence value : 1
If substring existed in the string it returns position.
If substring not existed in the string it returns 0.

Syntax:
Instr(<string>,<substring>[,<position>,<occurrence>])

Ex:
Instr('Ravi Teja','Teja') =>

Instr('Ravi Teja','Sai') => 0

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

Instr('this is his wish','is') => 3


searches for 1st occurrence of 'is'

Instr('this is his wish','is',1,2) => 6


searches for 2nd occurrence of 'is'

Instr('this is his wish','is',1,3) => 10


searches for 3rd occurrence of 'is'

Instr('this is his wish','as') => 0

Instr('this is his wish','is',4,1) => 6


Instr('this is his wish','is',7,1) => 10
Instr('this is his wish','is',11,1) => 14
Instr('this is his wish','is',15,1) => 0

Instr('this is his wish','is',4,2) => 10


Instr('this is his wish','is',7,2) => 14
Instr('this is his wish','is',7,3) => 0

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


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

Oracle7AM Page 73
Display the employee records which are
having 'AM' characters:

Select * from emp


where Instr(ename,'AM')>0;

Display the emp records whose names are


having 'E' as char:

Select * from emp


where Instr(ename,'E')>0;

Lpad() & Rpad():

Lpad():
pad => fill
is used to fill specified characters from left side.
default char [3rd argument] is: space

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

Ex:
Lpad('Ravi',10) => 6spacesRavi

Lpad('Sai',10,'*') => *******Sai


Lpad('Ravi,8,'#') => ####Ravi

Lpad('Ravi',10,'@$') => @$@$@$Ravi

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

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

Rpad('Sai',10) => Sai7spaces


Rpad('Sai',10,'*') => Sai*******

Rpad('Ravi',10,'@') => Ravi@@@@@@

Rpad('Ravi',10,'%$') => Ravi%$%$%$

Rpad('Sai',10,'%$') => Sai%$%$%$%

Lpad('Ravi',10,'*') => ******Ravi

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

Lpad('X',16,'X') => XXXXXXXXXXXXXXXX

amount debited from the account


num XXXXXX7890

Acno
--------
1234567890

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


Substr('1234567890',-4,4) => 7890

Select Lpad('X',6,'X') || Substr('1234567890',-4,4)


from dual;

XXXXX7890

Oracle7AM Page 75
Ltrim(), Rtrim() & Trim():

trim => remove


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

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

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

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

trim():
used to remove unwanted chars from left side or right
side or both sides.
Syntax:
trim(leading / trailing / both <char_set> from <string>

Examples:
Ltrim(' NARESH ') => NARESH5spaces
Ltrim('@@@NARESH@@@','@') => NARESH@@@

Rtrim(' NARESH ') => 5spacesNARESH


Rtrim('@@@NARESH@@@','@') => @@@NARESH

trim(' NARESH ') => NARESH


trim('@@@NARESH@@@','@') => ERROR

trim(leading '@' from '@@@NARESH@@@') => NARESH@@@

trim(trailing '@' from '@@@NARESH@@@') => @@@NARESH

trim(both '@' from '@@@NARESH@@@') => NARESH

Reverse():
used to reverse a string.
Oracle7AM Page 76
used to reverse a string.

Syntax:
Reverse(<string>)

Ex:
Reverse("ramu") => umar

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

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

Ex:
Replace('Ravi teja','Ravi','Sai') -> Sai teja
Replace('Ravi teja','teja','kumar') -> Ravi kumar

Translate():
is used to translate each occurrence of char with
corresponding char.

Syntax:
Translate(<string>,<from_String>,<to_string>)

Ex:
Translate('hello have a nice day','helo','abcd')

Replace() & Translate()

Replace() => replaces search string with replace string

Replace('abcdxyzabcdaabbccxxyyzz','abc','PQR')

Translate('abcdxyzabcdaabbccxxyyzz','abc','PQR')

Oracle7AM Page 77
ASCII():
used to know ASCII value of particular char.

Syntax:
ASCII(<char>)

Ex:
ASCII('A') => 65 ASCII('a') => 97
ASCII('B') => 66 ASCII('b') => 98
ASCII('Z') => 90 ASCII('z') => 122

Chr():
is used to get character of specified ascii value

Syntax:
Chr(<number>)

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

Soundex():
This function is used to get records based on
pronunciation.

Syntax:
Soundex(column_name)

Ex:
Display the emp record whose name is smith:

Oracle7AM Page 78
Aggregate [group] functions:

Aggregate functions are multi-row functions whereas


string functions are single row functions

single row function:


it is applied on one row [single value]

multi-row function:
it is applied on multiple rows [set of values]

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

Sum():
is used to find sum of column values.

Syntax:
Sum(<column_name>)

Ex:
Sum(Sal) => 23000

Sal
5000
10000
8000

Avg():
is used to find average value of a
21000/3 = 7000
column.

Oracle7AM Page 79
Syntax:
avg(<column_name>)
Sal
Ex:
---------
avg(Sal) => 7000
10000
5000
6000

Min():
used to minimum value in a
column.

Syntax:
Min(<column_name>)
Sal
Ex:
---------
Min(Sal) => 5000
10000
5000
6000
Max():
is used to find max value in a column

Syntax:
Max(<column_name>)

Ex:
Max(Sal) => 10000 Sal
---------
10000
5000
6000

Count():
is used to count number of column
values or number of records

Syntax:
Count(<column_name> / *)

Ex:
Sal
Count(sal) => 3 [counts not nulls]
---------
10000
Oracle7AM Page 80
Ex:
Sal
Count(sal) => 3 [counts not nulls]
---------
10000
Count(*) => 4 [counts no of records]
5000
null
6000

Find sum of salaries of all employees:

Select sum(sal) from emp;

Find sum of salaries of all clerks:

Select sum(sal) from emp where job='CLERK';

Find sum of salaries of deptno 10:

Select sum(sal) from emp where deptno=10;

Find sum of salaries of deptno 10 and 30:

Select sum(sal) from emp where deptno in(10,30);

Find the avrg sal of all employees:

Select avg(sal) from emp;

Find the avrg sal of managers:

Select avg(sal) from emp where job='MANAGER';

Find the avrg sal of deptno 20:

Select avg(sal) from emp where deptno=20;

Find the max sal in all employees:


Oracle7AM Page 81
Find the max sal in all employees:

Select max(sal) from emp;

Find the max salary in all managers:

select max(sal) from emp where job='MANAGER';

Find the max sal in deptno 20:

select max(sal) from emp where deptno=20;

Find minimum salary in all employees:

Select min(sal) from emp;

Find min sal in all clerks:

Select min(sal) from emp where job='CLERK';

Find min sal in deptno 30:

Select min(sal) from emp where deptno=30;

Find the no of emps who are getting commission:

Select count(comm) from emp;

Find the no of records in emp table:

Select count(*) from emp;

count(*) VS count(1):

count(*) => it counts number of records

count(1) => it counts no of 1s. no of 1s value is


Oracle7AM Page 82
count(1) => it counts no of 1s. no of 1s value is
equals to no of rows.

count(1) works faster than count(*)

find the number designations available in emp


table:

Select count(distinct job) from emp;

job
--------
CLERK CLERK
CLERK MANAGER
MANAGER SALESMAN
SALAESMAN ANALYST
MANAGER
ANALYST
MANAGER

Find the no of depts in emp table:

select count(distinct deptno) from emp;

-- => single line comment

Nested queries / Sub queries:


• Writing query in another query is called
"nested query / sub query".
• Outside query is called "Outer Query / Parent query /
main query".
• Inside query is called "Inner query / child query / sub
query".
• First inner query gets executed. then outer query
gets executed.
The result of inner query becomes input for the outer

Oracle7AM Page 83
• The result of inner query becomes input for the outer
query
• Inner query must be written in parenthesis.
• Inner query is always SELECT query. It cannot be
INSERT / UPDATE / DELETE.
• Outer query can be INSERT / UPDATE / DELETE /
SELECT.
• upto 255 levels we can write the nested queries.

Find the emp name who is earning max salary:

Select ename from emp


where sal=(Select max(Sal) from emp);

Find the second maximum salary:

Select max(sal) from emp sal


where sal<(Select max(Sal) from --------
emp); 5000
sal 7000
-------- 3000
5000 8000
7000
3000

• finding sal values less than max salary


• in this result find max sal => 2nd max sal

Find the emp name who is earning second max


sal:

Select ename from emp for()


where sal=(Select max(Sal) from emp {
where sal<(Select max(Sal) from emp)); for()
{
for()
}
Oracle7AM Page 84
}
}

find third max salary

=> find the salaries less than 2nd max


=> in this result find max value

find the emp name who is earning 3rd max sal

find min sal in the all employees:

select min(sal) from emp;

find emp name who is earning min sal:

select ename from emp


where sal=(Select min(sal) from emp);

find second min salary:

Select min(sal) from emp


where sal>(Select min(sal) from sal
emp); --------
2500
2000
5000
6000
4500
4000

display the emp name who is


earning second minimum salary:

PL/SQL Programs => SQL statements


Oracle7AM Page 85
PL/SQL Programs => SQL statements

Math / Numeric Functions:

power() ceil() log()


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

power():
used to find power values.

Syntax:
power(<number>,<power>)

Ex:
power(2,3) => 8
power(5,2) => 25

sqrt():
is used to find square root values

Syntax:
sqrt(<number>)
Ex:
sqrt(100) => 10
sqrt(81) => 9

sin():
is used to find sine values

Oracle7AM Page 86
is used to find sine values

Syntax:
sin(<angle>)

cos():
is used to find cosine values

Syntax:
cos(<angle>)

tan():
is used to find tangent values

Syntax:
tan(<angle>)

Note:
angle in the form of radians

Ex:
sin(90*3.14/180) degrees to radians:
cos(0*3.14/180)
tan(45*3.14/180) radians = degrees * pi/180

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

Syntax:
sign(<number>)

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

mod():
IN Java:
is used to find remainder values
% => modulus

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

Oracle7AM Page 87
Ex:
mod(20,2) => 0
mod(20,3) => 2

log():
is used to find logarithmic values.

Syntax:
log(<number>,<base>)

log(10,10) => 1

ln():
is used to find natural logarithmic
values.

Syntax:
ln(<number>)

ln(7)

abs():
is used to get absolute value.

Syntax:
abs(<number>)

Ex:
abs(5) => 5
abs(-5) => 5

ceil():
used to get upper integer value.
Oracle7AM Page 88
used to get upper integer value.

Syntax:
ceil(<number>)

floor():
used to get lower integer value.

Syntax:
floor(<number>)

ceil(123.45) => 124


floor(123.45) => 123

123 => 123.45 => 124

ceil(567.8923) => 568


floor(567.8923) => 567

567 => 567.8923 => 568

trunc():
is used to remove decimal places.

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

Ex:
trunc(123.45678) => 123

trunc(123.45678,2) => 123.45

trunc(123.45678,3) => 123.456

trunc(123.45678,-1) => 120


Oracle7AM Page 89
trunc(123.45678,-1) => 120

-1 => rounds in 10s => always gives lower value

120 => 123.45678 => 130

-2 => rounds in 100s

100 => 123.45678 => 200

trunc(1234.5678,-3) => 1000

-3 => rounds in 1000s

1000 => 1234.5678 => 2000

Round():
is used to get rounded values.
If value is .5 or greater than .5. it takes upper
value.
If value is less than .5, then it takes lower value.

Syntax:
Round(<number>[,<number>])

Ex:
Round(123.4567) => 123
Round(123.6789) => 124
Round(123.5678) => 124

Round(123.4567,2) => 123.46


Round(123.4547,2) => 123.45

Round(123.4567,-1) => 120

-1 => rounds in 10s


Oracle7AM Page 90
-1 => rounds in 10s

120 => 123.4567 < 125 => 130

120+130 = 250 /2 = 125

-2 => rounds in 100s


-3 => rounds in 1000s

Round(1234.5678,-2) => 1200

1200 => 1234.5678 => 1300


<1250
1200

Round(1264.5678,-2) => 1300


1250 => 1300

Number(p,s)

precision => valid range => 1 to 38


scale => valid range => -84 to 127

Conversion Functions:

There are 2 types of conversions. they are:


• Implicit conversion
• Explicit conversion

Implicit conversion:
If conversion is done implicitly by oracle then it is
called "Implicit Conversion".

Exs:
Select '100'+'200' from dual;
Oracle7AM Page 91
Select '100'+'200' from dual;

300

select * from emp where empno='7369';

select * from emp where deptno='20';

Explicit conversion:
The conversion which is done explicitly by using
built-in function is called "Explicit Conversion".

For Explicit Conversion we use following functions:


• to_char (date to string)
• to_char (number to string)
• to_date (string to date)
• to_number (string to number)

char

date number

to_char() [date to string]:


used to convert date value to string.

Syntax:
to_char(date,format)
Oracle7AM Page 92
to_char(date,format)

Format Purpose Example


yyyy 4 digits year 2016
yyy 3 digits year 016
yy 2 digits year 16
y 1 digit year 6
year / full name of year twenty-sixteen /
YEAR TWENTY-SIXTEEN
mm month 2 digits 12
mon / short month name dec /
MON DEC
month / full month name december /
MONTH DECEMBER
dd date 2 digits (or) 31
day number in the
month
d day number in the 1 => sun 2 => mon
week
ddd day number in the 31-jan => 31
year 01-feb => 32
dy / short week day name sun mon tue
DY SUN MON TUE
day / full week day name sunday /
DAY SUNDAY
q quarter number year => 4 quarters
1st quarter => jan,feb,mar
2nd quarter => apr,may,jun
3rd quarter => jul, aug, sep
4th quarter => oct, nov, dec
cc century number 20th century => 1900s
21st century => 2000s
hh / hh12 hour in 12 hours 10:30 AM => 10
format 02:30 PM => 02
hh24 hour in 24 hours 10:30 AM => 10
format 02:30 PM => 14
mi minutes 10:30 AM => 30
ss seconds 10:30:05 AM => 05
w weekday number in 1 2 3
the month
ww weekday number in 36 42
the year
AM / PM for AM or PM
AD / BC for AD or BC

Oracle7AM Page 93
AD / BC for AD or BC

getting year from today's date:

Select to_char(sysdate,'yyyy') from dual;


2022

Select to_char(sysdate,'yyy') from dual;


022

Select to_char(sysdate,'yy') from dual;


22

Select to_char(sysdate,'y') from dual;


2

Getting month part from today's date:

Select to_Char(sysdate,'mm') from dual;


02

Select to_Char(sysdate,'mon') from dual;


feb

Select to_Char(sysdate,'MON') from dual;


FEB

Select to_Char(sysdate,'month') from dual;


february

Select to_Char(sysdate,'MONTH') from dual


FEBRUARY

getting day part from today's date:

Select to_Char(sysdate,'dd') from dual;

Oracle7AM Page 94
Select to_Char(sysdate,'dd') from dual;
01

Select to_Char(sysdate,'ddd') from dual;


032

Select to_Char(sysdate,'d') from dual;


3

Select to_Char(sysdate,'dy') from dual;


tue

Select to_Char(sysdate,'DY') from dual;


TUE

Select to_Char(sysdate,'day') from dual;


tuesday

Select to_Char(sysdate,'DAY') from dual;


TUESDAY

getting quarter:
jan-mar => 1st quarter
apr-jun => 2nd quarter
Select to_Char(sysdate,'q')
jul-sep => 3rd
from dual;
oct-dec => 4th
1

getting century:

Select to_char(sysdate,'cc') from dual;


21

getting time from today's date [getting


current system time]:

Select to_char(sysdate,'hh:mi AM') from dual;

Getting date in INDIA date format [dd/mm/yyyy]:

Oracle7AM Page 95
Select ename,
to_char(hiredate,'dd/mm/yyyy') as hiredate
from emp;

Getting date in US Format [mm/dd/yyyy]:

Select ename,
to_char(hiredate,'mm/dd/yyyy') as doj
from emp;

Select ename,
to_char(hiredate,'mm/dd/yyyy dy') as doj
from emp;

to_char() [number to string]:

can be used convert number to string

Syntax:
to_char(number,format)

Select to_char(123) from dual;

Select to_Char(5000.00) from dual;

Format Purpose Example


L currency symbol $
C currency name USD
INR
SAR
GBP
, Thousand separator 5,000
. Decimal point 5,000.00
9/0 digits 5000

Select to_char(5000,'L9999.99') from dual;


$5000.00

Oracle7AM Page 96
$5000.00

Selecr to_Char(5000,'C9,999.99') from dual;


USD5,000.00

NLS_TERRITORY AMERICA UNITED KINGDOM


NLS_CURENCY $ £

Log in as DBA:

user name: system


password: nareshit

Alter session set nls_territory='united kingdom';

Alter session set nls_currency='£';

Alter session set nls_territory='INDIA';

Alter session set nls_currency='₹';

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

Syntax:
to_date(string,format)

to_date('25 oct,2018') => 25-oct-2018

select to_date('25 october, 2018') from dual;

select to_Date('25-oct-2018') from dual;

select to_Date('25/10/2018') from dual; => ERROR

select to_Date('25/10/2018','dd/mm/yyyy') from dual;

Inserting emp record:

Oracle7AM Page 97
Insert into emp(empno,ename,hiredate)
values(5678,'Ravi','25-nov-2019');

Insert into emp(empno,ename,hiredate)


values(5678,'Ravi',to_date('25-nov-2019'));

to get year part from today's date:

Select to_char(sysdate,'yyyy') from dual;

to get year part from specific date:

Select to_char('25-oct-2019','yyyy') from dual; => ERROR

Select to_char(to_date('25-oct-2019'),'yyyy') from dual;

Find week day of specific date - 23-sep-2018:

Select to_char('23-sep-2018','dy') from dual; => ERROR

Select to_char(to_date('23-sep-2018'),'dy') from dual;

on which week day india got freedom:

Select to_char(to_date('15-aug-1947'),'dy') from dual;


fri

what is the week day on sachin's birth day [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' => numeric string
Oracle7AM Page 98
'123' => numeric string
'raju' => not numeric string

Syntax:
to_number(string,format)

Select to_number('123') from dual;


123

Select to_number('5000.00') from dual;


5000

Select to_number('$5,000.00') from dual; //ERROR

Select to_number('$5,000.00','L9,999.99') from dual;

Select to_number('USD25,000.00','C99,999.99') from dual;

to_char() => date to string or number to string

to_date() => string to date

to_number() => string to number

Display the emp records who joined in 1983:

Select * from emp


where to_char(hiredate,'yyyy') = 1983;

Display the emp records who joined in


1980,1982,1983:

Select * from emp


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

Oracle7AM Page 99
Display the emp records who joined in december:

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

Display the emp records who joined in apr,may,jun


(or)
Display the emp records who joined in 2nd quarter:

Select * from emp


where to_char(hiredate,'q') = 2;

Display the emp records who joined in 1st quarter &


4th quarter:

Select * from emp


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

Display the emp records who joined on Sunday:


d
dy
Select * from emp
day
where to_Char(hiredate,'d') = 1;
(or)
Select * from emp
where to_Char(hiredate,'dy') = 'sun';

Select * from emp


where to_Char(hiredate,'day') = 'sunday';

no rows selected

Select * from emp


where rtrim(to_Char(hiredate,'day')) = 'sunday';

Display the emp records who joined in current


century:

Select * from emp


where to_Char(hiredate,'cc') = 21;
Oracle7AM Page 100
where to_Char(hiredate,'cc') = 21;

Date Functions:

sysdate => to get current system date


systimestamp => to get current sys date & time
Add_Months()
Last_Day()
Next_Day()
Months_Between()

Display current system date:

Select sysdate from dual;

Display current system time:

Select to_char(sysdate,'hh:mi AM') from


dual;

Display current system date & time:

Select systimestamp from dual;

getting date using systimestamp:


Select to_char(systimestamp,'dd/mm/yyyy')
from dual;

TO_CHAR(SY
----------
02/02/2022

Getting time using systimestamp:

Select to_char(systimestamp,'hh:mi AM')


from dual;
Oracle7AM Page 101
from dual;

TO_CHAR(
--------
07:48 AM

Add_Months():
This function is 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 yesterday's date:

Select sysdate-1 from dual;

Find the date After 10 days from sysdate:

Select sysdate+10 from dual;

Adding 2 months to today's date:

Select Add_Months(sysdate,2) from dual;

Subtract 2 months from today's date:

Select Add_months(sysdate,-2) from dual;

emp
empno ename dob doj dor
23-dec-2000

Oracle7AM Page 102


Update emp set dor = Add_months(dob,60*12);

India_CMs

cmid stcode cmname start_Date end_date


101 TS KCR 25-jun-2018
102 AP YS JAGAN 23-feb-2020

Update India_CMs set


end_date=Add_months(start_Date,5*12);

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

Syntax:
Last_day(date)

Find last day in current month:

Select Last_Day(sysdate) from dual;

28-feb-22

Find next month first date:

Select Last_Day(sysdate)+1 from dual;

Find next month last date:

2-feb-22 add 1 month 2-mar-22 => last_day

Last_day(Add_months(sysdate,1)) => 31-mar-22

Find previous month last day:

Last_Day(Add_Months(sysdate,-1)) => 31-jan-22


Oracle7AM Page 103
Last_Day(Add_Months(sysdate,-1)) => 31-jan-22

Current month first date:

Last_Day(Add_Months(sysdate,-1))+1 => 1-feb-22

Previous month first day:

Last_day(Add_months(sysdate,-2))+1

02-dec-22 => last_day => 31-dec-21 + 1 = 1-jan-22

Next_day():
it is used to find next coming weekday date.

Syntax:
Next_Day(date,weekday)

weekday => day num [1], short week day name


[sun] or full weekday name [sunday]

Find coming Sunday date:

Next_day(sysdate,'sun')

Find next month first Sunday date:

Next_day(Last_day(sysdate),'sun')

Find first Sunday in current month:

Select
Next_day(Last_day(Add_months(sysdate,-1)),'sun')
from dual;

Oracle7AM Page 104


Months_Between():
used to get months between 2 dates

Syntax:
Months_Between(date1,date2)

Find the age of sachin [24-apr-1973]:

Select
trunc(Months_Between(sysdate,'24-apr-1973')/12) age
from dual;

Select
Months_Between('12-dec-2020','12-jun-2020')
from dual;

Miscellaneous:

User => used to get current user name

Select user from dual;

UID => used to get user id

Select uid from dual;

Greatest =>
is used to find greatest in specified values

Greatest(40,59,89,24,101,35) => 101

Least =>
is used to get least value in a set of values

Least(40,59,89,24,101,35) => 24

max => finding max value in a column [in vertical values]


min => min value in a column [in vertical values]
greatest => max in horizontal values
least => min value in horizontal values

Oracle7AM Page 105


least => min value in horizontal values

NVL
NVL2
Rank
Dense_Rank

NVL():
used to replace null value with another value.

something + NULL = NULL

Syntax:

NVL(value1,value2)

If value1 => is not null, it returns value1


If value1 => is null, it returns value 2

NVL(500,1000) => 500


NVL(NULL,1000) => 1000

Calculate total salary of an employee:

Select ename,sal,comm,
sal+NVL(comm,0) as "tot sal" from emp;

Display comm values of an emp. if emp comm is null


replace it with N/A:

Select ename,sal,NVL(comm,'N/A') from emp; --ERROR

Select ename,sal,NVL(to_char(comm),'N/A') from emp;

Oracle7AM Page 106


Select ename,sal,NVL(to_char(comm),'N/A') from emp;

Student
sid sname m1
1001 Ravi 45
1002 Kiran
1003 Ramu 30
1004 Sravan

Replace null values with AB:

Select sid,sname,NVL(m1,'AB') from student; --ERROR

Select sid,sname,NVL(to_Char(m1),'AB') m1
from student;

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

Syntax:
NVL2(value1,value2,value3)
value1 => is not null, it returns value2
value1 => is null, it returns value3

NVL2(100,200,300) => 100 => returns 200


NVL2(NULL,200,300) => NULL => returns 300

Increase 250rs comm to the emps who are


getting comm. set comm value as 550 to
the emps who are not getting commission:

comm
Oracle7AM Page 107
comm
500 + 250 = 750
null = 550

Update emp set


comm=NVL2(comm,comm+250,550);

Rank():
used to apply ranks to column values

Ex:
750
970
950
970
950
890
950
650

Dense_Rank():
used to apply ranks to column values
Ex:
750
970
950
970
950
890
950
650

Syntax:
Rank() over(order by <column_name> asc/desc)

Dense_Rank() over(order by <column_name> asc/desc)

Oracle7AM Page 108


Apply ranks to the employees according to the
sal in descending:

sal
---------
4000
5500
3000
5500
4000
4000
2500

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 the ranks to the emps according to sal in


descending salary. If salary is same give rank according
to experience:

Select ename,sal,hiredate,
dense_rank() over(order by sal desc,hiredate asc) as rank
from emp;

RowID:
used to get row address

When duplicate records are


available in table, to delete
specific record use ROWID.

Oracle7AM Page 109


Sales
dateid amount
3-feb-22 20000
2-feb-22 15000

Create table Sales


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

insert a record with today's date:

Insert into sales values(sysdate,20000);

insert a record with yesterday's date:

Insert into sales values(sysdate-1,15000);

insert the record with 1 month ago date:

Insert into sales values(Add_Months(sysdate,-1),15000);

Insert the record with 1 year ago date:

Insert into sales values(Add_Months(sysdate,-12),15000);

Display today's sales:

Select * from Sales


where dateid = sysdate; --no rows selected

trunc(123.45678) => 123


Oracle7AM Page 110
trunc(123.45678) => 123

trunc(sysdate)

Displaying today's sales:

Select * from Sales


where trunc(dateid) = trunc(sysdate);

Display yesterday's sales:

Select * from Sales


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

Display 1 month ago sales on same date from today's


date:

Select * from sales


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

display 1 year ago sales on same date from today's date:

Select * from sales


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

emp

Oracle7AM Page 111


display the emp records who joined today

display the emp records who joined


yesterday

display the emp records who joined day


before yesterday

display the emp records who joined 1


month ago on same date

display the emp records who joined 1 year


ago on same date

Oracle7AM Page 112


Interval Expressions
Friday, February 4, 2022 7:28 AM

Interval Expressions:
• introduced in Oracle 9i version.
• we can add days, months, years to a date value
(or) we can subtract days, months, years from
date value.
• we can also add hours, minutes, seconds to a
time value or subtract hours, minutes, seconds
from time value.
• EX: sysdate+interval '1' day

Add 1 day to today's date:

Select sysdate+interval '1' day from dual;

Add 1 month to today's date:

Select sysdate+interval '1' month from dual;

Add 1 year to today's date:

Select sysdate+interval '1' year from dual;

Subtract 1 day from today's date:

Select sysdate-interval '1' day from dual;

Subtract 1 month from today's date:

Select sysdate-interval '1' month from dual;

Subtract 1 year from today's date:

Select sysdate-interval '1' year from dual;

Oracle7AM Page 113


Adding 1 and half year to today's date:

Select sysdate+interval '1-6' year to month


from dual;

Add 1 hour to current time:

Select systimestamp+interval '1' hour from dual;

Add 15 minutes to current time:

Select systimestamp+interval '15' minute from dual;

Subtract 1 hour from current system time:

Select systimestamp-interval '1' hour from dual;

Subtract 15 minutes from current time:

Select systimestamp-interval '15' minute from dual;

Add 1 and half hour to systime:

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


from dual;

display the emp records who joined today:

Select * from emp


where trunc(hiredate) = trunc(sysdate);

Oracle7AM Page 114


Display the emp records who joined yesterday:

Select * from emp


where trunc(hiredate) = trunc(sysdate-interval '1' day);

Display the emp records who joined 1 month ago from today's
date:

Select * from emp


where trunc(hiredate) = trunc(sysdate-interval '1' month);

Display the emp record who joined 1 year ago from today's
date:

Select * from emp


where trunc(hiredate) = trunc(sysdate-interval '1' year);

Flashback Query:
• This feature introduced in Oracle 10g version.
• It is used to recollect the data which is existed
some time ago. To recollect the past data we use
it.
• "AS OF TIMESTAMP" clause used for FLASHBACK
QUERY.
• After commit also we can recollect the data by
using this FLASHBACK QUERY.

to get5 minutes ago data:

Select * from emp


AS OF TIMESTAMP
sysdate-interval '5' minute;
Oracle7AM Page 115
sysdate-interval '5' minute;

5 minute ago data will be displayed

recollecting 10 minutes ago data in emp table:

insert into emp


select * from emp
as of timestamp
sysdate-interval '10' minute;

By default, up to 15 minutes we can recollect.


We can extend this time using a parameter
"undo_retention".

Log in as DBA:

extending upto 1 Hour:


Alter system set undo_rention = 3600;

Oracle7AM Page 116


CASE EXPRESSIONS
Friday, February 4, 2022 8:19 AM

Case Expressions:
• introduced in Oracle 9i version.
• are used to implement "if-then-else'.
• It avoids of writing a procedure in which we write 'if-
then-else' code.

It can be used in 2 ways:

• Simple Case => can check equality condition only


• Searched Case => can check any type of condition

Simple Case:

Syntax:

Case <column_name>
WHEN <value-1> THEN <return_expression>
WHEN <value-2> THEN <return_expression>
.
.
Else
<return_expression>
End

Searched Case:

Syntax:

Case
WHEN <condition-1> THEN <return_expression>
WHEN <condition-2> THEN <return_expression>
.
.
Else
<return_expression>
End

Oracle7AM Page 117


Examples on Simple Case:

Increase the salary of employees according to


department as following:
10 dept emps => increase 10%
20 dept => 20%
30 dept => 15%
others => 5%

Update emp set sal=


Case deptno
When 10 Then sal+sal*0.1
When 20 Then sal+sal*0.2
When 30 Then sal+sal*0.15
Else sal+Sal*0.05
End ;

Select ename,sal,deptno,
Case deptno
When 10 Then sal+sal*0.1
When 20 Then sal+sal*0.2
When 30 Then sal+sal*0.15
Else sal+Sal*0.05
End As "Incr salary"
from emp;

Assignment on Simple case:

Increase the salaries of emps


according to job as following:
CLERK => increase 10%
MANAGER => increase 20%
SALESMAN => increase 15%
Others => increase 5%

Oracle7AM Page 118


Update emp set sal =
Case Job
When 'CLERK' then sal+sal*0.1
When 'MANAGER' then sal+sal*0.2
When 'SALESMAN' Then sal+sal*0.15
else sal+sal*0.05
end ;

Searched Case:

Syntax:

Case
WHEN <condition-1> THEN <return_expression>
WHEN <condition-2> THEN <return_expression>
..
..
Else <return_expression>
End

Display salary range as following:


if sal>3000 => hisal
if sal<3000 => losal
if sal=3000 => avrgsal

Select ename,sal,
Case
WHEN sal>3000 THEN 'HiSal'
WHEN sal<3000 THEN 'LoSal'
Oracle7AM Page 119
WHEN sal<3000 THEN 'LoSal'
WHEN sal=3000 THEN 'AvrgSal'
End as "salary"
From emp;

Student
max marks: 100
sid sname M1 M2 M3
min marks: 40 in each sub
1001 A 50 70 60
1002 B 65 35 81

Select sid,sname,
Case
WHEN m1>=40 And m2>=40 And m3>=40 Then 'PASS'
Else 'FAIL'
End as Result
From Student;
m1<40 Or m2<40 Or m3<40

Find result as following for 3 subjects:

in any subject <40 => fail


if result pass then check avrg
if avrg>=60 then => first
if avrg b/w 50 to 59 => second
if avrg b/w 40 to 49 => third

In Oracle SQL,
we can implement if-then-else using 2 ways:
• Case Expression [from oracle 9i onwards]
• Decode() Function [till oracle 8i we were using]

Oracle7AM Page 120


simple case => can check equality condn only
searched case => can check any kind of condition

Decode() => can check equality [value matching]

Syntax:

Decode(<column>,
<column_value1>,<return_value1>,
<column_value2>,<return_value2>,
..
.. ,
<else_return_value>)

Display the emp designations as following:


MANAGER => BOSS
PRESIDENT => BIG BOSS
CLERK => WORKER
Others => Employee

Using Simple Case:

Select ename,
Case Job
When 'MANAGER' Then 'BOSS'
When 'PRESIDENT' Then 'BIG BOSS'
When 'CLERK' Then 'WORKER'
Else 'EMPLOYEE'
End as Job
from emp;

Decode() Function:

Select ename,
Decode(Job,
'MANAGER','BOSS',
'CLERK','WORKER',
'PRESIDENT','BIG BOSS',
'EMPLOYEE') as Job
from emp;

Oracle7AM Page 121


Increase sal of emps according to
deptno as following:
if deptno 10 => increase 10%
if 20 => 20%
30 => 15%
others => 5%

ename sal incr_Sal

Select ename,deptno,sal,
Decode(Deptno,
10,sal+sal*0.1,
20,sal+sal*0.2,
30,sal+sal*0.15,
sal+sal*0.05) as "Incr_Sal"
from emp;

Differences b/w Simple Case & Decode() :

Simple Case Decode()

is ANSI standard. is Not ANSI standard.


It is portable is not portable

Oracle SQL SERVER

My SQL

Oracle7AM Page 122


ANSI => standards

RDBMS => Oracle SQL Server My SQL

CASE Expression Decode

it can check any type can check equality only


of condition [searched case]

ANSI Standard Not ANSI Standard

It is portable It is not portable

Assignment:

Increase sal of emps according to Increase sal according to


job as following: joining year as following:
if clerk then => increase 10% if 1980 then => increase 30%
if manager then => increase 20% if 1981 then => increase 20%
if salesman then => increase 15% if 1982 then => increase 15%
for others => increase 5% for others => increase 5%

Case to_char(hiradate,'yyyy')
when 1980 then
when 1981 then

Oracle7AM Page 123


Clauses in SQL
Monday, February 7, 2022 7:27 AM

English SQL
Sentences Queries
Words Clauses

Clauses:
• Clause means, it is part of SQL query.

Oracle SQL provides following clauses:

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

SELECT [DISTINCT] <column_list>


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

SELECT empno,ename,sal
FROM emp
WHERE sal>5000;

SELECT clause:
is used to specify column list.

FROM clause:
is used to specify table list.

WHERE clause:
is used to write the condition on rows.

EXECUTION ORDER:

FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY

emp
empno ename job sal
1 A clerk 7000
2 B manager 10000
3 C clerk 4500
4 D salesman 4000
5 E manager 9000

Select empno,ename,sal from emp


where sal>5000;

FROM emp:

it selects entire table

empno ename job sal


1 A clerk 7000
2 B manager 10000
3 C clerk 4500
4 D salesman 4000
5 E manager 9000

Oracle7AM Page 124


where sal>5000:

condition will be applied on rows

empno ename job sal


1 A clerk 7000
2 B manager 10000
5 E manager 9000

SELECT empno,ename,sal:

columns will be selected

empno ename sal


1 A 7000
2 B 10000
5 E 9000

DISTINCT:
• is used to avoid duplicate rows.

Job Display the job designations


----------- offered by the company:
CLERK
MANAGER Select DISTINCT Job
MANAGER From emp;
CLERK
SALESMAN
CLERK
CLERK
MANAGER
SALESMAN
ANALYST
ANALYST
SALESMAN
ANALYST
MANAGER

Display the number of designations offered by


company:

Select count(DISTINCT Job)


From emp;

COURSE
display the course list which are
Cname
offered by the institute:
------------
Java
Select DISTINCT cname
Python
from course;
Python
Java
Java
HTML
Python
HTML
HTML
Java
Python

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

Display the emp records in alphabetical order


according to emp name:

Select empno,ename,sal
from emp
Order By ename; --default => Asc
(or)
Select empno,ename,sal
from emp
Order By ename Asc;

Oracle7AM Page 125


Display the emp records in
descending order according to sal:

Select empno,ename,sal
from emp
order by sal desc;

Display the emp records in


descending order according to sal.
place null salaries in the last:

Select empno,ename,sal
from emp
order by sal desc nulls last;

Display the emp records in


ascending order according to sal.
display null salries first:

Select empno,ename,sal
from emp
order by sal nulls first;

Display the emp records in Descending order


according to salary. If salary is same, display most
experienced person record first.

emp
empno ename hiredate sal
1001 A 23-AUG-2020 8000
1002 B 17-NOV-2019 10000
1003 C 18-OCT-2021 8000
1004 D 25-DEC-2018 10000

Select * from emp


Order By sal desc, hiredate Asc;

1004 D 25-DEC-2018 10000


1002 B 17-NOV-2019 10000
1001 A 23-AUG-2020 8000
1003 C 18-OCT-2021 8000

EX:

emp
empno ename hiredate sal
1001 A 23-AUG-2020 8000
1002 B 17-NOV-2019 10000
1003 C 18-OCT-2021 8000
1004 D 25-DEC-2018 10000
1005 E 17-NOV-2019 10000

Display the emp records in descending order


according to sal. If salary same arrange them in
ascending order according to hiredate. If hiredate
is same arrange them in ascending order
according to empno:

Select empno,ename,hiredate,sal
from emp
order by sal desc, hiredate asc,empno asc;

Assignment:

Arrange emp records in descending order according


to sal. If sal is same arrange those records in
alphabetical order according to name

Arrange emp records in descending order according to


sal. If sal is same arrange those records in
alphabetical order according to name. If name is same
arrange them in ascending order according to empno.

Oracle7AM Page 126


arrange them in ascending order according to empno.

Select empno,ename,sal
from emp
order by 2; --2 => ename

It displays emp records in


ascending order according to 2nd
column ename

Select empno,ename,sal
from emp
order by 3 desc;

It displays emp records in


descending order according to
third column sal.

empno ename job


Select * from emp
order by 2 desc; --ename

Group By Deptno
Group By:
• is used to group the records according to
specific column / columns. emp
• If column values are same, it will be empno ename sal deptno
treated as one group.
1001 A 5000 20 deptno sum(Sal)
• It converts detailed data to summarized
1002 B 8000 20 20 13000
data.
• We can apply aggregate functions on 1003 C 10000 30 30 22000
group of records. 1004 D 12000 30 10 30000
• It is used for data analysis. 1005 E 20000 10
1006 F 10000 10

Display dept wise sum of salaries:

emp
empno ename sal deptno
1001 A 5000 20 deptno sum_of_Salaries
1002 B 8000 20 20 13000
1003 C 10000 30 30 22000
1004 D 12000 30 10 30000
1005 E 20000 10
1006 F 10000 10
Order of Execution:
FROM
SELECT Deptno,Sum(Sal) as sum_of_Sal
WHERE
FROM emp
GROUP BY
WHERE deptno IN(10,20)
HAVING
GROUP BY deptno
SELECT
Order By 1;
ORDER BY

FROM emp:
selects entire table

emp
empno ename sal deptno
1001 A 5000 20
1002 B 8000 20
1003 C 10000 30
1004 D 12000 30
1005 E 20000 10
1006 F 10000 10

WHERE deptno IN(10,20):

selects 10 & 20 dept records

1001 A 5000 20

Oracle7AM Page 127


1001 A 5000 20
1002 B 8000 20
1005 E 20000 10
1006 F 10000 10

GROUP BY deptno:
it groups the records according to deptno

1001 A 5000 20
1002 B 8000 20

1005 E 20000 10
1006 F 10000 10

on this group of records aggregate function


will be applied.

SELECT deptno,sum(Sal) as sum_of_sal:


selects deptno & sum of salaries

deptno sum_of_sal
20 13000
10 30000

ORDER BY 1 [deptno]:
arranges records in ascending order according to
1st column deptno

deptno sum_of_sal
10 30000
20 13000

Display the number of emps who


are joined in different years:

Output:

Year No_of_emps
1980 2 SELECT to_char(hiredate,'yyyy') Year,
1981 5 count(*)no_of_emps
FROM emp
1982 3
GROUP BY Year
1983 4
Order By Year;

ERROR: "Year" Invalid Identifier

Note:
We can use Alias name in "Order By".
We cannot use Alias name in "Group By"
Because,
GROUP BY gets executed before SELECT.
In SELECT we are giving the alias name. So,
GROUP BY will not identify this alias name.

ORDER BY gets executed after SELECT.


So, ORDER BY can identify alias name.

When we use GROUP BY, in SELECT


clause we use grouping column or
aggregate function. Other than these
cannot be used in SELECT clause in case
of GROUP BY.

Display the no of emps joined in


different quarters:

quarter no_of_emps
SELECT to_char(hiredate,'q') quarter,
1 4
count(*) no_of_emps
2 8 FROM emp
3 2 GROUP BY to_char(hiredate,'q')
4 5 ORDER BY 1;

Oracle7AM Page 128


Find Dept wise max salary, min salary:

deptno max_sal min_sal


SELECT deptno,
10 20000 5000 max(sal) max_sal,
20 25000 8000 min(sal) min_sal
30 30000 7000 FROM emp
GROUP BY deptno
ORDER BY 1;

Display dept wise no of emps:

SELECT deptno,count(*) no_of_emps


FROM emp
GROUP BY deptno
ORDER BY 1;

Display the no of emps according to salary range:

sal>3000 => hisal


sal<3000 => losal
sal=3000 => avgsal

sal_range no_of_emps
hisal 3
losal 5
avgsal 2

Select
Case
When sal>3000 Then 'HiSal'
When sal<3000 Then 'LoSal' sal
When sal=3000 Then 'AvgSal' -----
End as sal_range, 5000
count(*) 2500
from emp 3000
Group By 4500
Case 2800
When sal>3000 Then 'HiSal' 6000
When sal<3000 Then 'LoSal'
When sal=3000 Then 'AvgSal'
End;

Display job wise sum of salaries:

Job sum_of_Salaries
Clerk 10000
Manager 25000
Analyst 18000

emp
empno ename job sal
1001 CLERK 4000
1002 CLERK 6000
1003 ANALYST 7000
1004 ANALYST 5000
1005 MANAGER 8000
1006 MANAGER 9000

Select Job,Sum(sal) sum_of_sal


FROM emp
GROUP BY job;

Oracle7AM Page 129


Find Job wise No of emps:

Job No_of_emps
CLERK 2
MANAGER 3
ANALYST 5
SALAESMAN 4

Select Job, Count(*) no_of_emps


FROM emp
GROUP BY job;

Find job wise max salary & min salary:

Job min_Sal max_sal


Clerk 2000 6000
Manager 8000 15000

SELECT Job, min(sal) min_sal, max(Sal) max_sal


FROM emp
GROUP BY job;

Find Job wise Avrg_Sal:

Select Job, trunc(avg(sal),2) avrg_sal


FROM emp
GROUP BY job;

HAVING clause:
• It is used to the write the conditions on
group of records.
• Using this, on result of GROUP BY we can
apply the conditions.
• It Cannot be used without GROUP BY.

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

deptno sum_of_Sal
10 30000
20 25000
30 40000

HAVING sum(Sal)>30000 => valid


WHERE sum(Sal)>30000 => invalid

We cannot use aggregate functions


in WHERE clause
We can Aggregate Functions in
HAVING clause.

Display the deptnos which are spending more


than 10000 on their employees:

Select Deptno, Sum(Sal) sum_of_sal


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

Display the deptnos which are


having more than 5 emps:

SELECT deptno,count(*) no_of_emps

Oracle7AM Page 130


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

Display the job titles on which organization is


spending more than 5000:

SELECT job,sum(Sal) sum_of_sal


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

Differences between WHERE & HAVING:

WHERE clause HAVING clause

• used to condition on row • used to condition on group

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


GROUP BY GROUP BY

• We cannot use aggregate • We can use aggregate functions


functions

• It will be executed before • It will be executed after


GROUP BY GROUP BY

Grouping the records according to multiple columns:

Emp
Empno Ename Deptno Job Sal
10 CLERK
1001 10 CLERK
10 MANAGER
10 CLERK
20 MANAGER
20 CLERK
20 CLERK
20 CLERK
10 MANAGER
10 MANAGER
20 MANAGER
20 MANAGER

Display Dept wise, with in dept job wise sum of salaries:

deptno Job sum_of_sal


10 CLERK
10 MANAGER
20 CLERK
20 MANAGER

break on deptno

SELECT deptno,job,sum(Sal) sum_of_Sal


FROM emp
GROUP BY deptno,job
ORDER BY 1;

deptno Job sum_of_sal


10 CLERK
MANAGER
20 CLERK
20 MANAGER

Oracle7AM Page 131


ASSIGNMENT

Display course wise total amount


Student
sid sname cname fee JAVA 4000
1001 A JAVA 2000 PYTHON 10000
1002 B PYTHON 5000
1003 C PYTHON 5000 Display the courses which are
1004 D JAVA 2000 having more than 5 students.

Display the course on which


minimum amount collected.

Display the course which is having


maximum no of students.

Rollup() & Cube() Functions:


These are used to calculate sub totals & grand totals.

Rollup():
It calculates sub totals & grand totals according to
first column

Syntax:
Rollup(Grouping_Column_List)

Cube():
It calculates sub totals & grand totals according to
every column specified in the list.

Syntax:
Cube(Grouping_Column_List)

Display dept wise, job wise no of emps. Also


calculate sub totals and gran total according
to deptno

10 CLERK 3
MANAGER 2
10th dept sub total 5
20 CLERK 5
MANAGER 3
20th dept sub total 8
GRAND TOTAL 13

Select deptno,job,count(*) no_of_emps


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

Display dept wise, job wise no of


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

10 CLERK 2
MANAGER 3
10th dept sub total 5
20 CLERK 5
MANAGER 3
2oth sub total 8

CLERK 7
MANAGER 6
GRAND TOTAL 13

Select deptno,job,count(*) no_of_emps


FROM emp
GROUP BY Cube(deptno,job)

Oracle7AM Page 132


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

Display dept wise, job wise sum of salaries &


also calculate sub totals & grand total:

SELECT deptno,job,sum(sal) sum_of_sal


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

Display Year wise, quarter wise no


of emps joined in the organization:

1980 1 4
2 3
3 5
4 3
1980 sub total
1981 1 4
2 8
3 7
4 3
1981 sub total
GRAND TOTAL

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;

SALES
dateid amount
1-JAN-2017 25000
2-JAN-2017 40000

1-JAN-2018 50000
2-JAN-2018 35000

Display Year wise, Quarter wise Sales:

SELECT to_char(dateid,'yyyy') year,


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

Oracle7AM Page 133


Person
personid pname state gender age aadhar

Display State wise, gender wise no of people:

TELANGANA M ….
F ….
TELANGANA sub TOTAL
GUJARAT M
F
Gujarat sub total
GRAND TOTAL

SELECT state,gender,count(*) no_of_people


FROM person
GROUP BY state,gender
ORDER BY state;

Display state wise, age range wise,


gender wise no of people:

TELANGANA scitizen M
scitizen F
minors M
minors F
midage M
midage F

SELECT state,
CASE
WHEN age>=60 THEN 'scitizen'
WHEN age<18 THEN 'minor'
WHEN age>=18 and age<60 THEN 'midage'
END as "age range",
Gender, count(*) as "no of people"
FROM person
GROUP BY state,
CASE
WHEN age>=60 THEN 'scitizen'
WHEN age<18 THEN 'minor'
WHEN age>=18 and age<60 THEN 'midage'
END,
gender
ORDER BY state;

CLAUSES :

SELECT => to specify column list


WHERE => to write condition on rows
FROM => to specify table list
GROUP BY => to group the records according to specific column/columns
HAVING => to write the condns on group of records
ORDER BY => to arrange the records in ascending or descending order
DISTINCT => avoids duplicate rows

GROUP BY
Execution Order:
HAVING

FROM
JOINS
WHERE
GROUP BY

Oracle7AM Page 134


GROUP BY
Execution Order:
HAVING

FROM
JOINS
WHERE
GROUP BY
SET OPERATORS
HAVING
SELECT
SUB QUERIES
ORDER BY
VIEWS
INDEXES
M VIEW
SEQUENCES
SYNONYMS

Oracle7AM Page 135


SET OPERATORS
Friday, February 11, 2022 7:29 AM

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

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

A I B = {2,3}

A-B = {1,4,5} => specific elements of A

B-A = {6,7,8,9} => specific elements of B

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

1001
1002
1003
5001
5003

SET OPERATORS:
• are used to combine the records
from multiple tables.

Oracle7AM Page 136


Syntax:

<SELECT STATEMENT>
set operator
<SELECT STATEMENT>;

ORACLE SQL provides following


SET operators:
• UNION
• UNION ALL
• INTERSECT
• MINUS

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

UNION:
• is used to get all records from multiple tables
uniquely [without duplicate records]
• It always gives result in the order.

SELECT cid,cname FROM cust1


UNION
SELECT cid,cname FROM cust2;

1001
1002
1003
Oracle7AM Page 137
1003
5001
5003

Create table cust1


(
cid number(4),
cname varchar2(10)
);

Create table cust2


(
cid number(4),
cname varchar2(10)
);

Insert into cust1 values(1001,'A');


Insert into cust1 values(1002,'B');
Insert into cust1 values(1003,'C');

Insert into cust2 values(5001,'D');


Insert into cust2 values(1002,'B');
Insert into cust2 values(5003,'E');

SELECT cid,cname FROM cust1


UNION
SELECT cid,cname FROM cust2;

Rules:
• Number of columns in Both SELECT
statements must be matched.
○ Ex:
Oracle7AM Page 138
• Number of columns in Both SELECT
statements must be matched.
○ Ex:
SELECT cid FROM cust1
UNION
SELECT cid,cname FROM cust2;

ERROR:
ERROR at line 1:
ORA-01789: query block has incorrect
number of result columns

• Corresponding column data types in both


SELECT statements should be matched.
○ Ex:
SELECT cname,cid FROM cust1
UNION
SELECT cid,cname FROM cust2;

ERROR:
ERROR at line 1:
ORA-01790: expression must have same
datatype as corresponding expression

• Corresponding column names


need not to be same
○ Ex:
cust1 cust2
cust_id cname cid cust_name

SELECT cust_id,cname FROM cust1


UNION
SELECT cid,cust_name FROM cust2;

RESULT
cust_id cname => column headings in result tables

Oracle7AM Page 139


cust_id cname => column headings in result tables

UNION ALL:
• is used get all records from multiple tables
including duplicate records.
• It does not give result in the order.

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;

1001
1002
1003
5001
1002
5003

Differences b/w UNION and UNION ALL:

Oracle7AM Page 140


UNION UNION ALL

• it gives records from • it gives records from multiple


multiple tables uniquely tables including duplicate
records.

• gives result in order • does not give result in order

• UNION is slower than • It gets executed faster than


UNION ALL. UNION

INTERSECT:
used to get common records from multiple tables

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

SELECT cid,cname FROM cust1


INTERSECT
SELECT cid,cname FROM cust2;

1002 B

MINUS:
Oracle7AM Page 141
MINUS:
• is used to get specific records from first table.
• It means, it gives all records from first table
except common records.

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

SELECT cid,cname FROM cust1


MINUS
SELECT cid,cname FROM cust2;

1001 A
1003 C

SELECT cid,cname FROM cust2


MINUS
SELECT cid,cname FROM cust1;

5001 D
5003 E

cust1 U cust2 = cust2 U cust1


cust1 UA cust2 = cust2 UA cust1
cust1 I cust2 = cust2 I cust1

cust1 M cust2 cust2 M cust1

Oracle7AM Page 142


deptno 10 deptno 20

JOB JOB
--------- ---------
MANAGER CLERK
PRESIDENT MANAGER
CLERK ANALYST
CLERK
ANALYST

Display the job titles offered by deptno 10 & 20:

SELECT job FROM emp WHERE deptno=10


UNION
SELECT job FROM emp WHERE deptno=20;

JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT

Display the common job titles of deptno 10


& 20:

Oracle7AM Page 143


SELECT job FROM emp WHERE deptno=10
INTERSECT
SELECT job FROM emp WHERE deptno=20;

JOB
---------
CLERK
MANAGER

Display the job titles which are specific to


deptno 10 only. These job titles should not be
available in deptno 20:

SELECT job FROM emp WHERE deptno=10


MINUS
SELECT job FROM emp WHERE deptno=20;

JOB
---------
PRESIDENT

Display the job titles which are specific to deptno


20:

SELECT job FROM emp WHERE deptno=20


MINUS
SELECT job FROM emp WHERE deptno=10;

JOB
---------
ANALYST
Oracle7AM Page 144
ANALYST

Oracle7AM Page 145


Joins
Saturday, February 12, 2022 7:25 AM

COLLEGE DB

student
marks
fee
library
employee

student
sid sname scity mobile

marks
sid maths physics chemistry

sid sname maths

sid sname maths physics chemistry

Products
pid pname qty

Orders
oid cid pid ord_date del_date order_qty amount

Customers
cid cname cstreet ccity cstate mobile

oid pid pname cid cname cstreet ccity mobile

Joins:
• Join => Combine / Connect / Link
• Join is an operation that combines one
table records with another based on join
condition.

student marks
sid sname scity mobile sid maths physics chemistry
1001 A .. .. 1001 70 60 80
1002 B .. .. 1002 77 44 55
1003 C .. .. 1003 63 49 81

Oracle7AM Page 146


student marks
sid sname scity mobile sid maths physics chemistry
1001 A .. .. 1001 70 60 80
1002 B .. .. 1002 77 44 55
1003 C .. .. 1003 63 49 81

sid sname maths

Joins:
• Join => Combine / Connect / Link
• Join is an operation that combines one
table records with another based on join
condition.
• Join Condition decides, the record in one
table should be joined with which record
in another table.
• used to retrieve the data from multiple
tables.
• Normally, to perform join operation one
common column is required.
• This common column name in both
tables need not to be same.
• Ex: student.stdid = marks.sid

Types of Joins:

• Equi Join / Inner Join


• Outer Join
○ Left Outer Join
○ Right Outer Join
○ Full Outer Join
• Non-Equi Join
• Self Join
• Cartesian Join / Product Join / Cross Join
• Natural Join

Equi Join / Inner Join:


• If Join Operation is performed based on equality
condition then it is called "EQUI JOIN".
Ex: student.sid = marks.sid

emp.deptno=dept.deptno

EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30

Oracle7AM Page 147


1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30
1006 30

Display the emp details along with dept details:

ename sal dname loc

SELECT ename,sal,dname,loc
FROM emp,dept
WHERE emp.deptno = dept.deptno;

Table Alias:
• It makes table name short
• It improves the performance

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;

Join Query can be written in 2 styles:


• Oracle style / Native style
• ANSI style

Oracle SQL SERVER

Join query Join query

If Join query is written in ORACLE style it may not


run in other RDBM softwares like SQL Server, MY
SQL ..etc
It means portability will not be there.

SQL SERVER
ORACLE

Join Query
Join Query

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d

Oracle7AM Page 148


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;

Note:
• To separate two table names use "keyword" in
ANSI style. Whereas in oracle style we use ,
• Write Join Condition in ON clause (or) USING clause
for ANSI style. Whereas in oracle style we write in
"WHERE" clause.

Example on USING clause:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
USING(deptno);

Note:
for USING clause, common column name must be
same

Display the emp records who are working in


CHICAGO. Display emp details along with dept
details:

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno AND d.loc='CHICAGO';

ANSI Style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE d.loc='CHICAGO';

Display the emp record whose name is BLAKE &


also display dept details of him:

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno and e.ename='BLAKE';

Oracle7AM Page 149


ANSI style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename='BLAKE';

Note:
To retrieve data from 3 tables, write 2 Join Conditions
To retrieve data from 5 tables, write 4 Join Conditions
To retrieve data from 10 tables, write 9 Join Conditions

No of Join Conditions = No of Tables-1

Retrieving data from 4 tables:

EMP1 DEPT1 Location1 COUNTRY1

empno deptno LocID cid


ename dname Lname cname
deptno LocID CID

ename dname lname cname


emp1 dept1 location1 country1

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

JOINS:

• INNER JOIN / EQUI JOIN


• OUTER JOIN
• NO-EQUI JOIN
SELF JOIN

Oracle7AM Page 150


• SELF JOIN
• CARTESIAN JOIN
• NATURAL JOIN

OUTER JOIN:
• INNER JOIN can display matching records only. It
cannot display unmatching records.
• OUTER JOIN can display matching & unmatching records
also.
• OUTER JOIN = matching records + unmatching records

• We use Outer Join operator to write Outer join query in


ORACLE style.
• Outer Join operator symbol is: (+)

There are 3 sub types in Outer Join. They are:


• Left Outer Join
• Right Outer Join
• Full Outer Join

Left Outer Join:

Left Outer = matching records + unmatching records from left table

• It is used to get all matching records and unmatching records


from left side table.

emp.deptno=dept.deptno(+)

EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30 40 OPERATIONS BOSTON
1006 30
1007 Ramu .. ..
1008 Kiran .. ..

Display the emp records along with dept details.


Also display the emp records to whom dept is not
assigned:

ORACLE style:

SELECT e.ename,d.dname
FROM emp e,dept d
WHERE e.deptno=d.deptno(+);

ANSI style:

SELECT e.ename, d.dname


FROM emp e LEFT OUTER JOIN dept d
ON e.deptno=d.deptno;

Oracle7AM Page 151


RIGHT OUTER JOIN:

Right Outer = matching records + unmatching records from right table

• It is used to get matching records and unmatching


records from right side table.

emp.deptno=dept.deptno(+)

EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30 40 OPERATIONS BOSTON
1006 30
1007 Ramu .. ..
1008 Kiran .. ..

Display the emp records along with dept details. Also


display the dept names which are not having
employees:

ORACLE Style:

SELECT e.ename,d.dname
FROM emp e,dept d
WHERE e.deptno(+)=d.deptno;

ANSI style:

SELECT e.ename,d.dname
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno=d.deptno;

FULL OUTER JOIN:

Full Outer = matching + unmatching from LEFT + unmatching from RIGHT

• used to get all matching records and unmatching


records from left & right tables

e.deptno = d.deptno(+) => LEFT OUTER

e.deptno(+) = d.deptno => RIGHT OUTER

e.deptno(+) = d.deptno(+) => ERROR

ORACLE style:

SELECT e.ename,d.dname

Oracle7AM Page 152


ORACLE style:

SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno=d.deptno(+)
UNION
SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno;

ANSI Style:

SELECT e.ename, d.dname


FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno;

Display the emp records to whom dept is not assigned:

emp.deptno=dept.deptno(+)

EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30 40 OPERATIONS BOSTON
1006 30
1007 Ramu .. ..
1008 Kiran .. ..

Display the emp records to whom


dept is not assigned:
[Left outer join + condition]

ORACLE style:

SELECT e.ename, d.dname


FROM emp e,dept d
WHERE e.deptno=d.deptno(+)
and d.dname is null;

ANSI style:

SELECT e.ename, d.dname


FROM emp e LEFT OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname is null;

Display the dept names which are not having


employees:
[Right outer join + condition]

ORACLE style:

SELECT e.ename, d.dname


Oracle7AM Page 153
SELECT e.ename, d.dname
FROM emp e,dept d
WHERE e.deptno(+) = d.deptno and
e.ename is null;

ANSI style:

SELECT e.ename, d.dname


FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename is null;

Display the employee records to whom dept is not


assigned and also display the dept names in which
employees are not existed:

FULL OUTER JOIN + Condition

ORACLE style:

SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno=d.deptno(+) and d.dname is null
UNION
SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno and e.ename is null;

ANSI style:

SELECT e.ename,d.dname
FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname is null OR e.ename is null;

Non-Equi Join:
If Join Operation is performed based on other
than equality condition then it is called
"Non-Equi Join"

Ex: other than equality => < > !=

e.deptno!=d.deptno

EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30
1006 30

Oracle7AM Page 154


Display the dept names in which
employee is not working:

ORACLE style:

SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno!=d.deptno
ORDER BY 1;

ANSI style:

SELECT e.ename,d.dname
FROM emp e JOIN dept d
ON e.deptno!=d.deptno
ORDER BY 1;

emp salgrade
empno ename job sal grade losal hisal
1001 A 3000 1 500 1000
1002 B 5000 2 1001 2000
1003 C 2500 3 2001 3000
1004 D 800 4 3001 4000
5 4001 5000

ename sal grade


A 3000 3
B 5000 5
C 2500 3
D 800 1

ORACLE style:

SELECT e.ename,e.sal,s.grade
FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;

ANSI style:

SELECT e.ename,e.sal,s.grade
FROM emp e JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;

Types of Joins:

• Inner Join / Equi Join e.deptno=d.deptno


• Outer Join => matching + unmatching
○ Left Outer => e.deptno = d.deptno(+)
○ Right Outer => e.deptno(+) = d.deptno
○ Full Outer => Left Outer U Right Outer
• Non-Equi Join => other than = operator
Self Join => joined to itself
Oracle7AM Page 155
• Self Join => joined to itself
• Cross Join / Cartesian Join / Product Join => all
possible combinations
• Natural Join => equi join without duplicate columns

Self-Join / recursive Join:


• It can be also called Recursive Join.
• If a table is joined to itself then it is called
"Self-Join".

emp emp
empno ename job sal MGR empno ename job sal MGR
1001 A CLERK 5000 1003 1001 A CLERK 5000 1003
1002 B SALESMAN 4000 1003 1002 B SALESMAN 4000 1003
1003 C MANGER 9000 1007 1003 C MANGER 9000 1007
1004 D CLERK 6000 1006 1004 D CLERK 6000 1006
1005 E ANALYST 5000 1006 1005 E ANALYST 5000 1006
1006 F MANAGER 10000 1007 1006 F MANAGER 10000 1007
1007 G CEO 15000 1007 G CEO 15000

Display the emp details & his manager details:

ORACLE style:

SELECT e1.ename employee,


e2.ename manager
FROM emp e1,emp e2
WHERE e1.mgr=e2.empno;

ANSI style:

SELECT e1.ename employee,


e2.ename manager
FROM emp e1 INNER JOIN emp e2
ON e1.mgr=e2.empno;

Display emp names and their salaries. Also


display their managers & salaries:

ORACLE style:

SELECT e1.ename employee,e1.sal emp_sal,


e2.ename manager,e2.sal mgr_Sal
FROM emp e1,emp e2
WHERE e1.mgr=e2.empno;

Oracle7AM Page 156


WHERE e1.mgr=e2.empno;

ANSI style:

SELECT e1.ename employee,e1.sal emp_sal,


e2.ename manager,e2.sal mgr_Sal
FROM emp e1 INNER JOIN emp e2
ON e1.mgr=e2.empno;

Display the employee records who are getting


salary more than his manager:

ORACLE style:

SELECT e1.ename ename,e1.sal esal,


e2.ename mname,e2.sal msal
FROM emp e1, emp e2
WHERE e1.mgr=e2.empno AND e1.sal>e2.sal;

ANSI style:

SELECT e1.ename ename,e1.sal esal,


e2.ename mname,e2.sal msal
FROM emp e1 INNER JOIN emp e2
ON e1.mgr=e2.empno
WHERE e1.sal>e2.sal;

CROSS JOIN / Cartesian Join / Product Join:

In Maths => SETS => Cartesian Product

A = {1,2,3}

B = {4,5}

AXB = {

Cross Join:
• Each record in one table will be joined with
each record another table.
• No of records in cross join result = no of
records in first table * no of records in second
table

GROUPA GROUPB
cid cname cid cname
10 IND 40 PAK
20 AUS 50 NZ
30 WI 60 ENG

Oracle7AM Page 157


ORACLE style:

SELECT a.cname,b.cname
FROM groupa a, groupb b;

ANSI style:

SELECT a.cname,b.cname
FROM groupa a CROSS JOIN groupb b;

Natural Join:
• Equi Join without duplicate columns
• We will not write join condn. Implicitly Equi Join
condition will be taken.

ANSI style:
SELECT * FROM emp NATURAL JOIN dept;

(or)

SELECT e.*,d.dname,d.loc FROM emp e,dept d


WHERE emp.deptno=dept.deptno;

dname sum_of_Sal
ACCOUNTING …
SALES …
RESEARCH …

emp.deptno=dept.deptno

EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30
1006 30

SELECT d.dname,sum(e.Sal) sum_of_Sal


FROM emp e, dept d
WHERE e.deptno=d.deptno
GROUP BY d.dname;

Display location wise, year wise no of emps in organization:

SELECT d.loc,
Location Year no_of_emps to_char(e.hiredate,'yyyy') year,
Oracle7AM Page 158
SELECT d.loc,
Location Year no_of_emps to_char(e.hiredate,'yyyy') year,
CHICAGO 1980 2 count(*) no_of_emps
1981 4 FROM emp e,dept d
1982 6 WHERE e.deptno=d.deptno
NEW YORK 1980 3 GROUP BY d.loc, to_char(e.hiredate,'yyyy')
ORDER BY 1;
1982 2

Assignment:

Student Course
sid sname cid cid cname
1001 A 20 10 Java
1002 B 30 20 Python
1003 C 20 30 Oracle
1004 D 30 40 HTML
1005 E
1006 F

Display the student records along with course


details [Equi Join]
sname cname

Display the student records along with course


details. Also display the student records who are
registered, But not joined in any course
[Left Outer Join]

Display the student records along with course


details. Also display the courses in which
students are not joined
[Right Outer Join]

Display the student records who are registered,


But not joined in any course.
Left Outer Join + Condition

Display the courses in which students are not


joined:
Right Outer Join + Condition

Oracle7AM Page 159


Sub Queries
Thursday, February 17, 2022 7:24 AM

Sub Queries / Nested Queries:


• Writing query in another query is called "Sub
Query / Nested Query".

Syntax:
SELECT <column_list>
FROM <table_list>
WHERE <column_name> <operator> (SELECT_Query);

• Outside query is called "Outer Query / Main Query /


Parent Query".
• Inside Query is called "Inner Query / Sub Query / Child
Query".
• Normally First, Inner Query gets executed. Then Outer
Query gets executed.
• The result of inner query is input for the outer query.
• We can write 255 levels of sub queries.
• Inner Query must be written in parenthesis [ (<inner
_query) ]
• Inner query must be SELECT statement only.
• Outer query can be SELECT / INSERT / UPDATE /
DELETE.
• When we don't know the exact value in WHERE clause
or HAVING clause then we write "Sub Query".

Types of Sub Queries:

• Single Row Sub Query


• Multi Row Sub Query
• Correlated Sub Query
• Inline View
• Scalar Sub Query

Single Row Sub Query:


If sub query returns single row then it is
called "Single Row Sub Query".

Display the emp records whose salary is greater than


BLAKE's salary:

Oracle7AM Page 160


• Find Blake's salary
• retrieve the records whose salary > blake's salary

SELECT * FROM emp


WHERE sal > (SELECT sal FROM emp
WHERE ename='BLAKE');

Display the emp records who joined after 'BLAKE'


[OR]
Display the emp records who are junior to BLAKE:

SELECT * FROM emp


WHERE hiredate>(SELECT hiredate FROM emp
WHERE ename='BLAKE');

Display the emp records who joined before BLAKE:


(or)
Display the emp records who are senior to BLAKE:

SELECT * FROM emp


WHERE hiredate<(SELECT hiredate FROM emp
WHERE ename='BLAKE');

Find Second Maximum Salary:


sal
-----
SELECT max(sal) FROM emp
4000
WHERE sal<(SELECT max(Sal)
3000
FROm emp);
6000
5000
4500
3500

Display the emp name who is


earing max salary:

SELECT ename FROM emp


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

Oracle7AM Page 161


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

Note:
SELECT ename FROM emp
WHERE sal = second max salary

Display the emp name who is earning min salary:

SELECT ename FROM emp


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

Find second min sal:

SELECT min(sal) FROM emp


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

Find the emp name who is getting second min


salary:

SELECT ename FROM emp


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

Finding 3rd Max Salary:

SELECT max(Sal) FROM emp


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

Oracle7AM Page 162


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

Note:
Find salary values less than 2nd max salary.
In that list we are finding max value.

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

Display the emp name Who is most


senior in all employees [who is
having max experience]:

SELECT ename FROM emp


WHERE hiredate=(SELECT
min(hiredate) FROM emp);

UPDATE ALLEN salary as deptno 30's max salary:

Update emp
SET sal=(SELECT max(Sal) FROM emp where deptno=30)
WHERE ename='ALLEN';

Delete an emp record who is having max experience:

DELETE FROM emp


WHERE hiredate = (SELECT min(hiredate) FROM emp);

Write the query for swapping 2 salaries:

Oracle7AM Page 163


Write the query for swapping 2 salaries:

UPDATE emp SET sal=


CASE empno
WHEN 7369 THEN (SELECT sal FROM emp WHERE empno=7499)
WHEN 7499 THEN (SELECT sal FROM emp WHERE empno=7369)
END
WHERE empno in(7369,7499);

Display the deptno which is spending max amount on


their employees:

1. Find the max amount in all depts


2. Find the deptno which is paying max amount

SELECT deptno FROM emp


GROUP BY deptno
HAVING sum(Sal) = (
SELECT max(sum(sal)) from emp
GROUP BY deptno);

Display the dept name which is spending max amount on


their employees:

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

Display the deptno which is having maximum


no of employees:

SELECT deptno FROM emp


GROUP BY deptno
HAVING count(*) = (SELECT max(count(*))
Oracle7AM Page 164
HAVING count(*) = (SELECT max(count(*))
FROM emp
GROUP BY deptno);

Display the dept name which is having max


no of employees:

SELECT dname FROM dept


WHERE deptno=(
SELECT deptno FROM emp
GROUP BY deptno
HAVING count(*) = (SELECT max(count(*))
FROM emp
GROUP BY deptno)
);

ASSIGNMENT

Display course wise total amount


Student
sid sname cname fee JAVA 4000
1001 A JAVA 2000 PYTHON 15000
1002 B PYTHON 5000
1003 C PYTHON 5000 Display the courses which are
1004 D JAVA 2000 having more than 2 students.
1005 E PYTHON 5000
Display the course on which
minimum amount collected.

Display the course which is having


maximum no of students.

Display the course wise no of students:

SELECT cname,count(*) FROM student


GROUP BY cname;

Display the amount collected on each


course:

SELECT cname,sum(fee) FROM student


GROUP BY cname;

Display the courses which are having


Oracle7AM Page 165
Display the courses which are having
more than 2 students:

SELECT cname,count(*) FROM student


GROUP BY cname
HAVING count(*)>2;

Display the course name on which minimum


amount collected:

SELECT cname FROM student


GROUP BY cname
HAVING sum(Fee) = (
SELECT min(sum(Fee)) FROM student
GROUP BY cname);

Display the course name which is having


maximum no of students:

SELECT cname FROM student


GROUP BY cname
HAVING count(*) = (
SELECT max(count(*)) FROM student
GROUP BY cname);

Multi Row Sub Queries:


A sub query which returns multiple rows is
called "Multi Row Sub Query".

display the emp records whose sal


is > than blake's salary:

SELECT * FROM emp


WHERE sal>(SELECT sal FROM
emp WHERE ename='BLAKE');

Oracle7AM Page 166


Multi Row Sub Queries:
A sub query which returns multiple rows is called "Multi
Row Sub Query".

Display all managers & clerks records:

Display the emp records whose job designations are


equals to SMITH and BLAKE:

SELECT * FROM emp


WHERE job IN(
SELECT job FROM emp
WHERE ename IN('SMITH','BLAKE'));

Assignment:

Display the emp records whose salary is


equals to SCOTT & WARD salary:

SELECT ename,sal FROM emp


WHERE sal IN(SELECT sal FROM emp
WHERE ename IN('SCOTT','WARD'));

IN => multi equality condition with OR


ALL => multi greater/less condition with AND
ANY => multi greater/less condition with OR

job='MANAGER' or job='CLERK' => job IN('MANAGER','CLERK')


sal>2000 and sal>3000 => sal>ALL(2000,3000)
sal>2000 or sal>3000 => sal>ANY(2000,3000)

Display the emp records whose salary is greater


than TURNER and CLARK salary:
Oracle7AM Page 167
than TURNER and CLARK salary:

SELECT * FROM emp


WHERE sal>ALL(SELECT sal FROM emp
WHERE ename IN('TURNER','CLARK'));

Display the emp records whose salary is greater


than TURNER or CLARK salary:
1500 2450

SELECT * FROM emp


WHERE sal>ANY(SELECT sal FROM emp
WHERE ename IN('TURNER','CLARK'));

Display the emp names who are earning max


salary in their dept:

SELECT deptno,ename FROM emp


WHERE (deptno,sal) IN(SELECT
deptno,max(Sal) FROM emp
GROUP BY deptno);

Display the emp names who are senior in their


depts:

SELECT ename,deptno,hiredate FROM emp


WHERE (deptno,hiredate)
IN(SELECT deptno,min(hiredate) FROM emp
GROUP BY deptno);

Display the emp names who are junior in their


depts:

Display the emp names who are earning


minimum salary in their depts:

Correlated Sub Query:


If outer query passes value to inner query then it
Oracle7AM Page 168
• If outer query passes value to inner query then it
is called "Correlated Sub Query".
• In this, Inner query gets executed multiple times.
Where as in remaining sub queries inner query
gets executed only once.
• The number of records passed by outer query =
number of execution times of inner query.

Normal Sub Query Correlated Sub query

• Inner query gets executed first • Outer query gets executed first
• Inner gets executed only once • Inner query gets executed for
multiple times

Execution process of Correlated Subquery:

• First Outer query gets executed.


• Outer Query passes value to Inner Query.
• Inner query gets executed.
• Inner Query passes value to Outer Query.
• Outer query condition will be tested. If condition
TRUE, record will be displayed. Otherwise, record
will not be displayed
• Above steps gets executed repeatedly for every
row.

Display the emp records who are getting


salary greater than their dept's average
salary:

emp deptno avrg_sal


empno ename deptno sal
1001 A 10 6000
1002 B 10 8000

Oracle7AM Page 169


empno ename deptno sal
1001 A 10 6000
1002 B 10 8000
1003 C 20 5000
1004 D 20 7000

SELECT ename,sal,deptno FROM emp e


WHERE sal>(SELECT avg(sal) FROM emp
WHERE deptno=e.deptno);

Find 3rd maximum salary:

emp Find
empno ename job sal how many sal values>emp sal
6000
8000 0 > emp sal max salary

5000 1> emp sal 2nd max sal

3000 2> emp sal 3rd max sal

4500 3 > emp sal 4th max sal


.
.
n-1 > emp sal nth max sal

SELECT sal FROM emp e


WHERE 2 = (SELECT count(distinct sal) FROM
emp
WHERE sal>e.sal);

Find 4th max sal:

SELECT sal FROM emp e


WHERE 3 = (SELECT count(distinct sal)
FROM emp
Oracle7AM Page 170
FROM emp
WHERE sal>e.sal);

Find 5th max sal:

SELECT sal FROM emp e


WHERE 4 = (SELECT count(distinct sal)
FROM emp
WHERE sal>e.sal);

Find nth max sal:

SELECT sal FROM emp e


WHERE (&n-1) = (SELECT count(distinct sal)
FROM emp
WHERE sal>e.sal);

exists: => It returns TRUE if record is existed.


not exists: => It returns TRUE if record is not existed

Dept
emp deptno dname loc
empno ename deptno 10 accounting
1001 10 20 research
1003 20 30 sales
1004 30 40 operations

Display the dept names which are having employees:

SELECT dname FROM dept d


WHERE exists(SELECT * FROM emp
WHERE deptno=d.deptno);

Display the dept names which are not having


employees:

Oracle7AM Page 171


SELECT dname FROM dept d
WHERE not exists(SELECT * FROM emp
WHERE deptno=d.deptno);

Inline View:
• If sub query is written in FROM clause then it is
called "Inline View".
• Sub query acts like table.
• We can change the execution order

Display the emp records whose annual salary is > 30000:

SELECT ename,sal,sal*12 An_sal FROM emp


WHERE An_sal>30000; --ERROR

execution order
FROM
WHERE => does not know alias name. alias name specified in SELECT
SELECT

SELECT * FROM (SELECT ename,sal,sal*12 an_sal FROM emp)


WHERE an_sal>30000;

rownum:
pseudo => FALSE
• Rownum is a pseudo column.
• It applies row number on the
result of SELECT query

Display the 3rd record:

SELECT rownum rn,ename,sal FROM emp


Oracle7AM Page 172
SELECT rownum rn,ename,sal FROM emp
WHERE rn=3; --ERROR

SELECT * FROM (SELECT rownum rn,ename,sal FROM emp)


WHERE rn=3;

Displaying 10th record:

SELECT * FROM (SELECT rownum rn,ename,sal FROM emp)


WHERE rn=10;

Display 3rd,7th &11 th records:

SELECT * FROM (SELECT rownum rn,ename,sal FROM emp)


WHERE rn IN(3,7,11);

Display even row number records:

2)8(4 2)7(3
8 6
------------ ----------
0 1

SELECT * FROM (SELECT rownum rn,ename,sal FROM emp)


WHERE mod(rn,2)=0;

Display odd number records:

SELECT * FROM (SELECT rownum


rn,ename,sal FROM emp)
WHERE mod(rn,2)=1;

Oracle7AM Page 173


Types of Sub Queries:
• Single Row Sub Query
• Multi Row Sub Query
• Correlated Sub Query
• Inline View
• Scalar Sub Query

Scalar Sub Query:


• If we write Sub Query in SELECT clause then it is
called "Scalar Sub Query".
• Sub query acts like a column.

Display number of records in emp & dept tables:

SELECT (Select count(*) from emp) emp,


(Select count(*) from dept) dept
FROM dual;

emp dept
---------- ------------
14 4

Calculate share of each dept:

SELECT deptno,sum(Sal) sum_of_sal,


(Select sum(Sal) FROM emp) tot_sal,
(sum(sal)*100)/(select sum(Sal) from emp) percentage
FROM emp
GROUP By deptno;

Tables
Views
Sequences
SQL-Introduction
Oracle7AM Page 174
Tables
Views
Sequences
SQL-Introduction
Synonyms
5 sub languages
Indexes
DDL, DRL, DML, DCL, TCL
Materialized Views
Operators in SQL
Built-In Functions
Clauses in SQL
Joins
SET operators
Sub Queries

Oracle7AM Page 175


Views
Tuesday, February 22, 2022 7:53 AM

View:
• View is a DB Object.
• View is a Virtual Table.
• Virtual Table means, It does not contain
physical data & It does not occupy the
memory.
• A view holds SELECT query.
• When we retrieve data through view,
implicitly oracle runs SELECT query which
is associated with that view.
• Some can be updated. These are called
"Updatable Views". Some views cannot be
updated. These are called "Read-Only
Views".

Syntax to create the view:

Create View <View_name>


As
<Select query>;

CREATE VIEW v1
AS
SELECT empno,ename,job
FROM emp;

USERA:
SELECT * FROM v1;

Security can be implemented in 3 levels:

DB LEVEL => SCHEMA [USER]


Advantages: TABLE LEVEL => Grant, Revoke
• Provides Security. DATA LEVEL => VIEW
• reduces complexity & => Row Level =>
simplifies the queries. create view on deptno 10 records
=> Column Level =>
create view with 3 columns out of 8
columns

SELECT ename,sal,dname,loc
FROM emp e,dept d

Oracle7AM Page 176


SELECT ename,sal,dname,loc
FROM emp e,dept d
WHERE e.deptno=d.deptno;

Create view v2
As
Complex Join Query;

Select * from v2;

JAVA developer

Log in As DBA:

username: system
password: nareshit

GRANT create view TO c##batch7am;

Log in as User [c##batch7am]:

Create View v1
As
SELECT empno,ename,Job FROM emp;

v1

SELECT empno,ename,Job FROM


emp

emp

empno ename job sal deptno


1001 A .. .. ..

Oracle7AM Page 177


View:
• DB Object.
• Virtual Table
• does not contain physical data. does not occupy the
memory.
• holds SELECT query.
• When we retrieve data through view implicitly oracle
runs SELECT query.
• A view will be created on table.
• A table on which view is created is called "Base Table".
• Some views can be updated. => updatable views
• Some views cannot be updated. => read-only views
• View always gives recent data [committed data].

Create View V1
As
SELECT * FROM emp;

emp => Base Table

Advantages:
• provides security [Data Level Security]
• reduces the complexity & simplifies the queries

Types of Views:

2 Types:

• Simple View
• Complex View

Simple View:
• If view is created based on one table then it is called
"Simple View".
• It can be also called as "Updatable View".
• We can perform DML operations through Simple View.

Using View, we can implement row level security &


column level security.

Implementing Row Level Security:

Oracle7AM Page 178


Login as c##batch7am:

emp -> Table


empno ename job sal deptno mgr hiredate comm
1001 .. .. .. .. .. .. ..
1002 ..

Creating View:

CREATE VIEW v1
AS
SELECT empno,ename,job FROM emp;

v1 -> VIEW

SELECT empno,ename,job FROM emp

emp => Base Table

Creating user / schema => [c##naresh]:

Log in as DBA:
username: system
password: nareshit

Create user c##naresh identified by naresh


default tablespace users
quota unlimited on users;

Grant connect,resource to c##naresh;

Log in as c##batch7am:

Grant SELECT on v1 to c##naresh;

Log in as c##naresh:

SELECT * FROM v1;

Implementing Row Level Security:

emp
empno ename job sal deptno

Oracle7AM Page 179


emp
empno ename job sal deptno
10
10
20
20
20
30
30

Batch7AM:

CREATE VIEW v2
AS
SELECT * FROM emp
WHERE deptno=20;

GRANT All ON v2
TO c##naresh;

c##naresh:

Oracle7AM Page 180


Insert into
c##batch7am.v2(empno,ename,deptno)
values(22,'AB',10);
1 row created

SELECT * FROM c##btach7am.v2;

does not display 10th dept record => empno 22

WITH CHECK OPTIONL

CREATE VIEW v2
AS
SELECT * FROM emp WHERE deptno=20
WITH CHECK OPTION;

Insert into
c##batch7am.v2(empno,ename,deptno)
values(22,'AB',10);
ERROR: WHERE condition violated

• WITH CHECK OPTION clause does not allow


the user to insert the records which cannot
displayed by the view.
• It means, the records which violates WHERE
condition will not be allowed.

CREATE OR REPLACE VIEW V2


AS
SELECT * FROM emp
WHERE deptno=20 WITH CHECK OPTION;

View created.

INSERT INTO v2(empno,ename,deptno)


values(55,'AB',10);
ERROR

M1+M2+M3 =>
sal*12 =>
COMPLEX VIEW:
expression
Oracle7AM Page 181
M1+M2+M3 =>
sal*12 =>
COMPLEX VIEW:
expression
• If a view is created based on multiple tables
[Joins] or SET operators or Sub Queries or
Aggregate Functions or expressions or
GROUP BY or HAVING then it is called "
Complex View".
• It can be also called as read-only view.
• We cannot perform DML operations using
COMPLEX VIEW.

SIMPLE VIEW COMPLEX VIEW

If a view created based If a view created based


on one table then it is on multiple tables then it is
SIMPLE VIEW COMPLEX VIEW

Updatable View Read-Only View

We can perform DML We cannot perform DML


operations through this operations through this view.
view

Performs simple operations Performs complex operations


group by, having ..etc

Ex on Complex View:

Create view v3
AS
SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno;

SELECT * FROM v3;

ename sal dname loc

INSERT INTO v3 => ERROR


DELETE FROM v3 => ERROR
UPDATE v3 SET => ERROR

Oracle7AM Page 182


CREATE VIEW v4
AS
SELECT deptno,sum(sal) sum_of_sal
FROM emp
GROUP BY deptno;

Views:
• Virtual Table
• no physical data
• not occupies memory
security
2 Types: reduces complexity
• Simple View =>
• based on one table
• DML operations
• Updatable View

• Complex View =>


• based on multiple tables, set operators,
sub queries, group by, having, aggregate
functions, expressions
• cannot perform DML operations
• Read-Only View

Can we create a view without Table?


No. Without table we cannot create the view.
But, using FORCE VIEW we can create the view
without table.

FORCE VIEW:
If a view is created forcibly with some errors
then it is called "FORCE VIEW".

Example:
Without existing table we can create the view
forcibly with some errors. This view will not
Oracle7AM Page 183
forcibly with some errors. This view will not
work till we create the table. This view is
called "FORCE VIEW".

Table View
View Table

View FORCE VIEW

Syntax to create force view:

CREATE FORCE VIEW <view_name>


AS
<SELECT query>;

Can we create a view from another view?


Yes. We can create.

Example:
emp
empno ename job sal mgr comm deptno hiredate

v1 => view
empno ename job

CREATE view v6
AS
SELECT * FROM v1;

SELECT * from v6;

After creating view, if we add columns to the base table does


it reflect to view?
No. It will not be reflected to view. View holds SELECT query.
We are not changing SELECT query which is in view.

Example:
emp
empno ename job sal mgr comm deptno hiredate

Oracle7AM Page 184


empno ename job sal mgr comm deptno hiredate

CREATE VIEW v7
AS
SELECT empno,ename,deptno
FROM emp;

ALTER TABLE emp add gender char;

CREATE VIEW v8
AS
SELECT *
FROM emp;

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

Alter table emp add city varchar2(10);

USER_TABLES
USER_VIEWS
USER_CONSTRAINTS
USER_SEQLENCES

text column displays SELECT query of view.

SELECT view_name,text FROM user_Views;

After creating view if we add records to base


table does it reflect to view?
Yes. When we retrieve data through view
implicitly oracle runs SELECT query. So, it
displays recent data [committed data].

CREATE view => v8

insert into emp(empno,ename)


values(4567,'ABCD');

Can we user ALTER or TRUNCATE command


Oracle7AM Page 185
Can we user ALTER or TRUNCATE command
on view?
No. Because, does not contain physical data.
does not have physical structure.

If we want to make changes of SELECT query


which is in view which command will be
used?
CREATE OR REPLACE command is used to
make changes in existing view.

CREATE VIEW v9
AS
SELECT empno,ename FROM emp;

CREATE OR REPLACE v9
AS
SELECT empno,ename,job FROM emp;

View created based on table. If we drop the


base table does it drop the view?
No. But, this view will not work. In future if we
create a table with that base table again this
view will work.

USER_VIEWS:
• It maintains all views information

SELECT view_name, text


FROM user_views;

Dropping the view:

Syntax:

DROP VIEW <view_name>;

DROP VIEW v9;

Oracle7AM Page 186


SEQUENCES
Thursday, February 24, 2022 8:11 AM

SEQUENCES:
• is a DB Object.
• It is independent of table.
• It is used to generate sequential
integer values.

Ex: order_id, transaction_id, cust_id

Syntax to create the SEQUENCE:

CREATE SEQUENCE <sequence_name>


[START WITH <value>]
[INCREMENT BY <value>]
[MINVALUE <value>]
[MAXVALUE <value>]
[cycle / nocycle]
[cache <size> / nocache];

Ex:
CREATE SEQUENCE s1;

clause default
START WITH 1
MINVALUE 1
MAXVALUE 10 power 28
INCREMENT BY 1
cycle nocycle
cache 20

SEQUENCE provides 2 pseudo columns to work with


the sequence. They are:
• NEXTVAL => returns next value in the sequence
CURRVAL => returns current value in the sequence
Oracle7AM Page 187
• CURRVAL => returns current value in the sequence

Syntax:

Sequence_name.pseudo_Column

Ex:
s1.nextval
s1.currval

START WITH clause:


used to specify starting value of sequence
Ex:
START WITH 1 => sequence starts from 1
START WITH 10 => sequence starts from 10
START WITH 1001 => sequence starts from 1001

MINVALUE clause:
used to specify minimum value
Ex:
MINVALUE 1
MINVALUE 300

MAXVALUE clause:
used to specify maximum value in the sequence
Ex:
MAXVALUE 10
MAXVALUE 500

INCREMENT BY clause:
used to specify step value. How many values should be
increased or decreased after a value will be specified
here.

Oracle7AM Page 188


CREATE SEQUENCE s2
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 5;

CREATE TABLE customer11


(
cid number(4),
cname varchar2(10)
);

cid cname
Insert into customer11
1 A
values(s2.nextval,'&cname');
2 B Enter value for cname: A
3 C
4 D /
5 E Enter value for cname: B

/
Enter value for cname: C

/
Enter value for cname: D

/
Enter value for cname: E

/
ERROR: reached MAXVALUE

ASSIGNMENT:
CREATE a sequence with minimum
cid cname value 10 & max value 40

Oracle7AM Page 189


CREATE a sequence with minimum
cid cname value 10 & max value 40
10 JAVA
20 PYTHON
30 C
40 C#

CREATE SEQUENCE s3
START WITH 10
INCREMENT BY 10
MINVALUE 10
MAXVALUE 40;

course5
cid cname

CREATE TABLE course5


(
cid number(2),
cname varchar2(10)
);

INSERT INTO course5 values(s3.nextval,'&cname');


Enter value for cname: JAVA

/
Enter value for cname: PYTHON

/
Enter value for cname: ORACLE

/
Enter value for cname: HTML

Enter value for cname: C


ERROR: exceeds MAXVALUE

Oracle7AM Page 190


Altering Sequence:

set maxvalue as 100:

Alter Sequence s3 MAXVALUE 100;

select s3.nextval from dual;


50

set increment by value as 1, max value 55:

Alter sequence s3 increment by 1 maxvalue 55


minvalue 1 cycle;

MINVALUE START WITH MAXVALUE


1 10 55

cycle / nocycle:

cycle:
If we create a sequence with cycle,
SEQUENCE starts from START WITH value.
It generates next value up to MAXVALUE.
After reaching maximum value it will be reset to MINVALUE.
Again it generates up to MAXVALUE.
After reaching maximum value again it will be reset to
MINVALUE.

CREATE SEQUENCE s4
START WITH 300
INCREMENT BY 1
Oracle7AM Page 191
INCREMENT BY 1
MINVALUE 100
MAXVALUE 350
cycle;

START WITH
300

CREATE SEQUENCE s5
INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
cycle;
--ERROR : CACHE size must be less than one cycle
default cache value is 20
In above example one cycle value is 10
cache size must be < 10

CREATE SEQUENCE s5
INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
cycle
cache 10; --ERROR => cache size must be < one cycle

CREATE SEQUENCE s5
INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
Oracle7AM Page 192
MAXVALUE 10
cycle
cache 9;

sequence created

nocycle:
• it is default one.
• If we create sequence with nocycle,
SEQUENCE starts from START WITH
value, it generates next value up to
MAXVALUE. After reaching MAXVALUE
it stops.

Ex:
CREATE SEQUENCE s6
INCREMENT BY 1
START WITH 200
MINVALUE 1
MAXVALUE 500
nocycle;

cache <size> / nocache:


Oracle7AM Page 193
cache <size> / nocache:
RAM cache
• Default cache size is 20

nocache:

CREATE SEQUENCE s7
INCREMENT BY 1
START WITH 101
MINVALUE 101
MAXVALUE 500
nocache;

s7.nextval => DB => identifies currval => adds increment by value

cache <size>:

CREATE SEQUENCE s8
INCREMENT BY 1
START WITH 101
MINVALUE 101
MAXVALUE 500
cache 100;

s8.nextval =>

cache <size> / nocache:

cache default size is 20


Oracle7AM Page 194
• cache default size is 20
• cache 100 => 100 values of sequence will be
loaded into cache memory. When we call the
sequence, it goes to cache & returns the next
value.
• nocache => When we call sequence, it goes to
DB, identifies current value, adds increment by
value & returns the next value. Always goes to
DB & returns next value. With this performance
will be degraded. To improve the performance
use "cache".
• Always cache size must be less than one
cycle.

Calling sequence in UPDATE command:

emp
empno ename Update empnos in the order with
7369 Sequential integers from 1001:
7454
7521 CREATE SEQUENCE s8
START WITH 1001
7900
INCREMENT BY 1
7902
MINVALUE 1001
7932 MAXVALUE 9999;

UPDATE emp
SET empno=s8.nextval;

Can we call sequence from CREATE command?


Oracle7AM Page 195
Can we call sequence from CREATE command?
• YES. From ORACLE 12c version onwards we can
call the sequence from create command in
"DEFAULT" constraint.
• We set sequence call as the default value when
we create the table.

CREATE SEQUENCE s9
START WITH 5001
INCREMENT BY 1
MINVALUE 5001
MAXVALUE 9999;

CREATE TABLE customer5


(
cid Number(4) default s9.nextval,
cname varchar2(10)
);

insert into customer5(cname) values('RAVI');

insert into customer5(cname) values('SRINU');

insert into customer5(cname) values('VIJAY');

SELECT * FROM customer5;


cid cname
---- ----------
5001 RAVI
5002 SRINU
5003 VIJAY

Oracle 12c version onwards, we can create


sequential integers using 2 ways:
• using sequence

Oracle7AM Page 196


sequential integers using 2 ways:
• using sequence
• using identity [oracle 12 c - generated
always as identity]

• using identity [ generated always as identity]:

CREATE TABLE customer55


(
cid number(4) generated always as identity,
cname varchar2(10)
);

INSERT INTO customer55(cname)


values('Ravi');

INSERT INTO customer55(cname)


values('Sai');

INSERT INTO customer55(cname)


values('Arun');

SELECT * FROM customer55;


cid cname
1 Ravi
2 Sai
3 Arun

• We can set INCREMENT BY value using


SEQUENCE. Whereas it is not possible
for "identity".
• You can start from any number using
"start with". Whereas it is not possible
using "identity".
• We can know current value in the
SEQUENCE using "CURRVAL". WHEREAS
it is not possible for "identity".
Oracle7AM Page 197
it is not possible for "identity".

Can we decrease the value in the


50
sequence?
49
Yes.
48
INCREMENT BY -1
.
.
CREATE SEQUENCE s11
1
START WITH 50
INCREMENT BY -1
MINVALUE 1
MAXVALUE 50;

Dropping sequence:

DROP sequence s11;

user_sequences:
It maintains information about the
user_tables
sequence.
user_views
user_constraints
user_sequences
SELECT sequence_name,
MIN_VALUE, MAX_VALUE,
INCREMENT_BY
FROM user_sequences;

Oracle7AM Page 198


Materialized View
Saturday, February 26, 2022 7:47 AM

View => Virtual Table


does not contain physical data
does not occupy the memory

PERSON
pid pname state aadhar

Display state wise no of people:

CREATE VIEW v1 state no_of_people


AS TS …
SELECT state, AP …
count(*) no_of_people MR …
FROM person
GROUP BY state;

SELECT * FROM v1; --several minutes => 30 minutes


SELECT * FROM v1;
SELECT * FROM v1;
SELECT * FROM v1;
SELECT * FROM v1;

Disadvantage of VIEW:
Less Performance

Materialized View:
• is a DB Object.
• It is not Virtual Table.
• It contains physical data. It occupies the memory.
• It is mainly used in DataWare Housing [DWH/OLAP] to
maintain summarized data physically.
• It holds precomputed result.
• Materialized view holds result of select query
physically. WHEREAS view holds SELECT query.
• Materialized view must be refreshed frequently to get
recent data.

LOG in AS DBA:

GRANT create materialized view


Syntax to create materialized view: TO c##batch7am;

CREATE MATERIALIZED VIEW <mview_name>


AS
<SELECT query>;

VIEW MATERIALIZED VIEW

emp emp
empno ename sal deptno empno ename sal deptno
Oracle7AM Page 199
emp emp
empno ename sal deptno empno ename sal deptno
1001 2000 10 1001 2000 10
1002 3000 10 1002 3000 10
1003 5000 20 1003 5000 20
1004 4000 20 1004 4000 20

deptno sum_of_Sal
10 5000
20 9000

CREATE MATERIALIZED VIEW mv1


CREATE VIEW v1
AS
AS
SELECT deptno,
SELECT deptno,
sum(sal) sum_of_sal
sum(sal) sum_of_sal
FROM emp
FROM emp
GROUP BY deptno;
GROUP BY deptno;
mv1
v1
SELECT deptno,
deptno sum_of_Sal
sum(sal) sum_of_sal
FROM emp 10 5000
GROUP BY deptno 20 9000

SELECT * FROM mv1; --calculates & stores in mview


SELECT * FROM v1;
SELECT * FROM mv1; --retrieves from mview
SELECT * FROM v1;
SELECT * FROM mv1; --retrieves from mview
SELECT * FROM v1;
SELECT * FROM mv1; --retrieves from mview
SELECT * FROM v1;
SELECT * FROM mv1; --retrieves from mview
SELECT * FROM v1;

5 times calculation
1 time calculation will be done
will be done

Performance will be degraded


Performance will be improved

emp
emp
empno ename sal deptno
empno ename sal deptno
1001 2000 10
1001 2000 10
1002 3000 10
1002 3000 10
1003 5000 20
1003 5000 20
1004 4000 20
1004 4000 20
1005 6000 10
1005 6000 10
1006 8000 20
1006 8000 20

SELECT * FROM v1; SELECT * FROM mv1;


Oracle7AM Page 200
1006 8000 20

SELECT * FROM v1; SELECT * FROM mv1;

deptno sum(sal) deptno sum_of_Sal


10 11000 10 5000
20 17000 20 9000
If we perform DML operations on
VIEW gives recent data base table, it gives wrong result

To avoid this problem, refresh the


materialized view frequently.

After refresh, we get


deptno sum(sal)
10 11000
20 17000

dbms_mview => package


exec dbms_mview.refresh('MV1'); refresh(…) => procedure
--code
package_name.procedure_name(args)

Advantages:
• improves the performance
• we can maintain local physical copy of remote
database.

Different ways of refreshing materialized view:


There are 3 ways to refresh the materialized view.
They are:
• On demand [Default]
• On commit
• On regular interval of time

• On demand [Default]:
• In this way, we call a procedure "refresh" which
is defined in "dbms_mview" package.

Create Materialized View mv2


Refresh On Demand
AS
SELECT deptno, sum(sal) sum_of_sal

Oracle7AM Page 201


SELECT deptno, sum(sal) sum_of_sal
FROM emp
GROUP BY deptno
ORDER BY 1;

INSERT INTO emp(empno,ename,sal,deptno)


values(5678,'AAA',4000,30);

COMMIT;

exec dbms_mview.refresh('mv2');

On Commit:
• When commit command is executed materialized
view will be refreshed.

CREATE MATERIALIZED VIEW mv3


refresh on commit
AS
Select deptno,count(*) from emp
GROUP BY deptno;

INSERT

COMMIT;
materialized view will be refreshed

On regular interval of time:


• Materialized view will be refreshed in a regular interval of
time.

CREATE MATERIALIZED VIEW mv4


REFRESH FORCE
START WITH sysdate NEXT sysdate+interval '2' minute
AS
SELECT deptno,count(*) from emp
group by deptno;

INSERT INTO emp(empno,ename,sal,deptno)


values(4567,'CC',3000,20);

Oracle7AM Page 202


Refresh Types:
3 refresh types:
• Complete
• Fast
• Force

SELECT * FROM mv1;

deptno sum_of_Sal
10 5000
20 9000

• Truncates complete info from materialized view.


• Runs select query which is associated with
materialized view.
• Result of SELECT query will be stored in
materialized view.

CREATE MATERIALIZED VIEW mv5


refresh complete
on commit
as
select deptno,sum(Sal) FROM emp
group by deptno;
FAST refresh:
• Recent changes of base table will be applied to
materialized view. FAST
emp => BASE TABLE SELECT * FROM mv1;
empno ename sal deptno
1001 2000 10 deptno sum_of_Sal
1002 3000 10 10 5000
1003 5000 20 20 9000
1004 4000 20
1005 8000 10
1006 5000 20

1005 8000 10
1006 5000 20

materialized view log

CREATE MATERIALIZED VIEW mv6


refresh fast
on commit
as
select deptno,sum(Sal) FROM emp
group by deptno;

ERROR: materialized view log file not available on emp

Oracle7AM Page 203


Note:
To create materialized view log file the base table must
have primary key column.

Log in as DBA:
username: system
password: nareshit

CREATE materialized view log on c##batch7am.emp;

COMPLETE truncates complete info from m.view. runs select


query. fills in m.vew
FAST the recent changes of base table will be applied to
m.view. recent changes are recorded in m.view log
file. If this log file not available it will be failed.
FORCE it will be done implicitly. Oracle gives first priority
for fast refresh. If materialized view log file is not
available, it gives priority for complete refresh. In
this refresh will not be failed.

Materialized view:
• Not a virtual table
• contains physical data
• occupy the memory

Refresh ways:
on demand => refresh procedure
on commit => after commit command
on reg int => for regular interval of time

Refresh Types:
Complete
Fast
Force

Enable Query Rewrite:

CREATE MATERIALIZED VIEW mv11


ENABLE QUERY REWRITE
AS
SELECT deptno,sum(sal) sum_of_sal
Oracle7AM Page 204
SELECT deptno,sum(sal) sum_of_sal
FROM emp
GROUP BY deptno;

Java Developer
---------------------
frequently he wants to work with
dept wise sum of salaries

SELECT deptno,sum(sal)
sum_of_sal
FROM emp
GROUP BY deptno;

=> Even if Java Developer submits


normal query, data will be retrieved
from materialized view. Because,
materialized view created using
the clause "Enable Query Rewrite".

When we create a materialized view using "ENABLE


QUERY REWRITE", always data will be retrieved
from materialized view even if we submit normal
query.

SQL> SET AUTOTRACE ON EXPLAIN

It displays execution plan

Dropping materialized view:

Drop materialized view mv11;

User_Mviews:
It maintains information about all
materialized views

SELECT MVIEW_NAME FROM


USER_MVIEWS;

Oracle7AM Page 205


Indexes
Thursday, March 3, 2022 7:55 AM

ORACLE BOOK => 200 PAGES

INDEX

DDL Commands 10
DML 20
FUNCTIONS 30
CLAUSES 40
JOINS 60
.. ..
..

Indexes:
• Index is a DB Object.
• Index is used to improve the performance of
Data Retrieval.
• In a BOOK, to refer particular chapter we use
INDEX for faster reference. Similarly, if index
is created on table data retrieval becomes
faster.
• BOOK INDEX
CHAPER_NAME PAGE_NUM
• ORACLE INDEX
DATA Row_ID
• Index is created on column / columns.
• We create the index on the columns which
we frequently use in WHERE clause or in
JOIN condition
Syntax:
CREATE INDEX <index_name>
ON <table_name>(<column>/<columns>);
Oracle7AM Page 206
Syntax:
CREATE INDEX <index_name>
ON <table_name>(<column>/<columns>);

Ex:
CREATE INDEX i1
ON emp(sal);

When we submit a query to ORACLE, it


performs any one of the 2 scans. They are:
• Table Scan
• Index Scan

Note:
Index Scan will be performed faster than
Table Scan.

Table Scan:
If 100 records are there, 100 comparisons will
be performed.

Index Scan:
If 100 records are there, maximum half of the
comparisons will be done. So, INDEX improves
the performance of data retrieval.

SET AUTOTRACE ON EXPLAIN

SELECT * FROM emp WHERE sal>3000; --Table Scan

CREATE INDEX i1 ON emp(sal);

SELECT * FROM emp WHERE sal>3000; --INDEX SCAN

SELECT * FROM emp WHERE sal<2000; --INDEX SCAN

Oracle7AM Page 207


Types of Indexes:

2 Types:

• B-Tree Index
○ Simple Index
○ Composite Index
○ Unique Index
○ Function-Based Index
• Bitmap Index

B-Tree Index:
• B-Tree => Balanced Tree
• In B-TREE Index, when index is created implicitly
one structure will be created. It is called
"Balanced Tree".
• Sub Types:
○ Simple Index
○ Composite Index
○ Unique Index
○ Function-Based Index

If value is < or equal to root node, place it at left side


If value is > root node, place it at right side
sal
-------
1000
1200
1800
2000
2000
2500
3000
Oracle7AM Page 208
2000
2500
3000
3500
3500
4000
4500
5000

Types of Indexes:

B-Tree Index / Normal Index


Simple Index
Composite Index
Unique Index
Function-Based Index
Bitmap Index

Simple Index:
If index is created on one column then it is called "Simple
Index".

Ex:
SELECT * FROM emp WHERE sal>2800; --Table Scan

CREATE INDEX i1 ON emp(sal);

SELECT * FROM emp WHERE sal>2800; --Index Scan

Composite Index:
If index is created on multiple columns then it is called "
Composite Index".

SELECT * FROM emp


WHERE deptno=20 and job='CLERK'; --Table Scan

CREATE INDEX i2 ON emp(deptno,job);

Oracle7AM Page 209


CREATE INDEX i2 ON emp(deptno,job);

Based on the first column in the list, B-Tree will be created

Before Oracle 9i:

SELECT * FROM emp


WHERE deptno=20 and job='CLERK'; --Index Scan

SELECT * FROM emp WHERE deptno=20; --Index Scan

SELECT * FROM emp WHERE job='CLERK'; --Table Scan

From Oracle 9i version onwards:

SELECT * FROM emp


WHERE deptno=20 and job='CLERK'; --Index Range Scan

SELECT * FROM emp WHERE deptno=20; --Index Range Scan

SELECT * FROM emp WHERE job='CLERK'; --Index Skip Scan

deptno job
10 manager
10 clerk
10 clerk
10 manager
20 clerk
20 manager
30 manager
30 clerk

Oracle7AM Page 210


Unique Index:
An index which is created on a column which is
having unique values is called "Unique Index".

We can maintain unique values in a column using 3


ways:
• Using PRIMARY KEY constraint
• Using UNIQUE constraint
• Using UNIQUE INDEX

Note:
If we apply primary key to a column, by default
index will be created for this column. This index
name is PK constraint's name.

Ex:
CREATE TABLE inddemo
(f1 number(4) primary key,
f2 varchar2(10) );

For f1 column, index will be created implicitly by


the oracle

maintaining unique values in a column without


using PK, Unique [use unique index]:

CREATE TABLE idemo


(
f1 number(4),
f2 varchar2(10)
);

CREATE UNIQUE INDEX i3 ON idemo(f1);

INSERT INTO idemo values(101,'A');

Oracle7AM Page 211


INSERT INTO idemo values(101,'A');

INSERT INTO idemo values(101,'A'); --ERROR

CREATE UNIQUE INDEX i4 ON dept(deptno);

Function-Based Index:
If index is created based on function or expression then it is
called "Function-Based Index".

EX:

SELECT * FROM emp WHERE ename='JAMES'; --table scan

CREATE INDEX i5 ON emp(ename);

SELECT * FROM emp WHERE ename='JAMES'; --index scan

SELECT * FROM emp WHERE lower(ename) = 'blake'; --table scan

CREATE INDEX i6 ON emp(lower(ename));

SELECT * FROM emp WHERE lower(ename) = 'blake'; --index scan

SELECT * FROM emp WHERE sal*12>30000; --table scan

CREATE INDEX i7 ON emp(sal*12);

SELECT * FROM emp WHERE sal*12>30000; --index scan

Oracle7AM Page 212


B-Tree Index:
• B-Tree will be created
• B-Tree index contains data & row ids

Bitmap Index:
• It stores bits i.e. 0s and 1s.
• Every bit will be associated with one ROW ID.
• This bit will be converted to ROW ID & picks the
record.
• Bitmap index is created on low cardinality
columns.

low cardinality column:


The column which is having less distinct values
Ex: deptno, gender
deptno
---------------
10 distinct values
10
30 deptno
20 -----------
30 10
20 20
20 30
20
10
10
30

gender
--------------
M
M
F
M
F
F

Oracle7AM Page 213


High cardinality column:
A column which is having more distinct values
Ex: empno, ename

empno
----------- distinct values
1001
1002 empno
1003 ---------
. 1001
. 1002
1010 .
.
1010

B-TREE index will be created on high


cardinality columns

Bitmap Index will be created on low


cardinality columns

bi1
std
M F
sid sname gender
0 1
F
1 0
M
1 0
M
0 1
F
1 0
M
0 1
F

SELECT * FROM emp


WHERE gender='M'; --table scan

CREATE BITMAP INDEX bi1


ON std(gender);
Oracle7AM Page 214
ON std(gender);

SELECT * FROM emp


WHERE gender='M'; --Bitmap index
scan

Differences b/w B-Tree Index & Bitmap Index:

B-Tree Index Bitmap Index

• B-Tree will be created • B-Tree will not be created

• contains data & row ids • contains bits [0s & 1s]. bit will
be converted to row id

• it is created on • it is created on low cardinality


high cardinality columns [deptno, gender]
columns
[empno,ename]

USER_INDEXES:
It maintains information about all
indexes.

SELECT index_name, index_type


FROM user_indexes;

Main goal of INDEX is,


Improving the performance of data retrieval.

In Bitmap Index, if 100 records are there 100


comparisons will be performed. Then how it
improves the performance?

Oracle7AM Page 215


Bit comparison is faster than value comparison.
So, it improves the performance.

Dropping Index:

Drop Index i1;

If we drop the table does it drop


the view?
No. But, view will not work until we
create table with this name.

If we drop the table does drop the


index?
Yes.

Oracle7AM Page 216


Synonyms
Saturday, March 5, 2022 7:26 AM

Synonym:
• is a DB Object.
• It is used to give alias name [alternative name] for
DB Object.
• Synonym is permanent whereas table alias and
column alias are temporary.

emp employee_salary_details
dept dept_location_details

SELECT * FROM employee_salary_details;

OWNER => c##batch7am


employee_salary_details
grant all on employee_salary_details to c##ramu;

Ramu:
SELECT * FROM c##batch7am.employee_salary_details;

SELECT ename,
sal salary,
sal*12 an_sal
FROM emp;

SELECT ename,salary FROM emp;


--ERROR

"salary" alias name can be used in


that query only. It means, column
Oracle7AM Page 217
that query only. It means, column
alias scope is limited to that query
only. It cannot be used in another
query.
Column alias is temporary.

Table alias is also temporary.

Synonym is permanent.

Advantages:
• It makes table name [db object name] short.
• It avoids of writing schema.
• It provides security.

Syntax:

CREATE SYNONYM <syn_name>


FOR <db_obj_name>;

Log in as DBA:
username: system
password: nareshit

GRANT create synonym TO c##batch7am;

Log in as c##batch7am:

Create a synonym for emp table as e:

CREATE SYNONYM e FOR emp;


Oracle7AM Page 218
CREATE SYNONYM e FOR emp;

GRANT all ON emp to c##ramu;

Log in as Ramu:
username: c##ramu
password: nareshit

SELECT * FROM c##batch7am.emp;

CREATE SYNONYM z FOR c##batch7am.emp;

SELECT * FROM z;

INSERT INTO z(empno,ename)


values(9001,'ABC');

Types of Synonyms:
There are 2 types of Synonyms. They are:
• Private Synonym
• Public Synonym

Private Synonym:
• It is created by the user.
• can be used by specific user [owner of synonym] only.

Public Synonym:
• It is created by the DBA.
• Any user can use this name if permission granted by
the DBA.
Oracle7AM Page 219
the DBA.

Ex:
Owner => c##batch7am
emp

GRANT permission to
c##oracle7am/c##oracle11am/c##oracle6pm

c##oracle7am:
SELECT * FROM c##batch7am.emp;
CREATE SYNONYM s1 for c##batch7am.emp;

c##oracle11am:
SELECT * FROM c##batch7am.emp;
CREATE SYNONYM s2 for c##batch7am.emp;

c##oracle6pm:
SELECT * FROM c##batch7am.emp;
CREATE SYNONYM s3 for c##batch7am.emp;

Number of synonyms will be increased. To reduce


number of synonyms create PUBLIC SYNONYM.

Log in as DBA:
username: system
password: nareshit

CREATE public synonym ps FOR c##batch7am.emp;


Oracle7AM Page 220
CREATE public synonym ps FOR c##batch7am.emp;

GRANT all ON ps
TO c##oracle7am,c##ramu,c##oracle6pm;

Dropping the synonym:

DROP SYNONYM e;

Dropping public synonym:

DROP PUBLIC SYNONYM ps;

USER_SYNONYMS:
It maintains information about all
synonyms

SELECT synonym_name FROM


user_synonyms;

ORACLE

• SQL
• PL/SQL

are 2 languages used to deal communicate the DB

Oracle7AM Page 221


SQL
5 sub languages
DDL, DML, DRL, DCL, TCL
Built-In Functions -
String, Conversion, Date, Miscellaneous
Clauses
SELECT, FROM, WHERE, GROUP BY, HAVING, DISTINCT
Joins
to retrieve data from multiple tables
Sub Queries
SET Operators

VIEWS
SEQUENCES
INDEXES
MATERIALIZED VIEW
SYNONYM

Oracle7AM Page 222

You might also like