0% found this document useful (0 votes)
13 views168 pages

Oracle 2 PMM

The document provides an overview of Oracle Database 19c, including installation resources, course links, and fundamental concepts of data, information, databases, and DBMS. It explains structured and unstructured data, the role of SQL and PL/SQL, and various data types in Oracle SQL. Additionally, it outlines the functions of DDL, DML, TCL, and DCL commands in managing databases.

Uploaded by

Blue Red
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views168 pages

Oracle 2 PMM

The document provides an overview of Oracle Database 19c, including installation resources, course links, and fundamental concepts of data, information, databases, and DBMS. It explains structured and unstructured data, the role of SQL and PL/SQL, and various data types in Oracle SQL. Additionally, it outlines the functions of DDL, DML, TCL, and DCL commands in managing databases.

Uploaded by

Blue Red
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 168

Thursday, October 13, 2022 12:44 PM

Admin:
Mobile: 91541 56192 (Only Whatsapp)

Notes link:
https://bit.ly/batch2pm

Oracle DB 19c installation process video link:


https://bit.ly/oracleinstall

ORACLE (SQL & PL/SQL) @ 2:00 PM by Mr. Shiva


Chaitanya
Day-1 https://youtu.be/ERr0cxACckQ
Day-2 https://youtu.be/0cBcBGzyHXs
Day-3 https://youtu.be/6OzIzl_SxwI
Day-4 https://youtu.be/-W32Xp6VQqk

Oracle2PM Page 1
ORACLE
Wednesday, October 12, 2022 2:24 PM

Data
Information
Database
DBMS
RDBMS
Metadata

Data:

People Places Things

1234 nareshit
Laptop
Ramu 4
Dell
B.Tech 2 class rooms
100000
67.8 200
Black

• Data is a raw collection of facts


about people, places, things …etc.

Data Information

25
sid sname marks
Ramu Data 25 Ramu 500
500 Processing

Micro processor
RAM
Mother Board Connecting Computer
Keyboard
Mouse
Monitor

Engine
Tyres
Connecting Bike
Break
body

Data:
• Data is a raw collection of facts about the
people, places, things ..etc
• It is unprocessed one.
• It is not in meaningful form
• we cannot make the decisions.

Types of Data:

2 Types:

• Structured Data
• Unstructured Data

Structured Data:
• If data is in the form of letters, digits and
symbols then it is called "Structured Data".

Ex:
1234
Kiran
H.NO.1-2-123/A/B

Unstructured Data:
• if data is in the form of images, audios,
videos, documents then it is called

Oracle2PM Page 2
videos, documents then it is called
"Unstructured Data".

Information:
• If data is arranged in meaningful form then it
is called "Information".
• It is processed one.
• It is in meaningful form.
• Using it, we can make the decisions.

Database:

Bank DB College DB amazon DB

Customers Student products


Transactions Marks customers
Staff Fee orders
Branches Staff suppliers
Products Library

• Database means,
complete details of an organization stored
in computer in meaningful format.

• Database is collection of interrelated data


in an organized form [in meaningful form].

Example:

College DB

STUDENT
sid sname scity mobile
1001 Ravi Hyd …

MARKS
sid M1 M2 M3
1001 70 60 80

Edit the photos => Photoshop


watching movies => media player

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

RDBMS:
• Relational DataBase Management System/Software.
• Relation => Table
• RDBMS is a software that is used to create & maintain
the database in the form of tables.

Ex:
ORACLE, SQL SERVER, My SQL, Postgre SQL, DB2

CUSTOMER => Table / Relation / Entity

cid cname ccity


1234 Arun Hyd row / record / tuple / entity instance
1235 Vijay Mumbai

Oracle2PM Page 3
CUSTOMER => Table / Relation / Entity

cid cname ccity


1234 Arun Hyd row / record / tuple / entity instance
1235 Vijay Mumbai
1236 Kiran Delhi Column / Attribute /
Property / Field

Table is a collection of rows & columns


field holds individual values
record a collection of field values

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

Examples:
field names => sid, sname, marks
table name => Marks_details
data types => Number, Varchar2, Date
field sizes => Number(4), Varchar2(10)

Marks_details
sid sname Marks
25 Ramu 500

ORACLE

• ORACLE is a Relational DataBase Management


Software. [RDBMS].
• Relation => Table
• It is used to create & maintain the database in the
form of tables.
• It allows us to store, manipulate & retrieve the data of
database.
• Manipulate => INSERT / UPDATE [modify] / DELETE
○ Ex:
emp joined => INSERT
emp got promotion => UPDATE
emp resigned => DELETE

customer opening account => insert


withdraw operation => Update balance
customer closing account => delete

• Retrieve => Opening existing data


○ Ex:
before 1960s => manually in books
▪ Check balance
Server 1960s => File Management System
ATM

1970s => Hierarchical DBMS


check balance Network DBMS

balance is:50000 1976 => E.F.Codd => RDBMS concept

Larry Ellison => Founder of Oracle


In 1977 => Software Development Laboratories
In 1979 => Relational Software Inc.
• ORACLE software is the product of "ORACLE" In 1983 => ORACLE carp.
company.
• ORACLE software 2nd version introduced in 1979.
• Latest version is: Oracle 21c.

Oracle2PM Page 4
ORACLE DB SERVER

SQL Database
PL/SQL Tables
rows & columns

To communicate with Oracle Database, we can


use 2 languages:
• SQL C, Java, python, C# => programming languages
• PL/SQL
used to develop the software.
SQL:
• SQL stands for "Structured Query Language". software => a set of programs
• SQL is a query language.
• It is used to write the queries.
• Query => is a request that is sent to Database withdraw program
Server. deposit program
check balance program
• SQL is a Non-procedural Language. It means, we
will not write any set of statements here. Just,
we write queries.
In C:
• SQL is a Unified Language. It means, it is
Function: a set of statements
common for many Relational DataBase
Management Softwares.
In Java:
Method: a set of statements

ORACLE SQL SERVER MY SQL In PL/SQL:


Database database database Procedure => is a set of statements

SQL SQL SQL

• SQL is 4GL [4th generation language].


4GLs provide readymade commands & functions.

• SQL provides operators to perform operations.

• SQL provides built-in functions.


Function => Task / Action / Job
Every function performs particular task.
To make our tasks easier SQL provides built-in
functions.

• SQL provides Joins concept to retrieve the data


from multiple tables.

STUDENT MARKS

sid sname scity sid math phy che

sid sname math


STUDENT MARKS

• SQL provides 5 sub languages. They are:

DDL CREATE
Data Definition Language ALTER

It deals with metadata DROP


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

TRUNCATE
RENAME

DRL / DQL SELECT


Data Retrieval Language
Data Query Language

It deals with data retrievals.

DML INSERT
Data Manipulation Language UPDATE
DELETE

Oracle2PM Page 5
DELETE
It deals with data
manipulations INSERT ALL [Oracle 9i]
MERGE [Oracle 9i]

TCL COMMIT
Transaction Control language ROLLBACK
SAVEPOINT
It deals with transactions

DCL / ACL GRANT


Data Control Language / REVOKE
Accessing Control Language

It deals with Data Accessibility

DDL commands:

• DDL stands for Data Definition Language.


• It deals with metadata.

Following commands are comes under DDL commands:


• CREATE
• ALTER
• DROP
• FLASHBACK
• PURGE
• TRUNCATE
• RENAME

CREATE:
CREATE command is used to create the database objects like tables, Database Objects:
views, indexes …etc. Tables
< > Any Views
Syntax to create a table: [ ] Optional Indexes
Sequences
CREATE TABLE <table_name> Synonyms
( Materialized views
<field_name> <data_type> [constraint <con_name> <con_type>, procedures
<field_name> <data_type> constraint <con_name> <con_type>, functions
. packages
.] triggers
);

Field Definition:
<field_name> <data_type> [constraint <con_name> <con_type>]
Data Types in SQL:
CREATE TABLE customer
• Data Type tells which type of data that (
column has to accept. cid NUMBER(4)
DOB DATE
ORACLE SQL provides following data types: );

cid DOB
Number Related Number(p)
Int 1234 25-DEC-1990
Integer
Ex: 56 78 1234 5678 45678
567A$
Number(p,s)
Float
Binary_Float
Binary_Double
Ex: 56.78 123.45678

Character Related Char(n)


Varchar2(n)
Long
CLOB

nChar(n)
nVarchar2(n)
nCLOB

n => national

Date & Time Related Date


Timestamp

Binary Related BFILE


BLOB

Oracle2PM Page 6
Number related Data Types:

Number(p):
• It is used to hold integers.
• p => precision => max no of digits
• p => range => 1 TO 38
• Number(2) => -99 TO 99
• Number(38) => -9999..999 38digits TO 999..99 38dgits

empno NUMBER(4) => -9999 TO 9999


------------
1001
1002
1003
1004
8769
12345 => ERROR: precision => 4

Max marks: 100

Marks Number(3) => -999 TO 999


-----------
78
55
567
4567 => ERROR: precision=> 3

Age Number(2) => -99 TO 99


------
17
23
21
25
99
100 => ERROR: pecision => 2

Aadhar_Num NUMBER(12)
Creditcard_num NUMBER(16)

Mobile_num NUMBER(10)

Number(p,s):
• It is used to floating point data.
• p => precision => max no of digits
• s => scale => no of decimal places
• p => range => 1 to 38
• s => range => -84 to 127

100000.00

salary NUMBER(8,2) -999999.99 TO 999999.99


------------
15000.00
25000.00
18000.00

100.00

avrg NUMBER(5,2) => -999.99 TO 999.99


--------
78.69
45.64
82.71

Height Number(2,1) => -9.9 TO 9.9


-------------
5.2
5.4
5.0

Oracle2PM Page 7
5.0

Character Related data types:

ename PAN_CARD_NUM
----------- ------------------------
Ravi ABCDE12345
Kiran
sai
Amar

HNO
----------
1-2-123/A/B

Demo
f1 Char(10) f2 Varchar2(10)
Ravi6spaces Ravi
Sai7spaces Sai
Ramesh4spaces Ramesh

Char(n):
• Used to hold string values. string is a group of chars.
• n => max no of chars
• It is Fixed Length Data Type
• max size is: 2000 bytes
• Default size: 1

Varchar2(n):
• Used to hold string values.
• n => max no of chars
• It is Variable Length Data Type
• max size is: 4000 bytes
• Default size: No default size. WE must specify the size.

State_Code Char(2) ename Varchar2(10)


------------------ ---------------
TS Ravi
AP Vijay
WB Sai
MH Naresh

PAN_CARD_NUM Char(10) Product_name varchar2(15)


--------------------------- ------------------------
ABCDE12345 laptop
mouse
keyboard
Vehicle_Num Char(10) mother board
-----------------------
TS01AA1234

Why varchar2?

• In first 6 versions varchar data type was


available maths_marks NUMBER(3)
• E.F.Codd 12 rules. Any RDBMS must follow these -----------------------
12 rules. Otherwise we may get problems. 78
• One of the rules is: there should be difference 0
between space and null char, 0 and null
• Ex: ' ' , ''
• Varchar was not differentiating space and null.
That'swhy they introduced Varchar2 data type in
ORACLE7 version.
• In Latest versions Varchar(), Varchar2() both data
types acts as same.

Oracle2PM Page 8
Varchar => ORACLE 2 TO 6

Varchar2 => ORACLE 7 version

LONG:
• It is used to hold string values.
• It is used to hold large amounts of chars.
• Max size: 2GB
• It has some restrictions:
○ In one table we can create only one column as
LONG type.
○ we cannot use built-in functions on LONG type

CLOB:
• CLOB stands for Character Large Object.
• It is used to hold string values.
• It is mainly used to hold large amounts of chars.

Ex:

product_features CLOB
-----------------------------

Experience_Summary CLOB
----------------------------------

Feedback CLOB
------------------

Character Related

Char(n) Single Byte Data Types


Varchar2(n) ASCII code data types In C:
LONG English only • char => 1 Byte
CLOB • supports ASCII coding system
• ASCII => 256 chars => 0 to 255
nChar(n) Multi Byte data types • 255 => 1111 1111
nVarchar2(n) UNI code data types • supports to ENGLISH language only.
nCLOB English + other lang chars
In Java:
n => national • char => 2 bytes
• supports to UNI coding system
• UNI => 65536 chars => 0 to 65535
• supports to ENGLISH language + other language chars

1000

sid sname gender marks avrg 100.00


1001 Ravi M 678 68.79

sid Number(4)
sname Varchar2(10)
gender Char
marks Number(4)
avrg Number(5,2)

Date & Time Related data types:

Date:
• It is used to hold date values.
• It can hold time values also.
• It can hold date, month, year, hours, minutes and
seconds.
• Default oracle date format is: DD-MON-RR
• Default time value is: 12.00.00 AM [midnight time]
• It is Fixed length data type.
• size is: 7 bytes
• To insert a date value, use to_date() function.
to_date() function converts string to date.

Oracle2PM Page 9
to_date() function converts string to date.
• It cannot hold fractional seconds.

Example:

Date_of_Joining
------------------------
23-OCT-2018
17-SEP-2020

CREATE TABLE datedemo(f1 date);

Table created.

INSERT INTO datedemo


2 VALUES('25-dec-2019');

1 row created.

INSERT INTO datedemo


2 VALUES(to_date('18-jul-2018'));

Timestamp:
• It is used to hold date & time values.
• It is introduced in Oracle 9i version.
• It can hold date, month, year, hours, minutes,
seconds & fractional seconds.
• It is extension of Date data type.
• It is fixed length data type.
• size is: 11 bytes

Date Timestamp

It cannot hold fractional It can hold fractional seconds


seconds

7 bytes 11 bytes

cannot display time value can display time value by


by default default

to hold date value use to hold date & time use


date type timestamp type

Binary Related:
Binary related data types are used to deal with
unstructured data [audios, videos, documents].

There are 2 binary related data types:


• BFILE
• BLOB

BFILE:
• BFILE stands for Binary File Large Object type.
• max size: 4GB
• It is used to maintain multimedia objects like
audios, videos, animations, documents …etc.
BFILE is a pointer to multimedia object.

Oracle2PM Page 10
• BFILE is a pointer to multimedia object.
• It is not secured one.

employee
empno ename ephoto BFILE
D: drive
1234 Ravi D:\emps\ravi.jpg
emps
ravi.jpg

Database

BLOB:
• BLOB stands for Binary Large Object type.
• max size: 4GB
• It is used to maintain multimedia objects like
audios, videos, animations, documents …etc.
• it is used to main multimedia objects inside of
database.
• It is secured one.

Ex:

employee d: drive
ellison.jpg
empno ename ephoto BLOB
1001 ellison 17623AEF23768ABCD

Database

Opening SQLPLUS:

After installing oracle,

Windows +R => sqlplus => OK

For DBA, user name: system


password: at the time oracle installation you
give a password. i.e. DBA password

Creating User:

Log in as DBA:

username: system
password: nareshit

Syntax to create the user:

CREATE USER <user_name>


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

Tablespace:
File in which oracle database will
be stored.

Example: ramu local user


c##ramu common user
CREATE USER c##oracle2pm
IDENTIFIED BY naresh
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO c##oracle2pm;

connect permission for log in


resource permission for creating table

Changing the password of DBA:

Oracle2PM Page 11
user name: sys as sysdba
password:
[don't enter any password]

SQL> ALTER USER system


IDENTIFIED BY <new_password>;

Changing password of user:

username: system
password: nareshit

ALTER USER c##oracle2pm


IDENTIFIED BY nareshit;

Examples on creating tables:

STUDENT

sid sname m1
1001 Ramu 67 100
1002 Vijay 56

sid Number(4)
sname Varchar2(10)
m1 Number(3)

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10),
m1 NUMBER(3)
);

Output:
Table created.

Syntax of INSERT command:

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


VALUES(<value_list>);

1001 Ramu 67

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

Output:
1 row created.

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

Output:
1 row created.

Inserting records using parameters:

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

Output:
enter value for sid:1003
enter value for sname:ravi
enter value for m1: 66

INSERT INTO student VALUES(1003,'ravi',66);

1 row created.

/ / (or) run it runs recent command


enter value for sid:1004
enter value for sname:arun
enter value for m1: 82

/
enter value for sid:1005
enter value for sname:..
enter value for m1: ..

Oracle2PM Page 12
enter value for m1: ..

to save table data:

COMMIT;

to see table data:

SELECT * FROM student;

to see table structure:

DESC / DESCRIBE:
it is used to see table structure

user_tables:
It maintains all tables information

to see the tables list created by user:

SELECT table_name FROM user_tables;

Output:

TABLE_NAME
--------------------------------------------------------------------------------
T1
STUDENT

Inserting limited column values:

sid sname m1
2001 Kiran

INSERT INTO student VALUES(2001,'Kiran');


ERROR: not enough values

INSERT INTO student(sid,sname)


VALUES(2001,'Kiran');

inserting limited column values by changing


order:

INSERT INTO student(sname,sid)


VALUES('Naresh',2002);

Example-2:

EMPLOYEE

empno ename gender sal DOJ


5001 AAA M 6000 25-dec-2019

empno number(4) 100000.00


ename varchar2(10)
gender char
sal Number(8,2)
DOJ date

CREATE TABLE employee


(
empno NUMBER(4),
ename VARCHAR2(10),
gender CHAR,
sal NUMBER(8,2),
doj DATE
);

INSERT INTO employee


VALUES(5001,'AAA','M',6000,'23-DEC-2019');

Oracle2PM Page 13
INSERT INTO employee
VALUES(5001,'AAA','M',6000,'23-DEC-2019');

INSERT INTO employee


VALUES(5002,'BBB','M',8000,to_date('17-jul-2020'));

Syntax to create a table:

CREATE TABLE <table_name>


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

Constraints: max marks: 100


• Constraint => restrict (or) control STUDENT
• Constraint is a rule that is applied on column. 0 TO 100
• It is used to restrict the user from entering sid sname maths
invalid data.
1 AA 78
• We can maintain accurate & quality data.
2 BB 55
• It is used to maintain "Data Integrity"
Feature. 3 CC 685
• Data Integrity means, maintaining accurate &
quality data.

ORACLE SQL provides following constraints:


gender
• Primary Key
-------------
• Not Null
M
• Unique
F
• Check
F
• Default
M
• References [Foreign Key]
F
Z => ERROR

Primary Key:

• It does not accept duplicate values.


• It does not accept null values.

Example:

EMPLOYEE

Empno Ename Job Sal


1001 Ramu clerk 5000
1002 Vijay manager 6000
1003 Sai manager 5000
1004 Ramu salesman 6000
Arun clerk 9000
1001 Sravan clerk 8000

CREATE TABLE t1
(
f1 NUMBER(4) Primary Key
);

INSERT INTO t1 VALUES(1);


INSERT INTO t1 VALUES(2);

INSERT INTO t1 VALUES(1);


ERROR: unique constraint violated

INSERT INTO t1 VALUES(null);


ERROR: cannot insert null into t1.f1

Not Null:

Oracle2PM Page 14
Not Null:
• It does not accept NULL values.
• It accepts DUPLICATE values.
• It demands for the value.

EXAMPLE:
CUSTOMER
NOT NULL
cid cname ccity
1001 Ramu Hyd
1002 Sai Mumbai
1003 Hyd
1004 Ramu Pune

CREATE TABLE t2
(
f1 VARCHAR2(10) NOT NULL
);

INSERT INTO t2 VALUES('ramu');


INSERT INTO t2 VALUES('ramu');

INSERT INTO t2 VALUES(null);


ERROR: cannot insert null into c##oracle2pm.t2.f1

UNIQUE:
• It does not accept duplicate values.
• It accepts null values. gmail account

Example:

CUSTOMER [email protected]

[email protected]
cid cname mail_id
1001 ravi [email protected]
1002 kiran
1003 sai [email protected]

Ex:

CREATE TABLE t3
(
f1 NUMBER(4) UNIQUE
);

INSERT INTO t3 VALUES(1);

INSERT INTO t3 VALUES(1);


ERROR: unique constraint violated

INSERT INTO t3 VALUES(null);

CONSTRAINT DUPLICATE NULL


Primary Key NO NO
Not Null YES NO
Unique NO YES

Primary Key = Unique + Not Null

empno ename sal >5000


CHECK:
1001 AA 8000
• It is used to apply our own conditions
1002 BB 4000
on a column

password
CREATE TABLE t4
---------------
(
abcdefghij
f1 NUMBER(3) CHECK(f1>=0 AND f1<=100)
ravi1234
);
ravi

INSERT INTO t4 VALUES(56);

INSERT INTO t4 VALUES(123);

Oracle2PM Page 15
INSERT INTO t4 VALUES(123);
--ERROR: check constraint violated

Default:

• It is used to apply default value to a column

Example:

STUDENT

sid sname cname ccity fee


1001 A Naresh Hyd 15000
1002 B Naresh Hyd 15000
1003 C Naresh Hyd 10000

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

15000.00
CREATE TABLE t5
(
f1 NUMBER(4),
f2 NUMBER(7,2) DEFAULT 15000
);

INSERT INTO t5 VALUES(5001);


ERROR: not enough values

INSERT INTO t5(f1) VALUES(5001);

INSERT INTO t5(f1) VALUES(5002);

INSERT INTO t5 VALUES(5003,10000);

REFERENCES [FOREIGN KEY]:

• Foreign Key accepts Primary Key values of


another table.

Ex:

COURSE STUDENT

cid cname sid sname cid


10 JAVA 2001 AA 30
20 PYHTON 2002 BB 10
30 C# 2003 CC 80
40 HTML 2004 DD 30
2005 EE

Example:

CREATE TABLE t6
(
f1 NUMBER(4) PRIMARY KEY
);

CREATE TABLE t7
(
f2 NUMBER(4) REFERENCES t6(f1)
);

INSERT INTO t6 VALUES(1001);


INSERT INTO t6 VALUES(1002);
INSERT INTO t6 VALUES(1003);
COMMIT;

INSERT INTO t7 VALUES(1003);


INSERT INTO t7 VALUES(1001);

INSERT INTO t7 VALUES(1234);

Oracle2PM Page 16
INSERT INTO t7 VALUES(1234);
ERROR: integrity constraint violated

Examples On Constraints:
100000.00
EMPLOYEE1

empno ename salary 5000 or more


5001 Ravi 8000
5002 Sai 4000

empno number(4) primary key


ename varchar2(10) not null
salary number(8,2) check => 5000 or more

CREATE TABLE employee1


(
empno NUMBER(4) PRIMARY KEY,
ename VARCHAR2(10) NOT NULL,
salary NUMBER(8,2) CHECK(salary>=5000)
);

Output:
Table created.

INSERT INTO employee1 VALUES(5001,'Ravi',8000);

INSERT INTO employee1 VALUES(5001,'Sai',9000);


ERROR: unique constraint violated

INSERT INTO employee1 VALUES(null,'Kiran',15000);


ERROR: cannot insert null into employee1.empno

INSERT INTO employee1 VALUES(6001,'Kiran',15000);

INSERT INTO employee1 VALUES(6002,'Charan',3000);


ERROR: check constraint violated

INSERT INTO employee1 VALUES(6003,null,7000);


ERROR: cannot insert null into employee1. ename

INSERT INTO employee1 VALUES(7001,'Kiran',17000);

Example-2:

users_list

uname pwd
raju kumar1234
vijay vijay1

uname varchar2(10) primary key


pwd varchar2(15) check => length 8 or more

CREATE TABLE users_list


(
uname VARCHAR2(10) PRIMARY KEY,
pwd VARCHAR2(15) CHECK(length(pwd)>=8)
);

INSERT INTO users_list VALUES('raju','kumar1234');

INSERT INTO users_list VALUES('vijay','vijay1');


ERROR:check constraint violated

INSERT INTO users_list VALUES('raju','abcdefgh');


ERROR: unique constraint violated

INSERT INTO users_list VALUES(null,'abcdefgh');


ERROR: cannot insert null

Oracle2PM Page 17
Example:

STUDENT2

sid sname cname ccity fee


1001 A Naresh Hyd 15000
1002 B Naresh Hyd 15000
C Naresh Hyd 15000

sid NUMBER(4) Unique


sname VARCHAR2(10)
cname VARCHAR2(6) default 'Naresh'
ccity VARCHAR2(3) default 'Hyd'
fee Number(7,2) default 15000

CREATE TABLE student2


(
sid NUMBER(4) UNIQUE,
sname VARCHAR2(10),
cname VARCHAR2(6) DEFAULT 'Naresh',
ccity VARCHAR2(3) DEFAULT 'Hyd',
fee NUMBER(7,2) DEFAULT 15000
);

INSERT INTO student2 VALUES(1001,'A');


ERROR: not enogh values

INSERT INTO student2(sid,sname) VALUES(1001,'A');

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

INSERT INTO student2(sid,sname) VALUES(null,'C');

INSERT INTO student2(sid,sname) VALUES(1001,'D');


ERROR: unique constraint violated

SELECT * FROM student2;

INSERT INTO student2(sid,sname,fee) VALUES(1005,'E',10000);

NOTE:
In default column,
If we don't pass the value, it takes default value.
If we pass the value, it takes that value

Example:

COURSE5 STUDENT5

cid cname sid sname cid


10 JAVA 5001 A 30
20 C# 5002 B 30
30 PYTHON 5003 C 10
40 ORACLE 5004 D 80

COURSE5

cid NUMBER(2) PRIMARY KEY


cname VARCHAR2(10)

CREATE TABLE course5


(
cid NUMBER(2) PRIMARY KEY,
cname VARCHAR2(10)
);

CREATE TABLE student5


(
sid NUMBER(4),
sname VARCHAR2(10),
cid NUMBER(2) REFERENCES COURSE5(cid)
);

Oracle2PM Page 18
);

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


INSERT INTO course5 VALUES(20,'PYTHON');
INSERT INTO course5 VALUES(30,'ORACLE');
COMMIT;

INSERT INTO student5 VALUES(1,'A',30);


INSERT INTO student5 VALUES(2,'B',30);

INSERT INTO student5 VALUES(3,'C',10);

INSERT INTO student5 VALUES(4,'D',80);


ERROR: integrity constraint violated

Assignment:

DEPT EMP

deptno dname empno ename deptno


10 ACCOUNTS 1001 A 30
20 SALES 1002 B 20
30 RESEARCH 1003 C 20
1004 D 70

deptno NUMBER(2) REFERENCES DEPT(deptno)

Syntax to create a table:

CREATE TABLE <table_name>


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

Naming Constraints:

• We can give names to the constraints.


• When we define a column with constraint, its better to
give a constraint name. If we don't give constraint
EMPLOYEE
name, oracle defines the constraint name.
• oracle defined is:
PK
a 6 digit random number will be prefixed with sys_c
EMPNO ENAME JOB
Ex: sys_c004567
1001 A CLERK
• Constraint name is useful when we disable or enable or B MANAGER
drop the constraints.

Example on creating tables with constraint names:

STUDENT6

sid sname M1
1001 Ramu 78

field datatype constraint type con name


sid NUMBER(4) PRIMARY KEY c1
sname VARCHAR2(10) NOT NULL c2
m1 NUMBER(3) CHECK => 0 to 100 c3

CREATE TABLE student6


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

INSERT INTO student6 VALUES(1001,'A',123);


ERROR: check constraint (c##oracle2pm.c3) violated

Oracle2PM Page 19
INSERT INTO student6 VALUES(1001,'A',78);

user_tables:
It maintains all tables information which are created by the
user.

DESC user_tables;

SELECT table_name FROM user_tables;

user_constraints:
It maintains all constraints information which are created by
the user

DESC user_constraints;

SELECT constraint_name, constraint_type, table_name


FROm user_constraints;

DDL commands:

CREATE
ALTER

ALTER:
2 columns
• ALTER => change
• Using ALTER command we can EMPLOYEE
change the structure of table.
• Using ALTER command we can: empno ename gender sal DOB
○ add the columns
○ rename the columns
○ drop the columns
○ modify the field sizes
○ modify the data types
○ add the constraints
○ rename the constraints
○ disable the constraints
○ enable the constraints
○ drop the constraints

Syntax:

ALTER TABLE <table_name> [ADD(<field_definitions>)]


[MODIFY(<field_Definitions>)]
[RENAME COLUMN <old_name> TO <new_name>]
[DROP COLUMN <column_name>]
[DROP(<column_list>)]
[ADD CONSTRAINT <con_name> <con_type>(<Column>)]
[DISABLE CONSTRAINT <con_name>]
[ENABLE CONSTRAINT <con_name>]
[RENAME CONSTRAINT <old_name> TO <new_name>]
[DROP CONSTRAINT <con_name>];

Example:

STUDENT

sid sname

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10)
);

Output:
Table created.

DESC student;

Oracle2PM Page 20
Output:
sid
sname

Adding a Column [add m1 column]:

ALTER TABLE student ADD m1 NUMBER(3);

Output:
Table Altered.

Adding multiple columns [m2, m3 columns]:

ALTER TABLE student


ADD(m2 NUMBER(3), m3 NUMBER(3));

Renaming a column [m3 to maths]:

ALTER TABLE student RENAME COLUMN m3 TO maths;

Dropping a column [drop maths column]:

ALTER TABLE student DROP COLUMN maths;


(or)
ALTER TABLE student DROP(maths);

Dropping multiple columns [m1 & m2 columns]:

ALTER TABLE student DROP(m1,m2);

Modifying field size [varchar2(10) to varchar2(20)]:

ALTER TABLE student MODIFY sname varchar2(20);

Can we decrease field size?


Yes. But, we can decrease up to max string length in
column.

sname
------------
arun
sai
vijay
ramesh

Modifying data types:

NOTE:
To modify the data type column must be empty.

STUDENT

sid NUMBER(4)

HYD_1001
MUM_5001
PUN_4005

ALTER TABLE student MODIFY(sid VARCHAR2(10));

ALTER TABLE student MODIFY(sid NUMBER(4));

Adding Constraint [Add PK to sid]:

ALTER TABLE student


ADD CONSTRAINT cc1 PRIMARY KEY(sid);

Disabling Constraint [disable cc1]:

Oracle2PM Page 21
Disabling Constraint [disable cc1]:

ALTER TABLE student DISABLE CONSTRAINT cc1;

Enabling Constraint [enable cc1]:

ALTER TABLE student ENABLE CONSTRAINT cc1;

Renaming Constraint [cc1 to xyz]:

ALTER TABLE student


RENAME CONSTRAINT cc1 TO xyz;

Dropping Constraint [drop constraint xyz]:

ALTER TABLE student DROP CONSTRAINT xyz;

DDL:

CREATE used create the table


ALTER used to change structure of table

DML
INSERT used to insert the records

DDL Commands:

CREATE
ALTER

DROP
FLASHBACK [oracle 10g]
PURGE [oracle 10g]

TRUNCATE
RENAME

DROP emp recyclebin [oracle 10g]


FLASHBACK
PURGE

DROP:

DROP command is used to drop the tables.

Syntax:

DROP TABLE <table_name> [PURGE];

DROP TABLE student;

when table is dropped, it will pe placed in


recyclebin.

FLASHBACK:

• used to restore the dropped table from recyclebin.

Syntax:

FLASHBACK TABLE <table_name>


TO BEFORE DROP
[RENAME TO <new_name>];

Ex:
FLASHBACK TABLE student

Oracle2PM Page 22
FLASHBACK TABLE student
TO BEFORE DROP;

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

Syntax:

PURGE TABLE <table_name>;

Ex:
PURGE TABLE student;

Emptying recyclebin:

PURGE recyclebin;

TO see recyclebin:

SHOW recyclebin;

Deleting a table permanent:

DROP TABLE student;


PURGE TABLE student; (or) DROP TABLE student PURGE;

Example:

create table student


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

insert into student values(1,'A');


insert into student values(2,'B');
insert into student values(3,'C');
COMMIT;

DROP TABLE student; --recyclebin


recyclebin
show recyclebin;
student

CREATE TABLE student


(
sid number(4)
ORACLE DB
);
insert into student values(1001); c##oracle2pm
COMMIT; student

FLASHBACK TABLE student


TO BEFORE DROP;
ERROR:

FLASHBACK TABLE student


TO BEFORE DROP
RENAME TO student_old;

TRUNCATE:
• used to delete complete information from the table
with auto commit.
it deletes table data. It does not delete table

Oracle2PM Page 23
• it deletes table data. It does not delete table
structure

Syntax:

TRUNCATE TABLE <table_name>;

Ex:
TRUNCATE TABLE student;
STUDENT

sid sname
1 A
2 B
3 C

TABLE = structure + data

RENAME:

used to rename the table.

Syntax:

RENAME <old_name> TO <new_name>;

Ex:
RENAME student TO std;

CREATE used to create the table


ALTER to change structure of table
DROP to drop the table
dropped table goes to recyclebin
FLASHBACK to restore dropped table from recyclebin
PURGE to delete from recyclebin
TRUNCATE to delete all rows from the table
RENAME to rename the table

DRL / DQL:
• DRL => Data Retrieval Language
• DQL => Data Query Language
• Retrieval => opening existing data
○ Ex: checking balance, online shopping
• Query => is a request that is sent to DB
server.
• DRL deals with data retrievals.
• SQL provides only one DRL command i.e:
○ SELECT

Syntax:

SELECT [DISTINCT/ALL] <column_list / *>


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

ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES

Clause => is a part of query

Oracle2PM Page 24
Using SELECT command we can
retrieve:
• Limited Columns
• All Columns
• Limited Rows
• All Rows

Retrieving Limited Columns:

Display the empnames and salaries of all emps:

SELECT ename, sal


FROM emp;

FROM used to specify the table names


Ex: FROM emp
WHERE used to write the conditions on rows
Ex: WHERE sal>=2500
SELECT used to specify the column list
Ex: SELECT ename,sal

Retrieving limited rows and columns:

Display the emp records whose salary is 2500 or more:

emp
empno ename job sal
1001 A clerk 3000
1002 B salesman 1500
1003 C manager 5000
1004 D clerk 2000

SELECT ename,sal
FROM emp
WHERE sal>=2500;

FROM emp:
entire table will be selected

empno ename job sal


1001 A clerk 3000
1002 B salesman 1500
1003 C manager 5000
1004 D clerk 2000

WHERE sal>=2500:

empno ename job sal


1001 A clerk 3000
1002 B salesman 1500
1003 C manager 5000
1004 D clerk 2000

empno ename job sal


1001 A clerk 3000
1003 C manager 5000

WHERE clause condition will be applied on every row.


It filters the rows.

SELECT ename,sal:

empno ename job sal ename sal


1001 A clerk 3000 A 3000
1003 C manager 5000 C 5000

SELECT clause selects the columns specified in the list

Retrieving all columns & all rows:

Oracle2PM Page 25
Retrieving all columns & all rows:

SELECT * FROM emp;

* All Columns

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

ORACLE replaces * with all column names

Operators in SQL:

OPERATOR:
• Operator is a symbol that is used to perform operations like
arithmetic or logical operations.

SQL provides following operators:

Arithmetic + - * /

Relational / Comparison < <= > >= = != / <> / ^=

Logical AND OR NOT

Special / Comparison IN NOT IN


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

SET UNION
UNION ALL
INTERSECT
MINUS

Concatenation ||

in c/java => % => modulus => remainder => 5%2 = 1

Calculate 20+40: in SQL => mod() function => mod(5,2) = 1

SELECT 20+40 FROM dual; in c/java => int/int = int => 5/2 = 2

20+40 in SQL => 5/2 = 2.5


----------
60

SELECT 20+40 AS total FROM dual;

TOTAL
---------
60

SELECT 20+40 AS "total" FROM dual;

total
----------
60

SELECT 20+40 AS "ToTal" FROM dual;

ToTal
----------
60

SELECT 20+40 AS total FROM dual;

TOTAL
---------
60

SELECT 20+40 total FROM dual;

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

SELECT 20+40 as total marks FROM dual;

ERROR: space

Oracle2PM Page 26
ERROR: space

SELECT 20+40 as "total marks" FROM dual;

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

Column Alias:
• Alias name => alternative name (or) another name
• "AS" keyword is used to give column alias. Using
this keyword is optional.
• Column alias is temporary. Its scope is limited to
the query only. It cannot be used in another query.
• To maintain the case or to give alias name in
multiple words specify alias name in double quotes.

DUAL:
• DUAL is a system table / built-in table /
predefined table.
• In "sys" schema [user] DUAL table is created.
• There are 1 row & 1 column in DUAL table.

DUAL
DUMMY
X

• to get result only once we use the system table


"dual".
• it is used to work with non-db values.

SELECT 20+40 FROM emp;

-- emp table has 14 rows


--14 60s will be returned
--for every row 20+40 will be calculated

to calculate it only once, we use DUAL

SELECT 20+40 FROM dual;

20+40
------------
60

because of DUAL table has 1 row, one time it


is calculating 20+40.

Examples on Arithmetic operators:

Calculate Annual Salary:

SELECT empno, ename, sal,


sal*12 AS "annual salary"
FROM emp;

Calculate TA, HRA & Gross salary of all emps:


10% on sal => TA
20% on sal => HRA
GROSS => sal + TA + HRA

SELECT empno,ename,sal,
sal*0.1 AS TA,
sal*0.2 AS HRA,
sal+sal*0.1+sal*0.2 AS GROSS
FROM emp;

Example:

STUDENT

sid sname m1 m2 m3
1001 A 50 80 70
1002 B 50 30 90

Oracle2PM Page 27
1002 B 50 30 90

calculate total & average marks:

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10),
m1 NUMBER(3),
m2 NUMBER(3),
m3 NUMBER(3)
);

INSERT INTO student


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

INSERT INTO student


VALUES(1002,'B',50,30,90);

COMMIT;

SELECT sid,sname,m1,m2,m3,
m1+m2+m3 AS TOTAL,
(m1+m2+m3)/3 AS AVRG
FROM student;

Relational Operators [Comparison Operators]:

Relational Operators are used to compare 2


values.

SQL provides following relational operators:

< less than


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

Examples on Relational Operators:

Display the emp records whose salary is 1600


or more:

SELECT empno,ename,sal
FROM emp
WHERE sal>=1600;

Display the emp records whose salary is less


than 1250:

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

Display the emp records who joined after 1981:

1 2020 calendar
2
3 1-jan-2020
4 2-jan-2020
5 3-jan-2020
. 4-jan-2020
. .
10 .
31-dec-2020
1-jan-2021
2-jan-2021

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate>'31-DEC-1981';

Display the emp records who joined before 1981:

Oracle2PM Page 28
Display the emp records who joined before 1981:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate<'1-jan-1981';

Display the emp record whose empno is 7521:

SELECT * FROM emp


WHERE empno=7521;

Display all managers records:

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

no rows selected

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

Ex:
'MANAGER' = 'MANAGER' TRUE
'MANAGER' = 'manager' FALSE

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

Display all emps records except managers:

SELECT empno,ename,job
FROM emp
WHERE job!='MANAGER';
(or)
SELECT empno,ename,job
FROM emp
WHERE job<>'MANAGER';
(or)
SELECT empno,ename,job
FROM emp
WHERE job^='MANAGER';

Display the emp records who are working in deptno 20:

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

Display the emp records who are not working in deptno


20:

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

Logical Operators:

Logical operators are used to perform logical


operations like logical AND, logical OR, logical NOT
operations.

SQL provides 3 Logical Operators:

AND used to perform logical AND operations


OR used to perform logical OR operations
NOT used to perform logical NOT operations

TRUTH TABLE:

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 all conditions should be satisfied

Oracle2PM Page 29
AND all conditions should be satisfied
OR at least 1 condition should be satisfied

NOTE:
AND, OR operators are used to separate
multiple conditions
max marks: 100

Example: min marks: 40 for pass in each sub

SELECT * FROM student;

SID SNAME M1 M2 M3
- --------- ---------- ---------- ---------- ----------
1001 A 50 80 70
1002 B 50 30 90

Display passed students records:

SELECT * FROM student


WHERE m1>=40 AND m2>=40 AND m3>=40;

Display failed students records:

SELECT * FROM student


WHERE m1<40 OR m2<40 OR m3<40;

Display all managers and clerks records:

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

job
--------
MANAGER
ANALYST
CLERK

Display the emp records whose empnos are 7369,


7521, 7900:

SELECT empno,ename,sal
FROM emp
WHERE empno=7369 OR empno=7521 OR
empno=7900;

Display the emp records who are working in deptno


10 & 30:

SELECT empno,ename,deptno
FROM emp
WHERE deptno=10 OR deptno=30;

Display the emp records whose salary is 1600 or


more and 3000 or less:

SELECT emnpo,ename,sal
FROM emp
WHERE sal>=1600 AND sal<=3000;

Display all managers records whose salary is more


than 2500:

SELECT empno,ename,job,sal
FROM emp
WHERE job='MANAGER' AND sal>2500;

Display all managers records who joined after april


1981:

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

Display all emps records except


managers:
condn NOT(Condn)

SELECT empno,ename,job T NOT(T) => F

Oracle2PM Page 30
Display all emps records except
managers:
condn NOT(Condn)

SELECT empno,ename,job T NOT(T) => F


FROM emp F NOT(F) => T
WHERE job!='MANAGER';
(or)
SELECT empno,ename,job
FROM emp
WHERE NOT(job='MANAGER');

job
--------
CLERK
MANAGER
ANALYST
MANAGER

Arithmetic + - * /
Relational > >= < <= = !=
Logical AND OR NOT

Special Operators:
• Special operators are also comparison
operators.

SQL provides following special operators:


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

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

Syntax:

<column> IN(<value_list>

Ex:

empno=7369 OR empno=7521 OR empno=7900

empno IN(7369,7521,7900)

empno
---------
7369
7499
7521
7498
7900

Display all managers and clerks records:

SELECT empno,ename,job,sal
FROM emp
WHERE job IN('MANAGER','CLERK');
(or)
SELECT empno,ename,job,sal
FROM emp
WHERE job='MANAGER' OR job='CLERK';

Display the emp records whose empnos are


7369, 7521, 7900:

SELECT empno,ename,job,sal
FROM emp
WHERE empno IN(7369,7521,7900);

Display all emps records except managers


and clerks:

SELECT empno,ename,job

Oracle2PM Page 31
SELECT empno,ename,job
FROM emp
WHERE job NOT IN('MANAGER','CLERK');

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

Display all emps records who are


working in 10 & 30 depts:

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

Display all emps records who are


not working in deptno 30:

SELECT empno,ename,deptno
FROM emp
WHERE deptno NOT IN(30);
(or)
SELECT empno,ename,deptno
FROM emp
WHERE deptno!=30;
(or)
SELECT empno,ename,deptno
FROM emp
WHERE NOT(deptno=30);

BETWEEN AND:
• used to compare a column value with a range
values.

Syntax:

<column> BETWEEN <lower> AND <upper>

Examples:

Display the emp records whose salary is


1600 or more and 3000 or less:

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

Display the emp records who joined in


1981:

1981 => 1-jan-1981 31-dec-1981

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

Display the emp records who joined in


1982 & 1983:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-jan-1982'
AND '31-dec-1983';

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

Output:
no rows selected

Oracle2PM Page 32
no rows selected

display the emp records whose salary is less


than 1600 or more than 3000:

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

Display the emp records who are not joined in


1981:

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

In Windows OS,

to search for all jpg files *.jpg


to serach all jpg files which a*.jpg
are started 'a'
to search for all mp3 files *.mp3
to search for all mp3 files s*.mp3
which are started with 's'
to search for any file *.*
to search for jpg files in which ?a*.jpg
2nd char is 'a'
to search for all jpg files in ??a*.jpg
which 3rd char is 'a'

windows OS provides 2 wildcard chars


to specify search pattern:

? used to replace 1 char


* used to replace 0 or any no of chars

LIKE:
• is used to compare column value with text pattern.
• SQL provides 2 wildcard chars. They are:

_ replaces 1 char
% replaces 0 or any no of chars

Syntax:

<column> LIKE <text_pattern>

Examples on LIKE operator:

Display the emp records whose names are


started with 'S':

SELECT ename,sal
FROM emp
WHERE ename LIKE 's%';

emp
ename sal
ALLEN
SMITH
WARD
SCOTT
BLAKE
SYMONDS
S

Display the emp records whose names


are ended with 'S':

ename sal SELECT empno,ename,sal


ALLEN FROM emp
WHERE ename LIKE '%S';

Oracle2PM Page 33
Display the emp records whose names
are ended with 'S':

ename sal SELECT empno,ename,sal


ALLEN FROM emp
WHERE ename LIKE '%S';
JAMES
SMITH
ADAMS
SYMONDS

Display the emp records whose


name's 2nd char is A:

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

Display the emp records whose


names are having A char:

ename
-----------
SELECT empno,ename,sal
ALLEN
FROM emp
BLAKE
WHERE ename LIKE '%A%';
JAMES
SMITH
MILLER

Display the emp records whose names


are started with M:

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

Display the emp records whose names


are ended with 'RD':

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

Display the emp records whose names


starting letter and ending letter is 'S':

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

ename
---------
SMITH
ALLEN
SYMONDS

Display the emp names which are


having 4 chars:

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

Display the emp names in which 3rd


char is A:

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

Display the emp records who joined in


1982:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate LIKE '%82';

Display the emp records who joined in


December month:

Oracle2PM Page 34
December month:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate LIKE '%DEC%';

Display the emp records who joined in


first 9 days in the month:

hiredate
------------ SELECT empno,ename,hiredate
17-AUG-1981 FROM emp
07-JAN-1982 WHERE hiredate LIKE '0%';
25-DEC-1983
09-MAY-1981

Display the emp records who are


getting 3 digit salary:

sal SELECT empno,ename,sal


------- FROM emp
6000 WHERE sal LIKE '___';
800
4000
950

ename Display the emp records whose names are


---------- having _ : printf(" \"hello\" "); // "hello"
raj_kumar
saiteja SELECT empno,ename,sal
vijay_kumar FROM emp
raviteja WHERE ename LIKE '%\_%' ESCAPE '\'; \" "

Display the emp records which are having % char:

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

Display the emp records whose


names are not started with S:

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

NULL:
• NULL means empty / blank. STUDENT
• When we don't know the value or
when we are unable to insert the sid sname maths
value we insert NULL value.
1001 A 70
• If NULL is participated operation
then result will be null. 1002 B 0
○ Ex: 1003 C
▪ 100+null = null D 89
▪ 20+30+10+null = null
▪ 10*20-null = null
• For null comparison we cannot
use = [equals to operator].
• For null comparison always use
"IS NULL".

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

Syntax:

<column> IS null

Example:

Display the emp records whose comm is 500:

Oracle2PM Page 35
Display the emp records whose comm is 500:

SELECT empno,ename,sal,comm
FROM emp
WHERE comm=500;

Display the emp records whose comm is NULL:

SELECT empno,ename,sal,comm
FROM emp
WHERE comm=NULL;

no rows selected

NOTE:
= operator cannot be used for null comparison

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

Display the emp records who are getting


commission:

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

Concatenation Operator:
• Symbol: ||
• Concatenation => combining
• It is used to combine 2 strings.

Syntax:
<string1> || <string2>

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

rajkumar

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

raj kumar

SELECT 10+20+30 FROM dual;

PLAYER
pid fname lname
1001 Virat Kohli
Virat Kohli
1002 Rohit Sharma
Rohit Sharma

Display pid & player full name:

SELECT pid, fname || ' ' || lname AS pname


FROM player;

pid pname
----- ----------
1001 Virat Kohli
1002 Rohit Sharma

Arithmetic + - * /
Ex: sal*12 sal*10/100
Relational / < > >= <= = != / <> / ^=
Comparison Ex: sal=3000 sal>3000
job='MANAGER'
Logical AND OR NOT
Ex:
job='MANAGER' OR job='CLERK'
sal>=1600 AND sal<=3000
NOT(job='MANAGER')

Special / IN
Comparison Ex: empno IN(7369, 7521, 7900)

Oracle2PM Page 36
Comparison Ex: empno IN(7369, 7521, 7900)

BETWEEN AND
Ex: sal BETWEEN 1600 AND 3000

LIKE
Ex: ename LIKE 'S%'
ename LIKE '_A%'

IS NULL
Ex: comm IS null

Concatenation ||

'sai' || 'teja'

SQL:

DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL SELECT
TCL
DML
DCl

TCL:
• TCL stands for Transaction Control Language.
• It deals with transactions.
• Transaction => a series of actions
• Ex: Withdraw Deposit Check Balance
purchasing a product

DB Server
ATM => Withdraw =>10000

Reads Card Info Account


Enter PIN: 1234 Acno Bal PIN
displays menu 4567 100000 1234
withdraw
enter amount: 10000
collects amount
updates balance

Withdraw Transaction

NOTE:
• A transaction must be successfully
completed or aborted [cancelled]
• If transaction is successful, to save it use
COMMIT
• If transaction is not successful, to cancel
it use ROLLBACK

TCL provides 3 commands:


• COMMIT
• ROLLBACK
• SAVEPOINT

ORACLE DB SERVER
CLIENT

INSTANCE DB
INSERT
INSERT emp
dept

RAM Hard DISK

SQL PLUS [CUI] ORACLE software


TOAD [GUI]

Oracle2PM Page 37
RAM Hard DISK

SQL PLUS [CUI] ORACLE software


TOAD [GUI]
SQL DEVELOPER [GUI]

ORACLE SERVER:

ORACLE SERVER is a combination


of ORACLE INSTANCE [RAM] &
ORACLE DATABASE [HARD DISK].

Oracle Server = Instance + DB

COMMIT [SAVE]:
• This command is used to save the
transactions.
• When COMMIT command is executed all
changes of ORACLE INSTANCE [RAM]
will be applied to ORACLE DB [HARD DISK]
• It makes the changes permanent.

Syntax:
COMMIT;

Ex:
COMMIT;

ROLLBACK [Undo All]:


• it is used to cancel the transactions.
Syntax:
• it cancels previous uncommitted actions.
ROLLBACK [TO <svaepoint_name>];
• After COMMIT, we cannot ROLLBACK it.

Example:

CREATE t2
CREATE t1

INSERT => 1001


INSERT => 1001
INSERT => 1002
INSERT => 1002
COMMIT; --2 actions are committed
ROLLBACK;
ROLLBACK; -- 0 actions will be cancelled

2 actions will be cancelled

Example on COMMIT & ROLLBACK:

CREATE TABLE t1
(
f1 NUMBER(4)
);

INSERT INTO t1 VALUES(1001);


INSERT INTO t1 VALUES(1002);
INSERT INTO t1 VALUES(1003);
COMMIT; --3 actions will be committed

INSERT INTO t1 VALUES(1004);


INSERT INTO t1 VALUES(1005);
ROLLBACK; -- 2 actions will be cancelled

SAVEPOINT:
used to set margin for ROLLBACK.

Example:
CREATE TABLE t2 CREATE TABLE t3
INSERT SAVEPOINT p1
INSERT INSERT
INSERT INSERT
INSERT SAVEPOINT p2
INSERT INSERT
INSERT INSERT
ROLLBACK => 6 actions cancelled SAVEPOINT p3
INSERT
INSERT
ROLLBACK TO p1; --6 actions cancelled

Oracle2PM Page 38
ROLLBACK TO p1; --6 actions cancelled
ROLLBACK TO p2; --4 actions cancelled
ROLLBACK TO p3; -- 2 actions cancelled

DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL SELECT
TCL COMMIT [save]
ROLLBACK [ undo all]
SAVEPOINT

DML INSERT
UPDATE
DELETE
INSERT ALL
MERGE

DML:
• Data Manipulation Language.
• It deals with data manipulations.
• Manipulation => INSERT / UPDATE / DELETE STUDENT joined => INSERT
○ Ex: STUDENT mobilenum => UPDATE
▪ customer opening new account => INSERT STUDENT left => DELETE
▪ customer depositing amount => UPDATE
▪ customer closing account => DELETE

DML provides 5 commands. They are:


• INSERT
• UPDATE
• DELETE
• INSERT ALL [Oracle 9i]
• MERGE [Oracle 9i]

NOTE:
• All DDL commands are auto-committed.
• When DDL command is executed, after
executing it, COMMIT will be executed.

DDL Command = DDL Command + COMMIT

• All DML commands are not auto-


committed.
• After using any DML command, to save it
use COMMIT. to cancel it use ROLLBACK.

Example-1:

CREATE TABLE t4 => COMMIT;


INSERT
INSERT
ROLLBACK;

Example:

CREATE t5
INSERT
INSERT
CREATE t6 => COMMIT;
INSERT
INSERT
ROLLBACK;

UPDATE:
• is used to modify the data.
• Using UPDATE command we can update: ALTER => modify table structure
○ single field value of single record
○ multiple field values of single record UPDATE => modify data
○ a group of records
○ all records
using parameters

Oracle2PM Page 39
○ using parameters

Syntax of UPDATE command: ENGLISH


SENTENCES
UPDATE <table_name> WORDS
SET <field_name>=<value>[,<field_name>=<value>, SQL
……..] QUERIES
[WHERE <condition>]; CLAUSES

CLAUSE => part of the query


Examples on UPDATE command:
SELECT
updating single field value of single record: FROM
WHERE
set salary as 4000 to an employee whose
empno is 7521: INSERT INTO
VALUES
UPDATE emp
SET sal=4000
WHERE empno=7521;

updating multiple field values of single record:

modify job title as manager, salary as 6000


to an employee whose empno is 7369:

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

updating a group of records:

Increase 2000 rupees salary to all salesmen:

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

updating all records:

Increase 1000 rupees salary to all emps:

UPDATE emp
SET sal=sal+1000;

updating records using parameters:

parameter asks value at run time


[read value at run time]

increase salary of emps as following:

7369 increase 2000


7499 increase 1500
7521 increase 3000

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

enter value for amount: 2000


enter value for empno: 7369

/
enter value for amount: 1500
enter value for empno: 7499

/
enter value for amount: 3000
enter value for empno: 7521

Examples on UPDATE command:

Increase 20% on sal to all managers & clerks:

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

Oracle2PM Page 40
WHERE job IN('MANAGER','CLERK');

Increase 10% on salary to all emps who are


having more than 40years experience:

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

Increase 20% on salary, 10% on comm to the


emps who are getting commission:

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

Transfer all deptno 10 emps to deptno 20:

UPDATE emp
SET deptno=20
WHERE deptno=10;

Example:

EMPLOYEE
empno ename sal TA HRA GROSS
1001 A 5000
1002 B 8000

calculate TA, HRA & GROSS salary:

10% on sal as TA
20% on sal as HRA
GROSS = sal+TA+HRA

CREATE TABLE employee


( 100000.00
empno NUMBER(4),
ename VARCHAR2(10),
sal NUMBER(8,2),
TA NUMBER(8,2),
HRA NUMBER(8,2),
GROSS NUMBER(8,2)
);

INSERT INTO employee VALUES(1001,'A',5000);


ERROR: not enough values

INSERT INTO employee(empno,ename,sal)


VALUES(1001,'A',5000);

INSERT INTO employee(empno,ename,sal)


VALUES(1002,'B',9000);

COMMIT;

UPDATE employee
SET TA=sal*0.1, HRA=sal*0.2,
GROSS=sal+sal*0.1+sal*0.2;

DELETE:
• used to delete the records from
the table.
• using DELETE command we can
delete:
○ single record
○ a group of records
○ all records

Syntax of DELETE command:

DELETE [FROM] <table_name>


[WHERE <condition>];

Deleting single record:

Oracle2PM Page 41
Delete an emp record whose empno is 7900:

DELETE FROM emp


WHERE empno=7900;

Deleting a group of records:

Delete all managers records:

DELETE FROM emp


WHERE job='MANAGER';

Delete all emp records who joined in 1982:

DELETE FROM emp


WHERE hiredate BETWEEN '1-jan-1982' AND
'31-dec-1982';

DELETE the emp records who are having more


than 40years experience:

DELETE FROM emp


WHERE trunc((sysdate-hiredate)/365)>40;

Delete the emp records who are working in 10 &


30 depts:

DELETE FROM emp


WHERE deptno IN(10,30);

Delete all emps records:

DELETE FROM emp;


(or)
DELETE emp;

Using TRUNCATE command we can


delete all records.

TRUNCATE TABLE emp;

Using DELETE command we can


delete all records

DELETE FROM emp;

Using TRUNCATE command we can


delete all records.
Using DELETE command we can
delete all records

What are the differences b/w


TRUNCATE & DELETE?

Oracle2PM Page 42
TRUNCATE DELETE

• It is DDL command • It is DML command

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

TRUNCATE = TRUNCATE+COMMIT

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

ORCLE SERVER
• We cannot delete single record • We can delete a single record or
or a group of records using it. a group of records or all records
Just we can delete all records ORACLE SERVER
with auto commit. DB
TABLESPACE
segment
block
• WHERE clause cannot be used • WHERE clause can be used extent
extent block [oracle page]
segment records

• It is faster • It is slower TS
DB

• deletes block by block • deletes row by row


[page by page] BLOCK => 8KB

EXTENT => 8 BLOCKS => 64 KB

• releases memory • does not releases the memory

BLOCK

10 records

BLOCK

10 records

SQL

DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
Transaction
RENAME
DRL SELECT withdraw
TCL COMMIT COMMIT
ROLLBACK ROLLBACK
SAVEPOINT
DML INSERT
UPDATE
DELETE
INSERT ALL c##userA
ALL emp
DCL GRANT
REVOKE c##userB
emp

c##userC
emp
DCL:
• DCL stands for Data Control Language. c##userA
• It deals with data accessibility. emp
• It provides security for the data.
c##userB
DCL provides 2 commands. They are:
• GRANT
• REVOKE

Oracle2PM Page 43
B.Tech - I yr
SECTION-A SECTION-B
1 1
GRANT: 2 2
It can be used to give permissions on 3 3
DB objects [tables, views] to other users. 4 4
. .
Syntax: . .
100 100
GRANT <priviliges_list>
ON <DB_Object>
TO <users_list>;

Ex:
c##oracle2pm
emp

c##userA

Ex:
Giving select permission to c##userA:

GRANT select
ON emp
TO c##userA;

Giving DML permissions to c##userA:

GRANT insert, update, delete


ON emp
TO c##userA;

Giving all permissions to c##userA:

GRANT all
ON emp
TO c##userA;

Giving permission to c##userA, c##userB,


c##useC:

GRANT select
ON emp
TO c##userA, c##userB, c##userC;

Giving permission to all users:

GRANT select
ON emp
TO public;

Giving permission to another user & allow that


user to grant permission to others:

c##oracle2pm
emp

c##userA

c##userB

c##oracle2pm:

GRANT all
ON emp
TO c##userA
WITH GRANT OPTION;

WITH GRANT OPTION clause allows


the user to grant the permission to
other users even if he is not owner

Oracle2PM Page 44
REVOKE:
• used to cancel the permissions from
other users on DB objects.

Syntax:

REVOKE privileges_list
ON <DB_Object_name>
FROM <user_list>;

Ex:

c##userA
create table t1

to give permission to c##userB:

GRANT select
ON t1
TO c##userB;

to can the permission from


c##userB:

REVOKE select
ON t1
FROM c##userB;

Example on GRANT, REVOKE:

Creating user:

FROM ORACLE 12c version onwards, we can create


2 types of users:
• Common User / Global User
• Local User

Prefix common user name with 'C##'

c##raju common user


kiran local user

Syntax to create the user:

CREATE USER <user_name>


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

NOTE:
username is not case sensitive
password is case sensitive

Creating users c##userA, c##userB:

Log in as DBA:

username: system
password: nareshit

CREATE USER c##userA


IDENTIFIED BY usera
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

conn c##userA/userA
ERROR: user has no permission for log in

Log in as DBA:

conn system/nareshit

GRANT connect,resource TO c##userA;

connect gives permission for log in


resource gives permission to create DB
objects like tables

Oracle2PM Page 45
CREATE USER c##userB
IDENTIFIED BY userb
DEFAULT TABLESPACE users
QUOTA unlimited ON users; OPEN 2 sqlplus windows
Window + Right Arrow => to arrange windows side by side
GRANT connect, resource TO c##userB; in one window log in as userA
in another window log in as userB

Oracle2PM Page 46
c##userA c##userB

CREATE TABLE t1
(
f1 NUMBER(4),
f2 VARCHAR2(10)
);

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


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

SELECT * FROM c##userA.t1;


ERROR: table or view does not exist

GRANT select
ON t1
TO c##userB;

SELECT * FROM c##userA.t1;


f1 f2
---------------
1 A
2 B

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


ERROR: insufficient privileges

UPDATE c##userA.t1 SET f2='sai' WHERE f1=1;


ERROR: insufficient privileges

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


ERROR: insufficient privileges

GRANT insert, update


ON t1
TO c##userB;

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


1 row created.

UPDATE c##userA.t1 SET f2='sai' WHERE f1=1;


1 row updated

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


ERROR: insufficient privileges

GRANT all
ON t1
TO c##userB;

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


1 row deleted

REVOKE insert, update, delete


ON t1
FROM c##userB;

INSERT => ERROR


DELETE => ERROR
UPDATE => ERROR

SELECT * FROM c##userA.t1;


--displays data

REVOKE all
ON t1
FROM c##userB;

SELECT * FROM c##userA.t1;


ERROR: table or view does not exist

Oracle2PM Page 47
c##userA => GRANTOR
t1
GRANT select

c##userB => GRANTEE

user_tables it maintains all tables


information created by the
user
user_Constraints it maintains all constraints
information

user_tab_privs_made:
• it is a system table.
• it maintains permissions list given by the
user.

c##userA:

DESC user_tab_privs_made;

SELECT privilege, grantee, table_name


FROM user_tab_privs_made;

user_tab_privs_recd:
• it is system table.
• it maintains permissions list received by
the user.

c##userB:

DESC user_tab_privs_recd;

SELECT privilege, Grantor, Table_name


FROM user_tab_privs_recd;

SQL:
• query language => used to write the queries
• Query => is a request i.e sent to the server

5 sub languages:

DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME

DRL SELECT

TCL COMMIT [SAVE]


ROLLBACK [undo all]
SAVEPOINT

DCL GRANT
REVOKE

DML INSERT
UPDATE
DELETE

INSERT ALL [Oracle 9i]


MERGE Oracle 9i]

Copying Table & Copying Records:

Copying Table:
Creating a new table from existing
table is called "Copying table"

Oracle2PM Page 48
Syntax:

CREATE TABLE <table_name>


AS
<SELECT query>;

With SELECT query result a new


table will be created.

cases:
• copying a table from existing table with
all rows & columns
• copying a table from existing table with
specific rows & specific columns
• copying a table from existing table with
specific columns without records
[copying table structure].

• copying a table from existing table with all


rows & columns:

EMP EMP1

8 columns 8 columns
14 rows 14 rows

Create a new table with the name emp1


with all columns & all rows of emp table:

CREATE TABLE emp1


AS
SELECT * FROM emp;

• copying a table from existing table with specific


rows & specific columns:

EMP CREATE EMP2

8 columns 4 columns => empno,ename,job,sal


14 rows managers records

Create a new table with 4 columns


empno,ename,job,sal & managers records
from existing table emp:

CREATE TABLE emp2


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

• copying a table from existing table with


specific columns without records [copying
table structure]:

TABLE = Structure + Data

t1 => Table
f1 f2
1 A
2 B

Create a new table with the name emp3 with 4


columns empno,ename,job,sal without records:

Write any false condition to copy table


structure.

Ex:
1=2
'A'='B'

Oracle2PM Page 49
'A'='B'
100=200
500=800

CREATE TABLE emp3


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

Copying Records:
inserting records from the existing table is
called "Copying records".

emp emp4 Syntax of copying records:

8 columns 8 columns INSERT INTO <table_name>[(<Column_list>)]


14 rows <SELECT query>

Create emp4 table with 4 columns


empno,ename,job,sal without records from existing
table emp:

CREATE TABLE emp4


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

INSERT INTO emp4


SELECT empno,ename,job,sal FROM emp;

--select query result will be inserted into emp4

Copy all managers records into emp4:

TRUNCATE TABLE emp4;

INSERT INTO emp4


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

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

EMP1
EMP empno ename job sal

8 columns
14 rows
EMP2
empno ename job sal

EMP3
empno ename job sal

INSERT ALL:
• Introduced in Oracle 9i version.
• Used to insert multiple records in multiple
tables or single table.
• Normally, it is used to copy one table
records to multiple tables.
• It avoids of writing multiple INSERT queries.

INSERT ALL can be used in 2 ways:

Oracle2PM Page 50
INSERT ALL can be used in 2 ways:

• Unconditional INSERT ALL


• Conditional INSERT ALL

Unconditional INSERT ALL:

Syntax:

INSERT ALL
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
INTO <table ame>[(<col_list>)] VALUES(<value_list>)
.
.
<SELECT query>;

INSERT
T1
INTO t1
VALUES(1,'A'); F1 F2
1 A

Example on unconditional INSERT ALL:

EMP1
EMP empno enmae job sal

8 columns
14 rows
EMP2
empno enmae job sal

EMP3
empno enmae job sal

Create emp1, emp2, emp3 tables with 4 columns


empno,ename,job,sal without records from emp table:

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 all records into emp1, emp2, emp3:

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

42 rows created.

Conditional INSERT ALL:

Syntax:

Oracle2PM Page 51
Conditional INSERT ALL:

Syntax:

INSERT ALL
WHEN <condition-1> THEN
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
WHEN <condition-2> THEN
INTO <table_name>[(<col_list>)] VALUES(<value_list>)
WHEN <condition-3> THEN
INTO <table ame>[(<col_list>)] VALUES(<value_list>)
.
.
[ELSE
INTO <table ame>[(<col_list>)] VALUES(<value_list>)]
<SELECT query>;

EMP => 8 cols, 14 rows emp_manager


empno ename job .. .. empno ename job sal
MANAGER
MANAGER
CLERK
CLERK emp_clerk
ANALYST empno ename job sal
SALESMAN
ANALYST
SALESMAN emp_others
empno ename job sal

Create emp_manager, emp_clerk, emp_others with 4 columns


empno,ename,job,sal without records from emp table:

CREATE TABLE emp_manager


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

CREATE TABLE emp_clerk


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;

Copy all managers records into emp_manager table, all clerks


records into emp_Clerk table & other than clerks, managers
copy into emp_others table:

INSERT ALL
WHEN job='MANAGER' THEN
INTO emp_manager VALUES(empno,ename,job,sal)
WHEN job='CLERK' THEN
INTO emp_clerk VALUES(empno,ename,job,sal)
ELSE
INTO emp_others VALUES(empno,ename,job,sal)
SELECT empno,ename,job,sal FROM emp;

WHEN deptno=10 THEN


Assignment:
dept10
emp empno ename deptno
empno ename deptno
10
10 dept20
20 empno ename deptno
20

Oracle2PM Page 52
10
10 dept20
20 empno ename deptno
20
30
dept_others
40
empno ename deptno

Assignment:
emp1980

empno ename hiredate empno ename hiredate

..1980
..1980
emp1981
..1981
empno ename hiredate
..1981
..1982
..1983 emp_others
empno ename hiredate

WHEN hiredate BETWEEN '1-jan-1980' AND '31-dec-1980' THEN


INTO emp1980 values(…)

Create a new table with the name T1 with the fields


F1 as number, F2 as varchar2
Insert multiple records into T1 table using INSERT
ALL:

T1
F1 NUMBER(4) F2 VARCHAR2(10)

CREATE TABLE t1
(
f1 NUMBER(4),
f2 VARCHAR2(10)
);

INSERT ALL
INTO t1 VALUES(1,'A')
INTO t1 VALUES(2,'B')
INTO t1 VALUES(3,'C')
INTO t1 VALUES(4,'D')
INTO t1 VALUES(5,'E')
SELECT * FROM dual;

MERGE:

Branch Office: Head Office

Customer1 S Customer2 T [Replica => duplicate copy]


cid cname ccity cid cname ccity
Replication:
1 A Bangalore 1 A Hyd the process of making duplicate
2 B Kolkata 2 B Delhi copy is called "Replication".
3 C Mumbai 3 C Mumbai
4 D Pune Replica:
5 E Chennai duplicate copy is called "Replica".

MERGE:
• introduced in Oracle 9i version.
• MERGE => combine
• MERGE = UPDATE + INSERT
• MERGE command is a combination of UPDATE &
INSERT commands.
• That's why it can be also called as "UPSERT"
command.
• MERGE command is used to apply one table
changes to its REPLICA [duplicate copy].

Syntax of MERGE command:

MERGE INTO <target_table_name> <alias>


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

Oracle2PM Page 53
MERGE INTO <target_table_name> <alias>
USING <source_table_name> <alias>
ON(<condition>)
WHEN matched THEN
<UPDATE query>
WHEN not matched THEN
<INSERT query>;

Example on MERGE:

Branch Office Head Office

Customer1 S Customer2 T
cid cname ccity cid cname ccity
1 A Bangalore 1 A Hyd
2 B Kolkata 2 B Delhi
3 C Mumbai 3 C Mumbai
4 D Pune
5 E Chennai

Create customer1:

CREATE TABLE customer1


(
cid NUMBER(4),
cname VARCHAR2(10),
ccity VARCHAR2(10)
);

INSERT INTO customer1 VALUES(1,'A','Hyd');


INSERT INTO customer1 VALUES(2,'B','Delhi');
INSERT INTO customer1 VALUES(3,'C','Mumbai');

COMMIT;

Make exact copy customer1 table with the name


customer2 [replica]:

CREATE TABLE customer2


AS
SELECT * FROM custoimer1;

Insert 2 customers records:

4 D Pune
5 E Chennai

INSERT INTO customer1 VALUES(4,'D','pune');


INSERT INTO customer1 VALUES(5,'E','Chennai');

Updating records:

1 A Bangalore
2 B Kolkata

UPDATE customer1
SET ccity='Bangalore'
WHERE cid=1;

UPDATE customer1
SET ccity='Kolkata'
WHERE cid=2;

COMMIT;

Apply customer1 table changes to its replica customer2:

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:

Oracle2PM Page 54
SQL:
• It is a query language
• used to write the queries.
• to communicate with DB we write queries.
• query => is a request that is sent to server.

5 sub languages:

DDL CREATE
deals with metadata ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL / DQL SELECT

deals with data retrievals

TCL COMMIT [save]


ROLLBACK [undo all]
deals with the SAVEPOINT
transactions

DCL / ACL GRANT


REVOKE
data accessibility
DML INSERT
UPDATE
deals with data DELETE
manipulations
INSERT ALL
MERGE

Oracle2PM Page 55
Built-In Functions
Tuesday, November 8, 2022 3:18 PM

SQL => 4 GL

4GLs provide readymade commands &


readymade functions

Built-In Functions:

• Function => Task / Action / Activity


• Every function performs particular task.
• To make our tasks easier, ORACLE developers
already defined some functions & placed in
ORACLE database. These functions are called
"Built-In Functions / Predefined Functions /
Readymade Functions".
• Every function returns a value. RETURN is
mandatory.

We can categorize Built-In Functions as following:


Analytical functions:
• String Functions / Text Functions sum()
• Conversion Functions avg()
• Aggregate Functions / Group Functions min()
• Date Functions max()
• Number Functions / Math Functions count()
• Miscellaneous Functions Rank()
Dense_Rank()

String Functions:

lower() Substr() Lpad() Replace()


upper() Instr() Rpad() Translate()
initcap() Soundex()
concat() Ltrim() ASCII()
length() Rtrim() Chr()
Trim() Reverse()

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

Syntax:
Lower(<string>)

Exs:
Lower('RAJU') raju
Lower('RAJ KUMAR') raj kumar

Upper():
it is used to convert the string to upper case.

Syntax:
Upper(<string>)

Exs:
Upper('raju') RAJU
Upper('raj kumar) RAJ KUMAR

Initcap() [Initial Capital]:

Oracle2PM Page 56
Initcap() [Initial Capital]:
It is used to get every word's starting letter as capital.

Syntax:
Initcap(<string>)

Exs:
Initcap('RAJU') Raju
Initcap('RAJ KUMAR') Raj Kumar
Initcap('RAK KUMAR VARMA') Raj Kumar Varma

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

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

Exs:
Concat('raj','kumar') rajkumar
Concat('raj','kumar','varma') ERROR
Concat(Concat('raj','kumar'),'varma') rajkumarvarma

Concatenation Operator ||

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

SELECT lower('RAJU') FROM dual;

length():
• used to find length of the string.
• length of string => no of chars in string

Syntax:
length(<string>)

Exs:
length('raju') 4
length('sai teja') 8

Display all emp records along with emp names.


Display emp names in lower case:

SELECT empno,lower(ename) as ename,sal


FROM emp;

Modify emp names to initcap case:

UPDATE emp
SET ename=initcap(ename);

ename
-----------
SMITH
ALLEN
WARD

Oracle2PM Page 57
Display the emp record whose name is
BLAKE when we don't know exact case:

SELECT * FROM emp


WHERE ename='blake';

no rows selected. BLAKE = blake => FALSE

ename
-----------
BLAKE

SELECT * FROM emp


WHERE lower(ename) = 'blake';

SMITH => smith = blake => F


BLAKE => blake = blake => T

Display the emp records whose names


are having 4 chars:

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

Display the emp records whose


names are having 14 chars:

SELECT empno,ename,sal
FROM emp
WHERE length(Ename)=14;

Display the emp names which are


having more than 4 chars:

SELECT empno,ename,sal
FROM emp
WHERE length(ename)>4;

Example:

PLAYER
pid Fname Lname
1001 ROHIT SHARMA
1002 VIRAT KOHLI

Oracle2PM Page 58
Add a column with the name PNAME:

ALTER TABLE player ADD pname VARCHAR2(20);

Store player names by concatenating FNAME &


LNAME in PNAME column. Store them in Initcap
case:

UPDATE player
SET pname = Initcap(FNAME || ' ' || LNAME);

PLAYER
pid Fname Lname PNAME
1001 ROHIT SHARMA Rohit Sharma
1002 VIRAT KOHLI Virat Kohli

ALTER TABLE player DROP(fname,lname);

PLAYER
pid PNAME
1001 Rohit Sharma
1002 Virat Kohli
1003 Sachin Tendulkar

Display the player names which


are having 12 chars:

SELECT * FROM player


WHERE length(pname)=12;

Display the player names which


are having more than 12 chars:

SELECT * FROM player


WHERE length(pname)>12;

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

Syntax:

Substr(<string>, <position> [, <no_of_chars>])

Exs:

s a I t e j a

Substr('sai teja',5) teja


Substr('sai teja',1) sai teja
Substr('sai teja',6) eja
Substr('sai teja',1,3) sai
Substr('sai teja',2,4) ai t

if position number is,

+ve from left to right

Oracle2PM Page 59
+ve from left to right
-ve from right to left

r a j k u m a r

Substr('raj kumar',-5) kumar


Substr('raj kumar',-4,3) uma
Substr('raj kumar',-9) raj kumar
Substr('raj kumar',-9,3) raj
Substr('raj kumar',-4) umar

Substr('raj kumar',5) kumar


Substr('raj kumar',1,3) raj
Substr('raj kumar',6,3) uma
Substr('raj kumar',6) umar
Substr('raj kumar',1,5) raj k

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

Syntax:
ASCII(<char>)

Exs:
ASCII('A') 65
ASCII('a') 97
ASCII('z') 122
ASCII('Z') 90

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

Syntax:
Chr(<ASCII_value>)

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

REVERSE():
used to get reverse string

Syntax:
Reverse(<string>)

Exs:
Reverse('RAMU') UMAR
Reverse('TEJA') AJET

lower() Substr()
upper() Ascii()
initcap() Chr()
concat() Reverse()
length()

Oracle2PM Page 60
length()

Instr():
• used to check whether sub string is existed in string or not.

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

search_position default value => 1


occurrence default value => 1

Exs:
s a I t e j a

Note:
Instr('sai teja','teja') 5 If sub string is existed in string, it
Instr('sai teja','ramu') 0 returns position number
Instr('sai teja','sai') 1 If sub string is not existed in string it
Instr('sai teja','eja') 6 returns 0.

s a I t e j a s a i

Instr('sai teja sai','sai') 1


Instr('sai teja sai','sai',1,2) 10
Instr('sai teja sai','sai',3) 10

t h I s I s h I s w I s h

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


Instr('this is his wish','is',-1,3) 6
Instr('this is his wish','is',-4) 10
Instr('this is his wish','is',-4,3) 3

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


Instr('this is his wish','is',4,2) 10
Instr('this is his wish','is',1,4) 14
Instr('this is his wish','is',7) 10
Instr('this is his wish','are') 0

Display the emp records whose name is started


with 'S':

SELECT empno,ename,sal
FROM emp

Oracle2PM Page 61
FROM emp
WHERE substr(ename,1,1)='S';
(or)
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE 'S%';

Display the emp records whose names are started


with 'AD' chars:

SELECT empno,ename,sal
FROM emp
WHERE substr(ename,1,2)='AD';

Display the emp records whose names are ended


with 'RD':

SELECT empno,ename,sal
FROM emp
WHERE substr(ename,-2,2)='RD';

Display the emp records whose name's starting


letter and ending letter are same:

SELECT empno,ename,sal
FROM emp
WHERE Substr(ename,1,1)=Substr(ename,-1,1);

Display the emp records which are having 'AM'


chars:

SELECT empno,ename,sal
FROM emp WHERE Instr(ename,'AM')>0;

ename
-----------
SMITH => 0
ALLEN => 0
ADAMS => 3
JAMES => 2

Display the names which are having %:

SELECT empno,ename,sal
FROM emp
WHERE Instr(ename,'%')>0;
(or)
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%\%%' ESCAPE '\';

ravi%teja

Generate email ids for all emps by taking emp


name first 3 chars & empno last 3 chars as

Oracle2PM Page 62
name first 3 chars & empno last 3 chars as
username for the domain 'nareshit.com':

Add mail_id column:

ALTER TABLE emp ADD mail_id varchar2(30);

generate mail ids:

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

Lpad() & Rpad():

• pad => fill

Lpad():
• used to fill specified char set at left side.

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

3rd argument char default char is: space

Rpad():
• used to fill specified char set at right side.

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

It fills max_size-string_length no of
chars will be filled

Exs:
Lpad('raju',10,'*') ******raju
Lpad('ramesh',10,'*') ****ramesh
Lpad('kiran',10,'@') @@@@@kiran
Lpad('sai',12,'#$') #$#$#$#$#sai
Lpad('raju',10) 6spacesraju

Rpad('raju',10,'*') raju******
Rpad('ramesh',10,'*') ramesh****
Rpad('kiran',10,'@') kiran@@@@@
Rpad('sai',12,'#$') sai#$#$#$#$#
Rpad('raju',10) raju6spaces

Lpad('A',10,'A') AAAAAAAAAA
Lpad('X',6,'X') XXXXXX

amount debited from acno: XXXXXX1234

acno:9876551234

SELECT 'amount debited from acno: ' ||


Lpad('X',6,'X') || Substr('9876551234',-4,4)
FROM dual;

Oracle2PM Page 63
Soundex():
• When we don't know the exact spelling, based
on the pronunciation [sounds] if we want to
retrieve the data use "Soundex()" Function.

Syntax:
Soundex(<string1>) = Soundex(<string2>)

Display the emp record whose name is


BLAKE:

SELECT empno,ename,sal
FROM emp
WHERE soundex(ename)=soundex('blek');

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

Trim => Remove

Ltrim():
used to remove left side unwanted
chars.

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

2nd arg default value: space

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

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

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

Exs:
Ltrim('@@@raju@@@','@') raju@@@
Rtrim('@@@raju@@@','@') @@@raju
Ltrim('@#@#@#ravi@#@#@#','@#') ravi@#@#@#
Rtrim('@#@#@#ravi@#@#@#','@#') @#@#@#ravi
Ltrim(' raju ') raju3paces
Rtrim(' raju ') 3spacesraju

Synyax of Trim():

Trim(Leading / Trailing / Both <char> FROM <string>)

Oracle2PM Page 64
Trim(Leading / Trailing / Both <char> FROM <string>)

Leading left side


Trailing right side
Both Left side & right side

Trim(Leading '@' FROM '@@@raju@@@') raju@@@


Trim(Trailing '@' FROM '@@@raju@@@') @@@raju
Trim(Both '@' FROM '@@@raju@@@') raju

leading / trailing / both Default => BOTH


Default char => space

Trim(' raju ') raju

Replace() & Translate():

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

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

Exs:
Replace('sai teja','teja','krishna') sai krishna
Replace('sai teja sai teja','teja','krishna') sai krishna sai krishna
Replace('sai teja','sai','ravi') ravi teja

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

Syntax:
Translate(<string>, <search_char_set>, <replace_char_set>)

Exs:
Translate('HELLO WELCOME','LO','AB') HEAAB WEACBME
L => replaced with => A
O => replaced with => O
Replace('HELLO WELCOME','LO','AB') HELAB WELCOME
LO replaced with AB

Translate('abcabcaabbccabc','abc','XYZ') XYZXYZXXYYZZXYZ
Replace('abcabcaabbccabc','abc','XYZ') XYZXYZaabbccXYZ

Translate() replaces the chars


Replace() replaces the strings

lower() Substr() Lpad() Soundex()


upper() Instr() Rpad()
initcap()
Oracle2PM Page 65
lower() Substr() Lpad() Soundex()
upper() Instr() Rpad()
initcap() Replace()
concat() Ltrim() ASCII() Translate()
length() Rtrim() Chr()
Trim() Reverse()

Display salaries of all emps with


mask chars as following:
0 )
1 !
sal
2 @
----
3 #
12500 => !@%))
4 $
5 %
6 ^ SELECT empno,ename,sal,
7 & Translate(sal,'0123456789',')!@#$%^&*(')
8 * FROM emp;
9 )

Aggregate Functions / Group Functions:

Aggregate =>
if one value is formed from a set of
individual values

50 max => 90
90 min => 30
30 sum => 320
70 count => 5
80 avg => 64

SQL provides following Group / Aggregate


Functions:

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

NOTE:
All string functions are single row functions
All group functions are multi-row functions

ename upper(ename) sal max(Sal)


-------------- -----
smith upper('smith') 6000 15000
allen upper('allen') 9000
ward upper('ward') 15000
12000
8000
7000

Oracle2PM Page 66
Sum():
is used to find sum of a set of values.

Syntax:
Sum(<column>)

Examples on Sum():

Find sum of salaries of all emps:

SELECT sum(sal) FROM emp;

sum(10,20,30) ERROR

Find sum of salaries of all managers:

SELECT sum(Sal) FROM emp


WHERE job='MANAGER';

Execution order:

FROM emp
WHERE job='MANAGER'
SELECT sum(Sal)

Find sum of salaries of deptno 10 & 30:

SELECT sum(sal) FROM emp


WHERE deptno IN(10,30);

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

Syntax:
avg(<column>)

Find avg salary of all emps:

SELECT avg(Sal) FROM emp;

Find avrg salary of deptno 30:

SELECT avg(Sal) FROM emp


WHERE deptno=30;

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

Syntax:
Min(<column>)

Examples:

Find minimum salary in all emps:

SELECT min(Sal) FROM emp;

Find min salary in all managers:

SELECT min(Sal) FROM emp


WHERE job='MANAGER';

Oracle2PM Page 67
WHERE job='MANAGER';

Find min salary in deptno 20:

SELECT min(Sal) FROM emp


WHERE deptno=20;

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

Syntax:
Max(<column>)

Examples:

Find max salary in all emps:

SELECT max(Sal) FROM emp;

Find max salary in all clerks:

SELECT max(sal) FROM emp


WHERE job='CLERK';

Count():
• can be used to count no of records or no
of column values.
• It cannot count the NULLs.
• it counts result of select query
Syntax:
Count(<column>) / Count(*)

Examples:

Display how many emps are getting


commission:

SELECT count(comm) FROM emp;

Display the no of records in emp table:

SELECT count(*) FROM emp;

Find no of managers:

SELECT count(*) FROM emp


WHERE job='MANAGER';

count(*) can be used to find no of


records
slower
counts the records

can be used to find no of


count(8) records
faster
counts the 8s

Oracle2PM Page 68
count(number)
count(8)
count(25)
count(100)

Conversion Functions:

SELECT 100+200 FROM dual;

300

SELECT '100' + '200' FROM dual;

300

Display the emp record whose empno is 7369:

SELECT * FROM emp WHERE empno = '7369';

displays 7369 emp record

There are 2 types of conversions. They are:


• Implicit Conversion
• Explicit Conversion

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

NOTE:
• Oracle company suggesting that Don't
depend on Implicit Conversion.
○ Performance may be degraded
○ In future versions they may remove
implicit conversion programs or they
may change the coding.

Explicit Conversion:
If conversion is done by Built-In Function
then it is called "Explicit Conversion".

For Explicit Conversion SQL provides


following Conversion Functions:

• to_Char()
• to_Date()
• to_Number()

Oracle2PM Page 69
• to_Date()
• to_Number()

DATE CHAR NUMBER

to_Char():
• can be used to convert Date type to String
type.
• It can be used to change the date formats like
IND data format [DD/MM/YYYY] or US Date
Format [MM/DD/YYYY]

Syntax:
to_Char(<date> [, <format>])

Exs:

to_Char(sysdate) 14-NOV-22

FORMAT PURPOSE Example [14-NOV-22]


YYYY gives year 4 digits to_char(sysdate,'YYYY')
2022
YYY gives year last 3 digits to_char(sysdate,'YYY')
022
YY gives year last 2 digits to_char(sysdate,'YY')
22
Y gives year last 1 digit to_char(sysdate,'Y')
2
YEAR / gives year in words to_char(sysdate,'YEAR')
year / TWENTY TWENTY-TWO
Year
to_char(sysdate,'year')
twenty twenty-two

to_char(sysdate,'Year')
Twenty Twenty-Two

MM gives month 2 digits to_Char(sysdate,'MM')


11
MON / gives short month to_Char(sysdate,'MON')
mon name NOV

MONTH / gives full month name to_Char(sysdate,'MONTH')


month NOVEMBER

d day number in the to_Char(sysdate,'d')


week 2

1 => sun
2 => mon
3 => tue
.
.
7 => sat

Oracle2PM Page 70
7 => sat

dd day number in the to_char(sysdate,'dd')


month 14

ddd day number in the to_char(sysdate,'dd')


year 318

dy / short week day name to_Char(sysdate,'DY')


DY MON

day / full week day name to_Char(sysdate,'DAY')


DAY MONDAY

HH / HH12 hours part [12 hrs to_Char(sysdate,'HH')


format] 03

HH24 hours part [24 hrs to_Char(sysdate,'HH24')


format] 15
SELECT
MI minutes part to_Char(sysdate,'MI') to_Char(sysdate,'YYYY')
05 FROM dual;
SS seconds part to_Char(sysdate,'SS')
2022
FF fractional seconds to_Char(systimestamp,'FF')
Display current system time:
AM/PM AM or PM format to_Char(sysdate,'AM')
PM SELECT to_Char(sysdate,'HH:MI:SS AM')
FROM dual;
Q quarter number to_Char(sysdate,'Q')
1 => jan - mar 4
2 => apr - jun
3 => jul - sep
4 => oct - dec
CC Century Number to_Char(sysdate,'CC')
21

AD / BC AD or BC format to_Char(sysdate,'BC')
AD

ww week day number in to_Char(sysdate,'ww')


the year 46

365 => 53 weeks


366 => 53 weeks

Display all emp records along with hiredates.


Display hiredates in IND date format
[DD/MM/YYYY]: 31-DEC-2022 => 365

SELECT empno,ename,sal,
to_Char(hiredate,'DD/MM/YYYY') as hiredate 31-JAN-2022 => 31
FROM emp; 1-FEB-2022 => 32
2-FEB-2022 => 33
.
.
Display all emp records along with hiredates. 31-DEC-2022 => 365
Display hiredates in US date format
[MM/DD/YYYY]:

SELECT empno,ename,sal,
to_Char(hiredate,'MM/DD/YYYY') as hiredate

Oracle2PM Page 71
to_Char(hiredate,'MM/DD/YYYY') as hiredate
FROM emp;

Display the emp records who joined in 1982:

hiredate to_Char(hiredate,'YYYY') = 1982


---------------
25-DEC-1981
17-NOV-1982

SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'YYYY') = 1982;
(or)
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-jan-1982' AND
'31-dec-1982';

Display the emp records who joined in 1980,1982,


1984:

SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'yyyy') IN(1980, 1982, 1984);

Display the emp records who joined in


December:

SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'MM') = 12;

Display the emp records who joined in jan,


nov, dec:

SELECT empno,ename,hiredate
FROm emp
WHERE to_char(hiredate,'mm') IN(1,11,12);

Display the emp records who joined in 4th


quarter:

SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'Q') = 4;

Display the emp records who joined in 1st


quarter & 4th quarter:

SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'Q') IN(1,4);

Display the emp records who joined on Sunday:

Oracle2PM Page 72
Display the emp records who joined on Sunday:

SELECT empno,ename,hiredate
d 1 1 => sun
FROM emp
WHERE to_char(hiredate,'D')=1; dy sun
(or) day sunday
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'DY')='SUN';

SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'DAY')='SUNDAY';
Output: SUNDAY3paces = SUNDAY => F
No rows Selected

SUNDAY SUNDAY3spaces
TUESDAY TUESDAY2spaces
WEDNESDAY WEDNESDAY
THURSDAY THURSDAY1space

SELECT empno,ename,hiredate
FROM emp
WHERE RTRIM(to_char(hiredate,'DAY')) = 'SUNDAY';

Display the emp records who joined in 4th quarter of


1981:

SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'YYYY') = 1981 AND
to_char(hiredate,'Q')=4;

To_Char() [Number To Char]:


• It can be used to convert number to string.
• To apply currency symbols or currency
names or thousand separators to numbers
we need to convert number type to string
type.

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

sal NUMBER(7,2)
---------
$5000 => ERROR
$5,000 => ERROR
USD5000 => ERROR

Number type can hold only digits

Oracle2PM Page 73
Exs:

TO_Char(123) '123'
To_Char(123.45) '123.45'

FORMAT PURPOSE
L Currency Symbol
C Currency Name
9 Digit
0 ZERO
, / G Thousand Separator
. / D Decimal Point

Apply currency symbol to the number 5000 &


display 2 decimal places:

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

$5000.00

Apply currency name to the number 5000,


display thousand separator & 2 decimal
places:

SELECT TO_Char(5000,'C9,999.99') FROM


dual;

USD5,000.00

Display all emp records along with


salaries. Display salaries using $
symbol:

SELECT empno,ename,
to_Char (sal,'L99999.99') as salary
FROM emp;

NOTE:
Number of 9s will be decided based on
precision & scale of that column.

sal => Number(7,2)

Display all emp records along with


salaries. Display salaries using
currency name USD, apply
thousand separator & 2 decimal
places:

SELECT empno,ename,
to_Char(sal,'C99,999.99') as sal
FROM emp;

Oracle2PM Page 74
default currency symbol $
default currency name USD

Changing currency symbols & names:

To change currency symbols & names we need to change 2


parameters:

NLS_TERRITORY default: AMERICA


NLS_CURRECY defaul£t: $

NLS => National Language Support

Log in as DBA:
username: system
password: nareshit

show parameters --displays all parameters list

show parameters 'NLS'

ALTER SESSION SET NLS_TERRITORY='UNITED KINGDOM';

ALTER SESSION SET NLS_CURRENCY='£';

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

TO_CHAR(5000,'L999
------------------
£5000.00

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

TO_CHAR(5000,'C
---------------
GBP5000.00

ALTER SESSION SET NLS_TERRITORY='JAPAN';

ALTER SESSION SET NLS_CURRENCY='¥';

ALTER SESSION SET NLS_TERRITORY='INDIA';

ALTER SESSION SET NLS_CURRENCY='RS.';

For parameter changing we can use,


SYSTEM PERMANENTLY IT WILL BE CHANGED
SESSION FOR CURRENT SESSION ONLY IT WILL BE
APPLIED

Log In => SESSION => Log Out

TO_Date():
• used to convert string to date.
• It can be used to insert date values.
It can be used get specific part [year, month,

Oracle2PM Page 75
• It can be used get specific part [year, month,
day] from specific date.

Syntax:
To_Date(<string> [, <format>)

Exs:
TO_Date('25-DEC-2019') 25-DEC-19

To_Date('25 December, 2019') 25-DEC-19


To_Date('25/12/2019') ERROR
To_Date('25/12/2019','DD/MM/YYYY') 25-DEC-19

Example:

T1
F1 DATE
------------
25-DEC-19
17-AUG-18

CREATE TABLE t1
(
f1 DATE f1
); -----
25-DEC-19
INSERT INTO t1 VALUES('25-DEC-2019');

NOTE:
don't depend on implicit conversion because of
2 reasons:
• performance will be degraded
• in future version implicit conversion
programs may be changed or deleted.

INSERT INTO t1 F1
VALUES(to_Date('25-DEC-2019')); ----
25-DEC-19

INSERT INTO t1
VALUES(to_date('&doj','DD/MM/YYYY'));
enter value for doj: 18/11/2021

/
enter value for doj: 17/08/2021

Display year from today's date:

Oracle2PM Page 76
Display year from today's date:

SELECT to_char(sysdate,'YYYY') FROm dual;

2022

Display yead value from the date 25-DEC-2019:

SELECT to_char('25-DEC-2019','YYYY') FROM


dual;
ERROR:

SELECT to_Char(to_Date('25-DEC-2019'),'YYYY')
FROM dual;

2019

Find weekday name oif the date 27-OCT-2020:

SELECT
to_char(to_date('27-OCT-2020'),'day')
FROM dual;

Find the weekday on weekday india got


independence:
15-AUG-1947

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

FRIDAY

Find on which weekday sachin born:


DOB: 24-APR-1973

SELECT
to_char(to_Date('24-APR-1973'),'DAY')
FROM dual;

To_Number():
• can be used to convert string to number.
• String must be numeric string.

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

Exs:
To_Number('123') 123
To_Number('123.45') 123.45
To_Number('$5000.00') ERROR
TO_Number('$5000.00','L9999.99') 5000
To_Number('USD5000.00','C9999.99') 5000

Number Functions / Math Functions:

power() ceil()

Oracle2PM Page 77
Number Functions / Math Functions:

power() ceil()
sqrt() floor()
abs() trunc()
round()
mod()

Power():
used to get power value

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

Exs:
Power(2,4) 16
Power(5,3) 125

Sqrt():
used to fin d square root value

Syntax:
Sqrt(<number>

Exs:
Sqrt(100) 10
Sqrt(81) 9

Abs():
• used to get absolute value
• Absolute => Non-Negative [+ve]

Syntax:
Abs(<number>)

Exs:
Abs(25) 25
Abs(-25) 25

ceil():
used to get round up int value

Syntax:
ceil(<number>)

floor():
used to get round down int value

Syntax:
floor(<number>)

Exs:
ceil(123.4567) 123 => 123.4567 => 124
124
floor(123.4567) 123 => 123.4567 => 124
123

Example:

Find average salary of all emps. Take upper

Oracle2PM Page 78
Find average salary of all emps. Take upper
integer as average value:

SELECT ceil(avg(sal)) FROM emp;

Find average salary of all emps. Take


lowerinteger as average value:

SELECT floor(avg(sal)) FROM emp;

Trunc():
• Trunc => Truncate [remove]
• used to remove decimal places.

Syntax:
Trunc(<number> [,<no_of_decimal_places>])

Exs:
Trunc(123.45678) 123
Trunc(123.45678,2) 123.45
Trunc(567.2345) 567
Trunc(567.234567,3) 567.234

2nd argument can be negative.


2nd argument -ve means, it will not give
decimal places.

-1 rounds in the 10s


-2 rounds in 100s
-3 rounds in 1000s
-4 rounds in 10000s Rounded values in 10s:

10, 20, 30, 40, …

NOTE:
Trunc() function always gives lower value

TRUNC(123.456,-1) 120 => 123.456 => 130


120
TRUNC(785.234,-1) 780 => 785.234 => 790
780
TRUNC(785.234,-2) 700 => 785.234 => 800
700
TRUNC(2345.678,-3) 2000 => 2345.678 => 3000
2000

Example:

Calculate experience of all employees:

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

NOTE:
date also contains time value
To remove time value from date we can use
TRUNC()

SELECT systimestamp FROM dual;

Oracle2PM Page 79
16-NOV-22 3:19:15:000123 PM

SELECT trunc(systimestamp) FROM dual;

16-NOV-22

Insert one employee record with today's date


as hiredate:

INSERT INTO emp(empno,ename,hiredate)


VALUES(1001,'A',sysdate); --3.22

Display the emp, records who joined today:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate = sysdate;

no rows selected

SELECT empno,ename,hiredate
FROM emp
WHERE TRUNC(hiredate) = TRUNC(sysdate);

ROUND():
• used to get rounded values.
• If value is avrg or above average, it takes
upper value
• If value is below average, it takes lower value

UNIVERSITY 67+68 = 135/2 = 67.5

Round( percentage) 67 => 67.89 => 68 avrg: 67.5


-------------------
67.89
82.34
76.5
77.23
66.92

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

Exs:
Round(123.789) 123 => 123.5 => 124
124
Trunc(123.789) 123
Round(123.345) 123
Trunc(123.345) 123
Round(123.45678,2) 123.46
Round(123.45378,2) 123.45
Round(678.234567,3) 678.235
Round(678.234267,3) 678.234

Oracle2PM Page 80
Round(678.234567,3) 678.235
Round(678.234267,3) 678.234

Round(123.45678,-1) 120 => 125 => 130


120
Round(127.45678,-1) 120 => 125 => 130
130
Round(4567.234,-2) 4500 => 4550 => 4600
4600

Mod():
used to get remainder value

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

Exs:
Mod(10,7) 3
Mod(5,2) 1

Date Functions:

• Sysdate
• Systimestamp
• Add_Months()
• Last_Day()
• Next_Day()
• Months_Between()

Sysdate:
used to get current system date

Example:

Display today's date:

SELECT sysdate FROM dual;

Display current system time:

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

systimestamp:
used to get current system date and time.

Example:

Display current system date & time:

SELECT systimestamp FROM dual;

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

Syntax:

Oracle2PM Page 81
Syntax:
Add_Months(<date>,<no_of_months>)

2nd argument no_of_months,


+ve adds months
-ve subtracts months

Examples:

Add 2 days to today's date: 17-NOV-2022

SELECT sysdate+2 FROM dual;

19-NOV-22

Add 2 months to today's date:

SELECT Add_Months(sysdate,2) FROM dual;

17-JAN-23

Add 2 years to today's date:

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

17-NOV-24

Subtract 2 days from today's date:

SELECT sysdate-2 FROM dual;

15-NOV-22

Subtract 2 months from todays' date:

SELECT Add_Months(sysdate,-2) FROM dual;

17-SEP-22

Subtract 2 years from today's date:

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

Example:
ORDERS
Order_Id Ordered_date Delivery_date
1234 sysdate sysdate+5 /
17-NOV-22 Ordered_date + 5
22-NOV22

CM_LIST
STATE_CODE CM NAME start_date end_date
TS KCR 19-MAR-2018 Add_Months(start_date,5*12)
AP
..

DOB => Date Of Birth


DOR => Date Of Retirement 60 years

EMP

Oracle2PM Page 82
EMP
EMPNO ENAME DOB DOR
1001 A 27-OCT-1998 Add_Months(DOB,60*12)

INSERT INTO emp(empno,ename,hiredate)


VALUES(1001,'A',sysdate);

INSERT INTO emp(empno,ename,hiredate)


VALUES(1002,'B',sysdate-1);

INSERT INTO emp(empno,ename,hiredate)


VALUES(1003,'C',Add_Months(sysdate,-1));

INSERT INTO emp(empno,ename,hiredate)


VALUES(1004,'D',Add_Months(sysdate,-12));

COMMIT;

Display the emp records who joined today:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate = sysdate;

no rows selected

SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(sysdate);

Display the emp records who joined yesterday:

SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(sysdate-1);

Display the emp records who joined 1 month ago from


today's date:

SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(Add_months(sysdate,-1));

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

SELECT empno,ename,hiredate
FROM emp
WHERE trunc(hiredate) = trunc(Add_Months(sysdate,-12));

HOME LOANS

3 months transactions

SELECT * FROM transactions


WHERE acno=1234 AND

Oracle2PM Page 83
WHERE acno=1234 AND
trans_Date between Add_Months(sysdate,-3) AND
sysdate;

Date_Id Amount
1-jan-2019 600000 today's sales
2-jan-2019 1000000
yesterday's sales
3-jan-2019 800000
.. 1 month ago sales
..
17-NOV-2022 1 year ago sales

Last_Day():
used to get last date in the month.

Syntax:
Last_day(<date>)

Example:

Find current month last date:

SELECT Last_Day(sysdate) FROM dual;

30-NOV-22

Find last date in feb month of 2022:

SELECT last_day('18-FEB-2022') FROM dual;

28-FEB-22

Find last date in feb month of 2020:

SELECT last_day('18-FEB-2020') FROM dual;

29-FEB-20

Find next month first date:

SELECT Last_Day(sysdate)+1 FROM dual;

Find next month last date:

SELECT Last_Day(Add_Months(sysdate,1))
FROM dual;

31-DEC-22

Find previous month last date:

SELECT Last_Day(Add_Months(sysdate,-1))
FROM dual;

Find current month first date:

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

Next_Day():
used to get coming date based on
Oracle2PM Page 84
• used to get coming date based on
weekday name.
• Ex:
○ coming Sunday date
○ coming Friday date

Syntax:
Next_day(<date>,<week_Day>)

Examples:

Find coming Sunday date:

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

Find coming Friday date:

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

Find next month 1st Sunday date:

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

Find current month first Sunday date:

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

Find current month last Sunday date:

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

Months_Between():
used to months between 2 dates.

Syntax:
Months_Between(<date1>,<date2>)

Ex:
Months_Between('31-DEC-2022','31-DEC-2021')

Calculate experience of all emps using months_between()


function:

trunc(sysdate-hiredate/365)

SELECT empno,ename,hiredate,
trunc(months_between(sysdate,hiredate)/12) as experience
FROM emp;

Oracle2PM Page 85
Miscellaneous Functions:

NVL()
NVL2()

RANK()
DENSE_RANK()

USER
UID

GREATEST()
LEAST()

NVL():
• used to replace null value with other value.
• If null is participated in operation then result will
be NULL.

SELECT 100+200 FROM dual;

300

SELECT 100+200+null FROM dual;

null

10+20*40-30+16-null = null

SELECT 100+200+NVL(null,0) FROM dual;

300

Syntax:
NVL(<argument1>, <argument2>)

If argument1 is not null, it returns argument1


If argument1 is null, it returns argument2

Exs:
NVL(100,200) 100
NVL(null,200) 200

Example:
Calculate total salary of all emps
[sal+Comm]:

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

Display all emp records along with


commission. If commission is NULL replace
it with 'N/A':

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

Oracle2PM Page 86
FROM emp;

ERROR: invalid number


comm => number
'N/A' => string
data types are mismatched => ERROR

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

STUDENT

sid sname M1
1001 A 70
1002 B
1003 C 80
1004 D
1005 E 66

Display student details. Replace null value with 'AB':

SELECT sisd,sname, NVL(to_char(m1),'AB') as m1


FROM student;

NVL2():
used to replace nulls & not nulls.

Syntax:
NVL2(<arg1>, <arg2>, <arg3>)

If arg1 is not null, it returns arg2


If arg1 is null, it returns arg3

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

NVL() NVL2()

used to replace nulls used to replace nulls & not nulls

takes 2 arguments takes 3 arguments

Example:

Update commission of all emps as following:


• if comm is not null, increase 1000 rupees
commission
• if commission is null, set comm as 700

UPDATE emp
SET comm = NVL2(comm,comm+1000,700);

RANK():
used to apply ranks to the records according to specific

Oracle2PM Page 87
used to apply ranks to the records according to specific
column order

Syntax:
RANK() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/ DESC)

DENSE_RANK():
used to apply ranks to the records according to specific
column order

Syntax:
DENSE_RANK() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/ DESC)

UNIVERSITY

MARKS Rank Dense_Rank


670 8 4
790 6 3
940 1 1
820 3 2
790 6 3
940 1 1
820 3 2
600 9 5
820 3 2
500 10 6

Dense_Rank() always follow sequence in ranking

Rank() does not follow sequence in ranking.

Apply ranks to emp records based on salaries.


TO highest salary give top rank:

sal DESC
------ sal Rank dense_rank
4000 ---------
8000 8000 => 1 1
6000 8000 => 1 1
7000 7000 => 3 2
3000 6000
5000 5000
8000 4000
3000

ORDER BY clause is used to arrange the records


in Ascending or Descending order

SELECT empno,ename,sal,
RANK() OVER(ORDER BY sal DESC) as Rank
FROM emp;
(or)
SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as Rank

Oracle2PM Page 88
DENSE_RANK() OVER(ORDER BY sal DESC) as Rank
FROM emp;

Apply ranks to all emps records. Give top rank to highest


salaried employee. If salaries are same then apply rank
according to seniority.

SELECT empno,ename,sal,hiredate,
DENSE_RANK() OVER(ORDER BY sal DESC, hiredate ASC)
as rank
FROM emp;

5000 25-DEC-1983 25-dec-1982 ASCENDING


4000 17-FEB-1981 15-sep-1981
15-feb-1981
4000 25-JAN-1981 15-feb-1981
15-sep-1981
25-dec-1982

sal
hiredate
--------
-------------
8000
17-SEP-1983
9000
25-DEC-1981
6000
27-FEB-1982
7000
8500

SELECT max(Sal) FROM emp; Most junior hiredate:


9000 SELECT max(hiredate) FROM emp;
17-SEP-1983
SELECT min(Sal) FROM emp;
6000 Most senior hiredate:
SELECT min(hiredate) FROM emp;
25-DEC-1981

ORDER BY clause:
• It arranges records in ascending or descending
order according to specific column / columns

PARTITION BY clause:
• It is used to group the records according to
specific column
• If we don't use PATITION BY clause, all records
will be treated as one group.

Syntax:
PARTITION BY <Column>

Ex:
PARTITION BY deptno

EMP
empno ename deptno sal RANK
10 4000 2
10 6000 1
20 8000 1
20 7000 2
30 4000 2

Oracle2PM Page 89
10 6000 1
20 8000 1
20 7000 2
30 4000 2
30 5000 1

DENSE_RANK() OVER(ORDER BY sal DESC)

Apply ranks to all emp records. apply ranks


dept wise, salaries in descending order:

SELECT empno,ename,deptno,sal,
DENSE_RANK() OVER(PARTITION BY deptno
ORDER BY sal DESC) as RANK
FROM emp;

USER:
used to get current user name.

UID:
used to get current user ID.

Ex:
SELECT user,uid FROM dual;

GREATEST() & LEAST():

GREATEST():
• used to find greatest value in horizontal
values
• can take variable length arguments.
• single row function.

Max():
• used to find max value in vertical values
• can take 1 argument.
• multi row function.

T1
F1 F2 F3
50 90 55
44 81 72
73 24 97

max(f3) => 97
GREATEST(f1,f2,f3)
----------------------
90
81
97

LEAST():
used to find least value in horizontal

Oracle2PM Page 90
• used to find least value in horizontal
values.
• it can take variable length arguments.
• single row function.

Min():
• used to find min value in vertical values
• can take 1 argument.
• multi-row function

SELECT greatest(10,20,30,40) FROM dual;


40

SELECT least(10,20,30,40) FROM dual;


10

Built-In Functions

Single Row Functions Multi-Row Functions

If function is applied If function is applied


on every row then it is on mulitple rows then it is
called "Single row function" called "Multi row function"

Ex: Ex:
string functions, math functions Aggregate / Group Functions
date functions, conversion
functions min() max() count() sum() avg()

lower() upper() to_char()

Oracle2PM Page 91
Clauses
Saturday, November 19, 2022 3:22 PM

Clauses in SELECT command:

Clause:
• Clause is a part of query
• Every clause has specific purpose & than can
perform specific functionality.

ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES

Ex:
UPDATE emp INSERT clause
SET sal=sal+1000 INTO clause
WHERE empno=7369; VALUES clause

UPDATE clause
SET clause
WHERE clause

Syntax of SELECT command:

SELECT [ALL / DISTINCT] <column_list / *>


FROM <table_list>
[WHERE <condition>]
[GROUP BY <grouping_column_list>]
[HAVING <group condition>]
[ORDER BY <column> ASC / DESC [, <column> ASC / DESC..]];

ALL [default]
ASC [default]

SELECT clause is used to specify column list


FROM clause is used to specify table list
WHERE clause is used to write the conditions on rows.
This condition will be applied on every row
It filters the rows.

Example:
Display the emp names and salaries of the
employees whose salary is more than 2500:

SELECT ename,sal
FROM emp
WHERE sal>2500;

EMP
EMPNO ENAME JOB SAL
1001 A CLERK 6000
1002 B ANALYST 2000
1003 C MANAGER 4000
1004 D CLERK 2400

FROM emp:
Selects entire table
Oracle2PM Page 92
Selects entire table

Ex:
FROM emp

EMP
EMPNO ENAME JOB SAL
1001 A CLERK 6000
1002 B ANALYST 2000
1003 C MANAGER 4000
1004 D CLERK 2400

WHERE sal>2500:
• It filters the records.
• WHERE clause condition will be applied on
every row.

EMP
EMPNO ENAME JOB SAL
1001 A CLERK 6000
1002 B ANALYST 2000
1003 C MANAGER 4000
1004 D CLERK 2400

Result of WHERE clause:


EMP
EMPNO ENAME JOB SAL
1001 A CLERK 6000
1003 C MANAGER 4000

SELECT ename,sal:
It selects the specified columns

ENAME SAL
A 6000
C 4000

ORDER BY clause:
• used to arrange the records in Ascending OR Descending
Order according to specific column / columns
• Default order is: ASC [ASCENDING ORDER]

Syntax:
ORDER BY <column> ASC/DESC [, <column> ASC/DESC, …]

NUMBER CHAR
DATE
ASC: DESC:
1 ASC: DESC: ASC:
10 DESC:
2 A Z 1-jan-2022
9 31-DEC-2022
3 B Y 2-jan-2022
8 30-DEC-2022
4 C X 3-jan-2022
7 .
. . . .
. .
. . . 31-jan-2022
. .
10 Z A 1-feb-2022
1 1-JAN-2022
.
.
31.dec-2022

Oracle2PM Page 93
31.dec-2022

Examples on ORDER BY:

Display all emp records along with emp names. Arrange emp
names in alphabetical order:

SELECT empno,ename,sal
FROM emp
ORDER BY ename ASC;
(or)
SELECT empno,ename,sal
FROM emp
ORDER BY ename ; --ASC => is optional [default: ASC]
(or)
SELECT empno,ename,sal
FROM emp
ORDER BY 2 ASC; -- 2 => ename [column number in SELECT]

SELECT * FROM emp


ORDER BY 2;

* will be replaced with all column names

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

column names are taken in table structure order

Display all emp records along with salaries.


Arrange salaries in Descending order:

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

Display the emp records in Descending order


according to salary. If salary is same arrange
them according to seniority:

sal hiredate sal hiredate


5000 25-DEC-1981 5000 25-DEC-1981
3000 17-SEP-1981 3000 15-MAR-1981
3000 15-MAR-1981 3000 17-SEP-1981

SELECT empno,ename,sal,hiredate
FROM emp
ORDER BY sal DESC, hiredate ASC;

Arrange all emp records in Ascending order


according to deptno:

Oracle2PM Page 94
SELECT empno,ename,sal,deptno,hiredate
FROM emp
ORDER BY deptno ASC;

Display the emp records in ascending order


according to deptno. Within the dept display
the records according to seniority:

break on deptno skip 1

break avoids duplication of that column value


skip it is used to get blank line

SELECT deptno,empno,ename,hiredate
FROM emp
ORDER BY deptno ASC, hiredate ASC;

clear breaks --breaks will be cleared

Display the emp records in ascending order


according to deptno. Within dept arrange salaries in
descending order. If salary is same arrange the
according to seniority:

SELECT empno,ename,deptno,sal,hiredate
FROM emp
ORDER BY deptno ASC, sal DESC, hiredate ASC;

NOTE:
If column has nulls,
ASCENDING ORDER nulls will be given last
Descending ORDER nulls will be given first

INSERT INTO emp(empno,ename) VALUES(1001,'A');


INSERT INTO emp(empno,ename) VALUES(1002,'B');
COMMIT;

Arrange emp records in Descending order


according to salary. Display nulls at last:

SELECT empno,ename,sal
FROM emp
ORDER BY sal DESC nulls last;

Arrange emp records in Ascending order


according to salary. Display nulls at first:

SELECT empno,ename,sal
FROM emp
ORDER BY sal ASC nulls first;

Oracle2PM Page 95
ALL: gives all values

DISTINCT clause:
• DISTINCT clause gives DISTINCT [unique/single]
values.
• It avoids duplicate values.

Examples on DISTINCT:

display all job titles offered by company using emp


table:

SELECT job FROM emp; --all job column values


(or)
SELECT ALL job FROM emp;

ALL job
SELECT DISTINCT job FROM emp;
JOB
----------- JOB
MANAGER -------
CLERK MANAGER
CLERK CLERK
SALESMAN SALESMAN
MANAGER
SALESMAN

Display the deptnos available in Company using


emp table:

SELECT deptno FROM emp; --all deptno col values

DEPTNO
--------- SELECT DISTINCT deptno FROM emp
20 ORDER BY deptno;
30
DEPTNO
30
-------------
20
10
10
20
10
30

Display dept wise, job titles offered by


company:

SELECT DISTINCT deptno,job FROM emp;

DEPTNO JOB DEPTNO JOB


10 CLERK 10 CLERK
20 CLERK 10 MANAGER
20 CLERK 10 ANALYST
10 CLERK 20 CLERK

Oracle2PM Page 96
10 CLERK 10 CLERK
20 CLERK 10 MANAGER
20 CLERK 10 ANALYST
10 CLERK 20 CLERK
10 MANAGER 20 MANAGER
20 MANAGER 20 SALESMAN
10 ANALYST
20 SALESMAN
10 ANALYST
20 SALESMAN

DISTINCT deptno,job

• If combination of two column values is


duplicated, for this it gives DISTINCT.
• Individually deptno can be duplicated
• Individually job can be duplicated.
• Combination should not be duplicated

FOR combination of columns, it is giving


DISTINCT values.

GROUP BY:
• GROUP BY is used to group the records according to
specific column or columns.
• Syntax: GROUP BY <grouping_column_list>
• Ex:
○ GROUP BY deptno => 10, 20, 30 => 3 groups
▪ If deptno is same, it will be treated as one group

○ GROUP BY job => ANALYST CLERK MANAGER


▪ if job value is same, it will be treated as one group

• After grouping records, we can apply aggregate


functions on group of records. To apply Aggregate
functions [group functions] on group of records, we use
GROUP BY.

• It can be used for data analysis.

• It is used to get summarized data from detailed data.

Example:

DETAILED DATA
SUMMARIZED DATE
EMP
EMPNO ENAME DEPTNO SAL
deptno sum_of_sal
1001 A 20 5000
20 14000
1002 B 20 9000
30 11000
1003 C 30 4000
10 14000
1004 D 30 7000
1005 E 10 8000
1006 F 10 6000

Examples on GROUP BY:


Find dept wise sum of salaries:

SELECT deptno, sum(Sal)

Oracle2PM Page 97
SELECT deptno, sum(Sal)
FROM emp
GROUP BY deptno
ORDER BY deptno;

Output:
deptno sum(Sal)
10 10000
20 25000
30 12000

Find dept wise sum of salaries. Find it for


deptno 10 & 30:

SELECT deptno, sum(Sal) Execution order of clauses:


FROM emp
WHERE deptno IN(10,30) FROM
GROUP BY deptno WHERE
ORDER BY deptno; GROUP BY
HAVING
FROM emp: SELECT
It selects entire table. DISTINCT
ORDER BY
EMP
EMPNO ENAME DEPTNO SAL
1001 A 20 5000
1002 B 20 9000
1003 C 30 4000
1004 D 30 7000
1005 E 10 8000
1006 F 10 6000

WHERE deptno IN(10,30):


It filters the rows.

EMP
EMPNO ENAME DEPTNO SAL
1003 C 30 4000
1004 D 30 7000
1005 E 10 8000
1006 F 10 6000

GROUP BY deptno:
It groups the records

1003 C 30 4000
1004 D 30 7000

1005 E 10 8000
1006 F 10 6000

On group of records aggregate function


will be applied

SELECT deptno,sum(Sal):
It selects the columns

deptno sum(Sal)

Oracle2PM Page 98
30 11000
10 14000

ORDER BY deptno:
it arranges records in asc / desc
order.

deptno sum(Sal)
10 14000
30 11000

Dept wise max salary & min salary:

SELECT deptno, max(sal) as max_Sal,


min(sal) as min_sal
FROM emp
GROUP BY deptno
ORDER BY 1;

Output:
deptno max_sal min_Sal
10 … ..
20 … …
30 … …

Find dept wise no of emps:

SELECT deptno, count(*) as no_of_emps


FROM emp
GROUP BY deptno
ORDER BY 1;

Output:

deptno no_of_emps
10 3
20 5
30 6

Find dept wise avrg salary:

SELECT deptno, TRUNC(avg(sal),2) as avrg_sal


FROM emp
GROUP BY deptno
ORDER BY 1;

Find year wise no of emps joined in


organization:

SELECT to_char(hiredate,'YYYY') as Year,


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

Oracle2PM Page 99
count(*) as no_of_emps
FROM emp
GROUP BY to_char(hiredate,'YYYY')
ORDER BY year;

Output:

YEAR no_of_emps
1980 1
1981 10
1982 2
1983 1

SELECT to_char(hiredate,'YYYY') as Year,


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

-- displays year wise no of emps joined in organization

SELECT to_char(hiredate,'YYYY') as Year,


count(*) as no_of_emps
FROM emp
GROUP BY Year
ORDER BY year;

ERROR: "Year" Invalid Identifier

Execution Order:

FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY

Can we use alias name in ORDER BY?


Yes. Because, ORDER BY gets executed after
SELECT

Can we use alias name in GROUP BY?


No. Because, GROUP BY gets executed
before SELECT

Find Job wise Sum Of salaries:

Job Sum_Of_Salaries
CLERK …
MANAGER …
ANALYST …

SELECT job, sum(sal) as sum_of_salaries


FROM emp
GROUP BY job;

Oracle2PM Page 100


Find job wise max salary & min salary:

Job max_sal min_sal

SELECT job, max(Sal) as max_Sal,


min(Sal) as min_sal
FROM emp
GROUP BY job;

Find job wise no of emps:

job no_of_emps
CLERK 4
MANAGER 3

SELECT job, count(*) as no_of_emps


FROM emp
GROUP BY job;

Example:

SALES
DateId Amount
1-JAN-2018 1000000
2-JAN-2018 700000
.. ..
31-DEC-2018 1200000
1-JAN-2019 900000
..
..
23-NOV-2022 1300000

Find year wise sales:

YEAR SALES SELECT to_char( DateId,'YYYY') as year,


2018 … Sum(Amount) as sales
2019 … FROM sales
2020 … GROUP BY to_char( DateId,'YYYY')
2021 … ORDER BY year;

2022 …

Find quarter wise sales:

SALES
DateId Amount
1-JAN-2018 1000000 Quarter Sales
2-JAN-2018 700000 1 ..
.. .. 2 ..
31-DEC-2018 1200000 3 ..
1-JAN-2019 900000 4 ..
..
..
23-NOV-2022 1300000

Oracle2PM Page 101


SELECT to_Char(dateId,'Q') as quarter,
Sum(Amount) as sales
FROM sales
GROUP BY to_Char(dateId,'Q')
ORDER BY quarter;

HAVING clause:
• "HAVING" is used to write the conditions
on groups.
• It cannot be used without GROUP BY.
It must be followed by GROUP BY.
• It will be applied on result of GROUP BY.
• It filters the groups.
• Aggregate functions [group functions]
can be used in HAVING clause.

Examples on HAVING clause:

Display the deptnos which are spending


more than 9000 on their emps:

SELECT deptno,Sum(Sal)
FROM emp
GROUP BY deptno
HAVING sum(Sal)>9000;
ORDER BY deptno;

Display the deptnos which are


having 5 emps:

SELECT deptno, count(*)


FROM emp
GROUP BY deptno
HAVING count(*)=5
ORDER BY deptno;

Display the deptnos which are


having more than 5 emps:

SELECT deptno, count(*)


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

Display the job titles on which


organization is spending less than
6000:

SELECT job, sum(Sal)


FROM emp
GROUP BY job
HAVING sum(Sal)<6000;

Differences WHERE clause & HAVING clause:

Oracle2PM Page 102


Differences WHERE clause & HAVING clause:

WHERE HAVING

• WHERE clause is • HAVING clause is used to write


used to write conditions the conditions on groups.
on rows

• filters the groups Execution ORDER


• It filters the rows
---------------------------
FROM
• aggregate functions • aggregate functions WHERE
cannot be used in can be used in GROUP BY
WHERE clause HAVING clause HAVING
SELECT
DISITNCT
• It can be used without • It cannot be used without ORDER BY
GROUP BY GROUP BY

• It gets executed • It gets executed after


before GROUP BY GROUP BY

Grouping the records according to multiple columns:

GROUP BY deptno If deptno is same, it will


be treated as one group
Ex: 10 20 30
GROUP BY job If job is same, it will be
treated as 1 group
Ex: CLERK MANAGER
GROUP BY If year is same, it will be
to_Char(hiredate,'YYYY') treated as 1 group
Ex: 1980 1981 1982

GROUP BY deptno, job:

If deptno & job are same, it will be treated


as 1 group.

Ex:
EMP GROUP BY deptno,job
EMPNO ENAME deptno job
10 CLERK
10 CLERK
10 CLERK
20 ANALYST
20 ANALYST
20 ANALYST
10 MANAGER
10 MANAGER
30 SALESMAN
30 SALESMAN
20 MANAGER
30 SALESMAN
30 MANAGER
20 MANAGER
20 CLERK
30 MANAGER
20 CLERK
20 CLERK

Find dept wise, job wise sum of salaries:

Oracle2PM Page 103


Find dept wise, job wise sum of salaries:

deptno job sum(Sal)


10 MANAGER ..
20 MANAGER ..
30 MANAGER
10 CLERK ..
20 CLERK ..
30 SALESMAN ..

break on deptno skip 1

SELECT deptno, job, Sum(sal)


FROM emp
GROUP BY deptno,job
ORDER BY deptno;

Calculating Sub totals & Grand Total:

To calculate sub totals & grand total, we


can use 2 functions. They are:
• Rollup()
• Cube()

Rollup():
• Rollup() function is used to calculate
sub totals & grand total.
• It is used to calculate sub totals &
grand total according to first column in
grouping column list.

Ex:
GROUP BY Rollup(deptno,job)

calculates dept wise sub totals &


grand total

GROUP BY Rollup(job,deptno)

calculates job wise sub totals &


grand total

Cube():
• Cube() function is used to calculate sub
totals & grand total.
• It is used to calculate sub totals &
grand total according to all columns in
grouping column list.

Ex:
GROUP BY Cube(deptno,job)

calculates dept wise sub totals, job


wise sub totals & grand total

Oracle2PM Page 104


Examples on Rollup() & Cube():

Display dept wise, job wise sum of salaries.


calculate sub totals & grand total according to
deptno:

SELECT deptno, job, sum(Sal)


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

Display dept wise, job wise sum of salaries.


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

SELECT deptno, job, sum(Sal)


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

Display year wise, quarter wise no of emps


joined in organization: GROUP BY to_char(hiredate,'YYYY'), to_Char(hiredate,'Q')

HIREDATE to_char(hiredate,'YYYY') to_char(hiredate,'Q')


1980 1 ? --------------
2 ? 17-FEB-1980
3 ? 27-JAN-1980
4 ? 15-MAR-1980
1981 1 ?
20-MAY-1980
2 ?
19-APR-1980
3 ?
4 ?

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


to_Char(hiredate,'Q') as quarter,
count(*) as "no of emps"
FROM emp
GROUP BY to_char(hiredate,'YYYY'), to_Char(hiredate,'Q')
ORDER BY year;

Display year wise, quarter wise no of emps joined in


organization. calculate sub totals & grand total
according to year:

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


to_Char(hiredate,'Q') as quarter,
count(*) as "no of emps"
FROM emp
GROUP BY Rollup(to_char(hiredate,'YYYY'),
to_Char(hiredate,'Q'))
ORDER BY year;

Display year wise, quarter wise no of emps joined in


organization. calculate sub totals & grand total

Oracle2PM Page 105


organization. calculate sub totals & grand total
according to year and quarter:

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


to_Char(hiredate,'Q') as quarter,
count(*) as "no of emps"
FROM emp
GROUP BY Cube(to_char(hiredate,'YYYY'),
to_Char(hiredate,'Q'))
ORDER BY year;

Example:

SALES
DateId Amount
1-JAN-2018 1000000 year quarter sales
2-JAN-2018 700000 2018 1 ..
.. .. 2 ..
31-DEC-2018 1200000 3 ..
1-JAN-2019 900000 4 ..
.. 2019 1 ..
.. 2 ..
23-NOV-2022 1300000 3 ..
4 ..

Display year wise, quarter wise sales:

SELECT to_Char(dateid,'YYYY') as year,


to_Char(dateid,'Q') as quarter,
sum(amount) as sales
FROM sales
GROUP BY to_Char(dateid,'YYYY'),to_Char(dateid,'Q')
ORDER BY year;

Display year wise, quarter wise sales. calculate year wise


collection [sub totals] & grand total:

SELECT to_Char(dateid,'YYYY') as year,


to_Char(dateid,'Q') as quarter,
sum(amount) as sales
FROM sales
GROUP BY Rollup(to_Char(dateid,'YYYY'),to_Char(dateid,'Q'))
ORDER BY year;

Display year wise, quarter wise sales. calculate year wise


collection [sub totals], quarter wise collection [sub totals] & grand
total:

SELECT to_Char(dateid,'YYYY') as year,


to_Char(dateid,'Q') as quarter,
sum(amount) as sales
FROM sales
GROUP BY Cube(to_Char(dateid,'YYYY'),to_Char(dateid,'Q'))
ORDER BY year;

Example:

PERSON

Oracle2PM Page 106


PERSON
PID PNAME STATE GENDER AGE AADHAR
TS M
TS M
TS M
TS F
TS F
MH M
MH M
MH F
MH F

STATE GENDER NO_OF_PEOPLE


TS M ..
F ..
MH M ..
F ..
UP M ..
F ..

Find state wise, gender wise no of people:

SELECT state, gender, count(*) as no_of_people


FROM person
GROUP BY state, gender
ORDER BY state;

Find state wise, gender wise no of people. calculate


state wise population [sub totals] & india population
[grand total]:

SELECT state, gender, count(*) as no_of_people


FROM person
GROUP BY Rollup(state, gender)
ORDER BY state;

Find state wise, gender wise no of people. calculate


state wise population [sub totals], gender wise
population [sub totals] & india population [grand
total]:

SELECT state, gender, count(*) as no_of_people


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

Clauses:

Clause => part of a query

SELECT command clauses:

SELECT used to specify column list


Ex: SELECT ename,sal
FROM used to specify table list
Ex: FROM emp
WHERE used to write conditions on rows
Ex: sal>3000

Oracle2PM Page 107


GROUP BY used to group the records according to specific
column/columns
Ex: GROUP BY deptno => 10 20 30
HAVING used to write conditions on groups
Ex:
GROUP BY deptno
HAVING count(*)>5
ORDER BY used to arrange the records in asc or desc order
default => ASC
Ex:
ORDER BY sal DESC
ORDER BY ename ASC

DISTINCT used to avoid duplicate values


Ex:
SELECT job / SELECT ALL job => all job values
SELECT DISTINCT job => every job value will be
displayed only once.
Ex:
MANAGER
CLERK
ANALYST

Execution ORDER:

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

Oracle2PM Page 108


Sub Queries
Friday, November 25, 2022 2:22 PM

Sub Queries [Nested Queries]:


Writing a query in another query is called "Sub Query
/ Nested Query".

Syntax:

SELECT <column_list>
FROM <table_name>
Display the emp records whose salary is
WHERE <column> <operator> (<SELECT query>);
more than BLAKE's salary:

BLAKE 2850

SELECT empno,ename,sal
Sub Queries [Nested Queries]: FROM emp
• Writing a query in another query is called WHERE sal>(SELECT sal FROM emp
"Sub Query / Nested Query". WHERE ename='BLAKE');
• Outside query is called "Outer / Main / Parent Query".
• Inside query is called "Inner / Sub / Child query".
• We must write sub query in parenthesis.
○ Ex: SELECT ……(SELECT query);
• When WHERE clause condition value is unkonown, to
find this value we write Sub Query.
• Inner query must be "SELECT" only. It cannot be
INSERT/UPDATE/DELETE. Because, We need to find
WHERE clause condition value. SELECT query finds
[selects] the value. INSERT / UPDATE / DELETE queries
cannot find the value.
• Outer query can be SELECT / INSERT / UPDATE /
SELECT
DELETE.
WHERE …(SELECT
• First inner query gets executed. This inner query result
(SELECT
becomes input for outer query. Then outer query gets
(SELECT ..
executed.
)))
• Sub queries can be nested up to 255 levels.

255 levels

Types of Subqueries:

5 Types:

• Single Row Sub Query


• Multi Row Sub Query
• Correlated Sub Query
• Inline view / Inline Sub Query
• Scalar Sub Query

Single Row Sub Query:


• If sub query returns one row then it is called
"Single Row Sub Query".

Examples on Single Row Sub Query:

Display the emp records whose salary is more

Oracle2PM Page 109


• Display the emp records whose salary is more
than BLAKE's salary:

BLAKE 2850

SELECT empno,ename,sal
FROM emp
WHERE sal>(BLAKE's salary => ?);

SELECT empno,ename,sal
FROM emp
WHERE sal>(SELECT sal FROM emp
WHERE ename='BLAKE');

NOTE:
SELECT ename,max(Sal) FROM emp; -ERROR

WHEN aggregate function is used we cannot


write column names.

SELECT deptno,max(Sal) FROM emp


GROUP BY deptno;
--displays dept wise max salary

SELECT ename,deptno,max(Sal) FROM emp


GROUP BY deptno;
--ERROR: ename is not grouping column

When GROUP BY is used, In SELECT clause we


can write aggregate [group] function or
grouping column.

Finding max salary:

SELECT max(Sal) FROM emp;

Find 2nd max salary:

Sal
SELECT max(sal) FROM emp
------
WHERE sal < (max sal)
2000
4000 sal<6000
6000
3000 2000
2500 4000
5000 3000 max sal => 2nd max sal
4500 2500
5000 5000 => 2nd max sal
4500

• find the salaries < max sal


• In these salaries find max value => 2nd max salary

Oracle2PM Page 110


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

Find 3rd max salary:

Sal SELECT max(sal) FROM emp


------ WHERE sal<(2nd max salary);
2000
4000 sal<5000
6000
3000 2000
2500 4000
max sal => 3rd max sal
5000 3000
4500 => 3rd max salary
4500 2500
4500

SELECT max(sal) FROM emp


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

Find the emp name who is earning maximum


salary:

max salary= 5000

SELECT ename FROM emp


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

Find emp name who is earning 2nd max salary:

SELECT ename FROM emp


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

Find emp name whos earning 3rd max salary:

SELECT ename FROM emp


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

Find most senior's hiredate:

Oracle2PM Page 111


SELECT min(hiredate) FROM emp;

Find most junior's hiredate:

SELECT max(hiredate) FROM emp;

Display the emp name who is most senior in all


employees:

SELECT ename FROM emp


WHERE hiredate = (find most seniors hiredate);

SELECT ename FROM emp


WHERE hiredate = (SELECT min(hiredate) FROM emp);

Display the emp name who is most junior in all


employees:

SELECT ename FROM emp


WHERE hiredate =(most junior's hiredate);

SELECT ename FROM emp


WHERE hiredate = (SELECT max(hiredate) FROM emp);

Display the emp records who are junior to KING:


(or)
Display the emp records who joined after KING's hiredate:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate>(find KING's hiredate);

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate>(SELECT hiredate FROM emp
WHERE ename='KING');

Display the emp records who are senior to KING:


(or)
Display the emp records who joined before KING's hiredate:

SELECT empno,ename,hiredate
FROM emp
WHERE hiredate<(SELECT hiredate FROM emp
WHERE ename='KING');

Update JAMES salary as deptno 30's max salary:

UPDATE emp SET sal=(Find deptno 30's max sal)


WHERE ename='JAMES';

UPDATE emp
SET sal=(SELECT max(sal) FROM emp WHERE deptno=30)
WHERE ename='JAMES';

Oracle2PM Page 112


Delete most senior's record from emp table:

DELETE FROM emp


WHERE hiredate=(Find most senior's hiredate);

DELETE FROM emp


WHERE hiredate=(SELECT min(hiredate FROM emp);

Find the deptno which is spending max


amount on their employees:

SELECT deptno FROM emp


GROUP BY deptno
HAVING sum(Sal)=(Find max value in dept
wise sum of salaries);

SELECT deptno FROM emp


GROUP BY deptno
HAVING sum(sal) = (SELECT max(sum(Sal))
FROM emp
GROUP BY deptno);

Find the job title on which organization is


spending max amount on their emps:

SELECT job FROM emp


GROUP BY job
HAVING sum(Sal)=(find max value in job
wise sum of salaries);

SELECT job FROM emp


GROUP BY job
HAVING sum(Sal) = (SELECT max(Sum(sal))
FROM emp GROUP BY job);

Display the deptno which is having max no of


emps:
30 => 6

SELECT deptno FROM emp


GROUP BY deptno
HAVING count(*) = (SELECT max(count(*))
FROM emp GROUP BY deptno);

Display the dept name which is having max no


of emps:

SELECT dname FROM dept


WHERE deptno = (Find deptno which is having
max no of emps);

Oracle2PM Page 113


SELECT dname FROM dept
WHERE deptno = (SELECT deptno FROM emp
GROUP BY deptno
HAVING count(*) = (SELECT max(count(*))
FROM emp GROUP BY deptno)
);

Display the dept name on which organization is


spending maximum amount:

SELECT dname FROM dept


WHERE deptno=(Find deptno which spending
max amt on emps);

SELECT dname FROM dept


WHERE deptno = (SELECT deptno FROM emp
GROUP BY deptno
HAVING sum(Sal) = (SELECT max(sum(sal))
FROM emp
GROUP BY deptno));

Multi Row Sub Query:


• IF sub query returns multiple rows then it
is called "Multi Row Sub Query".

Examples on Multi Row Sub Query:

Display the emp records whose job title is


equals to JAMES & BLAKE job titles:

JAMES CLERK
BLAKE MANAGER

SELECT empno,ename,job,sal
FROM emp
WHERE job IN(find job titles of JAMES and
BLAKE);

SELECT empno,ename,job,sal
FROM emp
WHERE job IN(SELECT job FROM emp
WHERE ename IN('JAMES','BLAKE'));

Display the emp records whose salaries are


equals to WARD & FORD salaries:

SELECT empno,ename,job,sal
FROM emp
WHERE sal IN(find salaries of WARD and
FORD);

SELECT empno,ename,job,sal FROM emp


WHERE sal IN(SELECT sal FROM emp
WHERE ename IN('WARD','FORD'));

Oracle2PM Page 114


WHERE ename IN('WARD','FORD'));

ANY & ALL:


ALL:
• It is used to compare column value with a list of values
• It avoids of writing multiple conditions using AND operators.
• ALL opereator preceded with relational operator like:
> < >= <= = !=
Syntax:
<column> <relational_operator> ALL(<value_list>)

Ex:
sal > ALL(2000,3000) sal>2000 AND sal>3000

sal
---------
2500

6000

4000

1500

sal < ALL(1000,2000,3000) sal<1000 AND sal<2000 AND sal<3000

ANY:
• It is used to compare column value with a list of values.
• It is used to avoid of writing multiple conditions using OR.

Syntax:
<column> <relational_operator> ANY(<value_list>)

Exs:
sal > ANY(1000,2000) sal>1000 OR sal>2000
sal < ANY(1000,2000) sal<1000 OR sal<2000
sal = ANY(1000,2000) sal=1000 OR sal=2000

sal IN(1000,2000)

Display the emp records whose salary is


more than 1600 and 2000:

SELECT empno,ename,sal
FROM emp
WHERE sal> ALL(1600,2000);

Display the emp records whose salary is


more than 1600 or 2000:

Oracle2PM Page 115


SELECT empno,ename,sal
FROM emp
WHERE sal>ANY(1600,2000);

multi equality condition using OR IN


multi > / multi < / multi >= using AND ALL
multi > / multi < / multi >= using OR ANY

Display the emp records whose salaries are more


than WARD & FORD salaries:

WARD 1250
FORD 3000

SELECT empno,ename,sal
FROM emp
WHERE sal>ALL(find WARD & FORD salaries);

SELECT empno,ename,sal
FROM emp
WHERE sal>ALL(SELECT sal FROM emp
WHERE ename IN('WARD','FORD'));

Display the emp records whose salaries are more


than WARD or FORD salaries:

WARD 1250
FORD 3000

SELECT empno,ename,sal
FROM emp
WHERE sal>ANY(SELECT sal FROM emp
WHERE ename IN('WARD','FORD'));

Correlated Sub Query:


• If outer query passes value to inner query
then it is called "Correlated Sub Query".
• In Normal Sub queries, first inner query will
be executed. And Inner query gets executed
only once. WHEREAS in Correlated Sub
Query first outer query gets executed. Then
inner query will be executed. IN this, Inner
query will be executed for multiple times.
• Number of values passed by outer query =
number of execution times of inner query

Execution process of Correlated Sub Query:


Steps:
• First outer query gets executed. It selects a
row.

Oracle2PM Page 116


row.
• Outer query passes value to inner query.
• Inner query gets executed.
• Inner query passes value to outer query.
• Outer query condition will be tested. If
condition is TRUE, row will be selected.
Otherwise, row will not be selected.
• Above steps will be executed repeatedly for
every row.

Example on correlated sub query:

EMP
EMPNO ENAME DEPTNO SAL deptno avg(sal)
1001 10 10000 10 15000
1002 10 20000 20 4000
1003 20 5000
1004 20 3000
1002 10 20000
1003 20 5000

Display the emp records who are earning more than


their dept's avrg salary:

SELECT e.empno,e.ename,e.deptno,e.sal
FROM emp e
WHERE e.sal>(SELECT avg(sal) FROM emp
WHERE deptno=e.deptno);

Display the emp records who are earning max


salary in each dept:

emp sal = his dept's max salary => he is earning


max salary in his dept

EMP
EMPNO ENAME DEPTNO SAL
deptno max(Sal)
1001 A 10 10000
10 20000
1002 B 10 20000
20 5000
1003 C 20 5000
1004 D 20 3000

1002 B 10 20000
1003 C 20 5000

SELECT e.empno,e.ename,e.deptno,e.sal
FROM emp e
WHERE e.sal = (SELECT max(sal) FROM emp
WHERE deptno=e.deptno);

Display the emp records who are senior in each


dept:

emp hiredate = his dept's most senior's hiredate

Oracle2PM Page 117


emp hiredate = his dept's most senior's hiredate

SELECT e.empno,e.ename,e.deptno,e.hiredate
FROM emp e
WHERE hiredate = (SELECT min(hiredate) FROM
emp WHERE deptno=e.deptno);

Find 3rd max salary:


how many distinct sals > emp sal
EMP
EMPNO ENAME SAL
1001 A 5000 no of distinct sals > emp sal is 0 max sal
1002 B 8000 no of distinct sals > emp sal is 1 2nd max
1003 C 7000 no of distinct sals > emp sal is 2 3rd max sal
1004 D 6000
1005 E 4000
SELECT e.sal
1006 F 6000 FROM emp e
WHERE 2 = (find no of distinct sal > e.sal)
SELECT DISTINCT e.sal
FROM emp e
WHERE 2 = (SELECT count(DISTINCT sal)
FROM emp
WHERE sal>e.sal);

6000

Find 4th max sal:

SELECT DISTINCT e.sal


FROM emp e
WHERE 3 = (SELECT count(DISTINCT sal)
FROM emp
WHERE sal>e.sal);

Find 5th max sal:

SELECT DISTINCT e.sal


FROM emp e
WHERE 4 = (SELECT count(DISTINCT sal)
FROM emp
WHERE sal>e.sal);

Find nth max salary:

SELECT DISTINCT e.sal


FROM emp e
WHERE &n-1 = (SELECT count(DISTINCT sal)
FROM emp
WHERE sal>e.sal);

enter value for n: 3 => displays 3rd max sal

/
enter value for n: 5 => displays 5th max sal

/
enter value for n: 10 => displays 10th max sal

Oracle2PM Page 118


enter value for n: 10 => displays 10th max sal

Find top 3 salaries:

no of distinct sals > emp sal is 0 max sal


no of distinct sals > emp sal is 1 2nd max
no of distinct sals > emp sal is 2 3rd max sal

SELECT DISTINCT e.sal


FROM emp e
WHERE 3 > (SELECT count(DISTINCT sal) FROM emp
WHERE sal>e.sal);

Find top 5 salaries:

SELECT DISTINCT e.sal


FROM emp e
WHERE 5 > (SELECT count(DISTINCT sal) FROM emp
WHERE sal>e.sal);

Find top-N salaries:

SELECT DISTINCT e.sal


FROM emp e
WHERE &n > (SELECT count(DISTINCT sal) FROM emp
WHERE sal>e.sal);

enter value for n: 3 --displays top 3 salaries

/
enter value for n: 5 --displays top 5 salaries

Inline View / Inline Sub Query:

• If sub query is written in FROM clause then it is


called "Inline View or Inline Sub Query".
• It is mainly used to change execution order.
• Sub query acts like table.

Execution Order of clauses:

FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT

Oracle2PM Page 119


DISTINCT
ORDER BY

Display 3rd max sal:

Apply ranks to all emp records according sal DESC

sal
----------
7000 9000 1
6000 8000 2
8000 7000 3
9000 6000 4
4000 5000 5
5000
4000 6

SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank=3;

ERROR: "rank" Invalid Identifier


We cannot use alias name in WHERE clause

SELECT * FROM emp


* All columns of emp

SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank=3;

* all columns of sub query

Find nth max sal:

SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank=&n;

enter value for n: 3 --3rd max sal

/
enter value for n: 5 --5th max sal

Display top 3 salaries:

Oracle2PM Page 120


Display top 3 salaries:

SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank<=3;

Display top-n salaries:

SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rank
FROM emp)
WHERE rank<=&n;

ROWNUM:
• ROWNUM is a pseudo column.
• pseudo => false.
• It is used to apply row numbers to rows / records.
• Row Number will be applied on result of SELECT
query.

Examples:

Apply row numbers to all emps records:

SELECT rownum,empno,ename,sal FROM emp;

Display all managers records. Apply row numbers to


them:

SELECT rownum,empno,ename,job,sal FROM emp


WHERE job='MANAGER';

Display 3rd row in employee table:

SELECT *
FROM (SELECT rownum as rn,Empno,Ename,Sal
FROM emp)
WHERE rn=3;

Display 3rd, 5th & 11th rows from EMP table:

SELECT *
FROM (SELECT rownum as rn,Empno,Ename,Sal
FROM emp)
WHERE rn IN(3,5,11);

Display even numbered rows:

SELECT *
FROM (SELECT rownum as rn,Empno,Ename,Sal
FROM emp)
WHERE mod(rn,2)=0;

Display odd numbered rows:

Oracle2PM Page 121


Display odd numbered rows:

SELECT *
FROM (SELECT rownum as rn,empno,ename,sal
FROM emp)
WHERE mod(rn,2)=1;

Scalar Sub Query:

Scalar Sub Query:


• If sub query is written in SELECT clause the it is
called "Scalar Sub Query".
• This sub query acts like column.

Examples:

Display no of records in emp table & dept table:

SELECT (SELECT count(*) FROM emp) as EMP,


(SELECT count(*) FROM dept) as DEPT
FROM dual;

Output:
EMP DEPT
---------- ------------
14 4

Calculate each dept share in salaries:

SELECT deptno,sum(Sal) as dept_amount,


(SELECT sum(Sal) FROM emp) as total_Amount,
TRUNC((Sum(Sal)/(SELECT sum(Sal) FROM emp))*100) as PER
FROM emp
GROUP BY deptno
ORDER BY deptno;

Sub Queries / Nested Queries:

Writing query in another query is called "Sub


Query"

Types:

Single Row Sub If sub query returns 1 row


Query
Multi Row Sub If sub query returns multiple
Query rows
Correlated If outer query passes value to
inner query
Inline View If We write sub query in FROM
clause
Scalar If we write sub query in SELECT
clause

Oracle2PM Page 122


NOTE:
• In WHERE clause, we can sub queries up
to 255 levels.
• In FROM clause, we can write any no of
sub queries.
• In SELECT clause, we can write any no of
sub queries.

Oracle2PM Page 123


JOINS
Wednesday, November 30, 2022 3:07 PM

JOINS:
• JOIN => Combine / Connect / Link
• GOAL => used to retrieve data from multiple tables

COLLEGE DB

STUDENT
MARKS
FEE
STAFF
LIBRARY

S.SID = M.SID Join Condition

STUDENT S MARKS M
SID SNAME SCITY SID MATH PHY CHE
1001 A Hyd 1001 70 90 80
1002 B Delhi 1002 55 77 66
1003 C Chennai 1003 45 72 39

SID SNAME MATH


STUDENT MARKS

JOINS:
• JOIN => Combine / Connect / Link
• GOAL: JOINS concept is used to retrieve the data
from multiple tables.
• JOIN is an operation like SORTING operation,
FILTERING operation that combines one table
records with another based on CONDITION. This
condition is called "JOIN CONDITION".
• JOIN CONDITION decides which record in one
table will be joined with which record in another
table.

Types of Joins:
• Equi Join / Inner Join
• Outer Join
○ Left Outer Join
○ Right Outer Join
○ Full Outer Join
• Non-Equi Join / Inner Join
• Self Join / Inner Join
• Cross Join

Equi Join:
If Join operation is performed based on equality
condition then it is called "Equi Join".

Ex:
WHERE S.SID = M.SID

EMP E DEPT D

EMPNO DEPTNO
ENAME DNAME
JOB LOC
SAL
COMM
HIREDATE
E.DEPTNO = D.DEPTNO
MGR
DEPTNO
ENAME SAL DNAME LOC

Oracle2PM Page 124


COMM
HIREDATE
E.DEPTNO = D.DEPTNO
MGR
DEPTNO
ENAME SAL DNAME LOC
EMP DEPT

Display the emp records along with dept details:

emp e
empno ename sal deptno dept d
1001 A .. 20 deptno dname loc

1002 B .. 20 10 ACCOUNT NEW YORK

1003 C .. 30 20 RESEARCH DALLAS

1004 D .. 10 30 SALES CHICAGO

1005 E .. 10 40 OPERATIONs BOSTON

1006 F .. 30
1007 G .. ename sal dname loc

1008 H .. EMP DEPT

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno;

From Oracle 9i version onwards, we can write a


Join Query in 2 styles. They are:
• ORACLE style / NATIVE style
• ANSI style

RDBMS => ORACLE, SQL SERVER, MY SQL, DB2, POSTGRE SQL

ANSI standards

If any feature follows ANSI standard then we


get PORTABILITY.

ORACLE SQL SERVER

ORACLE style ORACLE style

Join Query Join Query

ORACLE SQL SERVER

ANSI style ANSI style

Join Query Join Query

NOTE:
In ORACLE style, to separate 2 table names we use , [comma].
In ANSI style, to separate 2 table names, we use KEYWORD.

In ORACLE style, we write Join Condition in WHERE clause.


In ANSI style, we write join condition in ON clause (or)
USING clause.

ON => best way


Because, When we write USING clause implicitly ORACLE
converts it to ON clause only.

To use USING clause, common column name must be same.


If common column name is not same, we cannot use USING
clause.

Oracle2PM Page 125


clause.

Display emp details along with dept details:

ENAME SAL DNAME LOC


EMP E DEPT D

ORACLE STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;

ANSI STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno;

[OR]

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
USING(deptno);

Display the employee records who are working in


CHICAGO:

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

ON clause used to write Join Condition


WHERE clause used to write Filter Condition

Display BLAKE record along with his dept details:

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno AND e.ename='BLAKE';

ANSI style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename='BLAKE';

Outer Join:
• Inner Join can give matched records only. It
cannot give unmatched records. TO get
unmatched records also we use "OUTER JOIN".
• Outer Join can give matched records & unmatched
records.

Oracle2PM Page 126


Outer Join = matched + unmatched
Inner Join = matched only

emp e
empno ename sal deptno dept d
1001 A .. 20 deptno dname loc

1002 B .. 20 10 ACCOUNT NEW YORK

1003 C .. 30 20 RESEARCH DALLAS


1004 D .. 10 30 SALES CHICAGO
1005 E .. 10 40 OPERATIONs BOSTON

1006 F .. 30
1007 G ..
1008 H .. unmatched record from DEPT

Unmatched records from EMP

There are 3 sub types in Outer Join. They are:


• Left Outer Join
• Right Outer Join
• Full Outer Join

Left Outer:

• Left Outer = Matched records + Unmatched records


from Left Table

NOTE:
• In ORACLE style, Join Condition decides left
table & right table

Ex:
WHERE e.deptno = d.deptno

e Left Table
d Right Table

WHERE d.deptno = e.deptno

d Left Table
e Right Table

• In ANSI style, keyword decides left table &


right table.

Ex:
FROM emp e JOIN dept d

emp Left Table


dept Right Table

FROM dept d JOIN emp e

dept Left Table


emp Right Table

(+) Outer Join Operator

Left Outer Join:


• Left Outer Join can give matched records &
unmatched records from left table.
• In ORACLE style we write (+) at right side.
• In ANSI style we use the keyword "LEFT
OUTER JOIN / LEFT JOIN".

Example:
Display the emp details along with dept details.
Also display the emp records to whom dept is not

Oracle2PM Page 127


Also display the emp records to whom dept is not
assigned:
[Left Outer Join]

ename sal dname loc


EMP e DEPT d

INSERT INTO emp(empno,ename,sal)


VALUES(1001,'A',6000);

INSERT INTO emp(empno,ename,sal)


VALUES(1002,'B',8000);

COMMIT;

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+);

ANSI STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptno;

Right Outer Join:

• Right Outer = matched + unmatched from right

• Right Outer Join can give matched records &


unmatched records from right table.
• In ORACLE style, write (+) symbol at left side.
• In ANSI style, use the keyword "Right Outer Join /
Right Join".

Example:
Display the emp records along with dept details.
Also display the depts in which emps are not
existed:
[RIGHT OUTER JOIN]:

ORACLE style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno;

ANSI style:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno;

Full Outer Join:

• Full Outer = matched + unmatched from left +


unmatched from right

• Full Outer Join can give matched records,


unmatched records from left table & unmatched
records from right table.

In ORACLE style SETS

Oracle2PM Page 128


records from right table.

In ORACLE style SETS

e.deptno = d.deptno(+) Left Outer A = {1,2,3,4,5} B={1,2,3,6,7}


e.deptno(+) = d.deptno Right Outer
e.deptno(+) = d.deptno(+) ERROR A U B = {1,2,3,4,5,6,7}

U => gives all elements from A set


LEFT OUTER JOIN => matched + unmatched from LEFT & B set without duplicated
UNION UNION
RIGHT OUTER JOIN => matched + unmatched from RIGHT

UNION does not give duplicate records

Full OUTER = LEFT OUTER UNION RIGHT OUTER


matched + unmatched from left + unmatched from right

Example:
Display all emps records along with dept details.
Also display the emp records to whom dept is not
assigned. Also display the depts in which emps are
not existed: [FULL OUTER JOIN]:

ORACLE STYLE:
FULL OUTER JOIN = Left Outer UNION Right Outer

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+)
UNION
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno;

ANSI STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno;

Display the emp records to whom dept is not assigned:


[display unmatched records only from left table emp]:
[LEFT OUTER JOIN + CONDITION]

ORACLE STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+) AND d.dname IS NULL;

ANSY STLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS NULL;

Display the depts in which emps are not existed:


[unmatched records only from DEPT table]:
[RIGHT OUTER JOIN + CONDITION]

ORACLE STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno AND e.ename IS null;

ANSI STYLE:

Oracle2PM Page 129


SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno
WHERE e.ename IS null;

Display the emp records to whom dept is not assigned.


Also Display the depts in which emps are not existed:
[unmatched from emp & dept]:
[FULL OTER JOIN + CONDITION]

ORACLE STYLE:

LEFT OUTER + CONDITION


UNION
RIGHT OUTER + CONDITION

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno(+) AND d.dname IS NULL
UNION
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno AND e.ename IS NULL;

ANSI STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname IS null OR e.ename IS null;

Venn Diagram of Joins:

Equi Join:
If join operation is performed based on equality
condition then it is called "Equi Join".
Ex:
e.deptno = d.deptno

Non-Equi Join:
If join operation is performed based on other than
equality condition then it is called "Non-Equi Join".

Ex:
WHERE e.deptno != d.deptno
WHERE e.deptno > d.deptno
WHERE e.deptno < d.deptno

Example on Non-Equi Join:

EMP e SALGRADE s

GRADE LOSAL HISAL


EMPNO ENAME SAL
---------- ---------- ----------

Oracle2PM Page 130


EMP e SALGRADE s

GRADE LOSAL HISAL


EMPNO ENAME SAL
---------- ---------- ----------
1001 A 3500
1 700 1200
1002 B 1500 2 1201 1400
1003 C 1800 3 1401 2000
1004 D 1600 4 2001 3000
1005 E 4000 5 3001 9999

ENAME SAL GRADE


EMP e SALGRADE s

ORACLE STYLE:

SELECT e.ename,e.sal,s.grade
FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;

ANSI STYLE:

SELECT e.ename,e.sal,s.grade
FROM emp e INNER JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;

SELF JOIN:
• Self Join can be also called as "Recursive Join".
• If a table is joined to itself then it is called
"Self Join".
• In this, one record in a table will be joined with
another record in same table.

Example:

EMP e EMP m
EMPNO ENAME JOB MGR EMPNO ENAME JOB MGR
1001 A MANAGER 1001 A MANAGER
1002 B CLERK 1001 1002 B CLERK 1001
1003 C ANALYST 1001 1003 C ANALYST 1001
1004 D MANAGER 1004 D MANAGER
1005 E SALESMAN 1004 1005 E SALESMAN 1004
1006 F CLERK 1004 1006 F CLERK 1004

Display the emp details along with manager


details:

Employee emp_Sal Manager mgr_Sal

ORACLE STYLE:

SELECT e.ename as employee, e.sal as emp_Sal,


m.ename as manager, m.sal as mgr_Sal
FROM emp e,emp m
WHERE e.MGR = m.empno;

ANSI STYLE:

SELECT e.ename as employee, e.sal as emp_Sal,


m.ename as manager, m.sal as mgr_Sal
FROM emp e INNER JOIN emp m
ON e.MGR = m.empno;

Oracle2PM Page 131


Display the emp records who are earning more than
their manager:

ORACLE STYLE:

SELECT e.ename as emp_name,


e.sal as emp_sal,m.ename as mgr_name,
m.sal as mgr_Sal
FROM emp e, emp m
WHERE e.mgr=m.empno AND e.sal>m.sal;

ANSI STYLE:

SELECT e.ename as emp_name,


e.sal as emp_sal,m.ename as mgr_name,
m.sal as mgr_Sal
FROM emp e INNER JOIN emp m
ON e.mgr=m.empno
WHERE e.sal>m.sal;

CROSS JOIN / Cartesian Join / Product Join:

• In Cross Join, each record in one table will be SETS


joined with every record in another table.
• We will not write any join condition for Cross Join A = {1,2,3} B = {4,5}

Example: AXB = ?

GROUPA a GROUPB b
CID CNAME CID CNAME
10 IND 40 ENG
20 AUS 50 NZ
30 WIN 60 PAK

ORACLE STYLE:

SELECT a.cname || ' VS ' || b.cname


FROM groupa a, groupb b;

ANSI STYLE:

SELECT a.cname || ' VS ' || b.cname


FROM groupa a CROSS JOIN groupb b;

Output:

IND VS ENG
IND VS NZ
IND VS PAK

AUS VS ENG
AUS VS NZ
AUS VS PAK

WIN VS ENG
WIN VS NZ
WIN VS PAK

Joins
-----------

Goal: used to retrieve data from multiple tables

Types of Joins:

Oracle2PM Page 132


Equi Join if join operation is performed based on =
Outer matched + unmatched
Left Outer matched + unmatched from left

Right matched + unmatched from right


Outer
Full Outer matched + unmatched from left & right
Self Join if a table is joined to itself
Non-Equi if join operation is performed based on other
Join than =
Cross each record in one table will be joined with
Join every record in another table

we will not write any join condition

Natural Join:

• Natural Join is also equi join.


• In this we will not write any join condition.
• It is equi join without duplicate columns

SELECT *
FROM emp e NATURAL JOIN dept d;

Example:

EMP1 e DEPT1 d LOCATION1 l COUNTRY1 c

EMPNO DEPTNO LOCID CID


ENAME DNAME LNAME CNAME
DEPTNO LOCID CID

ENAME DNAME LNAME CNAME


EMP1 e DEPT1 d LOCATION1 l COUNTRY1 c

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;

Oracle2PM Page 133


Thursday, December 1, 2022 2:27 PM

emp
empno ename sal deptno dept
1001 A .. 20 deptno dname loc

1002 B .. 20 10 ACCOUNT NEW YORK

1003 C .. 30 20 RESEARCH DALLAS

1004 D .. 10 30 SALES CHICAGO


1005 E .. 10 40 OPERATIONs BOSTON

1006 F .. 30
1007 G ..
1008 H ..

Oracle2PM Page 134


SET OPERATORS
Monday, December 5, 2022 2:37 PM

SETS
SET Operators:
A = {10,20,30,40}
B = {30,40,80,90}
Syntax:

A U B = {10,20,30,40,80,90}
<SELECT query>
A UA B ={10,20,30,40,30,40,80,90}
<SET OPERATOR>
A I B = {30,40}
<SELECT query>
A M B = {10,20}
B M A = {80,90}

• SET OPERATOR is used to combine result of


two select queries.

SQL provides following SET OPERATORS:


• UNION
• UNION ALL
• INTERSECT
• MINUS

UNION:
• it is used to get all rows selected by
2 select queries without duplicates.
• It does not give duplicate records.
• It gives result in the order.

UNION ALL:
• it is used to get all rows selected by
2 select queries including duplicates.
• It gives duplicate records.
• It does not gives result in order.

Branch-1 Branch-2

CUSTOMER1 CUSTOMER2
CID CNAME CID CNAME
1001 A 5001 D
1002 B 1002 B
1003 C 5002 E

Display the customers of Branch-1 & Branch-2


without duplicates:

SELECT cid,cname FROM customer1


UNION

Oracle2PM Page 135


UNION
SELECT cid,cname FROM customer2;

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

Display the customers of Branch-1 &


Branch-2 with duplicates:

SELECT cid,cname FROM customer1


UNION ALL
SELECT cid,cname FROM customer2;

CID CNAME
1001 A
1002 B
1003 C
5001 D
1002 B
5002 E

Differences b/w UNION & UNION ALL:

UNION UNION ALL

• does not give duplicates • It gives duplicates

• gives result in order • it does not give result in


[according to 1st column order
in SELECT query]

• Slower • Faster

Rules:
No of Columns in both SELECT queries must
Oracle2PM Page 136
• No of Columns in both SELECT queries must
be same.

Example:
SELECT cid FROM customer1
UNION
SELECT cid,cname FROM customer2;

ERROR: query block has incorrect number of


result columns

• Corresponding column data types of both


SELECT queries must be matched.

Example:

SELECT cid,cname FROM customer1


UNION
SELECT cname,cid FROM customer2;

ERROR:
expression must have same datatype as
corresponding expression

• Corresponding column names in both SELECT


queries need not to be same. [NOTE: data type
must be same]

CUSTOMER1 CUSTOMER2

cid cname cust_id cust_name

SELECT cid, cname FROM customer1


UNION
SELECT cust_id, cust_name FROM customer2;

Output:

cid cname
----------- ------------------

Oracle2PM Page 137


INTERSECT:
• It gives common records from the result
of 2 SELECT queries.

Example:
Display the common customers who are
visiting branch-1 & branch-2:

SELECT cid,cname FROM customer1


INTERSECT
SELECT cid,cname FROM customer2;

MINUS:
• it is used to get specific records from
first select query result.

Example:
Display specific customers of Branch-1:

SELECT cid,cname FROM customer1


MINUS
SELECT cid,cname FROM customer2;

Display specific customers of Branch-2:

SELECT cid,cname FROM customer2


MINUS
SELECT cid,cname FROM customer1;

Oracle2PM Page 138


It gives all records from customer2
except common records.

Cust1 U Cust2 = Cst2 U Cust1


CUst1 UA Cust2 = Cust2 UA Cust1
Cust1 I Cust2 = Cust2 I Cust1
Cust1 M Cust2 != Cust2 M Cust1

SELECT job FROM emp WHERE deptno=20;

JOB
---------
CLERK CLERK
MANAGER MANAGER
ANALYST ANALYST
CLERK
ANALYST

SELECT job FROM emp WHERE deptno=30;

JOB SALESMAN
--------- MANAGER
SALESMAN CLERK
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK

Display all job titles offered by deptno 20 & 30:

SELECT job FROM emp WHERE deptno=20


UNION
SELECT job FROM emp WHERE deptno=30;

Output:
ANALYST
CLERK
Oracle2PM Page 139
CLERK
MANAGER
SALESMAN

Display the common job titles of deptno 20 & 30:

SELECT job FROM emp WHERE deptno=20


INTERSECT
SELECT job FROM emp WHERE deptno=30;

Output:
CLERK
MANAGER

From deptno 20 & 30,


Display the specific job designations of deptno 20:

SELECT job FROM emp WHERE deptno=20


MINUS
SELECT job FROM emp WHERE deptno=30;

Output:
Analyst

From deptno 20 & 30,


Display the specific job designations of deptno 30:

SELECT job FROM emp WHERE deptno=30


MINUS
SELECT job FROM emp WHERE deptno=20;

Output:
Salesman

Oracle2PM Page 140


ORACLE
DATABASE
SQL
TABLES
PL/SQL
Rows & Columns

SQL provides 5 sub languages:

DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL SELECT
DML INSERT
UPDATE
DELETE

INSERT ALL [9i]


MERGE [9i]
DCL GRANT
REVOKE
TCL COMMIT
ROLLBACK
SAVEPOINT

Built-In Functions:

String Functions
Aggregate Functions
Conversion Functions
Date Functions
Number Functions
Miscellaneous Functions

Clauses in SELECT command:

FROM
WHERE
GROUP BY
HAVING
SELECT
Oracle2PM Page 141
SELECT
DISTINCT
ORDER BY

Sub Queries:

5 types:

Single Row
Multi Row
Correlated
Inline
Scalar

Joins:

Goal: used to retrieve data from multiple tables

Equi Join
Non-Equi Join
Self-Join

Left Outer = matched + unmatched from left


Right Outer = matched + unmatched from right
Full outer = matched + unmatched from left & right

Cross Join

SET OPERATORS

UNION
UNION ALL
INTERSECT
MINUS

Oracle2PM Page 142


VIEWS
Tuesday, December 6, 2022 2:47 PM

VIEW:
• VIEW is a Database Object.
• VIEW is a Virtual Table. [Virtual => Not Real]
• Virtual Table means, it does not have physical data &
does not occupy the memory.

Syntax to create a View:

CREATE VIEW <view_name>


AS
<SELECT query>;

EMP
EMPNO ENAME JOB SAL COMM HIREDATE DEPTNO MGR

CREATE VIEW v1
V1
AS
SELECT empno,ename,job SELECT
FROM emp; empno,ename,job
FROM emp

SELECT * FROM v1;

VIEW:
• VIEW is a Oracle Database Object.
• VIEW is a virtual table.
• Virtual table means, it does not contain physical data &
does not occupy the memory.
• It holds SELECT query.
• When we retrieve data through view, implicitly ORACLE
runs SELECT query which is holded by view.
• Every VIEW is associated with SELECT query.
• A VIEW will be created based on Table. We cannot create
a view without Table.
• A table on which a view is created is called "Base Table".

Syntax to create a View:

CREATE VIEW <view_name>


AS
<SELECT query>;

Oracle2PM Page 143


Advantages:
• provides security for the data.
• reduces complexity & simplifies the queries.

SECURITY can be implemented in 3 Levels:


• Database Level => SCHEMA [USER]
• Table Level => GRANT, REVOKE
• Data Level => VIEW

Implementing Data level Security:

Data Level security can be implemented at 2 levels:


• Column Level Security
• Row Level Security

NOTE:
• To create a view permission is required.

DBA gives permission to create the view as following:

username: system
password: nareshit

GRANT create view TO c##oracle2pm;

CREATE USER c##userC


IDENTIFIED BY userc
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO c##userC;

Example:

Log in as user:
username: c##oracle2pm
password: nareshit

Column Level Security:

Oracle2PM Page 144


EMP
EMPNO ENAME JOB SAL COMM HIREDATE MGR DEPTNO

V1
EMPNO ENAME JOB

CREATE VIEW v1
AS
SELECT empno,ename,job FROM emp;

Output:
View created.

GRANT all ON v1 TO c##userC;

Log in as c##userC:

SELECT * FROM c##oracle2pm.v1;

EMPNO ENAME JOB


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

INSERT INTO c##oracle2pm.v1 VALUES(5001,'ABC','CLERK');

Output:
1 row created

DELETE FROM c##oracle2pm.v1 WHERE empno=5001;

Output:
1 row ddeleted.

UPDATE c##oracle2pm.v1 SET job='MANAGER'


WHERE empno=7369;

Output:
1 row updated.

When we performed DML operations through view,


these will be applied on base table.

Implementing Row Level Security:


Oracle2PM Page 145
Implementing Row Level Security:

EMP
EMPNO ENAME JOB SAL COMM HIREDATE MGR DEPTNO
1001 A 10 v10
1002 B 10
1003 C 20
v20
1004 D 20
1005 E 30
1006 F 30 v30

Create a view on 20th dept emp records:

CREATE VIEW v2
AS
SELECT * FROM emp
WHERE deptno=20;

SELECT * FROM v2;

--displays deptno 20 records

Inserting deptno 20 emp record thorough view:

INSERT INTO v2(empno,ename,deptno)


VALUES(5001,'A',20);

Output:
1 row created.

To see data through view:

SELECT * FROM v2;

Output:


5001 A .. 20

Inserting deptno 10 emp record thorough view v2


which is created on deptno 20:

INSERT INTO v2(empno,ename,deptno)


Oracle2PM Page 146
INSERT INTO v2(empno,ename,deptno)
VALUES(5002,'B',10);
Output:
1 row created.

SELECT * FROM v2;


Output:
5002 record will not be displayed

v2

SELECT * FROM emp


WHERE deptno=20;

WITH CHECK OPTION clause:


• It is used to restrict the user from entering
the data which cannot be displayed by view.
• WHERE condition violated records will not be
inserted.

insert => deptno 10 => ERROR

we can insert only deptno 20 records

Example:

CREATE VIEW v3
AS
SELECT * FROM emp
WHERE deptno=20 WITH CHECK OPTION;

SELECT * FROM v3;


-- displays all deptno 20 records

INSERT INTO v3(empno,ename,deptno)


VALUES(9001,'AB',10);

ERROR: WITH CHECK OPTION - WHERE clause violation

WHERE clause condition violated records will not be


accepted through this view because of WITH CHECK
OPTION.

Oracle2PM Page 147


Our frequent operation is, retrieve data from
10 tables:

CREATE VIEW v4
AS
SELECT <10 tables_column_list>
FROM <10 table_names>
WHERE <9 Join Conditions>;

SELECT * FROM v4;


-- retrieves data from 10 tables

VIEW reduces complexity & simplifies queries

Advantages:
• security
• reduces complexity & simplifies queries

Disadvantage:
• Less Performance

Types of Views:

2 Types:

• Simple View / Updatable view


• Complex View / Read-Only view

Simple View:
• A view which is created on one table is called "Simple
View".
• We can perform DML operations [Insert/Update/Delete]
on Simple view.
It can be also called "Updatable View".

Complex View:
• If a view is created on multiple tables
then it called "Complex View".
• A view which is created using joins or group by or
having or aggregate functions or set operators or
expressions or sub queries is called "Complex view".
We cannot perform DML operations

Oracle2PM Page 148


• We cannot perform DML operations
through Complex View.
• It can be also called as Read-Only View.

Example:

Create a view for displaying emp records along with dept


details:

CREATE VIEW v5
AS
SELECT e.ename, e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;

Can we create a view from another view?


YES.

CREATE VIEW v6
AS
SELECT empno,ename,job,sal FROM emp;

CREATE VIEW v7
AS
SELECT empno,ename FROM v6;

Can we create a view without Table?


NO. But,

FORCE VIEW:
• FORCE VIEW is used create a view forcibly with
some errors like base table not existed.

CREATE FORCE VIEW v8


AS
SELECT * FROM nareshit;

This view will not work until base table is


created

create table nareshit


(
f1 number(4)
);

Oracle2PM Page 149


);

Table created.

insert into nareshit values(1001);

insert into nareshit values(1002);

insert into nareshit values(1003);

commit;

SELECT * FROM v8;

F1
----------
1001
1002
1003

After creating view, if we add column to base


table does it reflect to view?
NO.

Example:
EMP
EMPNO ENAME JOB SAL hiredate

CREATE VIEW v11 v11


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

After adding column hiredate:

SELECT * FROM v11;

empno ename job sal

After creating a view, if we add record to


base table does it reflect to view?
YES

Oracle2PM Page 150


Example:
EMP
EMPNO ENAME JOB SAL
v12
v12
SELECT empno,ename
EMPNO ENAME
FROM emp

INSERT INTO emp


VALUES(2001,'A','CLERK',5000);

SELECT * FROMv12;

empno ename
----------- -------------
2001 A

Can we use ALTER or TRUNCATE on view?


No

How we make changes in existing view


[changing SELECT query of VIEW]?

CREATE OR REPLACE VIEW

CREATE OR REPLACE VIEW v2


AS
SELECT ename,sal,deptno
FROM emp
WHERE deptno=20;

If we drop a base table does it drop the view?

No. But, the view which created on that base


table will not work until flashbacking it or
recreating it.

USER_VIEWS:
• "USER_VIEWS" is a system table (or) built-in table.
• It maintains all view information which are
created by the user.

DESC USER_VIEWS;

SELECT view_name, text FROM user_views;

SELECT view_name,text FROM user_views


Oracle2PM Page 151
SELECT view_name,text FROM user_views
WHERE view_name='V1';

Dropping view:

Syntax:
DROP VIEW <view_name>;

Ex:
DROP VIEW v1;

VIEW:
• Virtual Table
• Virtual Table => does not contains physical data
• holds SECT query

Types of Views:

• Simple View
• Complex View

Oracle2PM Page 152


SEQUENCES
Thursday, December 8, 2022 2:27 PM

SEQUENCES:
• SEQUENCE is a Database Object.
• SEQUENCE is used to create sequential integers.
• SEQUENCE is independent of Table.

Syntax to create the Sequence:

CREATE SEQUENCE <sequnece_name>


[START WITH <value>]
[INCREMENT BY <value>]
[MINVALUE <value>]
[MAXVALUE <value>]
[CYCLE / NOCYCLE]
[CACHE <size> / NOCACHE];

Example:

CREATE SEQUENCE s1;

CLAUSE DEFALULT VALUE


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10 power 28
CYCLE NOCYCLE
CACHE 20

USER_SEQUENCES:
• USER_SEQUENCES is a system table.
• It maintains all sequences information which
are created by the user.

SELECT * FROM user_sequences;

pseudo columns:
To work with sequence we use 2 pseudo columns. pseudo => false
They are:
• NEXTVAL
• CURRVAL ROWNUM
Oracle2PM Page 153
• CURRVAL ROWNUM
NEXTVAL
Syntax: CURRVAL
<sequence_name>.<seudo_column>

Ex:
S1.NEXTVAL
S1.CURRVAL

NEXTVAL returns next value in the sequence


CURRVAL returns current value in the sequence

SELECT s1.NEXTVAL FROM dual;

SELECT s1.NEXTVAL FROM dual;

SELECT s1.NEXTVAL FROM dual;

SELECT s1.CURRVAL FROM dual;

Example:

CUSTOMER
cid cname

CREATE SEQUENCE s2
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 5;

Output:
Sequence created.

CREATE TABLE customer


(
cid NUMBER(4),
cname VARCHAR2(10)
);

Oracle2PM Page 154


);

INSERT INTO customer VALUES(s2.NEXTVAL,'&cname');


Output:
enter value for cname:A

/
enter value for cname:B

/
enter value for cname:C

/
enter value for cname:D

/
enter value for cname:E

/
enter value for cname: F
ERROR: sequence reached maxval

ALTER SEQUENCE s2 MAXVALUE 10;

Example:

COURSE

CID CNAME CREATE SEQUENCE s3


10 JAVA START WITH 10
20 PYHTON INCREMENT BY 10
30 HTML MINVALUE 10
MAXVALUE 50;
40 ORACLE
50 AWS

START WITH used to specify starting value in


sequence
INCREMENT BY used to specify step value
MINVALUE used to specify minimum value
in sequence
MAXVALUE used to specify maximum value
in the sequence

Oracle2PM Page 155


CYCLE / NOCYCLE:

• Default => NOCYCLE

CREATE SEQUENCE s4
START WITH 5001
INCREMENT BY 1
MINVALUE 1000
MAXVALUE 9999
NOCYCLE;

If sequence is created with NOCYCLE,


Sequence will be started with "START WITH"
value, generates next value up to max value.
After reaching max value, it will be stopped.

CREATE SEQUENCE s4
START WITH 5001
INCREMENT BY 1
MINVALUE 1000
MAXVALUE 9999
CYCLE;

If sequence is created with cycle,


Sequence will be started with "START WITH" value,
generates next value up to max value. After
reaching max value. It will be reset to Min Value.

Oracle2PM Page 156


Cache <size> / NOCACHE:

• Default size: 20
• It improves the performance of generating
sequential integers.

CREATE SEQUENCE s7
START WITH 500
INCREMENT BY 1
MINVALUE 100 goes to DB
MAXVALUE 1000 s7
NOCACHE; 500+1
501+1
502
s7.nextval => 500
s7.nextval => 501
s7.nextval => 502

When sequence is called,


ORACLE goes to Database.
Identifies current value in the sequence.
Adds INCREMENT BY value.
Returns Sequential Number.

If we call a sequence for 10 times, 10 times it


goes to DB & performs above steps. With this
performance will be degraded

To improve the performance we use cache.

CREATE SEQUENCE s7
START WITH 500
INCREMENT BY 1
Cache
MINVALUE 100
MAXVALUE 1000 500
CACHE 100; 501
502
.
s7.nextval .
s7.nextval 599

If sequence is created with cache,


Oracle2PM Page 157
If sequence is created with cache,
sequential numbers will be
preloaded into cache memory.
With this every time, it will not go
to Database. So performance will
be improves

NOTE:
Cache size must be less than one cycle

CREATE SEQUENCE s9
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
CYCLE;

ERROR: cache size must be less than

NOTE:
CACHE size must be less than one cycle.

CREATE SEQUENCE s11


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
NOCYCLE;

Output:
Sequence created.

CREATE SEQUENCE s12


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
CYCLE;

ERROR: cache size must be less


than one cycle

Oracle2PM Page 158


than one cycle

Default cache size => 20

CREATE SEQUENCE s12


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
CYCLE
CACHE 10;

ERROR: cache size must be less


than one cycle

CREATE SEQUENCE s12


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
CYCLE
CACHE 9;

OUTPUT:
Sequence created

Can we call a sequence from UPDATE command?


YES.

Make empnos in the sequence. strat empno from 1001:

CREATE SEQUENCE s13


START WITH 1001
INCREMENT BY 1
MINVALUE 1001
MAXVALUE 9999;

Output:
Sequence created.

UPDATE emp SET empno=s13.nextval;

Output:
14 rows updated.

Oracle2PM Page 159


SELECT empno,ename FROM emp;

Output:

empno ename
-------------- ----------
1001
1002
1003
..
..
1014

Can we call a sequence from CREATE command?

From ORACLE 12c version onwards, we can call


a sequence from CREATE command also.
Before Oracle 12c, it was not possible.

Example:

CREATE SEQUENCE s14


START WITH 101
INCREMENT BY 1
MINVALUE 101
MAXVALUE 999;

CREATE TABLE student


(
sid NUMBER(3) DEFAULT s14.nextval,
sname VARCHAR2(10)
);

FROM ORACLE 12C version onwards,


We can create sequential integers using 2 ways:

• Using SEQUENCE
• Using IDENTITY [introduced in ORACLE 12C]

Syntax:

<field_name> <data_type> GENERATED ALWAYS AS IDENTITY(sequence clauses)

Oracle2PM Page 160


Syntax:

<field_name> <data_type> GENERATED ALWAYS AS IDENTITY(sequence clauses)

Example:
CUSTOMER
CID CNAME
1 A
2 B
3 C

generate sequential cids using IDENTITY:

CREATE TABLE customer


(
cid NUMBER(4) GENERATED ALWAYS AS IDENTITY,
cname VARCHAR2(10)
);

INSERT INTO customer(cname) VALUES('A');


INSERT INTO customer(cname) VALUES('B');
INSERT INTO customer(cname) VALUES('C');
COMMIT;

SELECT * FROM customer;

cid
---------
1
2
3

Example:

COURSE1

CID CNAME
10 JAVA
20 PYTHON
30 C#

CREATE TABLE course1


(
cid NUMBER(2) GENERATED ALWAYS AS

Oracle2PM Page 161


cid NUMBER(2) GENERATED ALWAYS AS
IDENTITY(START WITH 10 INCREMENT BY 10),
cname VARCHAR2(10)
);

INSERT INTO course1(cname) VALUES('JAVA');


INSERT INTO course1(cname) VALUES('PYTHON');
INSERT INTO course1(cname) VALUES('C#');
COMMIT;

SELECT * FROM course1;

Difference b/w Sequence & Identity:

Sequence is independent of table. Same


sequence can be used for many tables.

SEQUENCE s15

T1 T2
F1 F1
---- -------
1001 1006
1002 1007
1003 1008
1004
1005

Identity is related to table. In that table only


we can use sequential numbers.

Can we generate sequential numbers in


Descending Order?
YES

f1 CREATE SEQUENCE s16


---- START WITH 50
50 INCREMENT BY -1
49 MINVALUE 1
48 MAXVALUE 50;
47
Oracle2PM Page 162
50 INCREMENT BY -1
49 MINVALUE 1
48 MAXVALUE 50;
47
. SELECT s16.nextval FROM dual;
. 50
1
SELECT s16.nextval FROM dual;
49

SELECT s16.nextval FROM dual;


48

How can we modify existing sequence?

Using ALTER command we can make changes in


existing sequence.

CREATE SEQUENCE s17


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10;

ALTER SEQUENCE s17 MAXVALUE 50;

ALTER SEQUENCE s17 INCREMENT BY 2;

Dropping Sequence:

Syntax:
DROP SEQUENCE <sequence_name>;

Example:
DROP SEQUENCE s1;

User_Sequences:
• "User_Sequences" is a system table / built-in
table.
• It maintains all sequences information.

Example:
DESC user_sequences;

SELECT sequence_name FROM user_Sequences;


Oracle2PM Page 163
SELECT sequence_name FROM user_Sequences;

SELECT * FROM user_sequences;

Oracle2PM Page 164


MATERIALIZED VIEWS
Saturday, December 10, 2022 2:14 PM

Materialized View:

View:
View is a virtual table
View holds SELECT query
When we retrieve data through view, it runs SELECT query

Disadvantage:
• Less Performance

PERSON
PID PNAME STATE AGE GENDER AADHAR

Frequent operation:

CREATE VIEW v1
AS
SELECT state, count(*) as no_of_people
FROM person
GROUP BY state;

Materialized View:
• Materialized view is a Database Object.
• Materialized view is not virtual table. It means, it
contains physical data & it occupies the memory.
• Materialized view holds result of SELECT query
WHEREAS view holds SELECT query.
• It is used to maintain summarized data physically.
• It is mainly used in DataWare Housing for Data
Analysis.
• It holds precomputed result.

Advantages:
• It improves the performance.
• We can maintain local copy of remote database.

Syntax to create materialized view:

CREATE MATERIALIZED VIEW <view_name>


AS
<SELECT query>;

EMP
EMPNO ENAME JOB SAL COMM DEPTNO HIREDATE MGR

FREQUENT OPERATION:
Working with dept wise sum of salaries

VIEW M.VIEW

Oracle2PM Page 165


CREATE VIEW v1 CREATE MATERIALIZED VIEW mv1
AS AS
SELECT deptno,sum(sal) as sum_of_sal SELECT deptno,sum(sal) as sum_of_sal
FROM emp FROM emp
GROUP BY deptno GROUP BY deptno
ORDER BY deptno; ORDER BY deptno; --calculates dept wise sum of sal

v1
mv1

SELECT ………
deptno sum_of_sal
10 …
20 …
SELECT * FROM v1; 30 …
--runs select query
--calculates dept wise sum of salaries

SELECT * FROM v1; SELECT * FROM mv1;


--runs select query --retrieves data from mv1
--calculates dept wise sum of salaries
SELECT * FROM mv1;
SELECT * FROM v1; --retrieves data from mv1
--runs select query
--calculates dept wise sum of salaries SELECT * FROM mv1;
--retrieves data from mv1
SELECT * FROM v1;
--runs select query
--calculates dept wise sum of salaries SELECT * FROM mv1;
--retrieves data from mv1
SELECT * FROM v1;
--runs select query SELECT * FROM mv1;
--calculates dept wise sum of salaries --retrieves data from mv1

5 times dept wise sum of 1 time dept wise sum of


salaries calculated salaries calculated

Materialized view improves performance

EMP old result


EMPNO ENAME JOB DEPTNO SAL
10 5000 deptno sum_of_Sal
10 6000 10 11000
20 4000 20 14000
20 10000 30 19000
30 12000
30 7000
10 10000

CREATE MATERIALIZED VIEW mv1


CREATE VIEW v1
AS
AS v1 SELECT deptno,sum(sal) as sum_of_sal
SELECT deptno,sum(sal) as sum_of_sal
FROM emp
FROM emp SELECT …. GROUP BY deptno
GROUP BY deptno
ORDER BY deptno;
ORDER BY deptno;

SELECT * FROM mv1;

SELECT * FROM v1;

deptno sum_of_Sal
deptno sum_of_Sal 10 11000
10 21000 20 14000

Oracle2PM Page 166


SELECT * FROM v1;

deptno sum_of_Sal
deptno sum_of_Sal 10 11000
10 21000 20 14000
20 14000 30 19000
30 19000
After inserting new record,

If we add any record to base table


SELECT * FROM mv1;
that will be reflected to view.
Because, When we retrieve data
old_result
through view every time it runs
select query. deptno sum_of_Sal
View always gives recent data. 10 11000
20 14000
30 19000

If we can make changes to base table, it will not


Log in as DBA: be reflected to materialized view. Because,
8750+3000 = 11750
username: system M.view holds precomputed result.
password: nareshit
That's why we must refresh the materialized view
GRANT create materialized view to get recent data.
TO c##oracle2pm;

Refreshing Materialized view:

• Applying changes of base table to materialized


view is called "Refreshing M.View".

We can refresh a materialized view using 3 ways:


• ON DEMAND [Default]
• ON COMMIT
• IN REGUTLAR INTERVAL OF TIME

ON DEMAND:
• In "ON DEMAND", we call a procedure to
refresh materialized view.

refresh() •is a procedure


•it is used to refresh m.view
dbms_mview •is a package

Syntax to call packaged procedure:

package_name.procedure_name

dbms_mview.refresh('MV1');

Example:

CREATE MATERIALIZED VIEW mv2


REFRESH
ON DEMAND
AS
SELECT deptno,sum(sal) FROM emp
GROUP BY deptno;

SELECT * FROM mv2;

UPDATE emp SET sal=sal+1000;

COMMIT;

SELECT * FROM mv2;

EXEC dbms_mview.refresh('MV2');

Oracle2PM Page 167


EXEC dbms_mview.refresh('MV2');

SELECT * FROM mv2;

ON COMMIT:
In this way,
WHEN COMMIT command is executed then
m.view will be refreshed.

CREATE MATERIALIZED VIEW mv3


REFRESH
ON COMMIT
AS
SELECT deptno,sum(sal) FROM emp
GROUP BY deptno;

SELECT * FROM mv3;

UPDATE emp SET sal=sal+1000;

SELECT * FROM mv3;

COMMIT;

SELECT * FROM mv3;

Oracle2PM Page 168

You might also like