0% found this document useful (0 votes)
600 views249 pages

ORACLE4PM

The document provides information about an Oracle database administration training session, including contact details for the administrator, links to installation video and notes, and the session schedule and topics to be covered over 9 days. It also defines key database concepts like what a database, DBMS, RDBMS, metadata, and how Oracle fits among other database management systems. The topics to be covered include SQL, PL/SQL, database concepts, and how data is structured in tables and relations in a relational database.
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)
600 views249 pages

ORACLE4PM

The document provides information about an Oracle database administration training session, including contact details for the administrator, links to installation video and notes, and the session schedule and topics to be covered over 9 days. It also defines key database concepts like what a database, DBMS, RDBMS, metadata, and how Oracle fits among other database management systems. The topics to be covered include SQL, PL/SQL, database concepts, and how data is structured in tables and relations in a relational database.
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/ 249

Thursday, April 20, 2023 5:40 PM

Admin name: Upender


WhatsApp Number:
Notes Link:
7997998954
https://bit.ly/oracledbnotes
s/w installation doubts:
ORACLE installation video link:
7794914592(whatsapp only)
https://bit.ly/orainstall
Kalyan [offline]
7893426469

ORACLE @ 4:00 PM (IST) by Mr. Shiva Chaitanya ¥

Day-1 https://youtu.be/UeMnnCqTY_o
Day-2 https://youtu.be/FpCHkGp4UMc
Day-3 https://youtu.be/pFX2pR8BFU0
Day-4 https://youtu.be/9AQQ4mNNafE
Day-5 https://youtu.be/epDMjhClQwE
Day-6 https://youtu.be/tyWq-ovCdac
Day-7 https://youtu.be/lwJuQjtwNF0
Day-8 https://youtu.be/UI1v8icChXk
Day-9 https://youtu.be/ZCPSOMlnHFQ

ORACLE4PM Page 1
Syllabus
Thursday, April 20, 2023 5:33 PM

SQL PL/SQL

5 sub languages: PL/SQL basics


DDL, DRL, DML, DCL, TCL print
read
Built-In Functions declare
assign
Clauses
Using SQL commands in PL/SQL
Sub Queries
Control Structures
Joins
Cursors
Views
Exception Handling
Indexes
Stored Procedures
Materialized Views Stored Functions

Sequences Packages

Synonyms Triggers

Collections

Working with LOBs

Dynamic SQL

ORACLE4PM Page 2
ORACLE
Thursday, April 20, 2023 4:20 PM

ORACLE

SQL
PL/SQL

Database
DBMS
RDBMS
Metadata

Database:

Bank DB College DB Amazon DB

Branches Courses Products


Customers Student Customers
Transactions Marks Orders
Staff Fee Suppliers
Products Library Manufacturers
Staff

Database:
• Database is a collection of interrelated data in an
organized form.
• database contains interrelated data.
• Database must be organized. Organized means,
arranging in systematic way. With this maintenance
will become easier.
• Database is complete details of an organization stored
in computer hard disk in meaningful format.

to watch the movies media player s/w


to visit the websites browser s/w
to create & maintain the database DBMS

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

GOAL: storing business data permanently in computer hard disk

Before 1960s => manually in Books

1960s => FMS [File Management System]


unsuccessful
1970s => Hierarchical DBMS softwares
Network DBMS

1976 => RDBMS Concept => E.F.Codd

1979 => introduced ORACLE s/w => RDBMS s/w

ORACLE4PM Page 3
1977 => ORACLE comapany established with the name
Software Development Laboratories => Larry Ellison

1979 => company name renamed as "Relational Software Inc."


oracle s/w introduced in 1979

1983 => company name renamed as "ORACLE Corporation".

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

Example:

CUSTOMER => Table / Relation / Entity

cid cname ccity


1001 SAI HYD Row / Tuple / Record / Entity instance
1002 ARUN MUMBAI

Column / Attribute / Field / Property

Table is a collection of rows & columns


record is a collection of field values
field is a collection of individual values

Examples:
ORACLE, SQL SERVER, MY SQL, DB2, Postgre SQL

DBMS
COMPUTER
RDBMS
LAPTOP
ORACLE => oracle company
DELL
SQL SERVER => microsoft company
MICROSOFT
DB2 => IBM
APPLE
MY SQL => Sun micro sys (ORACLE)
HP
Postgre SQL => postgre

ORACLE SQL SERVER MY SQL


database database database
tables tables tables

select select select

SQL SQL SQL

number(4) int
money

to_char() datepart()

Metadata:
Metadata is the about the data.
Examples:

ORACLE4PM Page 4
Examples:
field names => empno, emp_name,salary
table name => employee
data type => number, varchar2, date
field size => 4, 10

EMPLOYEE

number(4) varchar2(10)
empno emp_name salary
1001 RAMU 6000
RAJU ERROR
9999
10000 ERROR
-9999 to
9999

Database collection of interrelated data in an organized way

DBMS is a software
create & maintain the database

RDBMS is a software
create & maintain the database in the form of tables

Exs: ORACLE, SQL SERVER, MY SQL

Metadata Data about the data


Ex: table name, field name, field size, data type

ORACLE

• ORACLE is Relational DataBase Management Software.


• It is product of ORACLE company.
• Its 2nd version released in 1979. They didn't release first
version to the market.
• Latest version is: ORACLE 21C.

• ORACLE is used to create & maintain the database in


the form of tables.

• It allows us to store, manipulate and retrieve the data of


database.

• manipulate => INSERT / UPDATE [modify] / DELETE


○ emp joined => INSERT
○ emp promoted => UPDATE
○ emp resigned => DELETE

customer opening account => INSERT

withdraw => UPDATE the balance


deposit => UPDATE

closing => DELETE

• Retrieve => opening existing data [get back] /


selecting the data

Exs:
ATM Bank DB Server
check balance
50000 customers
acno balance

ORACLE4PM Page 5
acno balance
1234 50000
1235 100000

online shopping
searching products

ORACLE
SQL DATABASE
PL/SQL TABLES
ROWS & COLUMNS

To communicate with ORACLE DB, we can use 2 Languages.


They are:
• SQL
• PL/SQL C, C#, Java, Python

programming languages
SQL: software
• SQL stands Structured Query Language. programs
• SQL is a Query Language that is used to communicate with
ORACLE DB.
• In SQL we write the queries to communicate with DB.
• Query is a request that is sent to DB SERVER.
○ Ex: SELECT ename,sal FROM emp;

ATM Client
Bank DB Server

check balance => request =>


Account
SELECT balance FROM account
WHERE acno=1234 acno balance
1234 50000
QUERY 1235 10000

balance: 50000

OPENING ACCOUNT

Fill Form

firstname
lastname
city
mobile
mailid
DB SERVER
Submit => Request =>
INSERT INTO customer Customer
VALUES(…,…, … ….) cid fname lname city

QUERY

In C: sub programs
• SQL is Non-Procedural Language. It means, we Function:
will not write any set of statements or a set of statements
programs in SQL. Just we write the Queries.
In Java:
• SQL is unified language. It is common Method:
language to communicate with many RDBMSs. a set of statements

In PL/SQL:
Procedure:
a set of statements

ORACLE SQL SERVER MY SQL


DATABASE DATABASE DATABASE
TABLES TABLES TABLES
SELECT
SELECT SELECT

ORACLE4PM Page 6
ORACLE SQL SERVER MY SQL
DATABASE DATABASE DATABASE
TABLES TABLES TABLES
SELECT
SELECT SELECT
INSERT
INSERT INSERT
SQL SQL SQL

1 month 2 days

number(4) numeric(4)
money

25-dec-2022

to_char() datepart()

ANSI standards
SQL

ORACLE SQL SERVER My SQL


SQL SQL SQL

OOPS concepts

JAVA C# Python

class B extends A class B : A class B(A)

• SQL provides operators to perform operations like:


+ * > < between and like

• SQL provides readymade functions [built-in functions]


○ Ex: max(), min(), lower()

• SQL provides readymade commands


○ Ex: SELECT, INSERT, UPDATE, DELETE

• SQL provides JOINS concept to retrieve the data from


multiple tables.

EMP DEPT

EMPNO ENAME DEPTNO deptno dname

1001 A 20 10 HR

1002 B 10 20 SALES

JOINS
ENAME DNAME

ORACLE
SQL DATABASE
PL/SQL TABLES
ROWS & COLUMNS

ORACLE4PM Page 7
SQL:
• Query Language that is used to communicate with DB
• Query => is a request => to DB SERVER
• Non-Procedural Language
• Unified Language
• readymade commands, functions, clauses, joins,
operators

Sub Languages of SQL:


SQL provides 5 sub languages. They are:

DDL CREATE
• Data Definition Language ALTER
• Data Definition => metadata
• deals with metadata DROP
FLASHBACK [oracle 10g]
PURGE [oracle 10g]

TRUNCATE
RENAME

DRL / DQL SELECT


• Data Retrieval Language
• Data Query Language
• Retrieval => opening existing data
• It deals with data retrievals

TCL: COMMIT
• Transaction Control Language ROLLBACK
• It deals with the transactions SAVEPOINT

DML: INSERT
• Data Manipulation Language UPDATE
• Manipulation => insert/ update/ DELETE
delete customer
• It deals with data manipulations INSERT ALL cid cname cust_city gender
MERGE

DCL: GRANT
• Data Control Language REVOKE
• It deals with data accessibility

ORACLE
DATABASE
DATABSE OBJECTS

DATABSE OBJECTS

• Tables
• Views
• Indexes
• Sequences
• Synonyms
• Materialized Views

• Stored procedures
• Stored Functions
• Packages
• Triggers

DROP => used to drop the table => delete

ORACLE4PM Page 8
DROP => used to drop the table => delete
FLASHBACK => restore the table => restore
PURGE => deletes from recyclebin => delete

EMPLOYEE
EMPNO ENAME SAL
1001 AA 6000
1002 BB 5000

DDL

create used to create the table


alter used to change structure of table
• adding column
• dropping column
• renaming column
drop used to drop the table
dropped table goes to recyclebin
flashback used to restore the table
purge used to delete the table from rbin
truncate to delete all records
rename used to change the tablename

DRL / DQL:

SELECT:
used to select the data from database

BANK DB SERVER
check balance

ACCOUNT
SELECT balance FROM account
acno balance
WHERE acno=1001;
1001 500000
1002 800000

TCL:
• It deals with transactions

• Transaction => is a series of actions [SQL commands]


• Exs:
○ withdraw, deposit, purchasing product, check balance

ACCOUNT
withdraw
ACNO BALANCE
amount: 10000 1001 50000
gives money
UPDATE the balance

COMMIT used to save the


transaction
ROLLBACK used to cancel the
transaction

DML:
Manipulation => INSERT / UPDATE / DELETE

emp joined => INSERT => new record in EMP table


emp promoted => UPDATE => modify the job title, salary
emp resigned => DELETE => delete the record

ORACLE4PM Page 9
DCL:

RAMU
emp table
GRANT
Revoke

SAI

grant used to give permission on table to


other users
REVOKE USED TO CANCEL THE PERMISSIONS

SQL:

DDL DRL TCL DML DCL


metadata data transactions manipulations data
retrievals accessibility
create SELECT COMMIT INSERT GRANT
alter ROLLBACK UPDATE REVOKE
drop SAVEPOINT DELETE
flashback
purge INSERT ALL
truncate MERGE
rename

DDL Commands:
• Data Definition Language
• Data Definition => metadata
• It deals with metadata

ORACLE SQL provides following DDL commands:


• create
• alter
• drop
• flashback
• purge
• truncate
• rename

ORACLE DB OBJECTS:

Tables
Views
CREATE Indexes
CREATE:
Synonyms
Syntax: Sequences
Materialized views
CREATE TABLE <table_name> [ ] Optional
( < > Any stored procedures
<field_name> <data_type> [, stored functions
<field_name> <data_type> , packages
STUDENT triggers
<field_name> <data_type>
sid sname dob
.
.] 1001 Ramu 25-DEC-1998
); 1002 Vijay 17-AUG-1995

ORACLE4PM Page 10
Data Types in ORACLE SQL:

sid Number(4) -9999 TO 9999 DOB date


------------- ----------
1001 25-DEC-1998
1002 17-AUG-1995
9999 1234 => ERROR
10000 => ERROR RAMU => ERROR
RAMU => ERROR
1-2-123/A => ERROR

• Data type tells which type of data a column has to accept.


• It also tells how much memory has to be allocated.
• It also tells valid range of values

ORACLE SQL provides following data types:

Character Related Char(n)


Varchar2(n) / Varchar(n)
LONG
RAMU CLOB

nChar(n)
nVarchar2(n)
nCLOB

Integer related Number(p) *****


Integer
1001, 78 Int

Floating point related Number(p,s) *****


Float
Binary_Float
78.93 Binary_Double
Structured data
Real

1001
Date & Time related Date
RAMU
Timestamp
1-2-123/A/B
25-DEC-1998
25-DEC-1998 9:30:00.00 PM

NOSQL Databases => MongoDB, Cassandra


Binary Related BFILE
[unstructured data]
BLOB
unstructured data => images,
audios, videos, documents,
animations

Character related data types:

ORACLE SQL provides following Character related data types:


• Char(n)
• Varchar2(n)
• LONG
• CLOB

• nChar(n)
• nVarchar2(n)
• nCLOB

Char(n):
• n => max no of chars
• used to hold string [a set of chars] values.
• Fixed length char data type

Varchar2(n):
n => max no of chars

ORACLE4PM Page 11
• n => max no of chars
• used to hold string [a set of chars] values.
• Variable length char data type

ename varchar2(10) GENDER Char(1)


---------------- ---------
Vijay => 5 M
Sai => 3 F
Ramesh => 6 F
Ramu => 4 M
M
F
F
M

Pname varchar2(20) State_Code Char(2)


-------------- -------------------
mouse TS
laptop AP
keyboard WB
smartphone UP

fixed variable length


length Demo1
F1 Char(10) F2 Varchar2(10)
10 raju6spaces raju 4
10 sai7spaces sai 3
10
ramesh4spaces ramesh 6

Char(n):
• n => max no of chars
• used to hold string [a set of chars] values.
• Fixed length char data type
• Max size: 2000 Bytes [2000 chars]
• Default size: 1
• can accept alpha numerics.

Varchar2(n):
• n => max no of chars
• used to hold string [a set of chars] values.
• Variable length char data type
• Max size: 4000 Bytes [4000 chars]
• Default size: no default size [we must specify size]
• can accept alpha numerics.

Example:
Pan_Card_Number CHAR(10)
--------------------------
ABC1L34567

Vehicle_Number CHAR(10)
--------------------------
TS09AA1234

mail_id VARCHAR2(30)
--------------
[email protected]
[email protected]

ORACLE4PM Page 12
LONG:
• used to hold large amounts of chars
• It has some restrictions [limitations]:
○ we can take one column as LONG type per a table
○ Built-In Functions cannot be used on LONG type

CLOB:
• CLOB stands for Character Large Object
• used to hold large amounts of chars

Examples:

product_features CLOB

customer_feedback CLOB

experience_summary CLOB

ASCII:
• is a coding system
Char(n) • ASCII code char data types • American Standard Code for Information Interchange
Varchar2(n) • can hold english lang chars only • 256 chars are coded [code range: 0 to 255] [1 byte]
LONG • Single Byte Data types • A to Z => 65 to 90
CLOB • a to z => 97 to 122
• 0 to 9 => 48 to 57
nChar(n) • UNI code char data types • remaining codes are for special symbols like: @ # $ % + -
nVarchar2(n) • can hold english + other lang chars • English lang chars only
nCLOB • Multi Byte Data types
UNI:
n => national • is a coding system
• UNIVERSAL
• is extension of ASCII
• 65536 chars are coded [rang: 0 to 65535] [2 bytes]
• english lang chars +other lang chars [japanese, chinese, greek ]

Char(n) • fixed length data type


• max size: 2000 bytes [2000 chars] In C:
char ch; // 1byte => ASCII
nChar(n) • fixed length data type
• max size: 2000 bytes [1000 chars]

In Java:
char ch; // 2 bytes => UNI
Varchar2(n) • variable length data type
• max size: 4000 bytes [4000 chars]
nVarchar2(n) • variable length data type
• max size: 4000 bytes [2000 chars]

Integer related data types:

Number(p) / Numeric(p):
• p => precision => max no of digits
• p valid range: 1 to 38
• It is used to hold integers.
• Integer means, number without decimal places
• Exs: 78, 1234, 897

Exs:

empno NUMBER(4) -9999 TO 9999


-------------
1001
1002
1003
1004
6789
9999
10000 => ERROR
RAMU => ERROR

ORACLE4PM Page 13
Max marks: 100

maths_marks NUMBER(3) -999 TO 999


-------------------
78
67
55
786
999
1000 => ERROR

Mobile_number NUMBER(10)

Aadhar_Number NUMBER(12)

CreditCard_Number NUMBER(16)

Integer = Number(38)

Int = Number(38)

Note:
• Integer and Int are alias names of Number(38)

Floating Point related Data types:

Number(p,s) / Numeric(p,s):
• p => precision => max no of digits [total no of digits]
• s => scale => max no of decimal places
• It is used to hold floating point values.
• Floating point means, number with decimal places.
• Exs: 67.89, 123.45678

max salary:

100000.00

scale => 2

precision => 8

salary NUMBER(8,2) -999999.99 TO 999999.99


----------
20000
100000
999999
1000000 => ERROR
max marks: 100
3 subjects
300/3 = 100

100.00

s=2
p=5

avrg NUMBER(5,2) -999.99 TO 999.99


--------
67.89
123.67
999.99
1000 => ERROR
123.456789 => 123.46
123.453897 => 123.45

ORACLE4PM Page 14
123.453897 => 123.45
786.658342 => 786.66
786.654342 => 786.65

height number(2,1) => -9.9 to 9.9


-------------
5.3
5.2
5.9
5.7
6.0
9.9
10 => error
6.789 => 6.8
5.7238 => 5.7

Float
Real

Binary_Float
Binary_Double

Date & Time related data types:

Date:
• It is used to hold date values.
• It can also hold time value.
• Default ORACLE DATE FORMAT: DD-MON-RR [26-APR-23]
• Default time: 12:00:00 AM [midnight time]
• It can hold day, month, year, hours, minutes and seconds.
• It cannot hold fractional seconds.
• Fixed length data type
• memory: 7 bytes
• Ex:
Date_Of_birth Date
Date_Of_Joining Date

Example:
create table t7
(
f1 date
);

insert into t7 values('25-DEC-2019');

String
t7

f1 Implicit Conversion
-------
25-DEC-19 Date

to_date():
can be used to convert string to date

Ex:
to_date('25-DEC-2019') => 25-DEC-19

String -> Date

Explicit conversion

Note:
ORACLE supports to Implicit conversion.

ORACLE4PM Page 15
• ORACLE supports to Implicit conversion.
• Don't depend on implicit conversion. Always do explicit
conversion due to 2 reasons:
○ performance will be degraded with implicit conversion
○ In future versions, implicit conversion programs may
be changed or removed

insert into t7 values(to_date('17-AUG-2022'));


string

t7
to_date()
f1 explicit conversion
----------
17-AUG-22 => date

Note:
• to insert date value, use to_date() function.
• it improves the performance.

data types in SQL:

character related:

Char(n)
Statecode char(2)
PAN_CRAD_NUMBER char(10)

Varchar2(n)
ename VARCHAR2(10)

>4000 chars
CLOB

experience_summary CLOB

nchar(n), nvarchar2(n), nclob => other lang chars

Integer related:
Number(p)

mopbile_number number(10)
aadhgar_num number(12)

100.00
Floating Point related:
Number(p,s)

avrg number(5,2)

Date & time related:

Date:
used to hold date values

DOB DATE
DOJ DATE
DOR DATE

Timestamp:
• It is introduced in Oracle 9i version.
• It can hold day, month, year, hours, minutes,
seconds and fractional seconds.
• It is extension of DATE data type.
• Fixed Length data type.
memory: 11 bytes

ORACLE4PM Page 16
• memory: 11 bytes

Example
--------------
Transaction_date_time Timestamp
Session_strat_time Timestamp

CREATE TABLE t11


(
f1 TIMESTAMP
);

INSERT INTO t11


VALUES('22-DEC-2019 10:30:0.0 AM');

STRING

T11 Implicit Conversion


F1
------------
22-DEC-2019 10:30:0.0 AM timestamp

INSERT INTO t11


VALUES(to_timestamp('22-DEC-2019 10:30:0.0 AM'));
STRING

to_timestamp()
Explicit conversion
F1
-------
22-DEC-2019 10:30:0.0 AM => timestamp

Note:
to insert date value, use to_date() function
to insert timestamp value, use to_timestamp() function

Default time value is: 12:00:00.00 AM [midnight time]

Insert INTO t11


VALUES('25-NOV-2020');
Output:
1 row created.

F1
-----
25-NOV-20 12:00:00.00 AM

timestamp format:
DD-MON-RR HH:MI:SS.FF AM
25-NOV-20 12:00:00.000000 AM

INSERT INTO t11


VALUES('17-SEP-2022 10:30 AM');
ERROR

INSERT INTO t11


VALUES('17-SEP-2022 10:30'); 00.00 AM
Output:
1 row created

Binary Related Data Types:

BFILE
BLOB

RAW, LONG RAW => outdated


Nowadays we are using BLOB data type instead

ORACLE4PM Page 17
Nowadays we are using BLOB data type instead
of RAW, LONG RAW

BFILE:
• BFILE stands for BINARY FILE LARGE OBJECT
• used to maintain multimedia objects [unstructured data]
like :
images, audios, videos, documents, animations
• External Large Object. Object will be stored out of the DB.
Just path of Object will be maintained in DB
• It is not secured

BLOB:
• BLOB stands for BINARY LARGE OBJECT
• used to maintain multimedia objects [unstructured data]
like :
images, audios, videos, documents, animations
• Multimedia object will be stored inside of the database. It
can be also called as "internal Large Object"
• It is secured

1234 CLOB

10001011110001 BLOB

DIR1 => D:\EMPS

DATABASE
D: DRIVE
EMP
EMPID ENAME EPHOTO [BFILE] EMPS Folder
1001 RAJU DIR1,raju.jpg

raju.jpg

DATABASE
D: DRIVE

EMPS Folder
EMP
EMPID ENAME EPHOTO [BLOB]
1001 RAJU 1456A523BFD385C raju.jpg

SQL

5 sub languages:

DDL:

CREATE:

CREATE TABLE <table_name>


(
<field_name> <data_type>[,
<field_name> <data_type>,
.
.]
);

ORACLE DB SERVER
Client

ORACLE4PM Page 18
ORACLE
SQL PLUS => CUI
Instance DB

TOAD => GUI student

SQL DEVELOPER => GUI


RAM Hard Disk

CUI GUI

CREATE TABLE student sid


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

INSERT INTO student sid sname


VALUES(1001,'AA'); 1001 AA

Creating User [Schema]:

Syntax to create the User:

CREATE USER <user_name>


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

google account

username
password
15GB => memory
memory location

Note:
• ORACLE DB will be stored in tablespaces.
• built-in tablespaces are: sys, sysaux, users

Steps to create the user:

• Open SQLplus
press windows+R => type "sqlplus" => OK

• Login as DBA [dataBase Administrator]


 username: system
 password: nareshit
[at the time oracle s/w installation you have given
password]

• Type following queries:

CREATE USER batch4pm


IDENTIFIED BY naresh
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO batch4pm;

connect it is permission for login


resource it is permission to create the table

conn[ect]:
it is used to connect to DB server from SQL prompt.

ORACLE4PM Page 19
• it is used to connect to DB server from SQL prompt.

Syntax:
conn[ect] <username>/<password>

Ex:
conn batch4pm/naresh

DISC[ONNECT]:
• it is used to disconnect from db server

Syntax:
DISC[ONNECT]

Note:
• username is not case sensitive
• password is case sensitive

username: BATCH4PM (or) batch4pm => valid


password: naresh => valid
password: NARESH => invalid

• password must be "alphanumerics" only

• From ORACLE 12c version onwards,


there are 2 types of users:
• common user
• local user

• common username must be prefixed with "C##"


[C => common user].

c##batch4pm common user


batch4pm local user

note:
if yopu invalid common user error, prefix user
name with c##

Changing password:

ALTER USER <user_name>


IDENTIFIED BY <new_password>;

Login as DBA:
username: system
password: nareshit

ALTER USER batch4pm


IDENTIFIED BY nareshit;

Changing DBA password:

username: sys as sysdba


password: [don't enter any password]

ALTER USER system


IDENTIFIED BY 123456;

Syntax to create the table: STUDENT


sid sname avrg

ORACLE4PM Page 20
Syntax to create the table: STUDENT
sid sname avrg
CREATE TABLE <table_name>
(
<field_name> <data_type>[,
<field_name> <data_type>,
<field_name> <data_type>,
.
.]
);

Examples on creating tables:

Example-1:

STUDENT
sid sname avrg
1001 AA 67.89
100.00
1002 BB 56.92

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10),
avrg NUMBER(5,2)
);
Output:
Table created.

Note:
• SQL is not case sensitive language
• Every SQL command end with ;

Inserting records:

Syntax of INSERT command:

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


VALUES(<value_list>);

1001 AA 67.89
1002 BB 56.92

INSERT INTO student VALUES(1001,'AA',67.89);


INSERT INTO student VALUES(1002,'BB',56.92);

COMMIT; DB SERVER

instance DB
Note: 1001 student
when we insert the record, it 1002
will be inserted in instance. it means,
RAM HD
it is temporary. To save it permanently
use COMMIT command

when COMMIT command is executed, the data in


INSTANCE [RAM] will be moved to DATABASE [HARD DISK]

FORM => [FE] Middleware DB SERVER [BE]

first name Customer


Java
cid firname ..
Python
last name
C#

mobile num

SUBMIT
ORACLE
SQL SERVER
HTML
JavaScript
CSS

ORACLE4PM Page 21
ORACLE => RDBMS
SQL DATABASE
PL/SQL TABLES

SQL => Non-Procedural => Queries


PL/SQL => Procedural => procedures, functions [programs]

SQL:

DDL DRL DML TCL DCL


CREATE SELECT INSERT COMMIT GRANT
ALTER UPDATE ROLLBACK REVOKE
DROP DELETE SAVEPOINT
FLASHBACK
PURGE INSERT ALL
TRUNCATE MERGE
RENAME

CREATE:
• It is used to create the DB Objects like Tables, Views,
Indexes, ….. etc.

Syntax to create the table:

CREATE TABLE <table_name>


(
<field_name> <data_type>[,
<field_name> <data_type>,
<field_name> <data_type>,
.
.]
);

INSERT:
• used to insert the records.

Syntax:

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


VALUES(<value_list>);

SELECT:
• It is used to retrieve the data from table/tables.

Syntax:

SELECT <column_list>/*
FROM <table_name>
[WHERE <condition>];

ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES

CLAUSE: is part of a query


Query is made up with clauses

Exs of clauses:

ORACLE4PM Page 22
Examples on Creating tables & Inserting records:

Example-1:

STUDENT
SID SNAME GENDER AVRG
1001 AA M 78.96
1002 BB F 67.34

Creating table:

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10),
gender CHAR(1),
avrg NUMBER(5,2)
);
Output:
Table Created.

Inserting records:

1001 AA M 78.96
1002 BB F 67.34

INSERT INTO student VALUES(1001,'AA','M',78.96);


Output:
1 row created.

INSERT INTO student VALUES('AA',1001,'M',78.96); --ERROR

INSERT INTO student VALUES(1002,'BB','F',67.34);


COMMIT [SAVE]
Output:
1 row created. DB SERVER

INSTANCE DB

1001 student
1002 1001
1002
RAM HARD DISK

to see table data:

SELECT * FROM student;


Output: * All Columns

sid sname gender avrg


* = sid, sname, gender, avrg
1001 .. .. ..
1002 .. .. ..

SELECT * FROM student;

oracle rewrites above query as following:


SELECT sid, sname, gender, avrg FROM student;

DESC[RIBE]:
It is used to see table structure.

Syntax:

DESC[RIBE] <table_name>;

ORACLE4PM Page 23
Example:
DESC student;

Output:
Name Type
sid NUMBER(4)
sname VARCHAR2(10)
.. ..
.. ..

user_tables:
• It is a Built-In Table / System Table.
• It maintains all tables information which are created by
the user.

DESC user_tables;
Output:
Name Type
Table_name ..
.. ..
user_tables
table_name .. ..
SELECT table_name FROM user_tables;
Output:
T1
STUDENT

SELECT sname, avrg STUDENT


FROM student; sid sname gender avrg

create
insert
commit

desc
user_tables

/ (or) Run:
It is used to run recent command which is in memory.

INSERT INTO student VALUES(1003,'CC','M',55.66);


Output:
1 row inserted. [1003 record inserted]

/
Output:
1 row inserted. [1003 record inserted]

/
Output:
1 row inserted. [1003 record inserted]

Inserting multiple records using parameters:

parameter:
• parameter concept is used to read the value at runtime.
• parameter text need not be column name

Syntax:
&<text>

Ex:

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


Output:
enter value for sid: 1004

ORACLE4PM Page 24
enter value for sid: 1004
enter value for sname: ABC
enter value for gender: M
enter value for avrg: 45.66
these values will be substituted in place of parameters.
oracle rewrites query as following:
INSERT INTO student VALUES(1004,'ABC','M',45.66);
1 row created.

/
enter value for sid: 1005
enter value for sname: XYZ
enter value for gender: F
enter value for avrg: 66.23

/
enter value for sid: ..
enter value for sname: ..
enter value for gender: ..
enter value for avrg: ..

Inserting limited Column values:

STUDENT
sid sname gender avrg
XYZ 55.44
null
null INSERT INTO student VALUES('XYZ',55.44);
Output:
ERROR: not enough values
ORACLE is expecting 4. we are passing 2

INSERT INTO student(sname,avrg) VALUES('XYZ',55.44);


Output:
1 row created

5001 AAAA
INSERT INTO student(sid,sname) VALUES(5001,'AAAA');
Output:
1 row created.

Inserting limited column values by changing order of columns:


5002 BBBB
INSERT INTO student(sname,sid) VALUES('BBBB',5002);

create

inserting single record


insert multiple records using parameters => &
insert limited column values

commit

desc

user_tables

select

Pagesize & linesize:

Pages[ize]:
• default page size is 14

ORACLE4PM Page 25
we can change pagesize as following:

SET PAGES 200

In one oracle page, it can display 200 lines

Lines[ize]:
• default line size is 80

we can change linesize as following:

SET LINES 200

In one line, it can display 200 chars

Note:

SET LINES 200


(or) SET pages 200 lines 200
SET PAGES 200

lines 200
1 1234…………200
200 chars => 1 line
2
3
pages 200

1page => 200lines 200

Example-2:
DOJ => Date Of Joining

EMPLOYEE
EMPNO ENAME JOB SAL DOJ 100000.00
5001 SAI CLERK
5002 KIRAN MANAGER

empno NUMBER(4)
ename VARCHAR2(10)
job VARCHAR2(10)
sal NUMBER(8,2)
doj DATE

CREATE TABLE employee


(
empno NUMBER(4),
ename VARCHAR2(10),
job VARCHAR2(10),
sal NUMBER(8,2),
doj DATE
);
Output:
Table created

Inserting records:

INSERT INTO employee


VALUES(5001,'SAI','CLERK',6000,sysdate);
Output:
1 row created

INSERT INTO employee


VALUES(5002,'KIRAN','MANAGER',9000,'30-APR-2023');

STRING STRING

implicit conversion
ename
DOJ
=========
========
KIRAN => string

ORACLE4PM Page 26
STRING STRING

implicit conversion
ename
DOJ
=========
========
KIRAN => string
30-APR-23 => date

DD-MON-RR

INSERT INTO employee


VALUES(5003,'ARUN','SALESMAN',8000,to_date('25-NOV-2021'));
Output:
1 row created. string

to_date()
DOJ explicit conversion
--------
25-NOV-21 => date

empno ename job sal doj


RAMU 7000

INSERT INTO employee(ename,sal)


VALUES('RAMU',7000);

Example-3:

TRANSACTIONS
TID T_DATE_TIME TTYPE ACNO Amount
123456 2-may-2023 10:30:0.0 AM deposit 1001 10000
123457 30-apr-2023 5:30:0.0 PM withdraw 4567 15000

tid number(6)
t_date_time timestamp
ttype varchar2(10)
acno number(4)
amount number(9,2)

CREATE TABLE transactions


(
tid NUMBER(6),
t_date_time TIMESTAMP,
ttype VARCHAR2(10),
acno NUMBER(4),
amount NUMBER(9,2)
);
Output:
Table created.

INSERT INTO transactions


VALUES(123456, systimestamp, 'withdraw', 1234, 10000);
Output:
1 row created

INSERT INTO transactions


VALUES(123457, '30-APR-2023 10:30:0.0 AM', 'deposit', 7896, 15000);
string

implicit conversion
t_date_time
---------------
30-APR-2023 10:30:0.0 AM => timestamp

ORACLE4PM Page 27
INSERT INTO transactions
VALUES(123458, to_timestamp('24-APR-2023 5:30:0.0 PM'), 'deposit',
5123, 25000); string

to_timestamp()
Explicit Conversion
t_date_time
----------------------
24-APR-2023 5:30:0.0 PM => timestamp

Integer NUMBER(p)
Float NUMBER(p,s)
Date DATE
DATE & Time TIMESTAMP
fixed length chars CHAR(n)
variable length chars VARCHAR2(n)

ALTER:
• ALTER => change
• ALTER command is used to change structure of table.
• Using this command we can:
○ Add the columns => ADD
○ Rename the Columns => RENAME COLUMN
○ Drop the Columns => DROP
○ Modify the field sizes => MODIFY
○ Modify the data types => MODIFY

Syntax of ALTER command:

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


[RENAME COLUMN <old_name> TO <new_name>]
[DROP COLUMN <column_name>]
[DROP(<column_list>)]
[MODIFY(<new_field_definitions>)];

Example on ALTER command:

STUDENT
sid sname

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10)
);
Output:
Table created.

DESC student;
Output:
sid
sname

Adding a Column [M1]:

ALTER TABLE student ADD(m1 NUMBER(3));


(or)
ALTER TABLE student ADD m1 NUMBER(3);
Output:
Table altered

DESC student;
Output:
sid

ORACLE4PM Page 28
sid
sname
m1

Adding multiple columns [m2, m3]:

ALTER TABLE student ADD(m2 NUMBER(3), m3 NUMBER(3));


Output:
Table Altered.

DESC student;
Output:
sid
sname
m1
m2
m3

Renaming a Column [m3 to maths]:

ALTER TABLE student RENAME COLUMN m3 TO maths;


Output:
Table Altered.

DESC student;
Output:
sid
sname
m1
m2
maths

Dropping a Column [maths column]:

ALTER TABLE student DROP COLUMN maths;


(or)
ALTER TABLE student DROP(maths);

DESC student;
Output:
sid
sname
m1
m2

Dropping multiple columns [m1, m2]:

ALTER TABLE student DROP(m1, m2);

DESC student;
Output:
sid
sname varchar2(10)

Modifying field size [sname varchar2(10) 10 => 20]:

ALTER TABLE student MODIFY(sname VARCHAR2(20));


Output:
Table altered

DESC student;
Output:
sid
sname varchar2(20)

Can we decrease the field size?


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

sname varchar2(20) 20 to 4 => invalid


------------
RAMU 20 to 6 => valid
VIJAY

ORACLE4PM Page 29
20 to 6 => valid
VIJAY
SAI
RAMESH => 6 => max string length

SID NUMBER(4) => CHAR(8)


--------
HYD_1001
MUM_1002
BLR_1003

Modifying data type [sid number(4) => char(8)]:

ALTER TABLE student MODIFY(sid CHAR(8));


Output:
Table Altered.

DESC student;
Output:
sid char(8)

NOTE:
To modify the data type of a column, column must be empty

DROP
FLASHBACK
PURGE

Note:
• "RecycleBin" concept added to ORACLE in ORACLE 10g version
• FLASHBACK & PURGE are related to recyclebin. These 2
commands are introduced in ORACLE 10g version.

DROP:
• is used to delete the entire table.
• Table = Structure + Data

EMPLOYEE Table
EMPNO ENAME SAL Structure
1001 AA 6000 +
1002 BB 8000 Data

Syntax:
DROP TABLE <table_name> [PURGE];

Ex:
DROP TABLE employee;

When we drop the table, it goes to recyclebin

to see recyclebin:

show recyclebin;
Output:
Object_name
-----------------------
Employee

FLASHBACK:

ORACLE4PM Page 30
FLASHBACK:
• used to restore the dropped table from recyclebin

Syntax:

FLASHBACK TABLE <table_name>


TO BEFORE DROP
[RENAME TO <new_name>];

Example:
FLASHBACK TABLE employee
TO BEFORE DROP;

PURGE:
• used to delete the table from recyclebin
• Once table is deleted from recyclebin, it will be
deleted permanently. it cannot be restored.

Syntax:
PURGE TABLE <table_name>;

Ex:
PURGE TABLE employee;

To delete a table permanent:

DROP TABLE employee;


PURGE TABLE employee; (or) DROP TABLE employee PURGE;

username: system

For system user, recyclebin will not work by default

4-MAY-23
-------------------

DDL:

CREATE
ALTER

DROP
FLASHBACK
PURGE

CASE-1:

RBIN

RBINNAME
CREATED T1
T1 4:15 …..
T1 DROPPED => 4:10 PM
T1 4:10 ……

CREATED T1
T1 DROPPED => 4:15 PM

FLASHBACK TABLE t1
TO BEFORE DROP;
restores recently dropped one
T1 => 4:15 PM

To restore older one [t1 table dropped at 4:10 PM]:

ORACLE4PM Page 31
To restore older one [t1 table dropped at 4:10 PM]:

FLASHBACK TABLE <recyclebin_name>


TO BEFORE DROP;

• When multiple tables have same name in recyclebin,


when we restore the table using table name, always it
restores recently dropped table.
• If we want to retstore older one, we must use recyclebin
name.
• recyclebin name must be enclosed in double quotes.

Note:
Table name must be unique with in the schema [user => c##batch4pm]

CASE-2:
RBIN
CREATE TABLE T2
T2 DROPPED T2

CREATE TABLE T2

Restore
with another name

use RENAME TO clause

FLASHBACK TABLE t2 TO BEFORE DROP


RENAME TO t2_old;

After dropping a table, if a table created with dropped table


name, we cannot restore dropped table with same name.
Because, with in schema, table name must be unique.
To restore dropped table, rename it using "RENAME TO"
clause.

TRUNCATE:
• used to delete all records from the table with good
performance.
• These records will be deleted permanently. We cannot
recollect them.
Table = Structure + Data

CUSTOMER Table

CID CNAME CCITY structure


1001 AA HYD +
1002 BB MUMBAI data

TRUNCATE

Syntax:

TRUNCATE TABLE <table_name>;

Example:
TRUNCATE TABLE customer;

ORACLE4PM Page 32
DROP TRUNCATE

used to delete entire table used to all records [entire data]

it deletes structure also It does not delete structure of table

it can be flashed back it cannot be flashed back

RENAME:
used to change table name

Syntax:

RENAME <old_name> TO <new_name>;

Ex:
RENAME t2_old TO xyz;

DDL:

Alter:
create:
used to change structure of table
used to create the table
add the columns
drop the columns
syntax:
rename the columns
create table <tn>
modify the data types & field sizes
(
<fn> <dt>[,
ALTER TABLE <tn> ADD(..)
.
DROP COLUMN
.]
DROP(..)
);
MODIFY(..)

Drop: Flashback:
to delete entire table used to restore the table

Syn: Syn:
DROP TABLE <tn> [PURGE]; FLASHBACK TABLE <tn>
TO BEFORE DROP
[RENAME TO <name>];

truncate:
PURGE:
TO DELETE ALL ROWS
to delete from rbin

Syn:
Syn:
TRUNCATE TABLE <tn>;
PURGE TABLE <tn>;

Rename:
used to rename the table

Syn:
RENAME <old_name> TO <new_name>;

ORACLE4PM Page 33
Emptying Recyclebin:
Recyclebin

T1
PURGE RECYCLEBIN;
T2
T3
-- it empties recyclebin
.
.
T10

ORACLE4PM Page 34
DRL
Thursday, May 4, 2023 5:00 PM

DRL / DQL:
• DRL stands for Data Retrieval Language
• DQL stands for Data Query Language
• Retrieve => get back => opening existing data
• Query => request that is sent to DB SERVER
• Example:
○ check balance
○ searching for products in online shopping

• It deals with data retrievals

ORACLE SQL provides only 1 DRL command. i.e:


• SELECT

SELECT:

Syntax:

SELECT [ALL/DISTINCT] <column_list> / *


FROM <table_name>
[WHERE <condition>]
[GROUP BY <grouping_column_list>]
[HAVING <group_condition>]
[ORDER BY <column> ASC/DESC, …………]
[FETCH first <n> only];

ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES

CLAUSE:
• CLAUSE is a part of query
Every CLAUSE has specific purpose

SELECT:
• SELECT command is used to select the data from
table.
• Using SELECT command we can SELECT:
• all rows and all columns
• specific rows and all columns
• all rows and specific columns
specific rows and specific columns

ORACLE4PM Page 35
• specific rows and specific columns

SELECT used to specify column list


Ex:
SELECT ename,sal

FROM used to specify table list


Ex:
FROM emp

WHERE used to specify filter condition


Ex:
WHERE sal>2500

Display the emp names and salaries of emps whose


salary is more than 2500:

SELECT ename,sal
FROM emp
WHERE sal>2500;

Execution Order:

FROM
WHERE
SELECT

EMP
EMPNO ENAME JOB SAL
1001 AA CLERK 6000
1002 BB SALESMAN 2000
1003 CC MANAGER 8000

FROM emp:
It selects entire table

EMP
EMPNO ENAME JOB SAL
1001 AA CLERK 6000
1002 BB SALESMAN 2000
1003 CC MANAGER 8000

WHERE sal>2500:
• It filters the rows.
WHERE clause condition will be

ORACLE4PM Page 36
• WHERE clause condition will be
applied on every row.

EMP WHERE sal>2500


EMPNO ENAME JOB SAL
6000>2500 => T => selected
1001 AA CLERK 6000
2000>2500 => F
1002 BB SALESMAN 2000
8000>2500 => T => selected
1003 CC MANAGER 8000

EMP
EMPNO ENAME JOB SAL
1001 AA CLERK 6000
1003 CC MANAGER 8000

SELECT ename,sal:
It selects the columns

EMP
EMPNO ENAME JOB SAL ENAME SAL
1001 AA CLERK 6000 AA 6000
1003 CC MANAGER 8000 CC 8000

final result

• all rows and all columns:

Display all rows and all columns of emp table:

SELECT *
FROM emp;

* All Columns

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

Above query will be rewritten by oracle as follows:

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


FROM emp;

• specific rows and all columns:

Display the emp records whose salary is 3000:


ORACLE4PM Page 37
Display the emp records whose salary is 3000:

SELECT *
FROM emp
WHERE sal=3000;

• all rows and specific columns:

Display all emp names and salaries:

SELECT ename,sal FROM emp;

• specific rows and specific columns:

Display emp names and salaries of the emps whose salary is


3000:

SELECT ename,sal
FROM emp
WHERE sal=3000;

* All Columns
SELECT ename,sal Specific Columns
Not wrting WHERE condition All rows
WHERE sal=3000 Specific rows

5-may-23:
-------------------

OPERATORS in SQL:

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

ORACLE SQL provides following Operators:

Arithmetic + - * /

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


Comparison

Logical AND OR NOT

Special IN
BETWEEN AND
LIKE
IS NULL

ORACLE4PM Page 38
ANY
ALL
EXISTS

SET UNION
UNION ALL
INTERSECT
MINUS

Concatenation ||

Arithmetic Operators:

Arithmetic Operators are used to perform arithmetic operations.

SQL provides following Arithmetic Operators:

+ Addition 5+2 = 7 In C/Java:


int/int = int
- Subtraction 5-2 = 3
5/2 = 2
* Multiplication 5*2 = 10
5%2 = 1 [% modulus]
/ Division 5/2 = 2.5

In SQL:
5/2 = 2.5 [accurate]
mod(5,2) = 1
mod(10,7) = 3

Examples on Arithmetic Operators:

Calculate annual salary of all emps:

SELECT ename, sal, sal*12


FROM emp;

Output:
ENAME SAL SAL*12
----------- -------- ----------
SMITH 800 9600
ALLEN 1600 19200

SELECT ename, sal, sal*12 AS annual_sal


FROM emp;
(or)
ORACLE4PM Page 39
(or)
SELECT ename,sal, sal*12 annual_sal
FROM emp;

Output:

ENAME SAL ANNUAL_SAL


--------------- ---------- ----------------------
SMITH 800 9600
ALLEN 1600 19200

SELECT ename, sal AS monthly_sal,


sal*12 AS annual_sal
FROM emp;

Output:

ENAME MONTHLY_SAL ANNUAL_SAL


--------------- ---------------------- ----------------------
SMITH 800 9600
ALLEN 1600 19200

SELECT ename, sal,


sal*12 AS "annual_sal"
FROM emp;

Output:

ENAME SAL annual_sal

SELECT ename, sal,


sal*12 AS annual sal
FROM emp;

Output:
ERROR: alias name has space

SELECT ename, sal,


sal*12 AS "annual sal"
FROM emp;

Output:
ENAME SAL annual sal

ORACLE4PM Page 40
Column Alias:
• Alias => Alternative name / another name
• Column Alias is used to change column heading in
output.
• "AS" keyword is used to give column alias.
• Using "AS" keyword is optional.
• To maintain the case or to give column alias in
multiple words we must specify alias name in
double quotes.

Syntax:
<column> [AS] <column_alias>

Exs:
sal AS salary => SALARY
sal salary => SALARY
sal AS "salary" => salary
sal AS monthly sal => ERROR
sal AS "monthly sal" => monthly sal

Calculate experience of all emps:

SELECT ename, hiredate,


TRUNC((sysdate-hiredate)/365) AS experience
FROM emp;

Calculate TA, HRA, TAX and GROSS SALARY of all emps.


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

SELECT ename, sal,


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

NOTE:
Select query calculation is temporary. it will not be
stores in table

Add a Column TA
UPDATE query calculation is stored in table.

ORACLE4PM Page 41
UPDATE query calculation is stored in table.

Display the emp records whose


annual salary is more than 30000:

SELECT ename, sal, Execution Order


sal*12 as annual_sal -------------------------
FROM emp FROM emp => empno, ename, job, mgr, sal, comm, hiredate, deptno
WHERE annual_sal>30000; WHERE annual_sal>30000 => ERROR
SELECT sal*12 AS annual_Sal
Output:
ERROR:
annual_sal is invalid identifier

annual_sal is column alias


column alias cannot be used in WHERE clause
WHERE gets executed before SELECT

SELECT ename, sal,


sal*12 as annual_sal
FROM emp
WHERE sal*12>30000;

displays all emp records whose annual salary is more


than 30000

Assignment:
Display the emp records whose experience is
more than 41 years:

Relational Operators / Comparison Operators:

• All Relational operators are used to compare with


one value.

ORACLE SQL provides following relational


operators:

< <= > >= = != / <> / ^=


equals not equals

Exs:
sal > 3000
sal > 3000,4000 --Invalid
ORACLE4PM Page 42
sal > 3000,4000 --Invalid

sal < 3000


sal = 3000
sal >= 3000
sal <= 3000
sal != 3000

Examples on Relational operators:

Display the emp records whose salary is 3000:

SELECT ename,sal
FROM emp
WHERE sal=3000;

Display the emp records whose salary is 3000 or


more:

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

Display the emp records whose salary is 3000 or less:

SELECT ename,sal
FROM emp
WHERE sal<=3000;

Display the emp records whose salary is less than


1000:

SELECT ename,sal
FROM emp
WHERE sal<1000;

6-may-23
------------------

Display all managers records:

SELECT ename, job


FROM emp
WHERE job='manager';

no rows selected

ORACLE4PM Page 43
job
----------
CLERK
MANAGER = manager => F
SALESMAN
MANAGER

NOTE:
• SQL is not case sensitive language.
• String comparison is case sensitive.
• Case sensitive means, upper case and lower
case will be treated as different.

Ex:
MANAGER = MANAGER => T
MANAGER = manager => F

Display all managers records:

SELECT ename, job


FROM emp
WHERE job='MANAGER';

--displays all managers records

Display the emp record whose empno is 7521:

SELECT *
FROM emp
WHERE empno=7521;

Display the emp records who are working in 10th dept:

SELECT ename,deptno
FROM emp
WHERE deptno=10;

Display the emp records who are working in other than 10th
dept:

SELECT ename,deptno
FROM emp
WHERE deptno!=10; [deptno<>10] [deptno^=10]

ORACLE4PM Page 44
Display the emp record whose name is BLAKE:

SELECT ename,sal
FROM emp
WHERE ename='BLAKE';

Calendar Order => Ascending order => small to big

2019
2020
2021 25-JUN-2019 > 15-AUG-2017

2023 calendar
18-SEP-2020 < 23-NOV-2022
1-jan-2023
2-jan-2023
3-jan-2023
.
.
31-dec-2023

Display the emp records who joined after 1981:

hiredate

1-jan-1982 > 31-dec-1981


2-jan-1982
.
.

SELECT ename, hiredate


FROM emp
WHERE hiredate>'31-dec-1981';

Display the emp records who joined before 1981:

SELECT ename, hiredate


FROM emp
WHERE hiredate<'1-jan-1981';

hiredate

ORACLE4PM Page 45
WHERE hiredate<'1-jan-1981';

hiredate

31-dec-1980 1-jan-1981
<
30-dec-1980
.
.

Logical Operators:
Logical Operators are used to perform logical operations
like logical AND, logical OR, logical NOT operations.

SQL provides following Logical Operators:


• AND
• OR
• NOT

AND, OR are used to separate multiple conditions

AND all conditions should be satisfied


OR at least one condition should be satisfied

Truth Table:

condn1 condn2 c1 AND c2 c1 OR c2


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

Examples on Logical Operators:

Display all managers and clerks records:

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

job
-------
SALESMAN F F => F
ORACLE4PM Page 46
SALESMAN F F => F
MANAGER T F => T
CLERK F T => T

Display all managers records whose salary is more than 2500:

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

Display all managers records whose salary is more than 2500 and who
joined after april 1981:

SELECT ename, job, sal, hiredate


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

Display the emp records whose salary is 2000 or more,


3000 or less [sal must be b/w 2000 and 3000]:

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

sal
-------
6000 => F
1000 => F
2000 => T
3000 => T
2500 => T

Display the emp records whose empnos are 7369, 7521,


7900:

SELECT *
FROM emp
WHERE empno=7369 OR empno=7521 OR empno=7900;

Display the emp records who are working in 10 and 30

ORACLE4PM Page 47
Display the emp records who are working in 10 and 30
depts:

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

NOT truth table:

Condn NOT(condn)
T Not(T) => F
F Not(F) => T

Display all emp records except managers:

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

job
------
CLERK NOT(F) => T
MANAGER NOT(T) => F
ANALYST NOT(F) => T
MANAGER NOT(T) => F

Amazon

PID PNAME CNAME PRICE


1001 Laptop Dell 50000

searching for laptops:

WHERE pname='LAPTOP' AND cname='DELL';

searching for dell and lenovo laptops :

WHERE pname='LAPTOP' AND (cname='DELL' OR cname='LENOVO')

searching for dell laptops, price must be b/w 50000 to 60000:

WHERE pname='LAPTOP' AND cname='DELL' AND price between 50000 and 60000
ORACLE4PM Page 48
WHERE pname='LAPTOP' AND cname='DELL' AND price between 50000 and 60000

Example:
max marks: 100
min marks: 40 for pass in each sub
STUDENT
sid sname M1 M2 M3
1001 A 70 90 80
1002 B 60 30 55

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;

Special Operators:

IN:

WHERE sal=3000 => valid


WHERE sal=3000, 4000, 5000 Invalid

WHERE sal=3000 OR sal=4000 OR sal=5000


(or)
WHERE sal IN(3000,4000,5000)

sal
---------
2500 => F
4000 => T
6000 => F
5000 => T

IN:
used to compare column value with a list of values.

ORACLE4PM Page 49
• used to compare column value with a list of values.
• it avoids of writing multi equality conditions using OR
• It checks column value is in the list or not. If it is in list,
condition is TRUE. otherwise condition is FALSE.

Syntax:
<column> IN(<value_list>)

Ex:
WHERE sal IN(3000,4000,5000)

Examples on IN Operator:

Display all managers and clerks records:

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

job
-------
SALESMAN => F
MANAGER => T
ANALYST => F
CLERK => T

Display the emp records whose names are


BLAKE, WARD, SCOTT:

SELECT *
FROM emp
WHERE ename IN('BLAKE','WARD','SCOTT');

ename
---------
SMITH => F
WARD => T
BLAKE => T
ALLEN => F
SCOTT => T

ORACLE4PM Page 50
Display the emp records who are
working in deptno 10 and 30:

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

Display all emp records except managers and clerks:

SELECT *
FROM emp
WHERE job NOT IN('MANAGER','CLERK');

if job value not in list condition is T


if job value in list condn is F

job
--------
CLERK => F
ANALYST => T
MANAGER => F
SALESMAN => T

Display the emp records whose


empnos are 7499, 7521, 7900:

SELECT *
FROM emp
WHERE empno IN(7499,7521,7900);

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

Syntax:
<column> BETWEEN <lower> AND <upper>

Ex:
WHERE sal BETWEEN 2000 AND 3000

Examples on between and:

ORACLE4PM Page 51
Display the emp records whose salary is
between 2000 and 3000:

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

SELECT *
FROM emp
WHERE sal BETWEEN 3000 AND 2000;

What is the output?

A. displays sal b/w 2000 and 3000


B. Error
C. No rows selected
D. None

Answer: C

Display the emp records who joined in 1981:

joined after 1981 WHERE hiredate > '31-dec-1981'


joined before 1981 WHERE hiredate < '1-jan-1981'

SELECT ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-jan-1981' AND '31-dec-1981';
(or)
SELECT ename,hiredate
FROM emp
WHERE hiredate>='1-jan-1981' AND hiredate<='31-dec-1981';

ORACLE4PM Page 52
Display all emp records except the emps who joined 1981:

SELECT 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 search for all jpg files s*.jpg
which are started with S
to search for files in which ?a*.jpg
2nd char is A

srinu.jpg
james.jpg
ramu.jpg
aa.jpg
sravan.jpg
allen.jpg
symonds.jpg
scott.jpg
s.jpg

wildcard chars purpose


* replaces 0 or any no of chars
? replaces 1 char

LIKE:
• used to compare column value with text pattern

Syntax:
<column> LIKE <text_pattern>

SQL provides 2 wildcard chars to specify text pattern:

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

Examples on LIKE operator:

Display the emp records whose names are started with S:

SELECT *
FROM emp
WHERE ename LIKE 'S%';

ename
-----------
SMITH => T

ORACLE4PM Page 53
SMITH => T
ALLEN => F
SCOTT => T
WARD => F
SYMONDS => T
S => T

Display the emp records whose names are ended with S:

SELECT *
FROM emp
WHERE ename LIKE '%S';

ename
-----------
ALLEN => F
SMITH => F
SYMONDS => T => % replaces 6 chars
JAMES => T => % replaces 4 chars
SS => T => % replaces 1 char
S => T => % replaces 0 char

Display the emp records whose


names are ended with RD:

SELECT *
FROM emp
WHERE ename LIKE '%RD';

Display the emp records whose name's 2nd


char is A:

SELECT *
FROM emp
WHERE ename LIKE '_A%';

Display the emp records whose name's 3rd


char must be M:

SELECT *
FROM emp
WHERE ename LIKE '__M%';

ORACLE4PM Page 54
Display the emp records whose name is
having A char:

SELECT *
FROM emp
WHERE ename LIKE '%A%';

ename
-----------
SMITH
ALLEN
JAMES
ADAMS
SRAVAN

Display the emp records whose name is having 4 chars:

SELECT *
FROM emp
WHERE ename LIKE '____';

Display the emp records who joined in DECEMBER:

SELECT *
FROM emp
WHERE hiredate LIKE '%DEC%';

Display the emp records who joined in JANUARY or DECEMBER:

SELECT *
FROM emp
WHERE hiredate LIKE '%JAN%' OR hiredate LIKE '%DEC%';

Display the emp records who are getting 3 digit salary:

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

sal
-------
1600
12000
800

ORACLE4PM Page 55
800

Display the emp records whose names are not started


with S:

SELECT *
FROM emp
WHERE ename NOT LIKE 'S%';

Display the emp records whose name started and


ended with S:

SELECT *
FROM emp
WHERE ename LIKE 'S%S';

ename
---------
SMITH
SYMONDS
SS
SRINIVAS
SCOTT

NULL:
• NULL means empty or blank

STUDENT

SID SNAME M1 NUMBER(3)


1001 A 78
1002 B 66
1003 C 0
1004 D null

AB Error

EMPLOYEE
EMPNO ENAME SAL DOJ
1001 A 8000 17-aug-2019
1002 B 7000 null

null != 0

ORACLE4PM Page 56
null != 0

null != ' ' [space]

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

• null is not equals to 0 or space

Note:
• In first oracle 6 versions we were using
"varchar" data type
• varchar data type was not showing difference
between space and null.
• Oracle 7 version varchar2 data type introduced
to avoid drawback of varchar.
• Later they modified meaning of varchar also. In
latest versions varchar and varchar2 both acts
as same.

NULL:
• NULL means empty or blank
• NULL is not equals to 0 or space.
• When we don't know the value or when we are unable to
insert the value then we insert NULL.
• If NULL is participated in operation then result will be
NULL.
○ Exs:
100+200 = 300
100+200+ null = null

• We cannot = operator for null comparison

• We must use "IS NULL" operator for null comparison

Different ways of inserting NULLs:

NULL can be inserted using 2 ways. They are:


• Direct way: use NULL keyword
• Indirect way: Insert limited column values

Example:

EMPLOYEE
EMPNO ENAME SAL HIREDATE
1001 A 8000

CREATE TABLE employee


(
ORACLE4PM Page 57
(
empno NUMBER(4), ename VARCHAR2(10),
sal NUMBER(8,2), hiredate DATE
);

Direct way: use NULL keyword:

1001 A 8000

INSERT INTO employee


VALUES(1001,'A',8000,null);

• Indirect way: Insert limited column values:

1002 B

INSERT INTO employee


VALUES(1002,'B');

ERROR: not enough values

INSERT INTO employee(empno, ename)


VALUES(1002,'B');

IS NULL:
• It used to compare column value with NULL.
• For null comparison we must use IS NULL operator.
We cannot use = operator.

Syntax:
<column> IS NULL

Examples:

Display the emp records who are not getting commission:

SELECT ename,sal,comm
FROM emp
WHERE comm IS NULL;

Display the emp records who are getting commission:

SELECT ename,sal,comm

ORACLE4PM Page 58
SELECT ename,sal,comm
FROM emp
WHERE comm IS NOT NULL;

comm
--------
500 => not null => T
=> null => F

Concatenation operator:

Symbol: ||
It used to concatenate [combine] 2 strings

Example:

EMPLOYEE
EMPNO FNAME LNAME
1001 RAJ KUMAR
1002 SAI TEJA

SELECT fname || lname as name FROM employee;

name
-------------
RAJKUMAR
SAITEJA

SELECT fname || ' ' || lname as name FROM employee;

name
-------------
RAJ KUMAR
SAI TEJA

Display output as following:

SELECT ename || ' is earning ' || sal FROM emp;

Output:
SMITH is earning 800
ALLEN is earning 1600

ORACLE4PM Page 59
SQL

DDL DRL TCL DML DCL


create SELECT COMMIT
alter ROLLBACK
drop SAVEPOINT
flashback
purge
truncate
rename

ORACLE4PM Page 60
TCL
Tuesday, May 9, 2023 5:19 PM

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

• Transaction is a series of actions [SQL commands]


○ Exs of Transaction:
withdraw => SELECT + UPDATE commands
check balance => SELECT commands
deposit => SELECT + UPDATE commands

• Transaction Rule:
A Transaction must be successfully completed or
aborted [cancelled].

If transaction is successful , to save it => COMMIT


if transaction is unsuccessful, to cancel it => ROLLBACK

Withdraw => 10000


machine gives money 1001 50000
updates the balance

ORACLE SQL provides 3 TCL commands. They are:


• COMMIT [SAVE]
• ROLLBACK [UNDO]
• SAVEPOINT
COMMIT

ORACLE DB SERVER

instance DB
INSERT => 1001
emp
ORACLE4PM Page 61
instance DB
INSERT => 1001
emp
1001
dept
Hard Disk
RAM

COMMIT:
• COMMIT command is used to save the transaction.

• When COMMIT command is executed, all the changes


in ORACLE INSTANCE [RAM] will be applied to
ORACLE DB [HARD DISK]

• It is used to make the changes the permanent.

Syntax:
COMMIT;

ROLLBACK:
• used to cancel uncommitted actions.
• After COMMIT, we cannot use ROLLBACK.

Syntax:
ROLLBACK [TO <savepoint_name>];

Note:
All DDL commands are auto committed
Exs:
CREATE = CREATE + COMMIT
ALTER = ALTER + COMMIT

Example on ROLLBACK & COMMIT:

CREATE TABLE t1(f1 NUMBER(4));


ORACLE4PM Page 62
CREATE TABLE t1(f1 NUMBER(4));

INSERT INTO t1 VALUES(1001); => inserts in instance


INSERT INTO t1 VALUES(1002); => inserts in instance

SELECT * FROM t1;


Output:
F1
-----
1001
1002

ROLLBACK; --cancels 2 actions => 1001, 1002

SELECT * FROM t1;


Output:
no rows selected

INSERT INTO t1 VALUES(5001);


INSERT INTO t1 VALUES(5002);
COMMIT; --moves data from instance to DB

INSERT INTO t1 VALUES(5003);


INSERT INTO t1 VALUES(5004);

ROLLBACK; --cancels 2 actions => 5003, 5004


--cancels uncommitted actions

SAVEPOINT:
• Used to set specific point for rollback.

Syntax:
SAVEPOINT <savepoint_name>;

ORACLE4PM Page 63
Example-1:

CREATE TABLE t1 => CREATE + COMMIT


INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
ROLLBACK; --6 actions will be cancelled

Example-2:

CREATE TABLE t1 => CREATE + COMMIT

SAVEPOINT p1; 4.00 PM


INSERT
INSERT
SAVEPOINT p2; 4:10 PM
INSERT
INSERT
SAVEPOINT p3; 4:20 PM
INSERT
INSERT

ROLLBACK TO p3; --2 actions will be cancelled


ROLLBACK TO p2; --4 actions will be cancelled
ROLLBACK TO p1; --6 actions will be cancelled

CREATE TABLE t1(f1 NUMBER(4));

SAVEPOINT p1;
INSERT INTO t1 VALUES(1001);
INSERT INTO t1 VALUES(1002);
SAVEPOINT p2
INSERT INTO t1 VALUES(1003)
INSERT INTO t1 VALUES(1004);
SAVEPOINT p3;
INSERT INTO t1 VALUES(1005);
ORACLE4PM Page 64
INSERT INTO t1 VALUES(1005);
INSERT INTO t1 VALUES(1006);

SELECT * FROM t1;


Output:
F1
---
1001
1002
1003
1004
1005
1006

ROLLBACK TO p3;

SELECT * FROM t1;


Output:
F1
---
1001
1002
1003
1004

ROLLBACK TO p2;

SELECT * FROM t1;


Output:
F1
---
1001
1002

ROLLBACK TO p1;

SELECT * FROM t1;


Output:
no rows selected

SQL:

ORACLE4PM Page 65
DDL DRL / DQL TCL DML DCL
create select commit insert
alter rollback update
drop savepoint delete
flashback
purge insert all
truncate merge
rename

ORACLE4PM Page 66
Wednesday, May 10, 2023 4:40 PM

note:
• To modify table structure, use ALTER
• To modify table data, use UPDATE

UPDATE:
• Update command is used to change [modify] table data.
• Using this command we can modify:
○ single value of single record
○ multiple values of single record
○ specific records
○ all records
○ using parameters

Syntax:

UPDATE <table_name>
SET <column> = <new_value> [,<column> = <new_value>, ..]
[WHERE <condition>];

Examples on UPDATE:

modifying single value of single record:

set salary as 6000 to an employee whose


empno is 7499:

UPDATE emp
SET sal=6000
WHERE empno=7499;
Output:
1 row updated

COMMIT;

Modifying multiple values of single record:

set job value as manager, increase 2000 rupees salary


to an employee whose empno is 7369:

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

modifying specific records:

increase 10% on sal to all managers:

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

modifying all records:

increase 2000 rupees salary to all emps:

UPDATE emp
SET sal=sal+2000;

modifying records using parameters:

7499 => increase 10% on sal


7521 => increase 20% on sal
7900 => increase 15% on sal

7499 => increase 10% on sal:

UPDATE emp SET sal=sal+sal*&per/100 WHERE empno=&empno;

Output:
enter value for per:10
enter value for empno:7499

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

/
enter value for per:15
enter value for empno:7900

Examples:

Transfer all 10th dept emps emps to 20th dept:

ORACLE4PM Page 67
ORACLE4PM Page 68
ORACLE4PM Page 69
Transfer all 10th dept emps emps to 20th dept:

UPDATE emp
SET deptno=20
WHERE deptno=10;

increase 20% on sal to the emps who are not getting commission:

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

increase 20% on sal, 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;

Set commission value as 1000 to the emps who are not


getting commission:

UPDATE emp
SET comm=1000
WHERE comm is null;

set comm as null to an employee whose empno is 7521:

UPDATE emp
SET comm=null
WHERE empno=7521;

NOTE:
= operator cannot be used for null comparison
= operator can be used for null assignment

SET comm=null null assignment


WHERE comm is null null comparison

Increase 10% on sal to the emps who joined in 1982:

UPDATE emp
SET sal=sal+sal*0.1
WHERE hiredate BETWEEN '1-jan-1982' AND '31-dec-1982';

Increase 10% on sal to the emps who are having more than
41years experience:

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

Assignment:

Increase 20% on salary to the emps whose annual salary is


more than 30000

Increase 10% on sal to the emps who are working in deptno 20 and 30

increase 10% on sal to all emps except managers and clerks

increase 10% on sal to the emps who joined in may month.

DELETE:
• used to delete the records from table.
• Using it we can delete:
○ single record
○ specific records
○ all records
○ using parameters

Syntax:

DELETE [FROM] <table_name>


[WHERE <condition>];

Deleting single record:

Delete an emp record whose empno is 7369:

DELETE FROM emp


WHERE empno=7369;

Output:
1 row deleted.

Deleting specific records:

ORACLE4PM Page 70
ORACLE4PM Page 71
ORACLE4PM Page 72
Deleting specific records:

Delete all CLERKs records:

DELETE FROM emp


WHERE job='CLERK';

Deleting all records:

Delete all emp records:

DELETE FROM emp;


(or)
DELETE emp;

delete records using parameters:

delete from emp where empno=&empno;


Output:
enter .. empno: 7499

/
enter .. empno: 7934

DDL DRL TCL DML DCL


create select commit insert grant
alter rollback update revoke
drop savepoint delete
flashback
purge insert all
truncate merge
rename

DROP, TRUNCATE, DELETE:

DROP • deletes entire table


• it deletes table data + table structure
TRUNCATE • deletes all records
• it deletes entire table data
• it does not delete table structure
DELETE • used to delete the records
• we can delete single record, specific records and all
records

Differences between TRUNCATE & DELETE:

TRUNCATE DELETE

• It is DDL command • It is DML command

• used to delete all records. • used to delete single record or specific


records or all records

• it cannot delete single record • we can delete single record or specific


or specific records. we can records or all records
delete all records

• WHERE clause cannot be • WHERE clause can be used


used here

• It is auto committed • It is not auto committed

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

• It is faster • It is slower

• It deletes page by page • It deletes row by row


[block by block]

Tablespace

block / page block / page block / page block / page


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

ORACLE4PM Page 73
ORACLE4PM Page 74
ORACLE4PM Page 75
block / page block / page block / page block / page
------------------- ------------------- ------------------- -------------------
------------------- ------------------- ------------------- -------------------
------------------- ------------------- ------------------- -------------------

block / page block / page block / page block / page


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

block / page block / page block / page block / page


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

block / page block / page block / page block / page


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

extent extent

segment
segment segment

Tablespace-2 Tablespace-3

ORACLE DB

ORACLE DB
TABLE SPACES
SEGMENTS
EXTENTS
BLOCKS
RECORDS

Tablespace => is a collection of segments


Segment => is a collection of extents
Extent => a collection of blocks

one extent contains 8 blocks


each block size is 8KB
each extent size is 64 KB

ORACLE4PM Page 76
ORACLE4PM Page 77
ORACLE4PM Page 78
Built-In Functions
Thursday, May 11, 2023 4:59 PM

Built-In Functions:
• To make our tasks / actions easier ORACLE DEVELOPERS already
defined some functions & placed them in ORACLE DB. These
functions are called "Built-In Functions / Predefined Functions /
System-Defined Functions".

• Every function gets executed on calling

• Every function returns the value. Returning value is mandatory.

• Function => Task / Action


Every Function performs particular action

Built-In Functions can be categorized as following:

Built-In Functions

Single Row Functions Multi Row Functions /


Group Functions /
Aggregate Functions

String Functions
Conversion Functions
Date Functions
Math / Number Functions
Analytical Functions
Miscellaneous Functions

Single Row Function:


This function call will be applied on every row

Ex:
lower(ename)

ename
------------
SMITH lower('SMITH') => smith
ALLEN lower('ALLEN') => allen
WARD lower('WARD') => ward

Multi Row Function:


This function call will be applied on a set of values [multiple rows]

ORACLE4PM Page 79
Ex:
Sum(Sal)

sal sum(sal) => 5000+10000+4000 = 19000


---------
5000
10000
4000

String Functions:

lower() Substr() Lpad() Chr()


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

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

Syntax:
lower(<string>)

Examples:

SELECT lower('RAMU') FROM dual;

Output:
ramu

lower('RAJ KUMAR') raj kumar

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

Syntax:
upper(<string>)

Exs:
ORACLE4PM Page 80
Exs:
upper('ramu') RAMU
upper('raj kumar') RAJ KUMAR

initcap():
used to get every word's starting letter as capital.

Syntax:
initcap(<string>)

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

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

Syntax:
length(<string>)

Exs:
length('RAMU') 4
length('RAVI TEJA') 9

concat():
• used to concatenate [combine] 2 strings

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

Exs:
concat('RAJ', 'KUMAR') RAJKUMAR
concat('RAJ','KUMAR','VARMA') ERROR
concat(concat('RAJ', 'KUMAR'),'VARMA') RAJKUMARVARMA
(or)
'RAJ' || 'KUMAR' || 'VARMA'

Display emp names in lower case:

SELECT empno, lower(ename) as ename


FROM emp;

modify emp names to initcap case in emp table:

UPDATE emp
ORACLE4PM Page 81
UPDATE emp
SET ename = initcap(ename);

Display the emp record whose name is BLAKE when


we don't know exact case:

SELECT *
FROM emp BLAKE = blake => F
WHERE ename = 'blake';

Output:
no rows selected

SELECT * FROM emp


WHERE lower(ename) = 'blake';

ename lower(ename) = 'blake'


----------
SMITH lower('SMITH') => smith = blake => F
ALLEN lower('ALLEN') => allen = blake => F
BLAKE lower('BLAKE') => blake = blake => T

(or)

SELECT *
FROM emp
WHERE upper(ename) = 'BLAKE';

(or)

SELECT * FROM emp


WHERE initcap(ename) = 'Blake';

Display the emp records whose name is having 4 chars:

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

ename length(ename)
----------
SMITH 5

ORACLE4PM Page 82
ename length(ename)
----------
SMITH 5
WARD 4
MILLER 6
SCOTT 5
KING 4

Display the emp records whose names are having


14 chars:

SELECT *
FROM emp
WHERE length(ename)=14;

Display the emp records whose names are having


more than 14 chars:

SELECT *
FROM emp
WHERE length(ename)>14;

ASSIGNMENT:

PLAYER
PID FNAME LNAME PNAME
1001 ROHIT SHARMA ----------
1002 VIRAT KOHLI null Rohit Sharma
null Virat Kohli

• Add a column with the name PNAME => ALTER


• Concatenate FNAME and LNAME, convert it to Initcap
case & place it in PNAME column => UPDATE
• Drop FNAME & LNAME columns => ALTER

• Display the player names which are having 12 chars


• Display the player names which are having 12 or more
chars

DUAL:

Calculate 10+20:

ORACLE4PM Page 83
SELECT 10+20 FROM dual;

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

DUAL:
• DUAL is a readymade table / system table / predefined table.
• DUAL table created in "SYS" schema.
• This table has one column and one row.
• column name is: DUMMY varchar2(1)
○ DESC dual;
○ SELECT * FROM dual;
Output:
D
--
X

• It is used to work with non-table values


• When our requirement is getting one value as result then use
DUAL.
• Because of it is having one row, always it returns 1 value

Example:

DUAL => 1 row


EMP => 14 rows

SELECT 10+20 FROM dual;


Output:
one 30

SELECT 10+20 FROM emp;


Output:
fourteen 30s

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

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

Exs:

ORACLE4PM Page 84
Exs:
1 2 3 4 5 6 7 8 9
R A J K U M A R

Substr('RAJ KUMAR',5) KUMAR


Substr('RAJ KUMAR',6,3) UMA
Substr('RAJ KUMAR',1,3) RAJ
Substr('RAJ KUMAR',1,5) RAJ K

position => +ve => From Left Side


position => -ve => From Right Side

Note:
In Substr(), 2nd argument can be given as -ve also.
+ve means, from left side position number
-ve means, from right sider position number

R A J K U M A R
-9 -8 -7 -6 -5 -4 -3 -2 -1

Substr('RAJ KUMAR',-4) UMAR


Substr('RAJ KUMAR',-4,3) UMA
Substr('RAJ KUMAR',-5) KUMAR
Substr('RAJ KUMAR',-9,3) RAJ

Generate mail ids to all emps by taking emp name's first 3 chars
and empno's last 3 chars as user id for the domain '@tcs.com':

Add Mail ID column to emp table:

ALTER TABLE emp ADD mail_id VARCHAR2(20);

generate mail ids:

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

Display the emp records whose name is started with 'S':

SELECT *
FROM emp

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

Display the emp records whose names are ended


with RD:

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

(or)

SELECT *
FROM emp
WHERE ename LIKE '%RD';

Display the emp records whose name's starting


letter and ending letter are same:

ename
----------- WHERE ename LIKE 'A%A' OR
SMITH ename LIKE 'B%B' OR
SYMONDS ename LIKE 'C%C' OR
ALLEN .
DAVID .

26 conditions

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

Assignment:

• Display the emp records whose names are started with


Vowel

AEIOU

SELECT * FROM emp


WHERE ename LIKE 'A%' OR

ORACLE4PM Page 86
WHERE ename LIKE 'A%' OR
ename LIKE 'E%' OR
ename LIKE 'I%' OR
ename LIKE 'O%' OR
ename LIKE 'U%';

(or)

SELECT * FROM emp


WHERE Substr(ename,1,1) IN('A','E','I','O','U');

• Display the emp records whose names are ended with


Vowel

• Display the emp records whose names are started and


ended with Vowel

Lpad() & Rpad():

• pad => fill


• L => Left
• R => Right

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

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

Default char [3rd argument] Space

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

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

Default char [3rd argument] Space

no of chars to be filled = max_size - string length

Examples:

LPAD('RAJU',10,'*')

10-4 = 6 *s will be filled at left side

LPAD('RAJU',10,'*') ******RAJU
RPAD('RAJU',10,'*') RAJU******
LPAD('RAVI',12,'@') @@@@@@@@RAVI
RPAD('RAVI',12,'@') RAVI@@@@@@@@
LPAD('SAI',10,'#$') #$#$#$#SAI

ORACLE4PM Page 87
LPAD('SAI',10,'#$') #$#$#$#SAI
LPAD('A',8,'A') AAAAAAAA
LPAD('X',6,'X') XXXXXX
LPAD('*',5,'*') *****
RPAD('X',6,'X') XXXXXX

generate following message if account number is 1234569876:

amount debited from XXXXXX9876

SELECT 'amount debited from ' || LPAD('X',6,'X') ||


Substr('1234569876',-4,4) FROM dual;

Concatenate emp names and salaries:

SELECT RPAD(ename,10,' ') || ' ' || sal FROM emp;

LPAD('KIRAN',10) 5spacesKITAN
RPAD('KIRAN',10) KIRAN5spaces

default filling char [3rd arg]: space

LTRIM(), RTRIM() & TRIM():

• TRIM => Remove

LTRIM():
• used to remove unwanted chars from left side

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

default char [2nd argument] space

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

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

default char [2nd argument] space

Examples:
LTRIM('***RAJU***','*') RAJU***
RTRIM('***RAJU***','*') ***RAJU
LTRIM('3spacesRAJU3spaces') RAJU3spaces

ORACLE4PM Page 88
LTRIM('3spacesRAJU3spaces') RAJU3spaces
RTRIM('3spacesRAJU3spaces') 3spacesRAJU

TRIM():
it can be used to remove unwanted chars from left side or right
side or both

Syntax:
TRIM(LEADING / TRAILING / BOTH <char> FROM <string>)

TRIM(LEADING '@' FROM '@@@RAJU@@@') RAJU@@@


TRIM(TRAILING '@' FROM '@@@RAJU@@@') @@@RAJU
TRIM(BOTH '@' FROM '@@@RAJU@@@') RAJU
TRIM('3spacesRAJU3spaces') RAJU

default side: BOTH


default char: space

gmail.com

username: ravi
password: kumar

trim(ravispace) = ravi => T


mailbox

ravispace = ravi => F


error: invalid user

REVERSE():
used to get reverse string

Syntax:
REVERSE(<string>)

Exs:
REVERSE('RAJU') UJAR

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

Syntax:
ASCII(<char>)

Exs:

ORACLE4PM Page 89
Exs:
ASCII('A') 65
ASCII('Z') 90
ASCII('a') 97
ASCII('z') 122
ASCII('0') 48
ASCII('9') 57

CHR():
It returns char of specified ASCII value

Syntax:
CHR(<ASCII_value>)

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

Replace() & Translate():

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

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

Exs:
REPLACE('SAI KRISHNA', 'KRISHNA', 'TEJA') SAI TEJA
REPLACE('SAI TEJA SAI TEJA','SAI','RAVI') RAVI TEJA RAVI TEJA

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

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

Exs:
Replace('HELLO WELCOME HELLO WELCOME','LO','ab') HELab WELCOME HELab WELCOME

TRANSLATE('HELLO WELCOME HELLO WELCOME','LO','ab')

L will be replaced with a


O will be replaced with b

HEaab WEaCbME HEaab WEaCbME

ORACLE4PM Page 90
REPLACE('abcabcaabbccabcaa','abc','XYZ') XYZXYZaabbccXYZaa
TRANSLATE('abcabcaabbccabcaa','abc','XYZ') XYZXYZXXYYZZXYZXX

Replace() replaces the strings


Translate() replaces the chars

Translate() can be used for encrypting the data.

0 1 2 3 4 5 6 7 8 9
A @ # Z Y % * H G ^

SELECT ename,
TRANSLATE(sal,'0123456789','A@#ZY%*HG^') AS sal
FROM emp; => encrypt

TRANSLATE(sal,'A@#ZY%*HG^','0123456789') => decrypt

encrypt => converting normal text to cipher text


decrypt => converting cipher text to normal text

Instr():
• It is used to check whether substring is existed in string or not.
• If sub string is existed in string, it returns position number.
• If sub string is not existed in string, it returns 0

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

search position [3rd arg] default value 1


occurrence [4th arg] default value 1

Exs:
Instr('SAI TEJA','TEJA') 5
Instr('SAI TEJA','RAMU') 0
Instr('SAI TEJA RAVI TEJA','TEJA',1,2) 15

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

T H I S I S H I S W I S H

ORACLE4PM Page 91
T H I S I S H I S W I S H

Instr('THIS IS HIS WISH','IS') 3


Instr('THIS IS HIS WISH','IS',4,2) 10
Instr('THIS IS HIS WISH','IS',4,3) 14
Instr('THIS IS HIS WISH','IS',9,3) 0

-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

T H I S I S H I S W I S H
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Instr('THIS IS HIS WISH','IS',-1) 14


Instr('THIS IS HIS WISH','IS',-4,2) 6

Display the emp records whose are having AM chars:

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

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

Display the names which are having _ [underscore]:

SELECT *
FROM emp
WHERE Instr(ename,'_')>0;

(or)

SELECT *
FROM emp
WHERE ename LIKE '%\_%' ESCAPE '\';

(or)

ORACLE4PM Page 92
SELECT *
FROM emp
WHERE ename LIKE '%$_%' ESCAPE '$';

(or)

SELECT *
FROM emp
WHERE ename LIKE '%#_%' ESCAPE '#';

ename
------------
SAI TEJA
RAVI_TEJA

Display the names which are having %:

SELECT *
FROM emp
WHERE instr(ename,'%')>0;

(or)

SELECT *
FROM emp
WHERE ename LIKE '%\%%' ESCAPE '\';

Soundex():
• When we don't the exact spelling, based on sounds [pronunciation]
if we want to retrieve the records, we can use it.

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

Examples:

Display an emp record whose name is BLAKE:

SELECT *
FROM emp
WHERE ename='BLEK';
Output:
ORACLE4PM Page 93
Output:
no rows selected

SELECT *
FROM emp
WHERE soundex(ename)=soundex('BLEK');
Output:
displays blake record

Display an emp record whose name is scott:

SELECT *
FROM emp
WHERE soundex(ename) = soundex('skat');
Output:
displays scott record

Conversion Functions:

SELECT 100+200 FROM dual;


Output:
300

SELECT '100' + '200' FROM dual;


string string Implicit Conversion

number number
100 + 200

Output:
300

SELECT *
FROM emp
WHERE empno='7499'; '7499'
Output: string
displays 7499 emp record implicit conversion

number
7499

There are 2 types of conversions. They are:


• implicit conversion
• explicit conversion

implicit conversion:
ORACLE4PM Page 94
implicit conversion:
• If conversion is done implicitly by ORACLE then it is called
"Implicit Conversion".

NOTE:
• ORACLE supports to implicit conversion.
• Don't depend on implicit conversion. It degrades the performance.

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

ORACLE SQL provides following Conversion Functions:

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

to_Char() to_Char()

CHAR
DATE NUMBER
[STRING]

to_Date() to_Number()

To_Char() [DATE to CHAR]:

• It can be used to convert date to string.

• It can be used to change date formats [IND date format: DD/MM/YYYY, US date format:
MM/DD/YYYY].

• It can be used to get part of the date date, month, year, weekday, hours, minutes, seconds …etc

Syntax:
To_Char(<Date> , <Format>)

FORMAT PURPOSE EXAMPLE


sysdate: 16-MAY-23
YYYY gives year 4 digits to_char(sysdate,'YYYY') => 2023
YY gives year last 2 digits to_char(sysdate,'YY') => 23
ORACLE4PM Page 95
YY gives year last 2 digits to_char(sysdate,'YY') => 23
YEAR / gives year in words to_char(sysdate,'YEAR') => TWENTY TWENTY THREE
year
to_char(sysdate,'year') => twenty twenty three

MM gives month number to_char(sysdate,'MM') => 05

MON / gives short month to_char(sysdate,'MON') => MAY


mon name
Ex: JAN, FEB, MAR to_char(sysdate,'mon') => may

MONTH / gives full month name to_char(sysdate,'MONTH') => MAY


month Ex: JANUARY,
FEBRUARY to_char(sysdate,'month') => may

DD day num in month to_char(sysdate,'DD') => 16

D day num in week to_char(sysdate,'D') => 3

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

DDD day num in year to_char(sysdate,'DDD') => 136

31+28+31+30+16 = 136

DY / short week day name to_char(sysdate,'DY') => TUE


dy Ex: SUN, MON, TUE
to_char(sysdate,'dy') => tue

DAY / full weekday name to_char(sysdate,'DAY') => TUESDAY


day Ex: SUNDAY, TUESDAY
to_char(sysdate,'day') => Tuesday

Q quarter number to_char(sysdate,'Q') => 2

jan-mar => 1
apr-jun => 2
jul-sep => 3
oct-dec => 4
CC Century number to_char(sysdate,'CC') => 21

AD / BC gives AD or BC to_char(sysdate,'BC') => AD

W week number in the to_char(sysdate,'W') => 3


month
WW week number in the to_char(sysdate,'WW') => 20
year
HH / hours part in 12 hrs 4:58:15 PM
HH12 format

ORACLE4PM Page 96
HH12 format
to_char(sysdate,'HH') => 4

HH24 hours part in 24 hrs to_char(sysdate,'HH24') => 16


format

2:00 PM => 14
MI minutes part to_char(sysdate,'MI') => 58
SS seconds part to_char(sysdate,'SS') => 15
FF fractional seconds to_char(systimestamp,'FF')
AM / PM AM or PM to_char(sysdate,'AM') => PM

Display current system time from sysdate:

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

Display the emp records who joined in 1982:

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

Display the emp records who joined in 1980, 1982 and 1984:

SELECT ename, hiredate


FROM emp
WHERE to_char(hiredate,'YYYY') IN(1980,1982,1984);

Display the emp records who joined in december month:

SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'MM') = 12;
(or)
SELECT ename,hiredate
FROM emp
WHERE hiredate LIKE '%DEC%';

Display the emp records who joined in January, may, december:

SELECT ename,hiredate
ORACLE4PM Page 97
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'MM') IN(1,5,12);

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

SELECT ename, hiredate


FROM emp
WHERE to_char(hiredate,'Q') IN(1,4);

Display the emp records who joined on Sunday:

D => 1
DY => SUN
DAY => SUNDAY

SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'D')=1;
(or)
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'DY')='SUN';
(or)

SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'DAY')='SUNDAY';
SUNDAY3spaces = SUNDAY => F
Output:
no rows selected

SUNDAY3spaces
MONDAY3spaces
TUESDAY2spaces
WEDNESDAY => 9 => max string length in all weekday names
THURSDAY1space
FRIDAY3space
SATURDAY1space

SELECT ename,hiredate
FROM emp
WHERE RTRIM(to_char(hiredate,'DAY')) = 'SUNDAY';
RTRIM('SUNDAY3spaces')
SUNDAY = SUNDAY => T
(or)

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

ORACLE4PM Page 98
Display the emp records who joined in JANUARY:

SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'MONTH') = 'JANUARY';
JANUARY2spaces = JANUARY => F
Output:
No rows selected

SEPTEMBER => 9 => max string length in all month names

SELECT ename,hiredate
FROM emp
WHERE RTRIM(to_char(hiredate,'MONTH')) = 'JANUARY';

Display the emp records along with hiredates.


Display hiredates in INDIA date Format [DD/MM/YYYY]:

SELECT ename,
to_char(hiredate,'DD/MM/YYYY') as hiredate
FROM emp;

Assignment:

Display the emp records along with hiredates.


Display hiredates in US date Format [MM/DD/YYYY]:

Display the emp records along with hiredates.


Display hiredates in the format: 2023-05-16
YYYY-MM-DD

To_Char() [Number To Char]:

• It can be used to convert number to string.


• It is used to apply currency formats, thousand
separator, decimal point and decimal places ..etc.

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

Exs: NLS => National Language Support


To_Char(123) 123 [string]
To_Char(123.45) 123.45 [String]

ORACLE4PM Page 99
FORMAT PURPOSE
L Currency Symbol
Default currency symbol: $

C Currency Name
Default currency name: USD

,/G Thousand Separator


./D Decimal Point
9 Digit

Display 5000 as $5000.00:

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

$5000.00
L9999.99

Display 5000 as USD5,000.00 :

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

USD5,000.00
C9,999.99

NLS_Parameters:

NLS_CURRENCY it is a parameter that is used to specify currency


symbol
NLS_ISO_CURRENCY it is a parameter that is used to specify country
name

Display 5000 as ¥5000.00:

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

Display 5000 as JPY5000.00:

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

JPY5000.00

ORACLE4PM Page 100


Display all emp records along with salaries. Apply dollar
symbol to the salary:

sal => NUMBER(7,2)

SELECT ename, to_char(sal,'L99999.99') as sal


FROM emp;

Display all emp records along with salaries. Apply YEN


symbol to the salary:

sal => NUMBER(7,2)

SELECT ename, to_char(sal,'L99999.99','NLS_CURRENCY=¥') as sal


FROM emp;

Login as DBA:

username: system
password: nareshit

show parameters
--displays all parameters

show parameters NLS


--displays NLS parameters

SQL> ALTER SESSION SET NLS_TERRITORY='JAPAN';

Session altered.

SQL> ALTER SESSION SET NLS_CURRENCY='¥';

Session altered.

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

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

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

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

ORACLE4PM Page 101


ALTER SESSION it is applicable for that session only
ALTER SYSTEM permanently parameter value will be
modified

To_Date():
• It can be used to convert string to date.
• To insert date values, we can use it.
• To get part of specific date, we can use it.

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

Exs:
To_Date('25-DEC-2022') 25-DEC-22
To_Date('25 December 2022') 25-DEC-22
To_Date('25/12/2022') ERROR
To_Date('25/12/2022','DD/MM/YYYY') 25-DEC-22
to_date('DECEMBER 25 2022','MONTH DD YYYY') 25-DEC-22

Example:

CREATE TABLE t1
(
f1 DATE
);

INSERT INTO t1 VALUES('25-DEC-2022');

T1 string
F1
-------- Implicit conversion
25-DEC_22 date

Note:
• Don't depend on implicit conversion. It degrades the performance.
• to insert date value, use to_date() function.

INSERT INTO t1 VALUES(to_date('25-DEC-2022'));

T1 string
F1
-------
to_Date()
25-DEC-22
date Explicit conversion

ORACLE4PM Page 102


INSERT INTO t1 VALUES(to_date('25/12/2022'));
ERROR

INSERT INTO t1 VALUES(to_date('25/12/2022','DD/MM/YYYY'));


Output:
1 row created

INSERT INTO t1 VALUES(to_date('&DD/&MM/&YYYY','DD/MM/YYYY'));


Output:
enter value for DD: 25
enter value for MM: 12
enter value for YYYY:2022
1 row created

/
enter value for DD: 18
enter value for MM: 10
enter value for YYYY:2021

Extract year part from today's date:

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


Output:
2023

Extract year part from the date '17-AUG-2022':

SELECT to_char('17-AUG-2022','YYYY') FROM dual;


Output:
ERROR

SELECT to_char(to_date('17-AUG-2022'),'YYYY')
FROM dual;
Output:
2022

On which weekday india got independence?

15-AUG-1947

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


Output:
FRIDAY

ORACLE4PM Page 103


Assignment:
on which weekday sachin born.
sachin DOB is: 24-APR-1973

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

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

Exs:
To_Number('123') 123 Number
string
To_Number('ABC') ERROR
To_Number('123.45') 123.45
To_Number('$5000.00') ERROR
TO_Number('$5000.00','L9999.99') 5000
To_Number('USD5,000.00','C9,999.99') 5000

Date Functions:

sysdate
systimestamp

Add_Months()
Last_Day()
Next_Day()
Months_Between()

sysdate:
• it us used to get current system date

systimestamp:
• it is used to get system date & time

Display current system date:

SELECT sysdate FROM dual;

Display current system time using sysdate:

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

ORACLE4PM Page 104


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

Display current system date & time:

SELECT systimestamp FROM dual;

Extract date from systimestamp:

SELECT TRUNC(systimestamp) FROM dual;

Extract time from systimestamp:

SELECT to_char(systimestamp,'HH:MI:SS.FF AM') FROM dual;

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

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

Examples:

sysdate: 18-MAY-23

Add 2 days to today's date:

SELECT sysdate+2 FROM dual;


Output:
20-MAY-23

Add 2 months to today's date:

SELECT add_months(sysdate,2) FROM dual;


Output:
18-JUL-23

Add 2 years to today's date:

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


Output:
18-MAY-25

Subtract 2 days from today's date:

SELECT sysdate-2 FROM dual;


Output:
16-MAY-23

Subtract 2 months from today's date:

ORACLE4PM Page 105


SELECT add_months(sysdate,-2) FROM dual;
Output:
18-MAR-23

Subtract 2 years from today's date:

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


Output:
18-MAY-21

Assignment:

ORDERS
ORDERID PID PRICE QTY AMOUNT ORDERED_DATE DELIVERY_DATE
123456 1001 10000 1 10000 sysdate sysdate+5

EMPLOYEE
EMPNO ENAME DOB DOR
1001 A 23-NOV-1998 Add_Months(DOB,12*60)

DOB => Date Of Birth


DOR => Date Of Retirement

If emp age 60, that is retirement date

Product
Manufacturing_date Expiry_date
sysdate Add_Months(sysdate,3)

CM_LIST
STATE_CODE CM_NAME START_DATE END_DATE
TS KCR 18-JUN-2019 Add_Months(start_date,5*12)

SALES
DATEID AMOUNT Find today's sales:
1-JAN-2020 600000
Find yesterday sales:
2-JAN-2020 1200000
.. Find 1 month ago sales:
..
18-MAY-2023 900000 Find 1 year ago sales:

GOLD_RATE
find today's gold rate
DATEID PRICE [10gms]
1-JAN-2020 30000 find yesterday's gold rate
2-JAN-2020 30300

ORACLE4PM Page 106


2-JAN-2020 30300
.. find 1 month ago gold rate
..
find 1 year ago gold rate
18-MAY-2023 60000

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 ename,hiredate
FROM emp
WHERE hiredate = sysdate;
18-MAY-23 5:00PM = 18-MAY-23 5:05PM => F
Output:
No rows selected

NOTE:
TRUNC() function can be used to remove time value from
DATE TIME.

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

TRUNC(hiredate) = TRUNC(sysdate)
TRUNC(18-MAY-23 5:00PM) = TRUNC(18-MAY-23 5:09PM)

18-MAY-23 = 18-MAY-23 => TRUE

(or)

SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'DD/MM/YYYY') = to_char(sysdate,'DD/MM/YYYY');

ORACLE4PM Page 107


Display the emp records who joined yesterday:

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

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

SELECT 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 ename,hiredate
FROM emp
WHERE TRUNC(hiredate) = TRUNC(Add_Months(sysdate,-12));

Last_day():
• used to get last date in the month

Syntax:
Last_day(<date>)

Examples:
Last_day(sysdate) 31-MAY-23
Last_day('20-FEB-2023') 28-FEB-23
Last_day('20-FEB-2020') 29-FEB-23

Find next month first date:

SELECT Last_day(sysdate)+1 FROM dual;

31-MAY-23+1
1-JUN-23

Find current month first date:

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

Find previous month last date:

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

ORACLE4PM Page 108


Find previous month first date:

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

Next_Day():
• used to get coming date based on weekday
• Example: find next Sunday date, next Friday date

Syntax:
2nd arg:
Next_day(<date>,<weekday>)
sun
Sunday
1

Find next Sunday date:

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

Find next Friday date:

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

Find next month first Sunday date:

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

Assignment:
Find current month last Sunday date
Find current month first Sunday date

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

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

Example:
Months_Between('1-JAN-2023','1-JAN-2022') 12

Calculate experience of all emps:

ORACLE4PM Page 109


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

(or)

SELECT ename, TRUNC(months_between(sysdate, hiredate)/12) as experience


FROM emp;

Calculate age:

SELECT months_between(sysdate,your_DOB)/12 as age


FROM dual;

Number Functions / Math Functions:

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

sqrt():
used to find square root value

Syntax:
sqrt(<number>)

Exs:
sqrt(100) 10
sqrt(25) 5

power():
used to find power value

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

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

ORACLE4PM Page 110


power(5,3) 125

sign():
• can be used to check whether the given
number is +ve or -ve or zero.
• if number is +ve, it returns 1
• if number is -ve, it returns -1
• if number is 0, it returns 0

Syntax:
sign(<number>)

Exs:
sign(25) 1
sign(-25) -1
sign(0) 0

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

Syntax:
abs(<number>)

Exs:
abs(15) 15
abs(-15) 15

ceil():
is used to get round up value

Syntax:
ceil(<number>)

floor():
is used to get round down value

Syntax:
floor(<number>)

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

ORACLE4PM Page 111


Trunc():
• used to remove the decimal places

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

Exs:
Trunc(123.45678) 123
Trunc(123.45678,1) 123.4
Trunc(123.45678,2) 123.45
Trunc(123.45678,3) 123.456

2nd argument can be given as -ve


2nd argument -ve means, no decimal places will be given

-1 rounds in 10s
10,20,30,40,…..
-2 rounds in 100s
100,200,300,400,…..
-3 rounds in 1000s
1000, 2000, 3000, 4000,…..
-4 rounds in 10000s
10000, 20000, 30000, …..

Note:
Trunc() always gives lower value

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


120
TRUNC(786.34567,-1) 780 => 786.34567 => 790
780
TRUNC(567.83456,-2) 500 => 567.83456 => 600
500
TRUNC(8567.83456,-3) 8000 => 8567.83456 => 9000
8000

Round():
• if value is avrg or above avrg, it returns upper value
• if value is below avrg, it returns lower value

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

Exs:

percentage round(percentage)
67.8 67 & 68
avrg: 67.5

ORACLE4PM Page 112


avrg: 67.5
68
57.3 57 & 58
avrg: 57.5
57
78.5 78 & 79
avrg: 78.5
79
92.7 92 & 93
avrg: 92.5
93
54.2 54 & 55
avrg: 54.5
54

TRUNC() function will not consider average value. It


always gives lower value
ROUND() function considers avrg. if value is avrg or
ablove avrg, it returns upper value.
if value is below average, it returns lower value

TRUNC(123.45678) 123
ROUND(123.45678) 123
TRUNC(123.65678) 123
ROUND(123.65678) 124

ROUND(123.45678,2) 123.46
ROUND(123.45378,2) 123.45
ROUND(567.8923782,3) 567.892
ROUND(567.8928782,3) 567.893

2nd argument can be given as -ve.


2nd arg -ve means, it does not give decimal places.

-1 rounds in 10s
-2 rounds in 100s
-3 rounds in 1000s

ROUND(123.5678,-1) 120 & 130


avrg: 125
120
ORACLE4PM Page 113
120
ROUND(127.5678,-1) 120 & 130
avrg: 125
130
ROUND(3456.7892,-3) 3000 & 4000
avrg: 3500
3000
ROUND(3756.7892,-3) 3000 & 4000
avrg: 3500
4000

CREATE TABLE t1
NUMBER(5,2)
(
f1 NUMBER(5,2)
-999.99 TO 999.99
);

INSERT INTO t1 VALUES(56.78);

INSERT INTO t1 VALUES(1000); //ERROR

INSERT INTO t1 VALUES(123.456789); => 123.46

CREATE TABLE t2
(
f1 NUMBER(5,-2)
);

INSERT INTO t2 VALUES(527.3456); => 500


INSERT INTO t2 VALUES(587.3456); => 600

Mod():
used to get remainder value

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

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

Analytical Functions / Window Functions:

Rank()
Dense_Rank()
ORACLE4PM Page 114
Dense_Rank()
Row_Number()

Rank():
• is used to apply ranks to records according to specific
column order
• If multiple values are same, it does not follow sequence
in ranking. Gaps will be there in ranking.

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

Default order is : ASC

Dense_Rank():
• is used to apply ranks to records according to specific
column order
• It follows sequence in ranking even if multiple values
are same. No Gaps will be there in ranking.

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

Default order is : ASC

MARKS RANK DENSE_RANK


567 9 5
890 3 2
940 1 1
600 8 4
750 6 3
940 1 1
890 3 2
750 6 3
890 3 2
500 10 6

Apply ranks to emp records. give top rank to highest


salaried employee.

SELECT ename,sal,
RANK() OVER(ORDER BY sal DESC) as RNK
FROM emp;

(or)

ORACLE4PM Page 115


(or)

SELECT ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as RNK
FROM emp;

Apply ranks to emp records according to seniority:

EMP
EMPNO ENAME HIREDATE rank
1001 A 25-AUG-2019 1002 B 17-DEC-2018 1
1002 B 17-DEC-2018 1001 A 25-AUG-2019 2

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

Apply ranks to emp records. give top rank to highest salaried


emp. If salary is same give rank according to seniority.

EMP
EMPNO ENAME SAL HIREDATE 1001 A 7000 17-MAR-1982 1
1001 A 7000 17-MAR-1982 1004 D 6000 25-JAN-1983 2
1002 B 5000 23-JUL-1981 1003 C 5000 20-DEC-1980 3
1003 C 5000 20-DEC-1980 1002 B 5000 23-JUL-1981 4
1004 D 6000 25-JAN-1983

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

PARTITION BY clause:
It is used to apply ranks within groups.

Note:
By default ranks will be applied on entire table [all records]
To apply ranking within group, use PARTITION BY clause

Apply the ranks to employee records within dept.


Within the dept give top rank to highest salaried employee:

ORACLE4PM Page 116


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

Assignment:

Apply the ranks to employee records within job.


Within the job give top rank to highest salaried employee:

MANAGER 6000 3
MANAGER 8000 1
MANAGER 7000 2

CLERK 4000 1
CLERK 3000 2

Row_Number():
It is used to apply row numbers to records

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

Apply row numbers to emp records according to empno


ascending order:

SELECT row_number() OVER(ORDER BY empno ASC) as sno,


empno,ename,sal
FROM emp;

Apply row numbers to emp records according to ename


ascending order:

SELECT row_number() over(order by ename asc) as sno,


ename,sal
FROM emp;

Apply row numbers with in dept:

SELECT row_number() over(PARTITION BY deptno


ORDER BY empno ASC) as sno, empno,ename,deptno,sal

ORACLE4PM Page 117


ORDER BY empno ASC) as sno, empno,ename,deptno,sal
FROM emp;

Miscellaneous Functions:

NVL()
NVL2()

COALESCE()

GREATEST()
LEAST()

USER
UID

NVL():
• It is used to replace with other value.

Syntax:
NVL(<arg1>, <arg2>)

if arg1 is not null, it returns arg1


if arg1 is null, it returns arg2

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

Clalculate total salary of all emps [SAL+COMM]:

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

Display all emp records along with commission.


If comm is null display it as 'N/A':

SELECT ename,sal,
NVL(comm,'N/A') as comm
FROM emp;
Output:
ORACLE4PM Page 118
Output:
Error: Data types are mismatching
comm => number
N/A => char [string]

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

Assignment:

STUDENT
SID SNAME M1
1001 A 78
1002 B
Display nulls as AB
1003 C 66
1004 D
1005 E
1006 F 88

NVL2():
• It can be used to replace nulls and not nulls.

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

If arg1 is not null, it returns arg2


If arg1 is null, it returns arg3

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

Differences b/w NVL() & NVL2():

NVL():
• NVL() can be used to replace nulls only
• It takes 2 arguments

NVL2():
• NVL2() can be used to replace nulls and not nulls
• It takes 3 arguments

Update comm of all emps as following:


If emp is getting commission, increase 1000 rupees commission
If emp is not getting commission, set comm as 900

UPDATE emp

ORACLE4PM Page 119


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

USER:
it is use to get current user name

Syntax:
USER

UID:
it is used to get user id.

Syntax:
UID

Examples:

Display current user name and ID:

SELECT user, uid FROM dual;

Display current user:

SELECT user FROM dual;


(or)
show user

MAX():
It is used to find max value in vertical values

Syntax:
MAX(<column>)

Ex:
SAL
-----------
5000 SELECT max(sal) FROM emp;
8000 Output:
7000 8000
6000

ORACLE4PM Page 120


SELECT max(sal) FROM emp;
8000 Output:
7000 8000
6000

GREATEST():
It is used to find max value in horizontal values

Syntax:
GREATEST(<value1>,<v2>,<v3>,…..<v-n>)

demo
F1 F2 F3 SELECT greatest(f1,f2,f3) FROM demo;
10 80 70
50 30 90 greatest(10,80,70) => 80
greatest(50,30,90) => 90
100 70 40
greatest(100,70,40) => 100

F1 F2 F3
10 80 70 greatest(f1,f2,f3) => 80
50 30 90
100 70 40

max(f3) => 90

GREATEST() MAX()

used to find max in row used to find max val in column

It is variable length argument It takes 1 argument

Single row function Multi row function

LEAST():
used to find minimum value in horizontal values

Syntax:
LEAST(<value1>,<v2>,…..,<v-n>)

MIN():
used to fin min value in vertical values
ORACLE4PM Page 121
used to fin min value in vertical values

Syntax:
SELECT least(f1,f2,f3) FROM demo;
MIN(<column>)
Output:
10
demo 30
F1 F2 F3 40
10 80 70
50 30 90
SELECT min(f3) FROM demo;
100 70 40
Output:
40

Coalesce():
used to get first not null value

Syntax:
Coalesce(<arg1>,<arg2>,a3,a4…..,an)

Exs:
Coalesce(null,null,null,300,500) 300
Coalesce(null,null,'XYZ','AAA') XYZ

CUSTOMER
cid cname mobile1 mobile2
1001 AA 91234 56789
1002 BB 89123 45678

SELECT cname, coalesce(mobile1,mobile2 ) as mobile


FROM customer;
Output:
cid cname mobile
1001 AA 91234 56789
1002 BB 89123 45678

Group Functions / Aggregate Functions / Multi Row Functions:

sum => 120


40
avg => 40
60
min => 20
20
max => 60
count => 3

ORACLE4PM Page 122


ORACLE SQL provides 5 aggregate
functions. they are:
• sum()
• avg()
• max()
• min()
• count()

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

Syntax:
sum(<column_name>)

Examples:

Find sum of salaries of all emps:

SELECT sum(sal) FROM emp;

Find sum of salaries of all managers:

SELECT sum(Sal) FROM emp


WHERE job='MANAGER';

Find sum of salaries of deptno 10:

SELECT sum(sal) FROM emp


WHERE deptno=10;

SELECT sum(10,20,30) FROM dual;


ERROR

SELECT 10+20+30 FROM dual;


Output:
60

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

Syntax:
avg(<column>)

Examples:
ORACLE4PM Page 123
Examples:
Find average salary of all emps:

SELECT avg(sal) FROM emp;

Find avrg salary of deptno 10:

SELECT TRUNC(avg(sal)) FROM emp


WHERE deptno=10;

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

Syntax:
min(<column>)

Exs:
Find min salary in all emps:

SELECT min(sal) FROM emp;

Find min salary in all managers:

SELECT min(sal) FROM emp


WHERE job='MANAGER';

max():
used to find 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 deptno 10:

SELECT max(sal) FROM emp


WHERE deptno=10;

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

Syntax:
count(<column> / *)

Examples:

ORACLE4PM Page 124


Examples:
Find no of emps in emp table [find no of records]:

SELECT count(*) FROM emp;

Find no of emps in deptno 10:

SELECT count(*) FROM emp


WHERE deptno=10;

Find no of clerks in emp table:

SELECT count(*) FROM emp


WHERE job='CLERK';

Find how many emps are getting commission:

SELECT count(comm) FROM emp;

difference b/w count(*) and count(20):

count(*) count(20)

counts records counts 20s

slower faster

Built-In Function:
A function which is already defined & placed in
oracle db is called "Built-In Functions".

Single row function:


Function call will be applied on every row

Multi row function:


a function call will be applied on multiple rows

demo

F1 SELECT max(f1) FROM demo;


67 81

81
23
78
51

ORACLE4PM Page 125


51

ename SELECT lower(ename) FROM emp;


----------
SMITH lower('SMITH')
ALLEN lower('ALLEN')
WARD lower('WARD')

String functions lower(), upper(), initcap(), concat(),


length(), Lpad(), Rpad(), Ltrim(),
Rtrim(), Trim(),
Replace(), Translate()
Conversion Functions to_char(), to_date(), to_number()
Date Functions sysdate, systimestamp,
add_months(), months_between()
last_day(), next_day()
Number Functions ceil(), floor(), trunc(), round(), mod()
Analytical Rank(), Dense_Rank(), Row_Number(
Miscellaneous NVL(), NVL2(), Least(), Greatest(),
Coalesce()
Aggregate / Group sum(), avg(), min(), max(), count()

ORACLE4PM Page 126


CLAUSES
Monday, May 22, 2023 5:17 PM

CLAUSES in SELECT command:

Syntax of SELECT:

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, …………..]
[FETCH FIRST <n> rows only];

• Every SQL query is made up of with clauses.


• Clause is a part of query.
• Every Clause has specific purpose.

ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES

Following clauses can be used in SELECT command:

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

SELECT used to specify column names


Ex: SELECT ename,sal

FROM used to specify table names


ORACLE4PM Page 127
FROM used to specify table names
Ex: FROM emp

WHERE • used to specify condition


• this condition will be applied on every row
• it filters the rows
Ex: WHERE sal>=3000;

Display the emp names and salaries of the


employees whose salary is 3000 or more:

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

ORDER BY:
• used to arrange the records in ascending or descending order.
• default order is: ASC

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

Ascending => Small to Big


Descending => Big to Small

NUMBER CHAR

ASC DESC ASC DESC


1 10 A z
2 9 B y
3 8 . x
. . . .
. . Z .
10 1 a a
b Z
. .
. .
z A

Date

ORACLE4PM Page 128


ASC 2022, 2023 DESC 2022,2023

1-JAN-22 31-DEC-23
2-JAN-22 30-DEC-23
. .
. .
31-DEC-22 1-JAN-23
1-JAN-23 31-DEC-22
. .
. .
31-DEC-23 1-JAN-22

Examples on ORDER BY:

Display all emp records. Display emp names in alphabetical order:

SELECT ename,sal
FROM emp
ORDER BY ename ASC;
(or)
SELECT ename,sal
FROM emp
ORDER BY ename;
(or)
SELECT ename,sal
FROM emp
ORDER BY 1 ASC;

1 column number in SELECT

1 ename
2 sal

Display all emp records. Display salaries in descending order:

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

ORACLE4PM Page 129


SELECT ename,sal
FROM emp
ORDER By 2 DESC;

Display all emp records. Display them according to seniority:

SELECT ename,hiredate
FROM emp
ORDER BY hiredate ASC;

27-DEC-2019
17-SEP-2017
17-SEP-2017
25-AUG-2022
27-DEC-2019
25-AUG-2022

Display all emp records. Display deptnos in Ascending order:

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

Display all emp records. Display emp records in ascending order


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

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

if deptno is different, it will not check salary


if deptno is same, then only checks the salary arranges in desc

20 10
10 20

10 6000 10 9000
10 9000 10 6000

ORACLE4PM Page 130


Display all emp records. Display emp records in
ascending order according to deptno. within the dept
display salaries in descending order. if salaries are
same within dept, arrange them in ascending order
according to empno:

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

20 10
10 20

10 6000 10 9000
10 9000 10 6000

7521 20 5000 7369 20 5000


7369 20 5000 7521 20 5000

Display all emp records. display records in ascending


order according to deptno. Within dept arrange the
records according to seniority:

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

Note:
if a column has null values,
in ascending order, nulls will be displayed last
in descending order, nulls will be displayed first

null > remaining values

INSERT INTO emp(empno,ename)


VALUES(1001,'A');

INSERT INTO emp(empno,ename)


VALUES(1002,'B');

ORACLE4PM Page 131


Display all emp records. display salaries in descending
order. display nulls last:

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

Display all emp records. display hiredates according to


seniority. display nulls first:

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

GROUP BY:
• used to group the records according to specific
column or columns.
• We can apply aggregate (group) functions on group of
records.
• It can be used for data analysis.
• It gives summarized data from detailed data.

Example:
GROUP BY deptno
EMP => detailed data
EMPNO ENAME DEPTNO SAL summarized data

1001 A 10 10000 deptno sum_of_Sal


1002 B 10 12000 10 30000
1003 C 10 8000 20 16000
1004 D 20 7000 30 38000
1005 E 20 9000
1006 F 30 15000
1007 G 30 11000
1008 H 30 12000

Examples on GROUP BY:

ORACLE4PM Page 132


Examples on GROUP BY:

Find dept wise sum of salaries:

deptno sum_of_sal
10 ?
20 ?
30 ?

SELECT deptno, sum(sal) as sum_of_sal


FROM emp
GROUP BY deptno
ORDER BY 1;

Find dept wise max salary and min salary:

deptno max_sal min_sal


10 ? ?
20 ? ?
30 ? ?

SELECT deptno, max(Sal) as max_Sal,


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

Find dept wise no of emps:

deptno no_of_emps
10 ?
20 ?
30 ?

SELECT deptno, count(*) as no_of_emps


FROM emp
GROUP BY deptno
ORDER BY 1;

ORACLE4PM Page 133


Assignment:

Find job wise sum of salaries:

JOB SUM_OF_SAL
CLERK ?
GROUP BY job
MANAGER ? sum(Sal)
ANALYST ?

Find job wise no of emps

JOB NO_OF_emps GROUP BY job


Count(*)
CLERK ?
MANAGER ?
ANALYST ?

Find job wise max sal & min sal


GROUP BY job
max(sal)
JOB MAX_SAL MIN_SAL
min(sal)
CLERK ? ?
MANAGER ? ?
ANALYST ? ?

Find year wise no of emps joined in organization:

YEAR NO_OF_EMPS
1980 ?
1981 ?
1982 ?
1983 ?

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


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

ORACLE4PM Page 134


Find quarter wise no of emps joined in organization:

QUARTER NO_OF_EMPS
1 ?
2 ?
3 ?
4 ?

COLUMN QUARTER FORMAT A7

SELECT to_Char(hiredate,'Q') as quarter,


count(*) as no_of_Emps
FROM emp
GROUP BY to_char(hiredate,'Q')
ORDER BY quarter;

find year wise sales:


Assignment:
YEAR AMOUNT
SALES 2020 ?
DATE_ID AMOUNT 2021 ?
1-JAN-2020 1500000 2022 ?
2-JAN-2020 1800000 2023 ?
3-JAN-2020 1200000
.. find quarter wise sales:
.. QUARTER AMOUNT
.. 1 ?
23-MAY-23 1300000 2 ?
3 ?
4 ?

HAVING:
• HAVING clause is used to write condition on groups.
• It filters the groups.
• It must be followed by GROUP BY.
• It cannot be used without GROUP BY.
HAVING clause condition will be applied on result of
ORACLE4PM Page 135
• HAVING clause condition will be applied on result of
GROUP BY.
• Aggregate functions can be used in HAVING clause.

Examples on HAVING clause:

Display the deptnos which are spending


more than 10000 on their emps:

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

Display the depts which are having more than 5 emps:

deptno count(*) HAVING count(*)>5


3>5 => F
10 3
5>5 => F
20 5
6>5 => T
30 6
30 6

SELECT deptno, count(*)


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

Assignment:

Display the job titles which are having more than 3 emps:

GROUP BY job

HAVING => count(*)>3

ORACLE4PM Page 136


Display the job titles which are spending less
than 10000 on their emps:

GROUP BY job

HAVING sum(sal)<10000

Grouping the records according to multiple columns:

GROUP BY deptno: GROUP BY job:

10 MANAGER
10 10 group MANAGER MANAGER group
10 MANAGER

20 CLERK
20 20 group CLERK CLERK group
20 CLERK

GROUP BY deptno, job

10 CLERK 10 CLERK group


10 CLERK

10 MANAGER group
10 MANAGER

20 ANALYST
20 ANALYST 20 ANALYST group

20 MANAGER 20 MANAGER group

30 SALESMAN
30 SALESMAN 30 SALESMAN group

ORACLE4PM Page 137


20 MANAGER group

30 SALESMAN
30 SALESMAN 30 SALESMAN group
30 SALESMAN

30 MANAGER 30 MANAGER group

Find dept wise, job wise no of emps:

deptno job no_of_emps


10 CLERK ?
10 MANAGER ?
20 ANALYST ?
20 MANAGER ?
30 SALESMAN ?
30 MANAGER ?

break on deptno skip 1 => it will be applicable for entire session

SELECT deptno, job, count(*)


FROM emp
GROUP BY deptno, job
ORDER BY 1;

to remove breaks write following command:


clear breaks

Display dept wise, job wise sum of salaries:

deptno job sum_of_sal


10 CLERK ?
10 MANAGER ?
20 CLERK ?
20 MANAGER ?

ORACLE4PM Page 138


20 MANAGER ?

SELECT deptno, job, sum(Sal) as sum_of_sal


FROM emp
GROUP BY deptno, job
ORDER BY deptno;

Display year wise, quarter wise no of emps joined in


organization:

YEAR QUARTER no_of_emps


1980 1 ?
GROUP BY year, quarter
2 ?
3 ?
4 ?
1981 1 ? GROUP BY to_char(hiredate,'YYYY'), to_char(hiredate,'Q')
2 ?
3 ?
1980 1
4 ? 1980 1 group
1980 1
1980 2
1980 2 group
1980 2
1980 2

1981 1 1981 1 group


1981 1
1981 4 1981 4 group
1981 4

SELECT to_char(hiredate,'YYYY') as year, Execution Order


to_char(hiredate,'Q') as qrtr, -------------------------
count(*) as no_of_emps FROM
FROM emp WHERE
GROUP BY year, qrtr; GROUP BY
HAVING
ERROR: qrtr invalid identifier SELECT
DISTINCT
We cannot use alias name in GROUP BY ORDER BY
FETCH

ORACLE4PM Page 139


FETCH

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


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

Can we use alias name in GROUP BY?


NO.
GROUP BY gets executed before SELECT

Can we use alias name in ORDER BY?


YES.
ORDER BY gets executed after SELECT

Assignment:

SALES find year wise, quarter wise sales


DATE_ID AMOUNT
1-JAN-2020 1600000 year qrtr amount

2-JAN-2020 1000000 2020 1 ?

… .. 2 ?

.. .. 3 ?

24-MAY-2023 4 ?
2021 1 ?
2 ?
3 ?
4 ?

Rollup() & Cube():


These functions are used to calculate sub totals & grand total

Rollup():
used to calculate sub totals & grand total according to first

ORACLE4PM Page 140


• used to calculate sub totals & grand total according to first
column specified in Rollup() function

Syntax:
GROUP BY Rollup(<grouping_column_list>)

Ex:
GROUP BY Rollup(deptno,job)

according to deptno, it calculates sub totals & grand total

Cube():

Cube():
• used to calculate sub totals & grand total according to all
columns specified in CUBE() function.

Syntax:
GROUP BY Cube(<grouping_column_list>)

Ex:
GROUP BY Cube(deptno,job)

Find dept wise, job wise sum of salaries.


Calculate sub totals & grand total according to deptno:

deptno job sum_of_sal


10 CLERK ?
10 MANAGEr ?
10 Sub Total ?
20 CLERK ?
20 MANAGER ?
20 sub total ?
GRAND TOTAL ?

SELECT deptno, job, sum(Sal) as sum_of_sal


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

ORACLE4PM Page 141


Find dept wise, job wise sum of salaries.
Calculate sub totals & grand total according to deptno and job:

deptno job sum_of_sal


10 CLERK ?
10 MANAGEr ?
10 Sub Total ?
20 CLERK ?
20 MANAGER ?
20 sub total ?
CLERK ?
MANAGER ?
GRAND TOTAL ?

SELECT deptno, job, sum(Sal) as sum_of_sal


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

Display year wise, quarter wise no of emps joined in


organization. Calculate year wise sub totals & grand total:

YEAR QRTR NO_OF_EMPS


1980 1 ?
2 ?
3 ?
4 ?
1980 sub total ?
1981 1 ?
2 ?
3 ?
4 ?
1981 sub total ?
GRAND TOTAL ?

ORACLE4PM Page 142


SELECT to_char(hiredate,'YYYY') as year,
to_char(hiredate,'Q') as qrtr,
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 year wise sub totals, quarter wise sub
totals & grand total:

YEAR QRTR NO_OF_EMPS


1980 1 ?
2 ?
3 ?
4 ?
1980 sub total ?
1981 1 ?
2 ?
3 ?
4 ?
1981 sub total ?
1 [1st qrtr sub total] ?
2 ?
3 ?
4 ?
GRAND TOTAL ?

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


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

ORACLE4PM Page 143


Assignment:

Assignment:

SALES
DATE_ID AMOUNT
1-JAN-2020 1600000
2-JAN-2020 1000000
… ..
.. ..
24-MAY-2023 ..

find year wise, quarter wise sales. calculate sub totals


according to year and quarter & grand total:

year qrtr amount


sum(amount)
2020 1 ?
2 ?
3 ?
4 ?
2020 sub total ?
2021 1 ?
2 ?
3 ?
4 ?
2021 sub total ?
1 ?
2 ?
3 ?
4 ?
GRAND TOTAL ?

ASSIGNMENT:
PERSON
PID PNAME STATE_CODE GENDER AADHAR

ORACLE4PM Page 144


1234567890 AA TS M ---
TS M
TS F
AP M
AP F

Find state wise, gender wise no of people.


calculate state wise population [sub total according to state],
gender wise population [sub total according to gender] & grand
total:"

state gender no_of_people


TS M ?
F ?
TS population ?
AP M ?
F ?
AP population ?
M [male population] ?
F [female population] ?
Grand total [india population] ?

SELECT state, gender, count(*) as no_of_people


FROM person
GROUP BY cube(state, gender)
ORDER BY state;

DISTINCT clause:
• used to avoid duplicate rows.
• It avoids duplicates. It means, it gives distinct values.

Examples:

Display the deptnos available in organization using emp table:

SELECT deptno FROM emp;

ORACLE4PM Page 145


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

Display all job titles offered by company:

SELECT job FROM emp;

job
---------- SELECT DISTINCT job FROM emp;
CLERK
SALESMAN job
SALESMAN -------
MANAGER CLERK
CLERK SALESMAN
MANAGER MANAGER
ANALYST ANALYST
ANALYST
MANAGER

Display distinct deptno and job values:


(or)
display dept wise job titles offered by company:

SELECT deptno, job FROM emp;

deptno job

ORACLE4PM Page 146


deptno job
---------- ---------- SELECT DISTINCT deptno, job FROM emp
10 CLERK ORDER BY deptno;
10 CLERK
10 MANAGER
10 CLERK
20 ANALYST 10 MANAGER
20 ANALYST
20 MANAGER 20 ANALYST
20 MANAGER
30 SALESMAN
30 SALESMAN 30 SALESMAN
30 MANAGER 30 MANAGER

FETCH clause:
• it was introduced in ORACLE 12c version
• used to get top n records.

Syntax:
[OFFSET <n> row/rows] [FETCH FIRST/NEXT <n> row/rows only]

n => no of rows

Display first 3 rows in emp table:

SELECT * FROM emp


FETCH FIRST 3 rows only;

Display all rows except first 3 rows:

SELECT * FROM emp


OFFSET 3 ROWS;

first 3 rows will be skipped & remaining rows will be displayed

Display emp records. skip first 3 rows display next 3 rows :

SELECT * FROM emp


OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY;

ORACLE4PM Page 147


Display top 3 seniors records:

SELECT ename,hiredate
FROM emp
ORDER BY hiredate ASC
FETCH FIRST 3 ROWS ONLY;

Display top 3 salried emp records:

SELECT ename, sal


FROM emp
ORDER BY sal DESC
FETCH FIRST 3 ROWS ONLY;

SELECT to specify column list


Ex:
SELECT ename,sal
FROM to specify table names
Ex:
FROM emp
FROM emp, dept
WHERE • to specify filter condition.
• it will be applied on every row
• it filters the rows
Ex:
WHERE sal>3000

GROUP BY to specify grouping column list


Ex:
GROUP BY deptno
GROUP BY deptno,job
HAVING • to specify grouping condition
• it will be applied on every group
• it filters the groups
• aggreagte functions can be used

Ex:
GROUP BY deptno
HAVING sum(sal)>10000

ORDER BY • used to arrange records in ascending or


descending order
ORACLE4PM Page 148
descending order
• default order is: ASC
Ex:
ORDER BY ename ASC
ORDER BY sal DESC
ORDER BY deptno ASC, sal DESC
DISTINCT used to avoid duplicates
Exs:
DISTINCT job
DISTINCT deptno
DISTINCT deptno, job

FETCH used to get top-n rows


Exs:
FETCH FIRST 3 ROWS ONLY

ORACLE4PM Page 149


JOINS
Friday, May 26, 2023 4:14 PM

JOIN => Connect / Combine / Link

GOAL:
JOINS concept is used to retrieve the data
from multiple tables.

COLLEGE DATABASE

STUDENT
MARKS
FEE
STAFF
.
.

STUDENT.SID = MARKS.SID JOIN CONDITION

STUDENT MARKS
SID SNAME SCITY SID Maths Phy Che
1001 A HYD 1001 60 80 70
1002 B MUMBAI 1002 56 45 82
1003 C DELHI 1003 55 77 66

JOINS

SID SNAME Maths


STUDENT MARKS

JOINS:
• JOIN => connect / combine

• JOIN is an operation like sorting, filtering.

• In Join Operation, one table record will be joined [combined]


a record in another table based on some condition. This
condition is called "Join Condition".
This operation is called "Join Operation".

• JOIN CONDITION decides which record in a table should be


joined with which record in another table.

• JOINS concept goal is: retrieving data from multiple tables.

Types of Joins:

• Equi Join / Inner Join *****


• Outer Join *****
○ Left Outer Join
○ Right Outer Join
○ Full Outer Join
• Non-Equi Join
• Self-Join ***
• Cross Join / Cartesian Join

Equi Join:

ORACLE4PM Page 150


Equi Join:
• If join operation is performed based on equality
condition then it is called "Equi Join".
• It can be also called as Inner Join.

Example on Equi Join:

e.deptno = d.deptno Join Condition

matched records
Emp e Dept d
empno ename sal deptno Deptno Dname Loc
1001 A 20 10 Accounting DALLAS
1002 B 30 20 Research CHICAGO
1003 C 10 30 SALES BOSTON
1004 D 10 40 OPERATIONS NEW YORK
1005 E 20
1006 F 30
unmatched record from dept
1007 G
1008 H

unmatched records from emp

Display the emp records along with dept details:

ename sal dname loc


EMP DEPT

SELECT e.ename, e.sal, d.dname, d.loc


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

In above example,
e is table alias. it is alias name of emp table
d is table alias. it is alias name of dept table

Note:
Table alias makes table name short

From ORACLE 9i version onwards, we can write a Join Query in


2 styles. They are:
• ORACLE STYLE / NATIVE STYLE
• ANSI STYLE => Portable => Best Way

ANSI standards
SQL

ORACLE SQL SERVER MY SQL

ansi style ansi style ansi style


Joinquery Joinquery Joinquery

ORACLE4PM Page 151


NOTE:
• In ORACLE STYLE,
to separate 2 table names we use , [comma]
we write Join Condition in WHERE clause

• In ANSI STYLE,
to separate 2 table names we use keyword
we write Join condition in ON clause / USING clause

Example on Equi Join:

Display the emp records 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:

for equi join use the keyword: [INNER] JOIN

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

NOTE:
For USING clause, common column name must be same in 2 tables.
Otherwise, we cannot use USING clause.

oracle rewrites as
USING(deptno) ON e.deptno=d.deptno

Example on Equi Join+Condition:

Display the emp records who are working in CHICAGO:

ename sal dname loc

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

Emp
Dept
empno ename sal deptno
Deptno Dname Loc
1001 A 20
10 Accounting DALLAS

ORACLE4PM Page 152


Emp
Dept
empno ename sal deptno
Deptno Dname Loc
1001 A 20
10 Accounting DALLAS
1002 B 30
20 Research CHICAGO
1003 C 10
30 SALES BOSTON
1004 D 10
40 OPERATIONS NEW YORK
1005 E 20
1006 F 30
1007 G
1008 H

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 is used to specify Join Condition


WHERE clause is used to specify filter condition

Assignment:
Display BLAKE and ALLEN records along with dept details

ename sal dname loc


BLAKE
ALLEN

Note:
Inner Join = matched records only
Inner Join can give matched records only

Outer Join:
• Outer Join = matched +unmatched records

• Inner Join can give matched records only. To get unmatched


records also, we use Outer Join.

• Outer Join can give matched records and unmatched records.

It has 3 sub types. They are:

• Left Outer Join


• Right Outer Join
• Full Outer Join

Note:
In ORACLE STYLE, Join Condition decides left table & right table

Exs:

WHERE e.deptno = d.deptno


emp e Left Table
dept d Right Table

WHERE d.deptno = e.deptno


dept d Left table
emp e Right Table

ORACLE4PM Page 153


emp e Right Table

In ANSI STYLE, keyword decides left table and right table.

Exs:
FROM emp e JOIN dept d
emp e Left table
dept d Right Table

FROM dept d JOIN emp e


dept d Left table
emp e Right Table

Left Outer Join:

• Left Outer = matched + unmatched from left table

• Left Outer Join can give matched records and


unmatched records from left side table.

• In ANSI STYLE use the keyword: LEFT [OUTER] JOIN

• In ORACLE STYLE use the Outer Join operator. Its


symbol is: (+)

• For Left Outer Join write (+) symbol at right side.

Example on Left Outer Join:

Display emp details along with dept details.


Also display the emps to whom dept is not assigned:

INSERT INTO emp(empno,ename,sal)


VALUES(1001,'A',5000);

INSERT INTO emp(empno,ename,sal)


VALUES(1002,'B',4000);

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:

ORACLE4PM Page 154


• Right Outer Join = matched + unmatched records from right table

• Right outer Join can give matched records and unmatched records
from right side table.

• In ANSI STLE use the keyword: RIGHT [OUTER] JOIN

• In ORACLE STYLE use Outer Join Operator.


Write (+) symbol at left side for right outer join.

Example on Right Outer Join:

Display the emp records along with dept details.


Also display the depts in which emps are not existed.

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 table

• Full Outer Join can give matched records, unmatched records from left table
and unmatched records from right table.

• In ANSI STYLE use the keyword: FULL [OUTER] JOIN


SETS

• In ORACLE STYLE, apply UNION OPERATOR between Left Outer Join and
A = {1,2,3,4,5}
Right Outer Join

B = {4,5,6,7,8}

e.deptno = d.deptno(+) Left Outer Join


A U B = {1,2,3,4,5,6,7,8}
e.deptno(+) = d.deptno Right Outer Join
e.deptno(+) = d.deptno(+) ERROR Full Outer
Left Outer Join Full Outer Join
Left Outer = matched + unmatched from left
UNION
UNION UNION
Right Outer Join
Right Outer = matched + unmatched from right

Full Outer = matched + unmatched from left + unmatched from right

Example on full outer join:

Display emp 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.

ORACLE STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+)
UNION

ORACLE4PM Page 155


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;

Equi Join / Inner Join => matched

Outer Join => matched + unmatched

Left Outer = matched + unmatched from left

Right Outer = matched + unmatched from right

Full Outer = matched + unmathced from left & right

Displaying unmatched records only:

Left Outer Join + Condition:


• It gives unmatched records only from left table

Example:
Display the emp records to whom dept is not assigned:
[unmatched records only from emp]

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d
WHERE e.deptno = d.deptno(+) AND d.dname IS NULL;

ANSI STYLE:

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e LEFT JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS NULL;

Right Outer Join + Condition:

Right Outer Join + Condition = unmatched from right table

Display the depts in which emps are not existed:

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;

ORACLE4PM Page 156


WHERE e.deptno(+) = d.deptno AND e.ename IS NULL;

ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e RIGHT JOIN dept d
ON e.deptno = d.deptno
WHERE e.ename IS NULL;

Full Outer join + Conditions:

Full Outer join + Conditions = unmatched from left & right

ORACLE STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+) AND d.dname IS NULL
UNION
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno AND e.ename IS NULL;

ANSI STYLE:

SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS NULL OR e.ename IS NULL;

Venn Diagrams of Joins:

Equi Join

Outer Join
Left Outer
Right outer
Full Outer

Non-Equi Join / Inner Join

Self Join

Cross Join

ORACLE4PM Page 157


Equi Join:
If Join operation is performed based on equality condition
then it is called "Equi Join".

Exs:
WHERE e.deptno = d.deptno
WHERE s.sid = m.sid

Non-Equi Join:

If Join Operation is performed based on other than


equality condition then it is called "Non-Equi Join".

Exs:
WHERE e.deptno > d.deptno
WHERE e.deptno < d.deptno
WHERE e.deptno >= d.deptno

Example on Non-Equi Join:

e.sal BETWEEN s.losal AND s.hisal


EMP e SALGRADE s
EMPNO ENAME SAL GRADE LOSAL HISAL
1001 A 3500 1 700 1200
1002 B 1500 2 1201 1400
1003 C 950 3 1401 2000
1004 D 2500 4 2001 3000
1005 E 6000 5 3001 9999

ENAME SAL GRADE


EMP SALGRADE

Display emp records along with salary grades:

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:
• If a table is joined to itself then it is called "Self Join /
Recursive Join".
• IN this, one record in a table will be joined with another
record in same table.
• In this, physically one table is there. logically take it as 2
tables and join them based on some condition

e.mgr = m.empno
EMP e EMP m
EMPNO ENAME JOB SAL MGR EMPNO ENAME JOB SAL MGR

ORACLE4PM Page 158


EMPNO ENAME JOB SAL MGR EMPNO ENAME JOB SAL MGR
1001 A MANAGER 15000 1001 A MANAGER 15000
1002 B CLERK 6000 1001 1002 B CLERK 6000 1001
1003 C ANALYST 5000 1001 1003 C ANALYST 5000 1001
1004 D MANAGER 20000 1004 D MANAGER 20000
1005 E CLERK 8000 1004 1005 E CLERK 8000 1004
1006 F SALESMAN 7000 1004 1006 F SALESMAN 7000 1004

Display emp details along with manager details:

EMP_NAME EMP_SAL MGR_NAME MGR_SAL

ORACLE STYLE:

SELECT e.ename as emp_name, e.sal as emp_sal,


m.ename as mgr_name, m.sal
FROM emp e, emp m
WHERE e.mgr = m.empno;

ANSI STYLE:

SELECT e.ename as emp_name, e.sal as emp_sal,


m.ename as mgr_name, m.sal
FROM emp e INNER JOIN emp m
ON e.mgr = m.empno;

Display the emp records who are earning more than their
manager:

ORACLE STYLE:

SELECT e.ename as emp_name,


e.sal as emp_sal,
m.ename as mgr_name,
m.sal as mgr_sal
FROM emp e, emp m
WHERE e.mgr = m.empno AND e.sal>m.sal;

ANSI STYLE:

SELECT e.ename as emp_name,


e.sal as emp_sal,
m.ename as mgr_name,
m.sal as mgr_sal
FROM emp e INNER JOIN emp m
ON e.mgr = m.empno
WHERE e.sal>m.sal;

Example:

TEAMS
CID CNAME Display the output as following:
10 IND
IND VS AUS
20 AUS
IND VS WIN
30 WIN
AUS VS WIN

ORACLE4PM Page 159


x.cid < y.cid

TEAMS x TEAMS y
CID CNAME CID CNAME
10 IND 10 IND
20 AUS 20 AUS
30 WIN 30 WIN

ORACLE STYLE:

SELECT x.cname || ' VS ' || y.cname


FROM teams x, teams y
WHERE x.cid<y.cid;

ANSI STYLE:

SELECT x.cname || ' VS ' || y.cname


FROM teams x INNER JOIN teams y
WHERE x.cid<y.cid;

CROSS JOIN / CARTESIAN JOIN:


A B

1
A = {1,2,3} 4
2
B = {4,5} 5
3
AXB = ?

{ (1,4)(1,5)
3 X 2 = 6 pairs
(2,4)(2,5)
(3,4)(3,5) }

CROSS JOIN / CARTESIOAN JOIN:

• In this, each record in a table will be joined with every record in


another table.
• In Cross Join, we will not write any join condition

Example:

EMP e DEPT d
EMPNO ENAME DEPTNO DNAME
1001 A 10 ACCOUNTS
1002 B 20 RESEARCH
1003 C 30 SALES

ORACLE STYLE:

SELECT e.ename, d.dname


FROM emp e, dept d;

ANSI STYLE:

SELECT e.ename, d.dname


FROM emp e CROSS JOIN dept d;

ORACLE4PM Page 160


Example on Cross Join:

GROUPA a GROUPB b
cid cname cid cname
10 IND 40 ENG
20 AUS 50 NZ
30 WIN 60 BAN

ORACLE STYLE:
Output:
IND VS ENG
SELECT a.cname || ' VS ' || b.cname
IND VS NZ
FROM groupa a, groupb b;
IND VS BAN
ANSI STYLE:
AUS VS ENG
AUS VS NZ
SELECT a.cname || ' VS ' || b.cname
AUS VS BAN
FROM groupa a CROSS JOIN groupb b;

WIN VS ENG
WIN VS NZ
WIN VS BAN

JOINS:
• used to retrieve the data from multiple tables

Types of Joins:

Inner Join => matched records only


• Equi Join => join operation performs based on =
• Non-Equi Join => join operation performs based on other than =

Outer Join => matched + unmatched


• Left Outer => matched + unmatched from left
• Right Outer => matched + unmatched from right
• Full Outer => matched + unmatched from left & right

Self Join => a table will be joined to itself


one record in a table will be joined with another record in same table

Cross Join => each record in one table will be joined with every record in another

Joins & Group By:

Find dept wise sum of salaries. but, display dept names:

dname sum(Sal)
Accounting ?
Research ?
Sales ?

SELECT d.dname, sum(e.sal) as sum_of_sal


FROM emp e, dept d
WHERE e.deptno=d.deptno
GROUP BY d.dname;

ORACLE4PM Page 161


GROUP BY d.dname;

Find location wise no of emps working in organization:

LOC no_of_emps
NEW YORK ?
CHICAGO ?
DALLAS ?

SELECT d.LOC, count(*) as no_of_emps


FROM emp e, dept d
WHERE e.deptno=d.deptno
GROUP BY d.LOC;

Retrieving data from multiple tables:

E.deptno=D.deptno D.locid = L.locid L.cid=C.cid

EMP E DEPT D LOCATION L COUNTRY C

EMPNO DEPTNO LOCID CID


ENAME DNAME LNAME CNAME
DEPTNO LOCID STATE
CID

ENAME DNAME LNAME STATE CNAME


E D L L C

To retrieve data from 2 tables write 1 Join Condition


To retrieve data from 4 tables write 3 Join Conditions
To retrieve data from n tables write n-1 Join Conditions

ENAME DNAME LNAME STATE CNAME


E D L L C

ORACLE STYLE:

SELECT E.ENAME, D.DNAME, L.LNAME, L.STATE, C.CNAME


FROM EMP E, DEPT D, LOCATION L, COUNTRY 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, L.STATE, C.CNAME


FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO=D.DEPTNO INNER JOIN LOCATION L
ON D.LOCID=L.LOCID INNER JOIN COUNTRY C
ON L.CID = C.CID;

ORACLE4PM Page 162


Friday, May 26, 2023 4:45 PM

e.deptno = d.deptno
Emp Dept
empno ename sal deptno Deptno Dname Loc
1001 A 20 10 Accounting DALLAS
1002 B 30 20 Research CHICAGO
1003 C 10 30 SALES BOSTON
1004 D 10 40 OPERATIONS NEW YORK
1005 E 20
1006 F 30
1007 G
1008 H

ORACLE4PM Page 163


Assignment
Tuesday, May 30, 2023 2:38 PM

Example-1:
PROJECTS
EMPLOYEE
PROJECT_ID PNAME DURATION
EMPNO ENAME PROJECT_ID
10 X 6
1001 A 10
20 Y 12
1002 B 40
30 Z 8
1003 C
40 W 15
1004 D 20
50 N 10
1005 E 10
1006 F 40
1007 G
1008 H 20 duration in months
1009 I

 Display the emp details with project details [Inner Join]

 Display emp records with project details. Also display the emps who are on bench. Bench means,
not assigned to project. [Left Outer Join]

 Display emp records with project details. Also display the projects which are not assigned to any
employee.

 Display emp records with project details. Also display the emps who are on bench. Also display the
projects which are not assigned to any employee.

 Display the emp records who are on bench. [Left Outer Join + Condition]

 Display the projects which are not assigned to any employee. [Right Outer Join + Condn]

 Display the emp records who are on bench. Also display the projects which are not assigned to any
employee. [Full Outer Join + Condns]

Example-2:

STUDENT COURSE
SID SNAME CID CID CNAME
1 A 20 10 MCA
2 B 30 20 MBA
3 C 10 30 MSC
4 D 10 40 MA
5 E 30
6 F
7 G

ORACLE4PM Page 164


• Display student details with course details

• Display student details with course details. Also display the students who are not
joined in any course.

• Display the student details with course details. Also display the courses in which
students are not joined.

• Display the student details with course details. Also display the students who are
not joined in any course. Also display the courses in which students are not joined.

• Display the students who are not joined in any course.

• Display the courses in which students are not joined.

• Display the students who are not joined in any course. Display the courses in which
students are not joined.

Example-3:

CUSTOMER

CID CNAME STREET CITY STATE MOBILE MAIL_ID

PRODUCTS

PID PNAME PRICE QTY_ON_HAND

ORDERS

OID ORDERED_DATE CID PID QTY AMOUNT DELIVERY_DATE

 Display the customer details, product details and order details as following:
OID, PID, PNAME, QTY, PRICE, AMOUNT, CNAME, STREET, CITY, STATE, MOBILE

ORACLE4PM Page 165


Sub Queries
Wednesday, May 31, 2023 5:14 PM

Sub Queries / Nested Queries:

Example:

Display the emp records who are earning more than BLAKE:

BLAKE sal 2850

SELECT ename,sal
FROM emp
WHERE sal>(find BLAKE sal);

SELECT ename,sal
FROM emp
WHERE sal>(SELECT sal FROM emp WHERE ename='BLAKE');

Sub Queries / Nested Queries:

Syntax:

SELECT <column_list>
FROM <table_name>
WHERE <column> <operator> (<SELECT query>);

Inner Query / Sub Query / Child Query

Outer Query / Main Query / Parent Query

• If a query is written in another query then it is called "Sub Query /


Nested Query".

• Outside query is called "Outer Query / Main Query / Parent Query".

Inside query is called "Inner Query / Sub Query / Child Query".


ORACLE4PM Page 166
• Inside query is called "Inner Query / Sub Query / Child Query".

• When we don't WHERE condition value, to find it we write another


query. this query is called "Sub Query".

• Sub Query must be written parenthesis.

• Inner query must be SELECT query only. It cannot be INSERT /


UPDATE / DELETE.

• Outer query can be SELECT / INSERT / UPDATE / DELETE.

• We can write up to 255 levels of sub queries in WHERE clause.

• First Inner Query gets executed. The result of Inner Query


becomes input for Outer Query. Then Outer query gets executed.

Types of Sub Queries:

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:

• A sub query which returns one value is called "Single Row Sub
Query".
• For this, we use operators such as: > < >= <= = !=

Examples on Single Row Sub Query:

Display the emp records whose job title is same as BLAKE:

ORACLE4PM Page 167


BLAKE MANAGER

SELECT ename,job,sal
FROM emp
WHERE job=(Find BLAKE'S JOB title);

SELECT ename,job,sal
FROM emp
WHERE job=(SELECT job FROM emp WHERE ename='BLAKE');

Find max salary:

SELECT max(sal) FROM emp;

Find 2nd max salary:

sal SELECT max(sal)


------ FROM emp
4000 WHERE sal<7000;
6000
5000 4000
7000 6000 max sal => 6000
3000 5000 2nd max sal
3000

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

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

Find 3rd max salary:


ORACLE4PM Page 168
Find 3rd max salary:

sal
------ SELECT max(sal)
4000 FROM emp
6000 WHERE sal<6000;
5000
7000
3000 4000 max sal => 5000
5000 3rd max salary
3000

SELECT max(sal)
FROM emp
WHERE sal<(Find 2nd max sal);

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

Find the emp name who is earning max salary:

SELECT ename
FROM emp
WHERE sal=(Find max sal);

SELECT ename FROM emp


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

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

SELECT ename FROM emp


WHERE sal = (Find 2nd max sal);

SELECT ename FROM emp


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

ORACLE4PM Page 169


Assignment:
• Find the emp name who is earning 3rd max salary

• Find 4th max salary

Display most senior's record:

SELECT ename FROM emp


WHERE hiredate = (Find most senior's hiredate)

Find most senior's hiredate min hiredate

SELECT ename FROM emp


WHERE hiredate = (SELECT min(hiredate) FROM emp);

Display the emp name who is most junior in all emps:

SELECT ename FROM emp


WHERE hiredate = (SELECT max(hiredate) FROM emp);

Display the emp records who are senior to BLAKE:

SELECT ename,hiredate
FROM emp
WHERE hiredate<(find BLAKE's hiredate);

SELECT ename,hiredate
FROM emp
WHERE hiredate<(SELECT hiredate FROM emp
WHERE ename='BLAKE');

ORACLE4PM Page 170


Assignment:
Display the juniors of BLAKE

Find the deptno which is spending max amount on their emps:

SELECT deptno FROM emp


GROUP BY deptno
HAVING sum(Sal) = (find max sum of salary in all depts);

find max sum of salary in all depts:


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

SELECT deptno FROM emp


GROUP BY deptno
HAVING sum(Sal) = (SELECT max(sum(Sal)) FROM emp
GROUP BY deptno);

Find the dept name which is spending max amount on their emps:

SELECT dname FROM dept


WHERE deptno = 30;

3oth dept is spending max amount. But we don't know deptno. find it

SELECT dname FROM dept


WHERE deptno = (find the deptno which is spending max amount);

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

ORACLE4PM Page 171


Find the deptno which is having max no of emps:

SELECT deptno
FROM emp
GROUP BY deptno
HAVING count(*) = (find max no of emps in all depts);

SELECT deptno
FROM emp
GROUP BY deptno
HAVING count(*) = (SELECT max(count(*)) FROM emp
GROUP BY deptno);

Find the dept name which is having max no of emps:

SELECT dname FROM dept WHERE deptno=30;

SELECT dname FROM dept WHERE deptno=(find the deptno


which is having max no of emps);

SELECT dname FROM dept WHERE deptno=(SELECT deptno


FROM emp
GROUP BY deptno
HAVING count(*) = (SELECT max(count(*)) FROM emp
GROUP BY deptno));

Set 7934 salary as 10th dept's max salary:

7934 sal as 5000

UPDATE emp
SET sal=(find 10th dept max sal)
WHERE empno=7934;

find 10th dept max sal:


ORACLE4PM Page 172
find 10th dept max sal:
SELECT max(Sal) FROM emp WHERE deptno=10;

UPDATE emp
SET sal=(SELECT max(sal) FROM emp WHERE deptno=10)
WHERE empno=7934;

Delete most seniors record:

DELETE FROM emp


WHERE hiredate = (find most senior's hiredate);

DELETE FROM emp


WHERE hiredate = (SELECT min(hiredate) FROM emp);

Multi Row Sub Query:


• If sub query returns multiple rows then it is called
"Multi Row Sub Query".
• For this, we use operators such as: IN, ALL, ANY

Examples:

• Display the emp records whose job title is same as


BLAKE and SMITH job titles:
[display all managers and clerks records]

BLAKE MANAGER
SMITH CLERK

SELECT ename,job,sal
FROM emp
WHERE job IN(Find BLAKE and SMITH job titles);

SELECT ename,job,sal
FROM emp

ORACLE4PM Page 173


FROM emp
WHERE job IN(SELECT job FROM emp
WHERE ename IN('BLAKE','SMITH'));

Display the emp records whose deptno is same as


7900, 7934 emp's deptno:
[display 30, 10 dept emp records]

7934 MILLER 10
7900 JAMES 30

SELECT ename,deptno FROM emp


WHERE deptno IN(find deptnos of 7900, 7934);

SELECT ename, deptno FROM emp


WHERE deptno IN(SELECT deptno FROM emp
WHERE empno IN(7900,7934));

ALL:

Syntax:
<column> <relational_operator> ALL(<value_list>)

• It is used to avoid multi relational conditions using AND.


• It is mainly used in subqueries to compare with multiple
values.

Example:

Display the emp records whose salary is more than


2000 and 3000:

SELECT ename,sal
FROM emp
WHERE sal>2000 AND sal>3000;

ORACLE4PM Page 174


WHERE sal>2000 AND sal>3000;

sal>2000 AND sal>3000 sal> ALL(2000,3000)

if sal is > all the values in


list then condition is TRUE

sal
--------
6000
2500
1800
4000

Display the emp records whose salary is less than 2000 and
3000:

SELECT ename,sal
FROM emp
WHERE sal<2000 AND sal<3000;

sal<2000 AND sal<3000 sal<ALL(2000,3000)

sal sal<2000,3000 => invalid


-----
4000 F sal<ALL(2000,3000) => valid
1500 T
2500 F
1800 T

Display the emp records whose salary is more than all


managers:

SELECT ename,job,sal
ORACLE4PM Page 175
SELECT ename,job,sal
FROM emp
WHERE sal>ALL(find all managers sals);

SELECT ename,job,sal
FROM emp
WHERE sal>ALL(SELECT sal FROM emp
WHERE job='MANAGER');

Display the emp records who are earning less


than all managers:

SELECT ename,job,sal
FROM emp
WHERE sal<ALL(SELECT sal FROM emp
WHERE job='MANAGER');

ANY:

Syntax:
<column> <relational_operator> ANY(<value_list>)

• it is used to avoid multi relational conditions using OR.


• It is mainly used in sub queries to compare with multiple
values.

Examples:

Display the emp records whose salary is


more than 2000 or 3000:

SELECT ename,sal
FROM emp
WHERE sal>2000 OR sal>3000;
(or)
SELECT ename,sal
FROM emp
WHERE sal>ANY(2000,3000);

ORACLE4PM Page 176


sal>2000 OR sal>3000 sal>ANY(2000,3000)

sal
-------
OR AND
ANY ALL
5000 => T T
1500 => F F
2500 => T F
4000 => T T

Display the emp records whose salary is 2000 or 3000 or


4000:

SELECT ename,sal
FROM emp
WHERE sal=2000 OR sal=3000 OR sal=4000;

sal=2000 OR sal=3000 OR sal=4000 sal IN(2000,3000,4000) sal=ANY(2000,3000,4000)

Display the emp records whose salary is more than


any managers salary:

SELECT ename,sal
FROM emp
WHERE sal>ANY(find all managers sals);

SELECT ename,sal
FROM emp
WHERE sal>ANY(SELECT sal FROM emp
WHERE job='MANAGER');

Find 2nd max salary:

ORACLE4PM Page 177


Find 2nd max salary:

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

Correlated Sub Query:

• In Normal Sub query, first inner query gets executed then


outer query gets executed. Inner query gets executed
only once.

• In correlated sub query, first outer query gets executed.


then inner query gets executed. Inner query gets
executed for multiple times.

• If outer query passes value to inner query then it is called


"Correlated Sub Query".

Execution Process of Correlated Sub Query:

1 2 passes value 3

OUTER INNER
4 passes value

5 condition => T => selects the rows


=> F => will not select the row

These 5 steps will be executed for every row selected by outer query.

If outer query selects 5 rows, inner query gets executed for 5 times.

no of execution times of inner query = no of rows selected by outer query

Steps:
1. First outer query gets executed. It selects a row.
ORACLE4PM Page 178
1. First outer query gets executed. It selects a row.
2. Outer query passes value to inner query.
3. Inner query gets executed.
4. Inner query passes value to Outer query.
5. Outer query condition will be tested. If condition is TRUE,
it selects the row. Otherwise, row will not be selected.

Above 5 steps will be executed repeatedly for every row


selected by outer query.

Examples on Correlated Sub Query:

Display the emp records who are earning more than their
dept's avrg salary:

EMP
EMPNO ENAME DEPTNO SAL deptno avg_sal
1001 A 10 15000 10 20000
1002 B 10 25000 20 7500
1003 C 20 10000
1004 D 20 5000

Display the emp records who are earning more than


their dept's avrg salary:

SELECT ename, sal, deptno


FROM emp e
WHERE sal>(find emp 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);

EMP e deptno avg_sal


EMPNO ENAME DEPTNO SAL 10 20000
1001 A 10 15000 20 7500
1002 B 10 25000
ORACLE4PM Page 179
1002 B 10 25000
1003 C 20 10000
1002 B 10 25000
1004 D 20 5000
1003 C 20 10000

Display the emp records who are earning max salary in


each dept:

SELECT e.empno, e.ename, e.deptno, e.sal


FROM emp e
WHERE e.sal = (find emp dept's max sal);

SELECT e.empno, e.ename, e.deptno, e.sal


FROM emp e
WHERE e.sal = (SELECT max(sal) FROM emp
WHERE deptno=e.deptno);

EMP e deptno max_sal


EMPNO ENAME DEPTNO SAL 10 25000
1001 A 10 15000 20 10000
1002 B 10 25000
1003 C 20 10000
1002 B 10 25000
1004 D 20 5000
1003 C 20 10000

Assignment:
Display most senior record in each dept:

EXISTS:

SYNTAX:
EXISTS(<SELECT query>)

ORACLE4PM Page 180


If rows are selected by sub query, EXISTS returns TRUE
If rows are not selected by sub query, EXISTS returns FALSE

Display the dept names which are having emps:

SELECT d.dname
FROM dept d
WHERE EXISTS(SELECT * FROM emp
WHERE deptno=d.deptno);

DEPT d EMP
DEPTNO DNAME LOC EMPNO ENAME DEPTNO
10 ACCOUNTING 1001 A 10
20 RESEARCH 1002 B 10
30 SALES 1003 C 20
40 OPERATIONS 1004 D 20
1005 E 30

DNAME
ACCOUNTING
RESEARCH
SALES

Display the depts which are not having emps:

If rows are not selected by sub query, NOT EXISTS returns TRUE
If rows are selected by sub query, NOT EXISTS returns FALSE

SELECT d.dname
FROM dept d
WHERE NOT EXISTS(SELECT * FROM emp
WHERE deptno=d.deptno);

DEPT d EMP
DEPTNO DNAME LOC EMPNO ENAME DEPTNO
10 ACCOUNTING 1001 A 10
20 RESEARCH 1002 B 10
30 SALES 1003 C 20
40 OPERATIONS 1004 D 20

ORACLE4PM Page 181


20 RESEARCH 1002 B 10
30 SALES 1003 C 20
40 OPERATIONS 1004 D 20
1005 E 30

Inline View / Inline Sub Query:

• A sub query which is written in FROM clause is called


"Inline View / Inline Sub Query".
• It acts like table.
• To control the execution order of clauses we write
Sub Query in FROM clause.

Examples on inline view:

Find 3rd max salary:

SELECT sal
DENSE_RANK() OVER(ORDER BY sal DESC) as rnk
FROM emp
WHERE rnk=3;

ERROR: "RNK" invalid identifier

Execution Order: Problem:


WHERE gets executed Before SELECT.
FROM
WHERE Solution:
GROUP BY WHERE has to be executed after SELECT.
HAVING So, Write SELECT in FROM clause.
SELECT
DISTINCT
ORDER BY

SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rnk
FROM emp)
WHERE rnk=3;

SELECT *

ORACLE4PM Page 182


WHERE rnk=3;

SELECT *
* All columns of sub query FROM emp
empno, ename, sal, rnk

Find 5th max salary:

SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk=5;

Find 10th max salary:

SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk=10;

Find n-th max salary:

SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk=&n;

Display top 3 salaried emp records:

SELECT *
FROM (SELECT empno,ename,sal,

ORACLE4PM Page 183


FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal top 3 sal
DESC) as rnk 1
FROM emp) 2
WHERE rnk<=3; 3

Display top 5 salaried emp records:

SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk<=5;

Display top n salaried emp records:

SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk<=&n;

ROWNUM:
• ROWNUM is a pseudo column.
• It is used to apply row numbers.
• Row Number will be applied on result of SELECT QUERY.

Display row numbers for all emp records:

SELECT rownum, empno,ename,sal


FROM emp;

Display row numbers for all managers records:

ORACLE4PM Page 184


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

Display 3rd row in emp table:

SELECT rownum as rn, empno, ename, sal


FROM emp
WHERE rn=3;

ERROR: "RN" invalid identifier


alias name cannot be used in WHERE

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn=3;

Display 1st, 9th and 12th rows:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn IN(1,9,12);

Display the rows from 5 to 10:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn BETWEEN 5 AND 10;

Display even numbered rows:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE MOD(rn,2)=0;

ORACLE4PM Page 185


WHERE MOD(rn,2)=0;

Mod(2,2) =0
0=0 T

Mod(3,2) = 0
1=0 F

Display odd numbered rows:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE MOD(rn,2)=1;

Scalar Sub Query:


• A sub query which is written in SELECT clause is called
"Scalar Sub Query".
• It acts like column.

Examples:

Display no of rows in emp table and dept table:

SELECT (SELECT count(*) FROM emp) as emp,


(SELECT count(*) FROM dept) as dept
FROM dual;

Output:

EMP DEPT
-------- --------
14 4

Calculate share of each dept in the salaries:

DEPTNO DEPT_AMOUNT TOTAL_AMOUNT PER


ORACLE4PM Page 186
DEPTNO DEPT_AMOUNT TOTAL_AMOUNT PER
10 ? ? ?
20 ? ? ?
30 ? ? ?

SELECT deptno, sum(sal) as dept_amount,


(SELECT sum(Sal) FROM emp) as total_amount,
TRUNC(sum(sal)*100/(SELECT sum(sal) FROM emp),2) as per
FROM emp
GROUP BY deptno
ORDER BY deptno;

Sub Query / Nested Query

A query which is written in another query.


when we don't know filter condition value to find it we write sub query.

Types:

Single Row sub query returns 1 row


Multi Row sub query returns multiple rows
Correlated Outer query passes value to inner query
Inline View a sub query which is written in FROM clause
Scalar a sub query which is written in SELECT clause

In WHERE clause, we can write max of 255 sub queries.

In FROM clause, we can write any no of sub queries. [unlimited]

In SELECT clause, we can write ay no of sub queries. [unlimited]

ROWID:
• ROWID is a pseudo column.
ROWID returns row address.

ORACLE4PM Page 187


• ROWID returns row address.

Display row ids of all emp table records:

SELECT rowid, empno, ename, sal


FROM emp;

Example:

STUDENT
sid sname m1
1 A 70
2 B 70
1 A 70

create table student


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

INSERT INTO student VALUES(1,'A',70);


INSERT INTO student VALUES(2,'B',70);
INSERT INTO student VALUES(1,'A',70);

delete duplicated record:

DELETE FROM student


WHERE rowid='<row_id>';

DELETE FROM student


WHERE rowid='AAATiuAAHAAAAJ0AAC';

T1 create table t1(f1 int, f2 varchar(10));


ORACLE4PM Page 188
T1 create table t1(f1 int, f2 varchar(10));
F1 F2
1 A insert into t1 values(1,'A');
insert into t1 values(2,'B');
2 B
insert into t1 values(3,'C');
3 C
1 A insert into t1 values(1,'A');
2 B insert into t1 values(2,'B');
3 C insert into t1 values(3,'C');
4 D
insert into t1 values(4,'D');

Display t1 table records. eliminate duplicate records:

SELECT DISTINCT * FROM t1;

Display duplicated records only:

SELECT f1, f2
FROM t1
GROUP BY f1,f2
HAVING count(*)>=2;

Deleting duplicated records: [correlated sub query]

T1
F1 F2 rowid
1 A AAA <> AAA F => will not be deleted
2 B AAB <> AAB F => will not be deleted
3 C AAC <> AAC F => will not be deleted
AAD <> AAA => T => row will be deleted
1 A AAD
AAE <> AAB => T => row will be deleted
2 B AAE
3 C AAF AAF <> AAC => T => row will be deleted
ORACLE4PM Page 189
AAD <> AAA => T => row will be deleted
1 A AAD
AAE <> AAB => T => row will be deleted
2 B AAE
3 C AAF AAF <> AAC => T => row will be deleted
4 D AAG AAG <> AAG F => will not be deleted
1 A AAH AAH <> AAA T => will be deleted

DELETE FROM t1 t
WHERE rowid <> (SELECT min(rowid)
FROM t1 WHERE f1=t.f1 and f2=t.f2);

ORACLE4PM Page 190


CONSTRAINTS
Tuesday, June 6, 2023 4:16 PM

Field Definition:

<field_name> <data_type> CONSTRAINT <con_name> <con_type>

Syntax of Creating Table:

CREATE TABLE <table_name>


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

CONSTRAINTS in SQL:
Max Marks: 100
• CONSTRAINT => Restrict / Limit / Control 0 TO 100

STUDENT
check(m1>=0 AND m1<=100)

SID SNAME M1
1 A 78
2 B 56
3 C 82
4 D 567 ERROR: check constraint violated

• CONSTRAINT is a rule that is applied on a column.


• CONSTRAINT restricts the user from entering invalid data.
• It is used to implement data integrity feature.
Data Integrity means, maintaining accurate & quality data.

ORACLE4PM Page 191


• Data Integrity means, maintaining accurate & quality data.

SQL provides following Constraints:

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

Primary Key:
• Primary Key does not accept duplicates.
• Primary Key does not accept nulls.

Example: RDBMS concept => 12 rules

EMP
PK
EMPNO ENAME JOB SAL
1001 RAVI CLERK 6000
1002 SAI CLERK 7000
1003 RAVI SALESMAN 6000
1004 SAI SALESMAN 7000 Null
KIRAN MANAGER 10000 ERROR: PK does not accept null
1001 SRAVAN CLERK 5000
Duplicate
Error: PK does not accept duplicate

• When value is mandatory & that value must be unique then


use PK.

• One table can have 1 Primary Key only.

Example:

CREATE TABLE t1
(
f1 NUMBER(4) PRIMARY KEY
ORACLE4PM Page 192
f1 NUMBER(4) PRIMARY KEY
);

INSERT INTO t1 VALUES(1001);


INSERT INTO t1 VALUES(1002);

INSERT INTO t1 VALUES(1001);


ERROR: unique constraint violated

INSERT INTO t1 VALUES(null);


ERROR: cannot null into T1.F1 column

NOT NULL:

• It does not accept nulls.


• It accepts duplicates.

• When value is mandatory & it can be duplicated


then use NOT NULL.

Example:

EMP
NOT NULL
EMPNO ENAME SAL
1001 RAJU 5000 NULL
1002 8000 ERROR: cannot insert null
1003 RAJU 7000
DUPLICATE
Accepts duplicate value

Example:

CREATE TABLE t2
(
f1 NUMBER(4) NOT NULL
);

INSERT INTO t2 VALUES(1001);


INSERT INTO t2 VALUES(1002);

INSERT INTO t2 VALUES(null);


ORACLE4PM Page 193
INSERT INTO t2 VALUES(null);
ERROR: cannot insert null into c##batch4pm.T2.F1 Column

INSERT INTO t2 VALUES(1001); --accepts this record

Unique:

• It does not accept duplicates.


• It accepts nulls.

Example:

CUSTOMER
UNIQUE
cid cname mail_id
1001 AA [email protected] NULL
1002 BB accepts null

1003 AA [email protected]
DUPLICATE
ERROR

When we want to maintain unique values


and value is optional then use UNIQUE.

Example:

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

INSERT INTO t3 VALUES(1001);


INSERT INTO t3 VALUES(1002);

ORACLE4PM Page 194


INSERT INTO t3 VALUES(1001);
ERROR: unique constraint violated

INSERT INTO t3 VALUES(null);


--accepts null

INSERT INTO t3 VALUES(null);


--accepts null

CONSTRAINT DUPLICATE NULL


Primary Key NO NO
Unique NO YES
Not Null YES NO

PRIMARY KEY = UNIQUE + NOT NULL

Check:

sal CHECK(sal>=10000)
---------
5000 => ERROR
4000 => ERROR
9000 => ERROR
15000
20000
25000
7000 => ERROR

gender CHECK(gender IN('M','F'))


---------------
M
F
F
M
ORACLE4PM Page 195
M
M
Z => ERROR

• CHECK constraint is used apply our own condition


on column.

Example:

CREATE TABLE t4
(
f1 NUMBER(3) CHECK(f1 BETWEEN 0 AND 100)
);

INSERT INTO t4 VALUES(78);


INSERT INTO t4 VALUES(66);

INSERT INTO t4 VALUES(123);


--ERROR: check constraint violated

INSERT INTO t4 VALUES(101);


--ERROR: check constraint violated

DEFAULT:

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

• When column value is same for all records then it's


better to set it as default.

Example:

EMP default 'TCS' default 'HYD'


EMPNO ENAME Company_Name Company_City

ORACLE4PM Page 196


1001 A TCS HYD
1002 B TCS HYD
1003 C TCS HYD

STUDENT default 20000


SID SNAME FEE
1001 A 20000
1002 B 20000
1003 C 20000
1004 D 20000
1005 E 10000

Lpad('RAJU',10) => 6spacesRAJU


default 3rd arg => space

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

CREATE TABLE t5
(
f1 NUMBER(4),
f2 NUMBER(5) DEFAULT 20000
);

INSERT INTO t5 VALUES(1001);


ERROR: not enough values

INSERT INTO t5(f1) VALUES(1001);


INSERT INTO t5(f1) VALUES(1002);
INSERT INTO t5(f1) VALUES(1003);

INSERT INTO t5 VALUES(1001,10000);

PRIMARY KEY no duplicates

ORACLE4PM Page 197


PRIMARY KEY no duplicates
no nulls
UNIQUE no duplicates
accepts null
NOT NULL accept duplicates
no nulls
CHECK to apply our own condition on column
DEFAULT to apply default value to column

REFERENCES DEPT(DEPTNO)
REFERENCES [FOREIGN KEY]:
Child Table / Detailed Table
Parent Table / Master table
EMP Foreign Key
DEPT
EMPNO ENAME DEPTNO
PK
1001 A 30
DEPTNO DNAME
1002 B 10
10 HR
1003 C 30
20 SALES
1004 D 10
30 ACCOUNTS
1005 E 90 ERROR
1006 F 20
1007 G null
accepts null

• FOREIGN KEY accepts PRIMARY KEY values of another table.

• FOREIGN KEY accepts duplicates


• FOREIGN KEY accepts nulls

• It is used to establish relationship between 2 tables.

• PK column and FK column data types must be same.

• PK Column name and FK column name need not be same.

Example:

ORACLE4PM Page 198


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

CREATE TABLE t7
(
f1 NUMBER(4) REFERENCES T6(F1)
);

INSERT INTO t6 VALUES(10);


INSERT INTO t6 VALUES(20);
INSERT INTO t6 VALUES(30);
COMMIT;

INSERT INTO t7 VALUES(30);


INSERT INTO t7 VALUES(10);
INSERT INTO t7 VALUES(30);
INSERT INTO t7 VALUES(NULL);
INSERT INTO t7 VALUES(90); --error

Examples on Constraints:

STUDENT1
SID SNAME M1

SID don't accept duplicates and nulls PK


SNAME don't accept nulls NOT NULL
M1 value must be b/w 0 to 100 CHECK

CREATE TABLE student1


(
sid NUMBER(4) PRIMARY KEY,
sname VARCHAR2(10) NOT NULL,
m1 NUMBER(3) CHECK(m1 BETWEEN 0 AND 100)
);

INSERT INTO student1 VALUES(1,'A',70);

ORACLE4PM Page 199


INSERT INTO student1 VALUES(1,'A',70);

INSERT INTO student1 VALUES(2,'B',789);


ERROR: check constraint violated

INSERT INTO student1 VALUES(1,'C',55);


ERROR: unique constraint violated

INSERT INTO student1 VALUES(null,'D',60);


ERROR: cannot insert null into student1.sid

INSERT INTO student1 VALUES(5,null,60);


ERROR: cannot insert null into student1.sname

Example-2:

USER_LIST
userid uname pwd

userid don't accept duplicates and nulls PK


uname don't accept duplicates and nulls UNIQUE NOT NULL
pwd min 8 chars check

CREATE TABLE user_list


(
userid NUMBER(4) PRIMARY KEY,
uname VARCHAR2(15) UNIQUE NOT NULL,
pwd VARCHAR2(20) CHECK(length(pwd)>=8)
);

Example-3:

EMPLOYEE
EMPNO ENAME GENDER SAL HIREDATE CNAME CCITY

EMPNO don't accept duplicates and nulls PK


ENAME don't accept nulls NOT NULL
ORACLE4PM Page 200
ENAME don't accept nulls NOT NULL
GENDER value must be M or F CHECK
SAL must be min 10000 CHECK
HIREDATE today's date DEFAULT
CNAME TCS DEFAULT
CCITY HYD DEFAULT

CREATE TABLE employee


(
empno NUMBER(4) PRIMARY KEY,
ename VARCHAR2(10) NOT NULL,
gender CHAR(1) CHECK(gender IN('M','F')),
sal NUMBER(8,2) CHECK(sal>=10000),
hiredate DATE DEFAULT SYSDATE,
cname VARCHAR2(3) DEFAULT 'TCS',
ccity VARCHAR2(3) DEFAULT 'HYD'
);

INSERT INTO employee(empno,ename,gender,sal)


VALUES(1001,'A','M',12000);

INSERT INTO employee(empno,ename,gender,sal)


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

Example:

CUSTOMER
cid cname mobilenum mailid

cid don't accept duplicates and nulls PRIMARY KEY


cname don't accept nulls NOT NULL
mobilenum don't accept duplicates and nulls UNIQUE NOT NULL
it must have 10 digits CHECK
mailid maintain unique mail id UNIQUE

ORACLE4PM Page 201


mailid maintain unique mail id UNIQUE
accept nulls

CREATE TABLE customer


(
cid NUMBER(4) PRIMARY KEY,
cname VARCHAR2(10) NOT NULL,
mobilenum NUMBER(10) UNIQUE NOT NULL CHECK(length(mobilenum)=10),
mail_id VARCHAR2(20) UNIQUE
);

Example:

DEPT1 EMP1 FK
PK EMPNO ENAME DEPTNO
DEPTNO DNAME 1001 A 30
10 ACCOUNTS 1002 B 10
20 SALES 1003 C 30
30 HR 1004 D 20
1005 E 70 =>ERROR

CREATE TABLE dept1


(
deptno NUMBER(2) PRIMARY KEY,
dname VARCHAR2(10)
);

CREATE TABLE emp1


(
empno NUMBER(4),
ename VARCHAR2(10),
deptno NUMBER(2) REFERENCES DEPT1(DEPTNO)
);

INSERT INTO dept1 VALUES(10,'ACCOUNTS');


INSERT INTO dept1 VALUES(20,'SALES');
INSERT INTO dept1 VALUES(30,'HR');
COMMIT;

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


ORACLE4PM Page 202
INSERT INTO emp1 VALUES(1,'A',30);
INSERT INTO emp1 VALUES(2,'B',30);
INSERT INTO emp1 VALUES(3,'C',10);
INSERT INTO emp1 VALUES(4,'D',20);
INSERT INTO emp1 VALUES(5,'E',80); --ERROR
INSERT INTO emp1 VALUES(5,'E',null);

Syntax of CREATE command:

CREATE TABLE <table_name>


(
<fn> <dt> [CONSTRAINT <con_name> <con_type>,
<fn> <dt> CONSTRAINT <con_name> <con_type>,
<fn> <dt> CONSTRAINT <con_name> <con_type>,
.
.]
);

Naming Constraints:

• Giving names to constraints is called "Naming Constraints".

• We can give names to the constraints. If we don't give constraint name,


implicitly ORACLE gives constraint name.

• When we want to drop the constraints or enable the constraints or disable the
constraints these names are useful.

• We cannot give name for DEFAULT constraint.

Example on Naming Constraints:

ORACLE4PM Page 203


STUDENT2
SID SNAME M1

column name rule con type con name


SID Don't accept duplicates and nulls PRIMARY KEY c1
SNAME Don't accept nulls NOT NULL c2
M1 must be b/w 0 and 100 CHECK c3

CREATE TABLE student2


(
sid NUMBER(4) CONSTRAINT c1 PRIMARY KEY,
sname VARCHAR2(10) CONSTRAINT c2 NOT NULL,
m1 NUMBER(3) CONSTRAINT c3 CHECK(m1 BETWEEN 0 AND 100)
);

NOTE:
Constraint name must be unique with in the SCHEMA [user]

user_tables:
it maintains all tables information

user_constraints:
• it is a built-in table
• it maintains all constraints information.

to see constraints information write following query:

DESC user_constraints;

column table_name format a8

SELECT table_name,constraint_name, constraint_type


FROM user_Constraints
WHERE TABLE_NAME='STUDENT2';

ORACLE4PM Page 204


Constraints:

Constraint => is a rule that is applied on column


restricts the user from entering invalid data
can maintain quality & accurate data

PRIMARY KEY => no nulls, no duplicates


NOT NULL => no nulls
UNIQUE => no duplicates
CHECK => to apply our own condition
DEFAULT => to apply default value
REFERENCES [ FOREIGN KEY] => accepts PK values of another table

CREATE TABLE student


Column Level Constraint
(
sid NUMBER(4) PRIMARY KEY,
sname VARCHAR2(10)
);

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10), Table Level Constraint
PRIMARY KEY(sid)
);

We can apply constraint at 2 levels. They are:


• Column Level Constraint
• Table Level Constraint

Column Level Constraint:


• If constraint is defined in column definition then it is
called "Column Level Constraint".

• All 6 constraints can be applied at column level.

ORACLE4PM Page 205


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

• Only 4 constraints can be applied at table level. They


are: PK, Unique, Check and FK.

• NOT NULL and DEFAULT constraints cannot be


applied at table level.

Example on Table Level Constraint:

STUDENT
sid sname mail_id m1

sid don't accept duplicates and nulls PK


sname don't accept nulls NOT NULL
mail_id maintain unique mail ids UNIQUE
allow nulls
m1 must be b/w 0 and 100 CHECK

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10) NOT NULL,
mail_id VARCHAR2(20),
m1 NUMBER(3),
PRIMARY KEY(sid),
UNIQUE(mail_id),
CHECK(m1 BETWEEN 0 AND 100)
);

Applying foreign key at table level:


REFERENCES course(cid)

COURSE STUDENT FK
ORACLE4PM Page 206
REFERENCES course(cid)

COURSE STUDENT FK
PK sid sname cid
cid cname 1001 A 30
10 JAVA 1002 B 10
20 PYTHON 1003 C 10
30 C# 1004 D 30
1005 E 20
1006 F 80 => ERROR

COURSE
PK
cid cname

CREATE TABLE course


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

STUDENT FK
sid sname cid

CREATE TABLE student


(
sid NUMBER(4),
sname VARCHAR2(10),
cid NUMBER(2),
FOREIGN KEY(cid) REFERENCES COURSE(CID)
);

We can use Table Level Constraint for 2 reasons:


• to use another column name in constraint
• to apply combination of columns as constraint

ORACLE4PM Page 207


Example:

CM_LIST
CMID CM_NAME STATE_CODE START_DATE END_DATE
1001 KCR TS 18-MAY-2018 27-DEC-2015 => ERROR

CREATE TABLE cm_list


(
cmid NUMBER(4),
cm_name VARCHAR2(20),
state_code CHAR(2),
start_date DATE,
end_date DATE CHECK(end_date>start_date)
);
ERROR: we cannot use another column name in constraint

ERROR: Column check constraint cannot reference other columns

CREATE TABLE cm_list


(
cmid NUMBER(4),
cm_name VARCHAR2(20),
state_code CHAR(2),
start_date DATE,
end_date DATE,
CHECK(end_date>start_date)
);

NOTE:
If we want to use another column name in constraint
we must apply it at table level only. It cannot be applied
at column level.

Example:

STUDENT

PK(SID,SUBJECT) => Composite Key


ORACLE4PM Page 208
PK(SID,SUBJECT) => Composite Key

SID SNAME SUBJECT MARKS


1001 A M1 70
1001 A M2 60
1001 A M3 80
1002 B M1 68
1002 B M2 55
1002 B M3 60
1003 C M1 90
ERROR => duplicate record
1003 C M1 60
1003 M1
1003 C M2 80
1001 D M1 55 ERROR => duplicate recprd
E M1 56 1001 M1
2001 G 80
ERROR:
PK does not accept
null

ERROR:
PK does not accept null

• Sometimes we cannot identify the rows uniquely using 1


column.
• In such type of situations we need to set combination of
columns as PRIMARY KEY.

• If set combination of columns as PRIMARY KEY then it is called


"Composite Key".

• Max combination of 32 columns can be set as PK

Example on Composite Key:

CREATE TABLE student


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

ORACLE4PM Page 209


sname VARCHAR2(10),
subject CHAR(2),
marks NUMBER(3),
PRIMARY KEY(sid,subject)
);

ALTERING TABLE:

add the columns


drop the columns
rename the columns
modify the data types
modify the field sizes

add the constraint => ADD CONSTRAINT


rename the constraint => RENAME CONSTRAINT
disable the constraint => DISABLE CONSTRAINT
enable the constraint => ENABLE CONSTRAINT
drop the constraint => DROP CONSTRAINT

Adding Constraints:

• "ADD CONSTRAINT" is used to add the constraints.

• Using ADD CONSTRAINT we can add 4 constraints only. Those are: PK,
UNIQUE, CHECK, FK

• To add NOT NULL & DEFAULT constraints use "MODIFY"

Example:

STUDENT
sid sname mail_id fee m1

CREATE TABLE student


(

ORACLE4PM Page 210


(
sid NUMBER(4), ADD PK => sid
sname VARCHAR2(10), ADD NOT NULL => sname
mail_id VARCHAR2(20), ADD UNIQUE => mail_id
fee NUMBER(7,2), ADD default value 20000 => FEE
m1 NUMBER(3) ADD check [0 to 100] => m1
);

ADD PK => sid:

ALTER TABLE student ADD CONSTRAINT con1 PRIMARY KEY(sid);

ADD NOT NULL => sname:

ALTER TABLE student MODIFY sname NOT NULL;

ADD UNIQUE => mail_id:

ALTER TABLE student ADD CONSTRAINT con2 UNIQUE(mail_id);

ADD default value 20000 => FEE:

ALTER TABLE student MODIFY fee DEFAULT 20000;

ADD check [0 to 100] => m1:

ALTER TABLE student


ADD CONSTRAINT con3 CHECK(m1 BETWEEN 0 AND 100);

Example:

DEPT EMP
DEPTNO DNAME EMPNO ENAME DEPTNO

ORACLE4PM Page 211


create above 2 tables without constraints

add PK to deptno column in DEPT table


add FK to deptno column in EMP table

add PK to deptno column in DEPT table:

ALTER TABLE dept


ADD CONSTRAINT x PRIMARY KEY(deptno);

add FK to deptno column in EMP table:

ALTER TABLE emp


ADD CONSTRAINT y FOREIGN KEY(deptno) REFERENCES DEPT(deptno);

Renaming Constraint:
In student
sid => constraint name is con1 => rename it as "z"

ALTER TABLE student


RENAME CONSTRAINT con1 TO z;

Disabling Primary Key:

ALTER TABLE student DISABLE CONSTRAINT z;

--Temporarily PK will not work here

Enabling Primary Key:

ALTER TABLE student ENABLE CONSTRAINT z;

--again PK will work


--to enable PK, that column should not have duplicates and nulls

ORACLE4PM Page 212


Dropping Primary Key:

ALTER TABLE student DROP CONSTRAINT z;

--Permanently PK will be dropped

T1 => parent / master table T2 => child / detailed table

PK FK
F1 F1
10 10
20 10
20
20

By default, if we delete parent table record, it cannot be


deleted if it has related records in child table.

In above, if we delete 10 record in parent table, it cannot


be deleted. Because, it has related records in child table.

parent table:

CREATE TABLE t1(f1 NUMBER(2) PRIMARY KEY);

child table:

CREATE TABLE t2(f1 NUMBER(2) REFERENCES t1(f1));

INSERT INTO t1 VALUES(10);


INSERT INTO t1 VALUES(20);

ORACLE4PM Page 213


INSERT INTO t2 VALUES(10);
INSERT INTO t2 VALUES(10);

INSERT INTO t2 VALUES(20);


INSERT INTO t2 VALUES(20);
COMMIT;

deleting parent table record:

DELETE FROM t1 WHERE f1=10;


ERROR: this record has related records in child table

ON DELETE clause:

Syntax:

ON DELETE <cascade/set null>

ON DELETE clause is used to specify if parent record is


deleted what should be happened in child table.

ON DELETE cascade:

if parent table record is deleted, all related records


in child table will be deleted

T1 => parent / master table T2 => child / detailed table

PK FK => ON DELETE CASCADE


F1 F1
10 10
20 10
20
20
ORACLE4PM Page 214
20

Example on "ON DELETE CASCADE":

parent table:

CREATE TABLE t1(f1 NUMBER(2) PRIMARY KEY);

child table:

CREATE TABLE t2
(
f1 NUMBER(2) REFERENCES t1(f1) ON DELETE CASCADE
);

INSERT INTO t1 VALUES(10);


INSERT INTO t1 VALUES(20);

INSERT INTO t2 VALUES(10);


INSERT INTO t2 VALUES(10);

INSERT INTO t2 VALUES(20);


INSERT INTO t2 VALUES(20);
COMMIT;

Deleting parent table record:

DELETE FROM t1 WHERE f1=10;


--it deletes parent record. also deletes related records in child
table

ON DELETE SET NULL:

ORACLE4PM Page 215


ON DELETE SET NULL:

If parent table record is deleted, all related records


in child table will be set as NULL.

T1 => parent / master table T2 => child / detailed table

PK FK => ON DELETE SET NULL


F1 F1
10 10 NULL
20 10 NULL
20
20

Example on "ON DELETE SET NULL":

parent table:

CREATE TABLE t1(f1 NUMBER(2) PRIMARY KEY);

child table:

CREATE TABLE t2
(
f1 NUMBER(2) REFERENCES t1(f1) ON DELETE SET NULL
);

INSERT INTO t1 VALUES(10);


INSERT INTO t1 VALUES(20);

INSERT INTO t2 VALUES(10);


INSERT INTO t2 VALUES(10);

INSERT INTO t2 VALUES(20);


INSERT INTO t2 VALUES(20);
COMMIT;

Deleting parent table record:

ORACLE4PM Page 216


DELETE FROM t1 WHERE f1=10;
--it deletes parent record and sets related records in child table as NULL

ON DELETE CASCADE

CUSTOMER TRANSACTIONS
cid[PK] cname ac_type ac_opened CID[FK] TID T_TYPE AMOUNT DOT
_date 1001 .. W 10000 ..
1001 A S -- 1001 .. D 30000 ..
1001 .. D 50000 ..
1001 .. W 20000 .

1001 customer closed his account


Delete 1001 customer record
if 1001 record is deleted from customer table, delete all
his transactions from transactions table

ON DELETE SET NULL

PROJECT EMP
FK
PK
PROJID PNAME DURATION EMPNO ENAME PROJID
10 X 8 1001 A 20 NULL
20 Y 12 1002 B 20 NULL
30 Z 10 1003 C 30
1004 D 30
1006 E 10
1007 F 10

ORACLE4PM Page 217


DCL
Friday, June 9, 2023 4:52 PM

SQL:

DDL DML TCL DCL DRL


CREATE INSERT COMMIT GRANT SELECT
ALTER UPDATE ROLLBACK REVOKE
DELETE SAVEPOIN
DROP T
FLASHBACK INSERT ALL
PURGE MERGE

TRUNCATE
RENAME

DCL:
• Data Control Language
• It deals with data accessibility.
• It is used to implement table level security

Security:

Database Level Security => SCHEMA [USER]


Table Level Security => GRANT, REVOKE
Data Level Security => VIEW

DCL sub language provides 2 commands. They are:


• GRANT
• REVOKE

ORACLE4PM Page 218


GRANT:
used to give permission to other users on database
objects like tables, views.

Syntax:
privilege = permission
GRANT <privileges_list>
ON <db_object_name>
TO <user_list>;

Ex:
GRANT select
ON emp
TO c##batch11am;

GRANT insert, update, delete


ON emp
TO c##batch11am;

GRANT all
ON emp
TO c##batch6pm;

to give permission to c##batch9am, c##batch2pm:

GRANT select
ON emp
TO c##batch9am, c##batch2pm;

to give permission to all users:

GRANT select
ON emp
TO public;

REVOKE:
ORACLE4PM Page 219
REVOKE:
• used to can cancel the permissions on
DB Objects from users.

Syntax:

REVOKE <priviliges_list>
ON <db_obj_name>
FROM <user_list>;

Examples:

REVOKE insert, update, delete


ON emp
FROM c##batch11am;

REVOKE all
ON emp
FROM c##batch11am;

Example on GRANT & REVOKE:

Create 2 users with the names c##userA and c##userB:

creating userA:
[Log in as DBA]
CREATE USER c##userA
IDENTIFIED BY usera
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO c##userA;

creating userB:

ORACLE4PM Page 220


creating userB:

CREATE USER c##userB


IDENTIFIED BY userb
DEFAULT TABLESPACE users
QUOTA unlimited ON users;

GRANT connect, resource TO c##userB;

NOTE: open 2 windows.


press windows+right arrow to arrange the windows

c##userA [GRANTOR] c##userB [GRANTEE

T1
F1 F2
1 A
2 B

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 does not exist

GRANT select
ON t1
ORACLE4PM Page 221
GRANT select
ON t1
TO c##userB;

SELECT * FROM c##userA.T1;


Output:
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, delete, update


ON t1
TO c##userB;

INSERT INTO c##userA.t1


VALUES(3,'C');
Output: 1 row created

UPDATE c##userA.t1
SET f2='SAI' WHERE f1=1;
Output: 1 row updated

ORACLE4PM Page 222


SELECT * FROM c##userA.t1;
SELECT * FROM t1; F1 F2
1 SAI
T1 2 B
F1 F2 3 C
1 A
2 B
COMMIT;

After COMMIT changes reflected

SELECT * FROM t1;


DELETE FROM c##userA.t1
WHERE f1=1;
F1 F2 Output: 1 row deleted
1 SAI
2 B
3 C

COMMIT;

SELECT * FROM t1;

F1 F2
2 B
3 C

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

WITH GRANT OPTION clause


GRANT all
allows GRANTEE to give permission
ON c##userA.t1
to other users
TO c##batch4pm;

ORACLE4PM Page 223


REVOKE insert,update,delete
ON t1
FROM c##userB;

insert => ERROR


update => ERROR
delete => ERROR

select * from c##userA.t1;


--displays data

REVOKE all
ON t1
FROM c##userB;
select * from c##userA.t1;
ERROR:

A user who is giving permissions => GRANTOR


A user who is receiving permissions => GRANTEE

c##userA => GRANTOR

c##userB => GRANTEE

USER_TAB_PRIVS_MADE:
• is a system table
• It maintains list of privileges made by the GRANTOR.

ORACLE4PM Page 224


USER_TAB_PRIVS_RECD:
• is a system table
• It maintains list of privileges received by the GRANTEE.

Log in as c##userA:

GRANT all ON t1 TO c##userB;

DESC user_tab_privs_made;

SELECT table_name, privilege


FROM user_tab_privs_made;

Log in as c##userB:

DESC user_tab_privs_recd;

SELECT table_name, privilege, grantor


FROM user_tab_privs_recd;

ORACLE4PM Page 225


Copying table & copying records
Saturday, June 10, 2023 4:40 PM

Copying Table & Copying Records:

Copying Table:
• Copying table means, creating table from existing table

Syntax:

CREATE TABLE <table_name>


AS
<SELECT query>;

• With SELECT query result a new table will be created

Examples:

create a new table with the name employee1 from existing table
emp with all rows and all columns:
[create exact copy of emp]

CREATE TABLE employee1


AS
SELECT * FROM emp;

Create a new table with the name employee2


from existing table emp with 4 columns empno, ename,job, sal
and with all managers records:

CREATE TABLE employee2


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

Copying table structure:

Create a new table with the name employee3


with emp table structure without records:

CREATE TABLE employee3


AS
SELECT *
FROM emp
WHERE 1=2;

To copy table structure write select query with


any false condition.

Exs of False conditions:

1=2
'A'='B'
100=500

Create a new table with the name employee4


from the existing table emp with 4 columns empno,ename,job,sal
without records:

CREATE TABLE employee4


ORACLE4PM Page 227
CREATE TABLE employee4
AS
SELECT empno,ename,job,sal
FROM emp
WHERE 1=2;

Copying Records from existing table:

Syntax:
INSERT INTO <table_name>
<SELECT query>;

SELECT query result will be copied into table

Example:

EMP EMPLOYEE4
EMPNO ENAME JOB SAL .. EMPNO ENAME JOB SAL
1001 A MANAGER .. ..
copy manager records
1002 B CLERK .. ..
1003 C SALESMAN .. ..
1004 D MANAGER .. ..

Copy all managers records from emp table to employee4:

INSERT INTO employee4


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

ORACLE4PM Page 228


INSERT ALL
Saturday, June 10, 2023 5:09 PM

INSERT ALL:
• Introduced in ORACLE 9i version.
• used to copy one table data to multiple tables.
• It avoids of writing multiple INSERT commands.

EMP1
EMP
EMPNO ENAME SAL
EMPNO ENAME SAL copy 10 rows
1001 A ..
1002 B .. EMP2
.. .. ..
copy 10 rowsEMPNO ENAME SAL
.. .. ..
1010 .. ..
EMP3
EMPNO ENAME SAL
copy 10 rows

INSERT ALL

INSERT ALL can be used in 2 ways. They are:

• Unconditional INSERT ALL


• Conditional INSERT ALL

Unconditional INSERT ALL:

Syntax:

INSERT ALL
INTO <table_name>[(column_list>)] VALUES(<value_list>)
ORACLE4PM Page 229
INSERT ALL
INTO <table_name>[(column_list>)] VALUES(<value_list>)
INTO <table_name>[(column_list>)] VALUES(<value_list>)
INTO <table_name>[(column_list>)] VALUES(<value_list>)
.
.
<SELECT QUERY>;

Example on Unconditional INSERT ALL:

Copy Emp Table data into emp1, emp2 and emp3:

EMP EMP1
EMPNO ENAME SAL EMPNO ENAME SAL
1001 A .. copy emp table all records
1002 B ..
EMP2
.. .. ..
EMPNO ENAME SAL
.. .. ..
copy emp table all records
1010 .. ..

EMP3
EMPNO ENAME SAL
copy emp table all records

Create emp1, emp2, emp3 tables


with 3 columns empno,ename,sal
from existing table emp without records:

CREATE TABLE emp1


AS
SELECT empno,ename,sal
ORACLE4PM Page 230
SELECT empno,ename,sal
FROM emp
WHERE 1=2;

CREATE TABLE emp2


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

CREATE TABLE emp3


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

copy emp table data to emp1, emp2, emp3:

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

Output:
42 rows created

Note:
SELECT query result will be copied into emp1, emp2 and emp3

ORACLE4PM Page 231


Conditional INSERT ALL:

Syntax:

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

WHEN .. THEN acts as IF control Structure

INSERT FIRST
WHEN <condition-1> THEN
INTO <table_name>[(column_list>)] VALUES(<value_list>)
WHEN <condition-2> THEN
INTO <table_name>[(column_list>)] VALUES(<value_list>)
.
.
[ELSE]
INTO <table_name>[(column_list>)] VALUES(<value_list>)
<SELECT QUERY>;

WHEN .. THEN acts as IF ELSE IF control Structure

Example on Conditional INSERT ALL:

ORACLE4PM Page 232


EMP emp_mgr
EMPNO ENAME JOB sal copy EMPNO ENAME JOB sal
1001 A MANAGER
1002 B MANAGER
emp_clerk
1003 C CLERK
copy EMPNO ENAME JOB sal
1004 D CLERK
1005 E SALESMAN
1006 F ANALYST
copy
emp_others
EMPNO ENAME JOB sal

Create table emp_mgr, emp_clerk, emp_others:

CREATE TABLE emp_mgr


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;

ORACLE4PM Page 233


Copy all managers records into emp_mgr,
copy all clerks records into emp_clerk,
other than clerk, manager records copy into emp_others:

INSERT FIRST
WHEN job='MANAGER' THEN
INTO emp_mgr 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 * FROM emp;

Output:
14 rows created.

Assignment:

dept10
EMP
EMPNO ENAME DEPTNo
EMPNO ENAME DEPTNo copy 10th dept records
1001 A 10
1002 B 10 dept20
1003 C 20 copy 20
EMPNO ENAME DEPTNo
1004 D 20
1005 E 30
dept_others
1006 F 40 copy
EMPNO ENAME DEPTNo
other
than
ORACLE4PM Page 234
dept_others
1006 F 40 copy
EMPNO ENAME DEPTNo
other
than
10,20

Assignment-2
to_char(hiredate, 'YYYY')
EMP1980
EMP
copy 1980 emp records

1980
EMP1981
1981
copy 1981 emp records
1982
1983
EMP_OTHERS
copy other than 1980, 1981

ORACLE4PM Page 235


MERGE command
Monday, June 12, 2023 4:19 PM

MERGE:
• Introduced in Oracle 9i version.
• It is used to apply one table changes to its replica [duplicate copy].
• It avoids of writing a separate PL/SQL program.
• MERGE = UPDATE + INSERT
• MERGE is a combination of UPDATE and INSERT commands.
• It can be also called as "UPSERT" command.

Syntax:

MERGE INTO <target_table_name> <alias>


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

Branch Office HEAD OFFICE


S.cid = T.cid
CUSTOMER1 S
CUSTOMER2 T
cid cname ccity
matched [REPLICA => Duplicate copy]
1 A BANGALORE
cid cname ccity
2 B MUMBAI UPDATE 1 A HYD BANGALORER
ORACLE4PM Page 236
cid cname ccity
matched [REPLICA => Duplicate copy]
1 A BANGALORE
cid cname ccity
2 B MUMBAI UPDATE 1 A HYD BANGALORER
3 C PUNE
2 B MUMBAI
4 D CHENNAI
not matched 3 C PUNE
5 E KOLKATA
s.cid s.cname s.ccity
INSERT

CREATE TABLE customer1


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

1 A HYD
2 B MUMBAI
3 C PUNE

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


INSERT INTO customer1 VALUES(2,'B','MUMBAI');
INSERT INTO customer1 VALUES(3,'C','PUNE');

create exact copy of customer1:

CREATE TABLE customer2


AS
SELECT * FROM customer1;

4 D CHENNAI
5 E KOLKATA

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


ORACLE4PM Page 237
INSERT INTO customer1 VALUES(4,'D','CHENNAI');
INSERT INTO customer1 VALUES(5,'E','KOLKATA');

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


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

Output:
5 rows merged

ORACLE4PM Page 238


SET OPERATORS
Monday, June 12, 2023 5:03 PM

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

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

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

A I B = {4,5} = B I A

A M B = {1,2,3} => specific elements of A


B M A = {6,7,8} => specific elements of B

SET OPERATORS:

• SET OPERATOR is used to combine result of 2


SELECT queries.

Syntax:

SELECT query
<SET OPERATOR>
SELECT query;

SQL provides 4 SET OPERATORS. They are:


• UNION
• UNION ALL
• INTERSECT
MINUS

ORACLE4PM Page 239


• MINUS

UNION:
• UNION gives result of 2 select queries without
duplicate records.

UNION ALL:
• UNION gives result of 2 select queries including
duplicate records.

INTERSECT:
• INTERSECT gives common records from the result of
2 select queries.

MINUS:
• It gives specific records of 1st SELECT query.

Example:

HomeLoan GoldLoan
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5002 F

Display all customers who have taken homeloan &


goldloan:

SELECT cid,cname FROM HomeLoan


UNION
SELECT cid,cname FROM GoldLoan;

cid cname
1001 A
1002 B

ORACLE4PM Page 240


1003 C
5001 D
5002 F

Display all customers who have taken homeloan &


goldloan including duplicates:

SELECT cid,cname FROM HomeLoan


UNION ALL
SELECT cid,cname FROM GoldLoan;

cid cname
1001 A
1002 B
1003 C
5001 D
1002 B
5002 F

Differences b/w UNION & UNION ALL:

ORACLE4PM Page 241


UNION UNION ALL

• it does not give duplicates • It gives duplicates

• Slower • Faster

• Arranges result in order • Does not arrange result in order.

Display common customers of HomeLoan & Gold Loan:

SELECT cid,cname FROM homeloan


INTERSECT
SELECT cid,cname FROM goldloan;

cid cname
1002 B

Display the customers who have taken home loan only:

SELECT cid,cname FROM homeloan


MINUS
SELECT cid,cname FROM goldloan;

cid cname
1001 A
1003 C

Display the customers who have taken gold loan only:

SELECT cid,cname FROM goldloan


MINUS
ORACLE4PM Page 242
MINUS
SELECT cid,cname FROM homeloan;

cid cname
5001 D
5002 F

10 20
-------- --------
CLERK CLERK
MANAGER MANAGER
PRESIDENT ANALYST

Display common job titles of deptno 10 and deptno 20:

SELECT job FROM emp WHERE deptno=10


INTERSECT
SELECT job FROM emp WHERE deptno=20;

Display all job titles of deptno 10 and deptno 20:

SELECT job FROM emp WHERE deptno=10


UNION
SELECT job FROM emp WHERE deptno=20;

Display the job titles which are offered by deptno 10.


But not offered by deptno 20:

ORACLE4PM Page 243


SELECT job FROM emp WHERE deptno=10
MINUS
SELECT job FROM emp WHERE deptno=20;

Display the job titles which are offered by deptno 20.


But not offered by deptno 10:

SELECT job FROM emp WHERE deptno=20


MINUS
SELECT job FROM emp WHERE deptno=10;

DEPT
EMP_IND
DEPTNO DNAME
EMPNO ENAME Sal DEPTNO
10 HR
1001 A 8000 20
20 SALES
1002 B 10000 10
30 ACCOUNTS
..
..

EMP_US
EMPNO ENAME Sal DEPTNO
5001 XYZ 5000 20
5002 ABC 4000 10

Assignment:
Display the employees details along with dept details who
are working for INDIA & US:

ENAME SAL DNAME


JOIN QUERY => ind emp records with dept details
A SALES UNION
B HR JOIN QUERY => us emp records with dept details
XYZ SALES
ABC HR
ORACLE4PM Page 244
ABC HR

Rules:

• Number of Columns in both SELECT queries must be same.

Example:
SELECT cid FROM HomeLoan
UNION
SELECT cid,cname FROM GoldLoan;

ERROR

• data Types of corresponding columns in both SELECT queries


should be same.

Example:
SELECT cid,cname FROM homeLoan
UNION
SELECT cname,cid FROM GoldLoan;

ERROR

SQL => PL/SQL

Tables

VIEWS
INDEXES
SEQUENCES
SYNONYMS
MATERIALIZED VIEWS

ORACLE4PM Page 245


Wednesday, June 14, 2023 4:17 PM

SQL => Tables DB Object

ORACLE
SQL DATABASE
PL/SQL TABLES
ROWS & COLUMNS

SQL:
• Non-Procedural Language.
• We will not any set of statements [programs]
• We write Queries
• Query => is a request that is sent to DB SERVER

command, purpose
5 Sub Languages:
syntax, example

DDL DRL TCL DML DCL


CREATE SELECT COMMIT INSERT GRANT
ALTER ROLLBACK UPDATE REVOKE
SAVEPOINT DELETE
DROP
FLASHBACK INSERT ALL
PURGE MERGE

TRUNCATE
RENAME

Built-In Functions:
ORACLE4PM Page 246
Built-In Functions:

String Functions lower() upper() Substr() Instr()


Lpad() Rpad()
Ltrim() Rtrim() Trim()

Conversion to_char() to_date() to_number()


date to string
number to string
Aggregate [Group] max() min() sum() avg() count()

Number trunc() round() ceil() floor() mod()

Date sysdate systimestamp


add_months()

Analytical Rank() Dense_Rank() [no gaps]

Other NVL() NVL2()

Clauses:

Execution Order:
GROUP BY deptno
FROM
WHERE 10
GROUP BY 10 10 group
HAVING 10
SELECT
DISTINCT
ORDER BY
ORACLE4PM Page 247
ORDER BY
FETCH

Joins:

Goal: to retrieve data from multiple tables

Inner Join / Equi Join => join operation performed based on =


matched records only

Outer Join => matched + unmatched


Left Outer => matched + unmatched from left
Right Outer => matched + unmatched from right
Full Outer => matched + unmatched from left & right

Non-Equi Join / Inner Join

Self Join

Cross Join

Sub Queries:
A query written in another

Types:

Single Row Sub Query => sub query returns 1 row


Multi Row Sub query => sub query returns >1 row
Correlated Sub query => if outer query passes value to inner
Inline view => we write sub query in FROM clause
ORACLE4PM Page 248
Inline view => we write sub query in FROM clause
Scalar Sub Query => we write sub query in SELECT clause

Constraints:

PK
Not Null
Unique
Check
Default
References [Foreign Key]

SET operators:

to combine result of 2 select queries

UNION
UNION ALL
INTERSECT
MINUS

ORACLE4PM Page 249

You might also like