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

comple sql tables1

The document provides an overview of Oracle 21C, a Relational Database Management System (RDBMS), including installation links and a detailed syllabus covering SQL, PL/SQL, and various database concepts. It outlines the structure of databases, the functionality of SQL commands, and the evolution of Oracle software. Additionally, it describes the different data types, commands, and features associated with Oracle databases, emphasizing their application in managing business data.

Uploaded by

bsrassignment
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)
22 views

comple sql tables1

The document provides an overview of Oracle 21C, a Relational Database Management System (RDBMS), including installation links and a detailed syllabus covering SQL, PL/SQL, and various database concepts. It outlines the structure of databases, the functionality of SQL commands, and the evolution of Oracle software. Additionally, it describes the different data types, commands, and features associated with Oracle databases, emphasizing their application in managing business data.

Uploaded by

bsrassignment
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/ 239

Friday, May 10, 2024 12:01 PM

ORACLE 21C Software Link:


Akhil (Admin)
bit.ly/oracle21csoftware
Mobile: 9154156192 (Only Whatsapp)
Oracle Installation Video Link: bit.ly/oracle21cinstallation

Oracle @ 2:00 PM (IST) by Mr.Shiva Chaitanya


Day-1 https://youtu.be/qyS22JmRj4Q
Day-2 https://youtu.be/ON7pBny1S74
Day-3 https://youtu.be/XnqSKwezsy4
Day-4 https://youtu.be/_iD4wizlN3o
Day-5 https://youtu.be/iOt0KlGJfEk
Day-6 https://youtu.be/wbp4Dg2pdAI
ORACLE 2PM KPHB MAY 2024 Page 1

Syllabus
Friday, May 10, 2024 2:14 PM

ORACLE

SQL

TABLES

SQL commands DDL, DRL, DML, TCL, DCL


Built-In Functions
String, Conversion,
Aggregate, Analytic, date,
number

Clauses GROUP BY, HAVING, ORDER BY

Joins Inner Join, outer Join, Self Join, Cross Join

Sub Queries Non-correlated, Correlated

Constraints Primary Key, Foreign Key, Check

Set Operators Union, Union all, Intersect, Minus


Other DB Objects

VIEWS
INDEXES
SEQUENCES
SYNONYMS
MATERIALIZED VIEWS

PL/SQL
ORACLE 2PM KPHB MAY 2024 Page 2

PL/SQL Basics data types


declare, assign, print, read

Control Structures Conditional, Looping, Jumping

Cursors

Exception Handling

Collections

Stored procedures

Stored functions

Packages

Triggers

Working with LOBs

Dynamic SQL
ORACLE 2PM KPHB MAY 2024 Page 3
ORACLE
Thursday, May 9, 2024 2:12 PM

data store => is a location where data is stored database => is a location where
organization's business data stored permanently
DBMS => is a software => to create & maintain the database
RDBMS => is a software => to create & maintain DB in the form of tables metadata

BANK COLLEGE

Branches Courses
Customers Students
Transactions Fee
Products Marks
Employee

Goal:
Storing business data in computer permanently

In how many we can store the data in computer?

• variable => temporary


• object => temporary
• file => permanent
• database => permanent

In Java: age => variable

int age; 18
age=18;
Emplyee e1 = new Employee(1234,"Raju");

ORACLE 2PM KPHB MAY 2024 Page 4


e1 => object
empno ename

1234 Raju

File:
• we can store data permanently

Database:
• we can store data permanently

File Database

• is developed for 1 user • is developed for multiple users

• we can store small amounts • we can store large amounts


of data of data

• No security • provides security

Data Store:
• Data Store is a location where data is stored.
• Examples: File, Database

Database:
• Database is a kind of data store.
• It is a location where organization's business data stored permanently.
• Database is a collection of interrelated data in an organized form.
AMAZON DB Searching
for products products
Adding products to wish list wishlist
Placing order orders
payment payments

ORACLE 2PM KPHB MAY 2024 Page 5


BANK DB COLLEGE DB
Branches Courses
Customers Students
Transactions Fee

Products Marks
Employee

interrelated:
COLLEGE DB does not contain BANK related data BANK DB
does not contain college related data

organized:
arranged in specific way

DBMS:
• DBMS => database management system /software
• is a software
• used to create and maintain the database

Before 1960s => BOOKS

In 1960s => FMS [File Management Software]

In 1970s => HDBMS [Hierarchical DBMS]


NDBMS [Network DBMS]

In 1976 => RDBMS concept [Relational DBMS]


E.F.Codd
ORACLE company founder => Larry Ellison

In 1977 => established company with the name


SOFTWARE DEVELOPMENT LABORATORIES

ORACLE 2PM KPHB MAY 2024 Page 6


In 1979 => renamed company name as RELATIONAL SOFTWARE INC.

introduced first RDBMS software => ORACLE in 1983 => company name

renamed as ORACLE corp.

RDBMS:
• RDBMS => Relational Database Management System / Software.
• Relation => Table

• RDBMS is a software
• It is used to create and maintain the database in the form of tables
• RDBMS is one kind of DBMS

Examples:
ORACLE => ORACLE company
SQL SERVER => MICROSOFT company
MY SQL => SUN MICRO SYSTEMS
POSTGRE SQL => POSTGRE FORUM
DB2 => IBM

TABLE:

Example:

EMPLOYEE Table / Relation / Entity


EMPNO ENAME SAL
Structure [Columns]
1234 Ravi 8000
1235 Naresh 12000
Data [Rows]
1236 Kiran 9000
1237 Sai 11000

Table = Structure [columns] + Data [rows]

Table is a collection of rows and columns.

ORACLE 2PM KPHB MAY 2024 Page 7


Column => is vertical representation of data

EMPNO column / attribute / property / field


1234

1235

1236

1237

Row:
Row is horizontal representation of data

1234 Ravi 8000 Row / Record / Tuple / Entity Instance

Metadata:
Metadata is the data about the data.

Examples:
Column Names, Table Names, data types, field sizes

EMPLOYEE

EMPID number(4) ENAME varchar2(10) SALARY

1234 Ravi 8000

1235 Kiran 7000

Sai ERROR

12345 ERROR

ORACLE 2PM KPHB MAY 2024 Page 8


Thursday, May 9, 2024 3:14 PM

BANK DB
BRANCHES Table
IFSCCODE CITY STATE
CUSTOMERS Table
CID CNAME CCITY MOBILE MAIL AADHAR PAN ACNO
TRANSACTIONS Table
TID T_DATE_TIME T_TYPE ACNO AMOUNT
EMPLOYEE Table
EMPNO ENAME SAL

ORACLE 2PM KPHB MAY 2024 Page 9


ORACLE
Friday, May 10, 2024 2:35 PM

ORACLE:
• ORACLE is a Relational DataBase Management Software [RDBMS]

• It is used to create and maintain the database in the form of tables.

BANK DB
BRANCHES Table
IFSCCODE CITY STATE
CUSTOMERS Table
CID CNAME CCITY MOBILE MAIL AADHAR PAN ACNO
TRANSACTIONS Table
TID T_DATE_TIME T_TYPE ACNO AMOUNT
EMPLOYEE Table
EMPNO ENAME SAL

• This software allows us to store, manipulate and retrieve the data of database.

manipulate => 3 actions

INSERT => new emp joined


UPDATE => emp promoted
DELETE => emp resigned

Retrieval => opening existing data

Examples:

checking account balance searching


for products transactions statement

• ORACLE software 2nd version introduced in 1979.

• For WINDOWS OS, latest version is: ORACLE 21C


For LINUX OS, latest version is: ORACLE 23AI

Before 1960s => BOOKS

In 1960s => FMS [File Management Software]

In 1970s => Hierarchical DBMS


Network DBMS

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

ORACLE COMPANY FOUNDER: LARRY ELLISON

IN 1977 => established a company with the name


Software Development Laboratories
ORACLE 2PM KPHB MAY 2024 Page 10
In 1979 => renamed as
Relational SOFTWARE INC.
Introduced ORACLE 2nd version

In 1983 => renamed as


ORACLE carp.

ORACLE [RDBMS]
queries
DATABASE
SQL TABLES
PL/SQL ROWS & COLUMNS

TO communicate with ORACLE DATABASE we can


use 2 languages. They are:
• SQL
• PL/SQL

SQL:
• SQL => Structured Query Language.
• It is a query language.
• It is used to write queries.

• QUERY => is a request that is sent to DB SERVER.


• QUERY => request / instruction / command In C: Function: is a sub
program is a set of
• Using SQL Language we can communicate with ORACLE DB by statements
writing queries.
In Java: Method: is a
sub program is a set of
statements
• SQL is Non-Procedural Language.
In SQL we will not write any set of statements or programs. Just we
write QUERIES.

• SQL is Unified Language.


It is a common language to communicate with any Relational DataBase
Management Software.
ORACLE DATABASE SQL SERVER DB2
DATABASE DATABASE

TABLES TABLES TABLES


ORACLE 2PM KPHB MAY 2024 Page 11
SQL SQL SQL
In PL/SQL: Procedure:
is a sub program is a
set of statements

ORACLE 2PM KPHB MAY 2024 Page 12


Wednesday, May 15, 2024 2:13 PM

ORACLE => RDBMS


Queries
SQL DATABASE
TABLES
PL/SQL ROWS & COLUMNS
Programs

Sub Languages of SQL:

ORACLE SQL provides 5 sub languages. They are:


DDL CREATE

•DDL => Data Definition Language ALTER


•Data Definition => metadata
DROP
•it deals with metadata FLASHBACK [ORACLE 10g]
PURGE [ORACLE 10g]

TRUNCATE RENAME

DRL / DQL SELECT

DRL => Data Retrieval Language


DQL => Data Query Language

Retrieve => opening existing data


Query => request

It deals with data retrievals

ORACLE 2PM KPHB MAY 2024 Page 13


DML INSERT
UPDATE
•DML => Data Manipulation Language DELETE

•It deals with Data Manipulations INSERT ALL [ORACLE 9i]

MERGE [ORACLE 9i]

TCL COMMIT
ROLLBACK
•TCL => Transaction Control Language SAVEPOINT
•It deals with transactions

DCL / ACL GRANT


REVOKE
•DCL => Data Control Language
•ACL => Accessing Control Language
•It deals with data accessibility

DDL commands:

CREATE:
CREATE command is used to
create ORACLE DB Objects like
Tables, Views, ..etc.
ORACLE DATABSE OBJECTS:

TABLES
VIEWS
INDEXES
SEQUENCES
SYNONYMS
MATERIALIZED VIEWS
Stored Procedures
Stored Functions
Packages
Triggers
EMPLOYEE
EMPNO ENAME SAL
ALTER:

• ALTER => Change

ORACLE 2PM KPHB MAY 2024 Page 14


• ALTER command is used to change structure of table.

• Using ALTER command we can:


○ Add the columns
○ rename the columns
○ drop the columns
○ modify the field sizes
○ modify the data types

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

In ORACLE 10g, RECYCLEBIN feature added

DROP TABLE EMPLOYEE; RECYCLEBIN

EMPLOYEE
To Restore the table
FLASHBACK

to delete from RBIN


PURGE
TRUNCATE: it is used to delete entire
table data.

Example:

EMPLOYEE => Table


EMPNO ENAME SAL Structure [Columns]
1001 Raju 6000
Data [Rows]
1002 Kiran 8000

TRUNCATE => to deletes all rows with good performance

ORACLE 2PM KPHB MAY 2024 Page 15


RENAME:
used to rename the table

DRL / DQL:

SELECT:
• it is used to retrieve the data from table
• retrieve => opening existing data

DML:

INSERT: used to insert the


records

UPDATE:
used to modify table data
DELETE: used to delete the
records

TCL:

TCL => Transaction Control Language

Transaction:
• Transaction is a series of actions [SQL Commands].

Examples:
Withdraw, Deposit, Fund Transfer, Placing Order

Fund transfer TRANSACTION ACCOUNTS

ORACLE 2PM KPHB MAY 2024 Page 16


ACNO NAME BALANCE
Sufficient funds available?
Updates from account balance 1001 AA 50000-20000 = 30000
Updates to account balance 1002 BB 80000+20000 = 100000

Every transaction must be successfully finished or cancelled

if transaction is successful, save it COMMIT

if transaction is unsuccessful, cancel it ROLLBACK


DCL:

GRANT:
to give permission to other users we use GRANT

REVOKE:
to cancel the permissions we use REVOKE
SQL
DDL DRL DML TCL DCL
data definitions retrievals manipulations transactions accessibility
[metadata]

create alter select insert update commit grant revoke


delete rollback
drop flashback savepoint
purge truncate insert all
rename merge

ORACLE => RDBMS


queries
SQL DATABASE
TABLES
PL/SQL ROWS & COLUMNS
programs

ORACLE 2PM KPHB MAY 2024 Page 17


CREATE
Thursday, May 16, 2024 2:17 PM

CREATE:
It is used to create the DB Objects like tables, views,
indexes …etc.

Syntax to create the table:

CREATE TABLE <table_name> [] Optional


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

Note:
for WINDOWS OS, latest version is ORACLE 21C for LINUX
OS, latest version is ORACLE 23AI

Till ORACLE 21C, we can create max of 1000 columns only. From ORACLE
23AI, we can create max of 4096 columns.

Table / Relation /
Entity
EMPLOYEE
EMPID ENAME SAL
1234 Ravi 8000
column / field / property /
1235 Sai 10000 attribute
1236 Kiran 7000

Row / Record / Tuple / Entity Instance

Data Types ibn ORACLE SQL:

data Type tells,


• how much memory has to be allocated • which type of data
should be accepted ORACLE SQL provides following data types:

Character Related Char(n)


Varchar2(n)
Examples: LONG CLOB
'RAJU'
'MANAGER' nChar(n) nVarchar2(n)
'B.Tech' nCLOB
'M'
'TS'

Integer Related Number(p)


Integer
Examples: Int
1234
678
18

Floating Point Related Number(p,s)


Float

ORACLE 2PM KPHB MAY 2024 Page 18


Examples: Binary_Float
8000.00 Binary_Double
1600.80
67.89
5.4

Date & Time Related DATE


TIMESTAMP
Examples:
25-DEC-23
17-APR-98

16-MAY-24 2:49:15.123456 PM

Binary Related BFILE


BLOB
Examples:
Images
Audios Videos

Character Related Data Types: string =>


is a group of characters Example:'raju'

Char(n):
• It is used to hold string values.
• n => max no of chars
• It is Fixed Length Data Type.
• extra memory will be filled with spaces.
• max size: 2000 Bytes [2000 chars]
• default size: 1
• to hold fixed length chars use CHAR(n)

Varchar2(n):
• It is used to hold string values.
• n => max no of chars • It is Variable Length Data Type.
• spaces will not be filled here.
• max size: 4000 Bytes [4000 chars]
• default size: no default size
• to hold variable length chars use VARCHAR2(n) Examples:

STATE_CODE CHAR(2) ENAME VARCHAR2(10)


------------------------ ----------------
TS SAI
AP RAMESH KIRAN
MH WB

Note:
All character related data types can accept digits, letters and
special characters.

VEHICLE_NUM CHAR(10) mail_id VARCHAR2(30)


-------------------- -------------------
TS09AA1234 [email protected]

ORACLE 2PM KPHB MAY 2024 Page 19


[email protected] [email protected]

PAN_CARD_NUM CHAR(10) pname VARCHAR2(20)


char x; //1 Byte
----------------------- -----------
C follows ASCII
ABCDE1234F laptop
monitor keyboard
mouse
In Java:
char x; //2 Bytes Java
follows UNI

Note:
Varchar2 data type can hold max of 4000 chars only.
To hold more than 4000 chars we can use LONG or CLOB. CLOB is best ASCII:
one. • American
Standard Code for
Information
LONG:
• it is used to hold large amounts of chars.
nChar(n) •it is fixed length data type
• it has some restrictions:
•max size: 2000 Bytes [1000 chars]
○ A table can have only 1 column as LONG type.
•n => max no of chars
○ We cannot use built-in functions on LONG type.
• Max size: 2GB
nVarchar2(n) •it is variable length data type
•max size: 4000 Bytes [2000 chars]
CLOB: •n => max no of chars
• CLOB => Character Large Object
• it is used to hold large amounts of chars. Interchange
• A table can have multiple columns as CLOB type. • It is a coding
• We can use built-in functions on CLOB type column. system
• Max size: 4GB • 256 chars coded
• ranges from 0 to
255
• 255 => 1111
Examples: product_features
CLOB feedback CLOB 1111 => 8 bits [1
Byte]
• it supports to
ENGLISH language
only.

UNI:
• UNI =>
UNIVERSAL
In C:
Char(n) •ASCII code char data types
Varchar2(n) •Single Byte char data types
LONG •can hold ENGLISH language chars only
CLOB

nChar(n) •UNI code char data types


nVarchar2(n) •Multi Byte char data types
nCLOB •can hold ENGLISH + other language chars

n => national
• It is a coding system

• it is extension of ASCII
Note:
• 65536 chars coded
nVarchar2 data type can hold max of 2000 chars only.
• ranges from 0 to 65535
To hold more than 2000 chars use nCLOB. nCLOB can
• 65535 => 1111 1111 1111 1111 => 16 bits [2 Bytes]
hold upto 4GB.
• It supports to ENGLISH + Other Language Chars.
Integer Related data types:

NUMBER(p):
• It is used to hold integers.
• Integer => number without decimal places
• p => precision => max no of digits
• p valid range => 1 to 38

Examples:

EMPID NUMBER(4) -9999 TO 9999


-----------

ORACLE 2PM KPHB MAY 2024 Page 20


1001
1002
1003
89
786
9999
10000 => ERROR

Max marks: 100

Maths_Marks NUMBER(3) -999 TO 999


-------------------
78
123
999
1000 => ERROR

Mobile_Number NUMBER(10)

Credit_Card_Number NUMBER(16)

Aadhar_Number NUMBER(12)

Integer, Int are alias names of NUMBER(38)

Number(38) = Integer = Int

age NUMBER(2) -99 TO 99


-----
25
9
100

Floating point related data types:

NUMBER(p,s):
• It is used to hold floating point values.
• number with decimal places is called "Floating point".
• p => precision => max no of digits
• s => scale => max no of decimal places
Examples:
-999.99 TO 999.99 Max Marks: 100
3 subjects
Avrg NUMBER(5,2) 300/3 = 100
----------
67.89

ORACLE 2PM KPHB MAY 2024 Page 21


123.78
999.99 100. 00
1000 ERROR
786.2378645 => 786.24
786.2348645 => 786.23

p=5 s=2

-999999.99 TO 999999.99

SALARY NUMBER(8,2)

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

35000

100000 100000.00

999999.99

1000000 ERROR

Height NUMBER(2,1) -9.9 TO 9.9

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

5.4 5.8
6.0 5.3
5.6
8.4 9.9
10 ERROR
6.3456789 => 6.3
6.3756789 => 6.4

Date & Time related data types:

DATE:
○ It is used to hold date values.
○ Default ORACLE date format: DD-MON-YY
○ Example: 18-MAY-24, 25-DEC-23
○ date also contains time value
○ it can hold date, month, year, hours, minutes and seconds.
○ By default it displays date only. ○ default time:
12:00:00 AM [mid night time] ○ fixed length data
type. ○ max size: 7 Bytes

Examples:
DOB DATE
DOJ DATE
Ordered_Date DATE Delivery_Date
DATE Timestamp:
• introduced in ORACLE 9i version.
• It is used to maintain date and time values.
• It is extension of DATE data type.
• It can hold fractional seconds also.
• It can hold date, month, year, hours, minutes, seconds and fractional
seconds.
• default time: 12:00:0.0 AM [mid night time]
• fixed length data type
• max size: 11 Bytes

Examples:
Transaction_date_time TIMESTAMP
----------------------------------
25-APR-24 10:30:0.0 AM

DOJ DATE LOGIN_DATE_TIME TIMESTAMP


----------- ------------------------------
25-DEC-23 25-APR-24 2:30:15.123456 PM
Differences b/w DATE & TIMESTAMP:

ORACLE 2PM KPHB MAY 2024 Page 22


DATE TIMESTAMP

• it is used to hold date values • it is used to hold date and time values

• cannot hold fractional seconds • can fractional seconds also

• max size: 7 Bytes • max size: 11 Bytes

• by default it displays time

• by default it will not display time

Example: Example:
Date_Of_Joing DATE Transaction_date_time TIMESTAMP

Example:

EMPLOYEE
EMPNO ENAME STATE SAL Date_of_joining

NUMBER(4) VARCHAR2(10) CHAR(2) NUMBER(8,2) DATE

1234 NARESH TS 100000.00 25-DEC-23

1235 SAI AP 30000.00 17-AUG-20


Attendance
EMPNO LOGIN_DATE_TIME LOGOUT_DATE_TIME
NUMBER(4) TIMESTAMP TIMESTAMP

1234 17-MAY-24 10:30:15.123456 AM 17-MAY-24 5:00:15.456789 PM


Binary related data types:

BFILE:
• BFILE => Binary File Large object
• max size: 4 GB
• it is used to maintain multimedia objects like images, audios, videos,
animations and documents.
• it is used to maintain multimedia object's path.
• BFILE is pointer to multimedia object.
• It can be also called External Large Object. Because, Object will be
stored out of the database.
• It is not secured.

Database

EMP1 D:
EMPID ENAME EPHOTO [BFILE] Photos Folder
1001 Ravi D: \Photos \Ravi.jpg

Ravi.jpg

BLOB:
• BLOB => Binary Large Object
• max size: 4 GB

• it is used to maintain multimedia objects like images, audios, videos,


animations and documents.

• it is used to maintain multimedia object in table.

ORACLE 2PM KPHB MAY 2024 Page 23


• It can be also called as "Internal Large Object".

• It is secured.

Example:
Database

EMP2 D:
Photos Folder
EMPID ENAME EPHOTO [BLOB]

1234 Ravi 145AB65EF4646 Ravi.jpg

ORACLE 2PM KPHB MAY 2024 Page 24


Thursday, May 16, 2024 3:00 PM

Fixed Length T1
Variable Length
F1 CHAR(10) F2 VARCHAR2(10)

RAJU6spaces RAJU
104
106 NARESH4spaces NARESH
103
SAI7spaces SAI
ORACLE 2PM KPHB MAY 2024 Page 26
Monday, May 20, 2024 2:10 PM

Download and Install ORACLE Software: bit.ly/oracle21csoftware =>

download it bit.ly/oracle21cinstallation => install it

ORACLE:
• Server side software.
• the machine in which we install ORACLE software is called "ORACLE DB SERVER".

Note:
When we install ORACLE software, along with ORACLE, SQL PLUS
Software will be installed.

SQL PLUS:
• Client Side Software
• Using SQL PLUS software we can connect to ORACLE DB SERVER.

Client ORACLE DB SERVER [ORACLE s/w]

INSTANCE DB
SQL PLUS / connect query execution
Branches
services
Customers
SQL DEVELOPER /
Trans
TOAD
RAM Hard Disk

communicate
SQL => queries
PL/SQL => programs

SQL PLUS => CUI [character user interface]


SQL DEVELOPER => GUI [graphical user interface]
TOAD => GUI
Note:
• Installing ORACLE SOFTWARE is the duty of DBA [DataBase Administrator].
• At the time of installation, in 4th step you give one password. It is DBA's password.
• For DBA username is: system.
ORACLE 2PM KPHB MAY 2024 Page 26
Opening SQL PLUS:

• Press Windows + R. It displays RUN dialog box. • Type "sqlplus" command


• click on OK.
• It displays SQL PLUS window.

Login as DBA:
username: system
password: nareshit [at the time of installation you have given password]

• It connects to ORACLE DB Server and display SQL command prompt.

SQL> --- type the queries

Note:
To implement database security DBA creates user. DBA provides
username and password to every SQL DEVELOPER.

Creating User:

Syntax:

CREATE USER <user_name>


IDENTIFIED BY <password>; (first this) alter session set"_oracle_script"=true ;

Example:
Create a user with the name c##batch2pm and

password nareshit: Login as DBA:

username: system
password: nareshit [at the time of installation you have given password]

SQL> CREATE USER c##batch2pm Note:


IDENTIFIED BY nareshit;
From ORACLE 12c,
Output: there are 2 types of users:
User created. • common user => c##userA
• local user => userA
ORACLE 2PM KPHB MAY 2024 Page 27
SQL> GRANT connect, resource, unlimited tablespace TO
c##batch2pm;

Output:
Grant succeeded.

connect •It is a privilege


•It is a permission for login

resource •It is a privilege


•It is a permission to create the tables, procedures, functions…etc

unlimited tablespace •It is a privilege


•It is a permission to insert the records
Logging in from SQL command prompt:

CONN[ECT] command is used to login from SQL command prompt.

Syntax:
CONN[ECT] <user_name>/<password>

Example:
SQL> CONN c##batch2pm/nareshit

to see current username:

SQL> SHOW USER


Note:
user name is not case sensitive password is
case sensitive

Modifying user's password:

Syntax:

ALTER USER <user_name>


IDENTIFIED BY <new_password>;

Example:

Login as DBA:

username: system password:


nareshit
ORACLE 2PM KPHB MAY 2024 Page 28
ALTER USER c##batch2pm IDENTIFIED BY
naresh;

Modifying DBA's password: login

as DBA:

username: sys as sysdba


password: [don't enter any password]

SQL> ALTER USER system


IDENTIFIED BY naresh;

Dropping user:

Syntax:
DROP USER <user_name> [CASCADE];
Note:
If USER [SCHEMA] is empty, no need to write CASCADE. If USER
is not empty, we must write CASCADE.

c##userAc##userB
T1
T2 empty

DROP USER c##userA CASCADE;DROP USER c##userB;

to see table structure:

Syntax:
DESC[RIBE] <table_name>

ORACLE 2PM KPHB MAY 2024 Page 29


Example: DESC
t1 Output:
NAME TYPE
---------------------------------------------
F1 NUMBER(4)

to see all users list:

all_users:
○ it is a system table / readymade table / built-in table
○ it maintains all users information

DESC all_users

SELECT username FROM all_users; Output:


USERNAME
----------------------
C##BATCH2PM

ORACLE 2PM KPHB MAY 2024 Page 30


Creating Tables and Inserting Records
Tuesday, May 21, 2024 2:37 PM

Creating Tables and Inserting Records:

CREATE:
• It is DDL command.
• It is used to create the DB objects like tables, views … etc.

Syntax to create the Table:

CREATE TABLE <table_name>


ORACLE 21C:
(
max => 1000 columns
<field_name> <data_type> [,
<field_name> <data_type> ,
ORACLE 23AI: max => 4096
.
columns
.]
);

INSERT:
• It is DML command.
• It is used to insert the records into table.

Syntax:

INSERT INTO <table_name>[(<columns_list>)] VALUES(<values_list>);

max avrg: 100.00

Example-1: p=5
s=2
STUDENT
SID SNAME AVRG

1234 ABC 67.89

1235 XY 55.66

SID NUMBER(4)

SNAME VARCHAR2(10)

ORACLE 2PM KPHB MAY 2024 Page 31


AVRG NUMBER(5,2)
Creating Table:

CREATE TABLE student


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

Inserting Records:
1234 ABC 67.89 COMMIT

1235 XY 55.66
INSERT INTO student VALUES(1234, 'ABC', 67.89);
ORACLE DB SERVER

INSERT INTO student VALUES(1235,


'XY', 55.66); INSTANCE DB
1234
COMMIT; student
1235 1234
1235

RAM Hard Disk

CL[EAR] SCR[EEN]:

Syntax: CL[EAR]
SCR[EEN]

Example:
SQL> CL SCR
-- it clears the screen

Note:
Syntax to define parameter:

ORACLE 2PM KPHB MAY 2024 Page 32


&<text>

Example:
&sid

Output: enter value


for sid:

Using parameter means, reading value at run time.

Inserting multiple records using parameters:

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


enter value for sid: 5001 enter
value for sname: BB enter value
for avrg: 77.88
INSERT INTO student VALUES(&sid, '&sname', &avrg);
INSERT INTO student VALUES(5001, 'BB', 77.88); 1 row
created.

/
Output:
enter value for sid: 5002 enter
value for sname: CC enter value
for avrg: 34.23

/
enter value for sid: 5003 enter
value for sname: DD enter value
for avrg: 66.28

Inserting Limited Column Values:

STUDENT
SID SNAME AVRG

7123 ZZZ

INSERT INTO student VALUES(7123, 'ZZZ'); Output:


ERROR: not enough values

INSERT INTO student(sid, sname) VALUES(7123, 'ZZZ'); Inserting limited


column values by changing order:

STUDENT

ORACLE 2PM KPHB MAY 2024 Page 33


SID SNAME AVRG

7124 89.23

INSERT INTO student(avrg, sid) VALUES(89.23, 7124);

COMMIT;

SELECT * FROM student;

Example-2:

EMPLOYEE

empid NUMBER(4)

ename VARCHAR2(10)

state CHAR(2)

sal NUMBER(8,2)

doj DATE

EMPID ENAME STATE SAL DOJ

5001 ABC TS 12000 25-DEC-23

5002 AA AP 15000 17-AUG-20


max sal: 100000.00

Creating Table:

CREATE TABLE employee


(
empid NUMBER(4),
ename VARCHAR2(10),
state CHAR(2), sal
NUMBER(8,2), doj DATE
);

ORACLE 2PM KPHB MAY 2024 Page 34


Output:
Table created.
Inserting records:
5001 ABC TS 12000 25-DEC-23
INSERT INTO employee
VALUES(5001,'ABC','TS',12000,'25-DEC-2023');
string

EMPLOYEE
DOJ DATE Implicit Conversion
----------
25-DEC-23 date

5002 AA AP 15000 17-AUG-20


INSERT INTO employee
VALUES(5002,'AA','AP',15000,to_date('17-AUG-2020')); string

EMPLOYEE
DOJ DATE to_date()
-------------- Explicit Conversion
17-AUG-20 date

Note:
To insert the date value use to_date() function.

COMMIT;

SELECT * FROM employee;

Note: sysdate:
• it is a built-in function.
• it returns current system date.
Example:
SELECT sysdate FROM dual;

Inserting record with today's date:

ORACLE 2PM KPHB MAY 2024 Page 35


5003 Kiran TS 20000 sysdate
INSERT INTO employee
VALUES(5003,'Kiran','TS',20000,sysdate); Inserting
Limited column values:
5005 Ramu 7000

INSERT INTO employee


VALUES(5005,'Ramu',7000);
ERROR: not enough values

INSERT INTO employee(empid,ename,sal) VALUES(5005,'Ramu',7000);

Example-3:

EMPLOYEE1
EMPID ENAME LOGIN_DATE_TIME

1001 AA 20-MAY-24 10:30:0.0 AM

1002 BBB 21-MAY-24 2:30:0.0 PM

empid NUMBER(4)

ename VARCHAR2(10)

login_date_time TIMESTAMP
CREATE TABLE employee1
(
empid NUMBER(4), ename
VARCHAR2(10),
login_date_time TIMESTAMP
);

1001 AA 20-MAY-24 10:30:0.0 AM


INSERT INTO employee1
VALUES(1001,'AA','20-MAY-2024 10:30 AM'); --ERROR

INSERT INTO employee1


VALUES(1001,'AA','20-MAY-2024 10:30:0.0 AM');
Output: string 1 row created

implicit conversion Login_date_time TIMESTAMP


-------------------------
20-MAY-24 10:30:0.0 AM timestamp

ORACLE 2PM KPHB MAY 2024 Page 36


1002 BBB 21-MAY-24 2:30:0.0 PM
INSERT INTO employee1
VALUES(1002,'BBB',to_timestamp('21-MAY-2024 2:30:0.0 PM')); string

login_date_time timestampto_timestamp()
---------------------------explicit conversion 21-MAY-2024
2:30:0.0 PM timestamp

systimestamp:
• it is a built-in function.
• it returns current system date and time.

Example:
SELECT systimestamp FROM dual;

Inserting record with today's date and time:


1003 CC systimestamp
INSERT INTO employee1
VALUES(1003,'CC',systimestamp);
COMMIT;

SELECT * FROM employee1;

ORACLE 2PM KPHB MAY 2024 Page 37


Wednesday, May 22, 2024 2:22 PM

There are 2 types of conversions in ORACLE. They are:


• implicit conversion • explicit conversion

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

Example:

SELECT '100'+'200' FROM dual;


string string implicit conversion

num num
100 + 200
Output: 300

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

Example:

SELECT to_number('100')+to_number('200') FROM dual;


string string
Explicit
Conversion

ORACLE 2PM KPHB MAY 2024 Page 40

Conversion
number number
+
Output: 100 200
300

Note:
• Don't depend on Implicit Conversion.
• Implicit Conversion degrades the performance.
ORACLE 2PM KPHB MAY 2024 Page 41

Setting PAGE SIZE and LINE SIZE


Thursday, May 23, 2024 2:25 PM

PAGE
default PAGESIZE 14
default LINESIZE 80 abcd……………….. 80 chars
………….
………..
……….

14 lines

Setting Line Size:

Syntax:
SET LINES[IZE] <size>

Example:
SET LINES 200

Setting Page Size:

Syntax:
SET PAGES[IZE] <size>

Example:
SET PAGES 200
ORACLE 2PM KPHB MAY 2024 Page 42

Setting Page size and line size:

SET LINES 300 SET PAGES 300 LINES 300


(or)
SET PAGES 300

to see all parameters list: SQL>

show all

Output:
LINESIZE 300

PAGESIZE 300
ORACLE 2PM KPHB MAY 2024 Page 43

Column Alias
Thursday, May 23, 2024 3:14 PM

Column Alias:
• It is used to change column heading in output.
• It temporary name.
• Its scope is limited to that query only.
• To give column alias we use 'AS' keyword.
• Using 'AS' keyword is optional.

• To give column alias in multiple words or to maintain the


case we must specify column alias in double quotes.

Syntax to give column alias:


<original_column_name> [AS] <column_alias>

Example:
SELECT ename AS A, sal AS B FROM
emp;

Output:
A B
--------- -----------
SMITH 800
ALLEN 1600
ORACLE 2PM KPHB MAY 2024 Page 44

Editing Query
Friday, May 24, 2024 3:28 PM

SQL> SELECT enmae, sle FRM emp;

SQL> ED

displays editor

SELECT ename, sal FROM emp

edit the query


don't write ; at end of query
Save it. File => Save Close editor
to run recent query type /

SQL> /
ORACLE 2PM KPHB MAY 2024 Page 45
DRL
Wednesday, May 22, 2024 3:30 PM

DRL / DQL:

• DRL => Data Retrieval Language


• DQL => Data Query Language

• Retrieve => Opening existing data

• Query => Request / Instruction / Command • Query is a request that is sent to DB

Server.

• DRL deals with data retrievals.

• ORACLE SQL provides only one DRL command.


i.e.: SELECT

SELECT:
○ SELECT command is used to retrieve the data from table.
○ Using SELECT command we can select:
▪ all columns and all rows
▪ all columns and specific rows ▪ specific columns and all rows
▪ specific columns and specific rows Syntax of SELECT command:

SELECT [ALL/DISTINCT] <columns_list> / *


FROM <table_name>
WHERE <condition>
GROUP BY <grouping_columns_list>
HAVING <condition>
ORDER BY <column> ASC/DESC
OFFSET <number> ROW/ROWS
FETCH FIRST/NEXT <number> ROW/ROWS ONLY;
ORDER BY <column> ASC/DESC
OFFSET <number> ROW/ROWS
FETCH FIRST/NEXT <number> ROW/ROWS ONLY;

ORACLE 2PM KPHB MAY 2024 Page 45


SQL ENGLISH
QUERIES SENTENCES
CLAUSES WORDS
selecting all columns and all rows:

SELECT * FROM emp;

* All Columns
Implicitly ORACLE replaces * with all column names.

SELECT * FROM emp;

above query will be rewritten by ORACLE as following:

SELECT empno, ename, job, mgr, hiredate, sal, comm, deptno FROM emp;

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


* will be replaced with all column names in table structure order.

Selecting all columns and specific rows:

Display the emp records whose salary is 3000:

SELECT *
FROM emp
WHERE sal=3000;

Selecting specific columns and all rows:

Display emp names and salaries of all emps:

SELECT ename, sal FROM emp;

Selecting specific columns and specific rows:

ORACLE 2PM KPHB MAY 2024 Page 46


Display emp names and salaries of the emps whose salaries are 3000:

SELECT ename, sal


FROM emp
WHERE sal=3000;

All Columns SELECT *

Specific Columns SELECT ename, sal

All Rows Don't write WHERE condition

Specific rows WHERE sal=3000


Operators in ORACLE 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 equals not equals

Logical AND OR NOT

Special / IN NOT IN
Comparison BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL

ANY
ALL
EXISTS

Concatenation ||

ORACLE 2PM KPHB MAY 2024 Page 47


SET UNION
UNION ALL
INTERSECT MINUS

Arithmetic Operators:

Arithmetic Operators are used to perform arithmetic operations like addition, subtraction …
etc.

ORACLE SQL provides following Arithmetic operators:

+ Addition In C/ Java:
5/2 = 2
- Subtraction 5%2 = 1
* Multiplication
In SQL:
/ Divison 5/2 = 2.5
Mod(5,2) = 1
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;

Output:
ENAME SAL ANNUAL_SAL
-------------------------------------------------------
SMITH 800 9600
ALLEN 1600 19200

ORACLE 2PM KPHB MAY 2024 Page 48


SELECT ename, sal, sal*12 AS Annual Salary
FROM emp; Output:
ERROR:

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

Output:
ENAME SAL Annual Salary
-------------------------------------------------------
SMITH 800 9600
ALLEN 1600 19200
Calculate TA, HRA, TAX and GROSS salaries of all emps:
TA => 10% on sal
HRA => 20% on sal
TAX => 5% on sal
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;

Calculate experience of all emps:

SELECT ename, hiredate,


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

Assignment: STUDENT
SID SNAME M1 M2 M3

1234 A 70 80 50

1235 B 44 66 55
calculate total marks and average marks of all students

ORACLE 2PM KPHB MAY 2024 Page 49


Relational Operators / Comparison Operators:
Relational operator is used to compare column value with 1 value.

ORACLE SQL provides following Relational Operators:

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

Syntax:
<column> <relational_operator> <value>

Examples: sal>3000 sal<3000 sal>=3000 sal<=3000 sal=3000


sal!=3000

Examples on relational oeprators:

Display the emp record whose empno is 7698:

SELECT * FROM emp


WHERE empno=7698;

Display all managers records:

SELECT ename, job, sal


FROM emp
WHERE job='manager';
MANAGER = manager FALSE Output: no rows selected

SELECT ename, job, sal


FROM emp
WHERE job='MANAGER'; --displays MANAGERS records

Note:
SQL is not case sensitive language. But, String comparison is case sensitive.

Display all emp records except managers:

SELECT ename, job, sal

ORACLE 2PM KPHB MAY 2024 Page 50


FROM emp
WHERE job!='MANAGER';

Display the emp records who are working in deptno 30:

SELECT ename, sal, deptno


FROM emp
WHERE deptno=30;

Display the emp records whose salary is more than 2500:

SELECT ename, sal


FROM emp
WHERE sal>2500;

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 1250 or less:

SELECT ename, sal


FROM emp
WHERE sal<=1250;

Note:
Calendar Order is Ascending order.

1-JAN-23 2-JAN-23 3-JAN-23


.

ORACLE 2PM KPHB MAY 2024 Page 51


.
who joined After 2023
31-DEC-23
1-JAN-24 2-JAN-
24
. hiredate> '31-DEC-2023'
.
31-DEC-24

Display the emp records who joined after 1981:

1-JAN-1981
..
31-DEC-1981 joined after 1981
1-JAN-1982

. hiredate>'31-DEC-1981'
.

SELECT ename, hiredate


FROM emp
WHERE hiredate>'31-DEC-1981';
Display the emp reocrds who joined before 1981:

. . hiredate<'1-JAN-1981'
30-DEC-1980 31-
DEC-1980
1-JAN-1981
..
31-DEC-1981

ORACLE 2PM KPHB MAY 2024 Page 52


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

Display the emp records whose annual salary is more than 30000:

SELECT ename, sal, sal*12 AS "Annual Salary"


FROM emp
WHERE sal*12>30000;

Display the emp records who are having more than 42years experience:

SELECT ename, hiredate, TRUNC((sysdate-hiredate)/365) AS experience


FROM emp
WHERE TRUNC((sysdate-hiredate)/365)>42;
Logical Operators:

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

To separate multiple conditions we use AND or OR

AND All conditions should be satisfied

OR At least 1 condition should be satisfied


TRUTH TABLE:

c1 Condtion1

c2 Condition2

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

T F F T

ORACLE 2PM KPHB MAY 2024 Page 53


F T F T

F F F F
Examples on AND, OR:

Display all managers and clerks records:

SELECT ename, job, sal


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

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

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

SELECT ename, sal, deptno FROM emp


WHERE deptno=10 OR deptno=20;

Display the emp reocrds whose empnos are: 7499, 7698, 7900:

SELECT *
FROM emp
WHERE empno=7499 OR empno=7698 OR empno=7900;

Display the emp reocrds whose names are:


BLAKE, WARD and MILLER

SELECT *
FROM emp
WHERE ename='BLAKE' OR ename='WARD' OR ename='MILLER';

ORACLE 2PM KPHB MAY 2024 Page 54


Display the emp records whose salary is 2450 or more and 3000 or less [whose salaries b/w
2450 and 3000]:

SELECT ename, sal


FROM emp
WHERE sal>=2450 AND sal<=3000;

Display the managers records whose salary is more than 2500:


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

Display the managers who joined after may 1981:

SELECT ename, job, hiredate


FROM emp
WHERE job='MANAGER' AND hiredate>'31-MAY-1981';

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

Example:

STUDENT5
SID SNAME M1 M2 M3

1001 A 60 90 80

1002 B 70 30 60
CREATE TABLE student5

ORACLE 2PM KPHB MAY 2024 Page 55


(
sid NUMBER(4), sname VARCHAR2(10),
m1 NUMBER(3), m2 NUMBER(3), m3
NUMBER(3)
);
INSERT INTO student5 VALUES(1001,'A',60,90,80); INSERT INTO student5
VALUES(1002,'B',70,30,60); COMMIT;

Display passed students records:

SELECT * FROM student5


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

Display failed students records:

SELECT * FROM student5


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

Display all salesmen and clerks records whose salaries are more than 1250:

SELECT ename, job, sal


FROM emp
WHERE (job='SALESMAN' OR job='CLERK') AND sal>1250;

NOT:
• it is used to perform logical NOT operations.

Truth Table:

ORACLE 2PM KPHB MAY 2024 Page 56


Condition NOT(condition)
T NOT(T) => F

F NOT(F) => T
Display all emp records except managers:

SELECT ename, job, sal FROM emp


WHERE job!='MANAGER';

(or)

SELECT ename, job, sal FROM emp


WHERE NOT(job='MANAGER');

IN:

Display the emp records whose salary is 1250 or 2450 or 3000:

SELECT ename, sal


FROM emp
WHERE sal=1250 OR sal=2450 OR sal=3000;

(or)

SELECT ename, sal


FROM emp
WHERE sal IN(1250,2450,3000);

if sal is IN list, condn is TRUE if sal is not in LIST then condn is


FALSE
sal IN(1250,2450,3000)
SAL
-------
800 F
3000 T
1400 F

ORACLE 2PM KPHB MAY 2024 Page 57


1250 T
9000 F
2450 T

IN:

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


• It avoids of writing multi equality conditions using OR.

Syntax:
<column> IN(<values_list>)

Examples:
WHERE sal IN(1250,2450,3000)

SAL
----
1000 F
3000 T

Examples on IN:

Display all managers and clerks records:

SELECT ename, job, sal


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

JOB
--------------
MANAGER T
ANALYST F
CLERK T
SALESMAN F

ORACLE 2PM KPHB MAY 2024 Page 58


Display the emp records whose empnos are:
7499, 7698, 7900

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

EMPNO
---------
7369 F
7499 T
7521 F
7698 T
7876 F
7900 T

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

SELECT ename, sal, deptno


FROM emp
WHERE deptno IN(10,30);

Display the emp records whose names are: SCOTT, MILLER and
JAMES
SELECT *
FROM emp
WHERE ename IN('SCOTT','MILLER','JAMES');

Display all emp records except managers and clerks:

ORACLE 2PM KPHB MAY 2024 Page 59


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

if JOB value NOT IN list, condn is TRUE if JOB value is IN list, condn is FALSE

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

JOB
----------
MANAGER F
SALESMAN T
CLERK F ANALYST T

Display all emp records except deptno 10 and 30:

SELECT ename, sal, deptno FROM emp


WHERE deptno NOT IN(10,30);

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

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

Examples on BETWEEN AND:

Display the emp records whose salary is 2450 or more and 3000 or less [whose sal is b/w
2450 and 3000]:

SELECT ename, sal


FROM emp
WHERE sal>=2450 AND sal<=3000;
ORACLE 2PM KPHB MAY 2024 Page 60
(or)

SELECT ename, sal


FROM emp
WHERE sal BETWEEN 2450 AND 3000;

SAL
---------
2800 T
5000 F
3000 T
1000 F
2450 T

Display the emp records who joined in 1982:

1-JAN-1982 min
..
31-DEC-1982 max
SELECT ename, hiredate
FROM emp
WHERE hiredate>='1-JAN-1982' AND hiredate<='31-DEC-1982';

(or)

SELECT ename, hiredate


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

Display the emp records whose empnos between 7400 to 7700:

SELECT *
FROM emp
WHERE empno BETWEEN 7400 AND 7700;

ORACLE 2PM KPHB MAY 2024 Page 61


Display the emp records whose salary is not between 1250 and 3000
[display the emp records whose salary is less than 1250 or more than 3000]:

SELECT ename, sal


FROM emp
WHERE sal NOT BETWEEN 1250 AND 3000;

(or)

SELECT ename, sal


FROM emp
WHERE sal<1250 OR sal>3000;
SELECT ename,sal
FROM emp
WHERE sal BETWEEN 3000 AND 2000; What is the output of above query?

A. displays whose sal b/w 2000 and 3000


B. ERROR
C. No rows selected
D. None of Above

Answer: C

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

Syntax:
<column> LIKE <text_pattern>

In windows os,

search all jpg files *.jpg

search for jpg files which are started with a a*.jpg

search for jpg files in which 2nd char is a ?a*.jpg

ORACLE 2PM KPHB MAY 2024 Page 62


? replaces 1 char

* replaces 0 or any
In SQL,
to specify text pattern it provides 2 wildcard characters. They are:

_ replaces 1 char

% replaces 0 or any no of chars


Examples on LIKE operator:

Display the emp records whose names are started with 'S' letter:

SELECT ename, sal


FROM emp
WHERE ename LIKE 'S%';

Display the emp records whose names are ended with S:

SELECT ename, sal FROM emp


WHERE ename LIKE '%S';

Display the emp records whose names are ended with RD:

SELECT ename, sal


FROM emp
WHERE ename LIKE '%RD';

Display the emp records whose name's 2nd char is A:

SELECT ename, sal FROM emp


WHERE ename LIKE '_A%';

Display the emp records whose names are having


A letter:

SELECT ename, sal FROM emp


WHERE ename LIKE '%A%';

Display the emp records whose names are started and ended with S:

ORACLE 2PM KPHB MAY 2024 Page 63


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

Display the emp records whose names 3rd char is L:

SELECT ename, sal FROM emp


WHERE ename LIKE '__L%';

Display the emp records whose names are having 4 letters:

SELECT ename, sal FROM emp


WHERE ename LIKE '____';

Display the emp records who joined in december month:

SELECT ename, hiredate


FROM emp
WHERE hiredate LIKE '%DEC%';

Display the emp records who are getting 3 digit salary:


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

Display the emp records whose names are not started with S letter:

SELECT ename, sal


FROM emp
WHERE ename NOT LIKE 'S%';

IS NULL:

ORACLE 2PM KPHB MAY 2024 Page 64


• It is used to compare column value with NULL.

• For NULL comparison we cannot use =. We must use "IS NULL".

Syntax:
<column> IS NULL

Examples:

Display the emp records who are not getting commission:

SELECT ename, sal, comm


FROM emp
WHERE comm=null; Output:
no rows selected

• For NULL comparison we cannot use =.


We must use "IS NULL".

SELECT ename, sal, comm


FROM emp
WHERE comm IS null;

Display the emp records who are getting commission:

SELECT ename, sal, comm FROM emp


WHERE comm IS NOT NULL;

Concatenation Operator:

ORACLE 2PM KPHB MAY 2024 Page 65


• Symbol: ||
• It is used to combine 2 strings

Syntax:
<string1> || <string2> Examples:

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


RAJKUMAR

EMPLOYEE
EMPID FNAME MNAME LNAME

1234 RAJ KUMAR VARMA

1235 SACHIN RAMESH TENDULKAR


SELECT fname || ' ' || mname || ' ' || lname FROM employee;

RAJ KUMAR VARMA


SACHIN RAMESH TENDULKAR

Display output as following:


SMITH earns 800
ALLEN earns 1600

SELECT ename || ' earns ' || sal FROM emp;

Display output as following:


SMITH works as CLERK and joined on 17-DEC-80
ALLEN works as SALESMAN and joined on 25-AUG-81

SELECT ename || ' works as ' || job || ' and joined on ' || hiredate
FROM emp;

ORACLE 2PM KPHB MAY 2024 Page 66


NULL
Monday, May 27, 2024 2:51 PM

NULL:
• NULL means empty or blank.
• It is not a value.
• When we don't know the value or when we are unable to insert
the value we insert NULL

• NUL is not equals to 0


• NULL is not equals to space

• If NULL is participated in operation then result will be NULL.

Example:
SELECT 100+200 FROM dual; --300

SELECT 100+200+NULL FROM dual; --null

• For null comparison we cannot use = [equals]. we must use 'IS


NULL'.

Note:
We can insert NULL using 2 ways. They are:
• direct way: using NULL keyword
ORACLE 2PM KPHB MAY 2024 Page 72

• indirect way: insert limited column values

• In SQL, for every data type default value is NULL.

Example:

EMPLOYEE
EMPNO ENAME SAL
CREATE TABLE employee
(
empno NUMBER(4), ename
VARCHAR2(10), sal
NUMBER(8,2)
);
1234 A
1st way: direct way => using null keyword

INSERT INTO employee VALUES(1234,'A',null);


1235 7000
INSERT INTO employee VALUES(1235,null,7000);

1236 C
2nd way: indirect way => insert limited column values

INSERT INTO employee(empno,ename) VALUES(1236,'C');

ORACLE 2PM KPHB MAY 2024 Page 73


Monday, May 27, 2024 2:52 PM
when we are unable to insert the value we insert NULL
STUDENT
SID SNAME M1 [NUMBER(3)]
1001 A 78
1002 B 0
1003 C 66
NULL
1004 D

when we don't know the value we insert NULL.


EMPLOYEE
EMPNO ENAME SAL
1234 A 12000
1235 B 9000
1236 C NULL

ORACLE 2PM KPHB MAY 2024 Page 74


UPDATE
Tuesday, May 28, 2024 2:14 PM

UPDATE:
• UPDATE command is used to modify table data.

• using UPDATE command we can modify:


○ single value of single record
○ multiple values of single record
○ specific group of records
○ all records Syntax:

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

Modifying single value of single record:

Increase 2000 rupees salary to an employee whose empno


is 7698:

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

Modifying multiple values of single record:

Set job as manager, salary as 6000 to the


employee whose empno is 7369:

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

ORACLE 2PM KPHB MAY 2024 Page 70


Modifying specific group of records:

Increase 10% on salary to all managers:

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

Modifying all records:

Increase 1000 rupees salary to all emps:

UPDATE emp
SET sal=sal+1000;

Transfer all deptno 10 emps to deptno 20:

UPDATE emp
SET deptno=20
WHERE deptno=10;

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 20% on
salary to the employees who are having more than 42years experience:

UPDATE emp
SET sal=sal+sal*0.2
WHERE TRUNC((sysdate-hiredate)/365)>42;

ORACLE 2PM KPHB MAY 2024 Page 71


Increase 10% on sal, 20% on comm to the emps who are getting
commission:

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

Set comm as 900 to the emps who are not getting comm:

UPDATE emp
SET comm=900
WHERE comm is null;

Set comm as null to the emps whose empnos are 7499, 7521,
7698:

UPDATE emp
SET comm=null
WHERE empno IN(7499,7521,7698);

ORACLE 2PM KPHB MAY 2024 Page 72


DELETE
Tuesday, May 28, 2024 3:09 PM

DELETE:
• DELETE command is used to delete the records from table.

• Using DELETE command we can delete:


○ single record
○ specific group of records
○ all records Syntax:

DELETE [FROM] <table_name> [WHERE


<condition>];

Examples on DELETE:

Deleting single record:

delete an emp reocrd whose empno is 7876:

DELETE FROM emp


WHERE empno=7876;

Deleting specific group of records:


ORACLE 2PM KPHB MAY 2024 Page 78

delete the emp records who are working in deptno 10 and 30:

DELETE FROM emp


WHERE deptno IN(10,30);

Deleting all records:

delete all emp records:

DELETE FROM emp;


(or)
DELETE emp;

Delete the emp records who are getting annual salary


as more than 30000:

DELETE FROM emp


WHERE sal*12>30000;

ORACLE 2PM KPHB MAY 2024 Page 74


ORACLE 2PM KPHB MAY 2024 Page 79
TCL
Tuesday, May 28, 2024 3:21 PM

TCL:
• TCL => Transaction Control Language

• It deals with transactions.

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

Examples: withdraw, deposit, fund transfer, placing order

Fund Transfer Transaction:

ACCOUNTS
ACNO NAME BALANCE

1234 A 60000-20000 = 40000

1235 B 80000+20000 = 100000


Transfer 20000 amount to 1235 account from 1234 account:

• sufficient funds available? => SELECT


• If funds available, UPDATE from account balance => UPDATE
• UPDATE to account balance => UPDATE

Note:
Every transaction must be successfully finished or cancelled.
If transaction is successful, to save it use COMMIT
If transaction is unsuccessful, to cancel it use ROLLBACK

ORACLE SQL provides following TCL commands:


• COMMIT [save]
• ROLLBACK [undo all]
• SAVEPOINT [to set specific point for rollback]

COMMIT [Save]:

• COMMIT command is used to save the transaction.

• When COMMIT command is executed the data in INSTANCE [RAM] will be moved to
DATABASE [HARD DISK].

• It makes the changes the permanent.


Syntax:
COMMIT; COMMIT

ORACLE DB SERVER
Client

INSTANCE DB
1001 => INSERT 1001 EMP
1002 1001
1002 => INSERT
1002
RAM Hard Disk

ROLLACK [undo all]:

• ROLLBACK command is used to cancel the transactions.

• It cancels uncommitted actions.

• After COMMIT we cannot use ROLLBACK.

Syntax:
ROLLBACK [TO <savepoint_name>];
Note:

ORACLE 2PM KPHB MAY 2024 Page 76


• All DML commands are not auto committed.
• After performing DML operations, to save it we use COMMIT. to cancel it we use
ROLLBACK.

Example on COMMIT and ROLLBACK:

EMPLOYEE10
EMPNO ENAME SAL
CREATE TABLE employee10
(
empno NUMBER(4), ename
VARCHAR2(10), sal
NUMBER(8,2)
);

INSERT INTO employee10 VALUES(1001,'A',7000); -- inserts in INSTANCE INSERT INTO


employee10 VALUES(1002,'B',10000); -- inserts in INSTANCE

COMMIT; --data moves from INSTANCE to DB

INSERT INTO employee10 VALUES(1003,'C',15000);


INSERT INTO employee10 VALUES(1004,'D',9000);

SELECT * FROM employee10;

Output: empno
----------
1001 1002
1003
1004

ROLLBACK; --2 actions will be cancelled => uncommitted actions


SELECT * FROM employee10;

Output: empno
----------
1001
1002

ORACLE 2PM KPHB MAY 2024 Page 77


SAVEPOINT:
• SAVEPOINT command is used to set margin for ROLLBACK.

Syntax:
SAVEPOINT <savepoint_name>;

Example:

CREATE TABLE t2(f1 int); --CREATE+COMMIT => committed

INSERT INTO t2 VALUES(1);


INSERT INTO t2 VALUES(2);

SAVEPOINT p1;

INSERT INTO t2 VALUES(3);


INSERT INTO t2 VALUES(4); SAVEPOINT p2;

INSERT INTO t2 VALUES(5); INSERT INTO t2


VALUES(6);

ROLLBACK TO p2; --cancels 2 actions

ORACLE 2PM KPHB MAY 2024 Page 78


Wednesday, May 29, 2024 2:42 PM

Note:
All DDL commands are auto committed.
All DML commands are not auto committed.

When DDL command is executed, this DDL command and COMMIT


command will be executed .

DDL = DDL + COMMIT

CREATE = CREATE + COMMIT ALTER =


ALTER + COMMIT

Example:

CREATE TABLE t1(f1 NUMBER(4)); CREATE+COMMIT => committed

INSERT INTO t1 VALUES(1); INSERT


INTO t1 VALUES(2);
CREATE TABLE t2(f1 VARCHAR2(10); CREATE+COMMIT => committed
INSERT INTO t1 VALUES(3);
INSERT INTO t1 VALUES(4);
ROLLBACK; --2 actions will be cancelled
ORACLE 2PM KPHB MAY 2024 Page 84

ALTER
Wednesday, May 29, 2024 3:12 PM

ALTER:
• ALTER => Change

• ALTER command is used to change structure of table.

Note:
• to modify table data we use UPDATE
• to modify table structure we use ALTER

Example:
Table
EMPLOYEE
EMPNO ENAME SAL Table Structure [columns]
1001 A 7000
1002 B 10000
1003 C 8000 Table data [rows]

1004 D 9000

Table = structure + data


Table = columns + rows

Using ALTER 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:

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


ORACLE 2PM KPHB MAY 2024 Page 80
[RENAME COLUMN <old_name> TO <new_name>]
[DROP COLUMN <column>]
ALTER TABLE <table_name> [ADD(<field_definitions>)]
[RENAME COLUMN <old_name> TO <new_name>]
[DROP COLUMN <column>]
[DROP(<columns_list>)]
[MODIFY(<field_definitions>)];

Example on ALTER:

STUDENT
SID SNAME VARCHAR2(10)
CREATE TABLE student
(
sid NUMBER(4), sname
VARCHAR2(10)
);
Output:
Table created.

DESC student Output:


NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)

Adding a column [add m1 column]:

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


Table Altered.

DESC student Output:


NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10) M1
NUMBER(3)

Adding multiple columns [Add m2, m3 columns]:


ALTER TABLE student ADD(m2 NUMBER(3), m3 NUMBER(3)); Output:
ORACLE 2PM KPHB MAY 2024 Page 81
Table Altered.

DESC student Output:


NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
M1 NUMBER(3) M2 NUMBER(3)
M3 NUMBER(3)

Renaming a column [m3 to maths]:

ALTER TABLE student RENAME COLUMN m3 TO maths; Output:


Table Altered.

DESC student Output:


NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
M1 NUMBER(3)
M2 NUMBER(3)
MATHS NUMBER(3)

Dropping a Column [Drop maths column]:

ALTER TABLE student DROP COLUMN maths;


(or)
ALTER TABLE student DROP(maths); Output:
Table Altered.

DESC student
Output:
NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10) M1 NUMBER(3)
M2 NUMBER(3)

Dropping multiple columns [drop m1, m2 columns]:


ORACLE 2PM KPHB MAY 2024 Page 82
ALTER TABLE student DROP(m1, m2); Output:
Table Altered.

DESC student Output:


NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)

Modifying field size [modify sname field size from 10 to 20]:

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


Table Altered.

DESC student Output:


NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(20)

Can we decrease the field size?


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

SNAME
------------
SAI
NARESH => MAX STRING LENGTH => 6 RAVI

Modifying data type [modify number type to char]:

ALTER TABLE student MODIFY sid CHAR(7); Output:


Table Altered.

DESC student Output:


NAME TYPE
------------------------------------
SID CHAR(7)
SNAME VARCHAR2(20)
ORACLE 2PM KPHB MAY 2024 Page 83
Note:
To modify the data type column must be empty.

ORACLE 2PM KPHB MAY 2024 Page 84


DROP, FLASHBACK and PURGE
Thursday, May 30, 2024 2:41 PM

DROP
FLASHBACK
PURGE

Note:
RECYCLEBIN feature added in ORACLE 10g version.

DROP:
• DROP command is used to delete (drop) the table.

• When we drop the table, it will be move to RECYCLEBIN.

Syntax:

DROP TABLE <table_name> [PURGE];

RECYCLEBIN
Example:
student
DROP TABLE student;

Output:
Table dropped.

TO see RECYCLEBIN:

SHOW RECYCLEBIN
Output:
ORIGINAL_NAME RECYCLEBIN_NAME
------------------------ -------------------------------
STUDENT ……..

FLASHBACK:
• FLASHBACK command introduced in ORACLE 10g version.

• It is used to restore the dropped table.

ORACLE 2PM KPHB MAY 2024 Page 85


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

Example:
FLASHBACK TABLE student TO BEFORE DROP;

PURGE:
• PURGE command introduced in ORALCLE 10g version.

• It is used to delete the table from RECYCLEBIN. This table will be deleted permanently. Again we
cannot recollect it.

Syntax:
PURGE TABLE <table_name>;

Example:
PURGE TABLE student;

RECYCLEBIN
DROP TABLE student;
student

FLASHBACK RESTORE

delete from RECYCLEBIN

PURGE

Example:

CREATE TABLE student5


(
sid NUMBER(4), sname VARCHAR2(10)
);
INSERT INTO student5 VALUES(1,'A'); INSERT INTO student5 VALUES(2,'B'); INSERT
INTO student5 VALUES(3,'C');

COMMIT;

ORACLE 2PM KPHB MAY 2024 Page 86


Dropping table:

DROP TABLE student5;


--it will be moved to RECYCLEBIN

TO see Recyclebin:

SHOW RECYCLEBIN
Output:
STUDENT5

Restore dropped table student5:

FLASHBACK TABLE student5


TO BEFORE DROP;

SHOW RECYCLEBIN

SELECT * FROM student5;


--it displays student table data

DROP TBALE student5;


--it will be moved to recyclebin

PURGE TABLE student5;


--student5 table permanently deleted from recyclebin

CASE-1:

CREATE TABLE t1(f1 int);


INSERT INTO t1 VALUES(1);

ORACLE 2PM KPHB MAY 2024 Page 87


INSERT INTO t1 VALUES(2); DROP TABLE t1;
COMMIT; RECYCLEBIN

T1 => 3:22
T1 => 3:20
INSERT INTO t1
CREATE TABLE t1(f1 VARCHAR2(10)); VALUES('A');

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

DROP TABLE t1;

FLASHBACK TABLE t1 TO BEFORE DROP; --restores recently dropped table

To restore older t1:

Syntax:
FLASHABCK TABLE "<recyclebin_name>" TO BEFORE DROP;

Example:
FLASHBACK TABLE "BIN$+dM9bzlNS9mBqngd1+3j8g==$0" TO BEFORE DROP;

CASE-2:

CREATE TABLE t2(f1 int);

INSERT INTO t2 VALUES(1);


INSERT INTO t2 VALUES(2); RECYCLEBIN
COMMIT;
T2
DROP TABLE t2;

ORACLE 2PM KPHB MAY 2024 Page 88


T2
DROP TABLE t2;

CREATE TABLE t2(f1 CHAR);

INSERT INTO t2 VALUES('A'); INSERT INTO t2


VALUES('B'); COMMIT;

FLASHBACK TABLE t2
TO BEFORE DROP;
Output: ERROR:
original name already used by existing object

FLASHBACK TABLE t2
TO BEFORE DROP RENAME TO
t2_old;

Note: don't practice RECYCLEBIN concept in


SYSTEM user. practice as user like
c##batch2pm

Dropping a table permanent:

DROP TABLE employee;


--table will be moved to recyclebin
(or) DROP TABLE employee PURGE;
PURGE TABLE employee; --table will be deleted permanently
--deletes from RECYCLEBIN

Emptying recyclebin:

PURGE RECYCLEBIN;
--it empties recyclebin

ORACLE 2PM KPHB MAY 2024 Page 89


DCL
Friday, May 31, 2024 2:24 PM

DCL / ACL:
• DCL => Data Control Language
• ACL => Accessing Control Language

• it deals with data accessibility.


• it is used to implement table level security.

• ORACLE SQL provides following DCL commands:


○ GRANT
○ REVOKE

GRANT:
• It is used to give permission on DB Objects to other users.

Syntax:

GRANT <privileges_list>
ON <DB_Object> TO <users_list>;

Examples:
USER c##batch2pm:

Grant read-only permission on emp table to c##userA:

GRANT select
ON emp
TO c##userA; login as

c##userA:

SELECT * FROM c##batch2pm.emp;


--displays data

ORACLE 2PM KPHB MAY 2024 Page 90


Grant DML permissions on emp table to c##userA:

GRANT insert, update, delete


ON emp
TO c##userA;

Grant all permissions on emp table to c##userA:

GRANT all
ON emp
TO c##userA;

Grant read-only permission on emp table to c##userA, c##useBr and


c##userC:

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

Grant read-only permission to all users:

GRANT select
ON emp
TO public;

REVOKE:
• REVOKE command is used to cancel the permissions.

Syntax:

Syntax:

REVOKE <privileges_list>
ON <DB_Object>

ORACLE 2PM KPHB MAY 2024 Page 91


FROM <users_list>;

Examples:

Cancel select permission on emp table from userA:

REVOKE select
ON emp
FROM c##userA;

Cancel DML permissions on emp table from userA:

REVOKE insert, update, delete


ON emp
FROM c##userA;

Cancel all permissions on emp table from userA:

REVOKE all
ON emp
FROM c##userA;

Cancel all permissions on emp table from userA, userB, userC:

REVOKE all
ON emp
FROM c#3userA, c#3userB, c##userC; Cancel all permissions on emp table from
all users:

REVOKE all
ON emp
FROM public;

Example on GRANT and REVOKE:

ORACLE 2PM KPHB MAY 2024 Page 92


Create 2 users c##userA, c##userB:

Login as DBA:

username: system password: naresh

CREATE USER c##userA IDENTIFIED BY usera;

GRANT connect, resource, unlimited tablespace


TO c##userA;

CREATE USER c##userB IDENTIFIED BY userb;

GRANT connect, resource, unlimited tablespace TO c##userB;

ORACLE 2PM KPHB MAY 2024 Page 93


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; Output:


ERROR: table does not exist

ORACLE 2PM KPHB MAY 2024 Page 94


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');
Open 2 SQL PLUS windows arrange them side by side
Output:

ORACLE 2PM KPHB MAY 2024 Page 95


INSERT INTO c##userA.t1
VALUES(3,'C'); Output:
ERROR: insufficient privileges

UPDATE c##userA.t1
SET f2='SAI' WHERE f1=1;
Output:
ERROR: insufficient privileges

DELETE FROM c##userA.t1 WHERE


f1=2; Output:
ERROR: insufficient privileges

GRANT insert, update, delete


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

DELETE FROM c##userA.t1


WHERE f1=2;
Output: 1 row deleted.

COMMIT;

ORACLE 2PM KPHB MAY 2024 Page 96


ALTER TABLE c##userA.t1 ADD f3
date; Output:
ERROR: insufficient privileges

GRANT all
ON t1
TO c##userB;

ALTER TABLE c##userA.t1 ADD f3


date; Output:
Table altered

DESC t1 Output:
F1
F2
F3

REVOKE insert, update, delete


ON t1
FROM c##userB;

INSERT => ERROR


DELETE => ERROR
UPDATE => ERROR

SELECT * FROM c##userA.t1;


-- displays data
REVOKE all
ON t1
FROM c##userB;

SELECT * FROM c##userA.t1;


--ERROR: table does not exist

ORACLE 2PM KPHB MAY 2024 Page 97


user_tab_privs_made user_tab_privs_recd

user_tab_privs_made:
• it is a system table / readymade table.
• it maintains all the permissions made by the GRANTOR.

DESC user_tab_privs_made

SELECT grantee, table_name, privilege FROM


user_tab_privs_made;

user_tab_privs_recd:
• it is a system table / readymade table.
• it maintains all the permissions received by the GRANTEE.

DESC user_tab_privs_recd

SELECT grantor, table_name, privilege


FROM user_tab_privs_recd;

ORACLE 2PM KPHB MAY 2024 Page 98


Copying tables and copying records
Saturday, June 1, 2024 2:09 PM

Copying table:

• Copying table means, Creating new table from existing table.

Syntax:

CREATE TABLE <table_name>


AS
<SELECT QUERY>;

With result of SELECT QUERY a new table will be created.

Example-1:

Create a new table with the name emp1 from existing table emp.
Create exact copy of emp:

exact copy
EMP EMP1
8 columns 8 columns 15 rows 15 rows

CREATE TABLE emp1


AS
SELECT * FROM emp;
Example-2:

Create a new table with the name emp2 from existing table emp
with 4 columns empno, ename, job, sal and managers records:

CREATE TABLE emp2


AS

ORACLE 2PM KPHB MAY 2024 Page 99


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

Copying table structure:

Syntax: false_condition:

1=2 F 'A'='B' F 500=600 F


CREATE TABLE <table_name> AS
SELECT <columns_list> / * FROM
<table_name>
WHERE <false_condition>;

Example-1:

Create a new table with the name emp3 with emp table structure.
Don't copy the records:

EMP3
EMP 8 columns
8 columns no rows
15 rows
CREATE TABLE emp3
AS
SELECT * FROM emp WHERE 1=2;

Example-2:

Create a new table with the name emp4 from existing emp
with 4 columns empno, ename, job, sal and without rows:

CREATE TABLE emp4


AS
SELECT empno, ename, job, sal

ORACLE 2PM KPHB MAY 2024 Page 100


FROM emp
WHERE 1=2;

Copying records:

Syntax:

INSERT INTO <table_name>


<SELECT QUERY>;

SELECT QUERY result will be inserted into table.

Example:

Copy all emp table rows to emp6:


EMP EMP6

8 columns copy 8 columns


15 rows NO ROWS

CREATE TABLE emp6


AS
SELECT * FROM emp
WHERE 1=2;

INSERT INTO emp6


SELECT * FROM emp;

Example-2:

ORACLE 2PM KPHB MAY 2024 Page 101


EMP EMP7
8 columns 4 columns => empno,ename,job,sal
15 rows no rows
MANAGER
rows
Copy all managers records from emp to emp7:

CREATE TABLE emp7


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

INSERT INTO emp7


SELECT empno,ename,job,sal
FROM emp
WHERE job='MANAGER';
INSERT ALL
Saturday, June 1, 2024 2:49 PM

INSERT ALL:
• Introduced in ORACLE 9i version.
• It is used to copy one table records to multiple tables.
• it avoids of writing multiple INSERT commands.
• it can be used to perform ETL operations
• E => Extract, T => Transfer, L => Load

• 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>[(<columns_list>)] VALUES(<values_list>)

ORACLE 2PM KPHB MAY 2024 Page 102


INTO <table_name>[(<columns_list>)] VALUES(<values_list>) INTO
<table_name>[(<columns_list>)] VALUES(<values_list>)
.
.
<SELECT QUERY>;

Example on Unconditional INSERT ALL:

EMP10
EMP
columns empno,ename,job,sal
columns copy
no
rows
15 rows copy

EMP11

15 rows
copy
EMP11
4 columns empno,ename,job,sal
copy no rows
create

EMP12
4 columns empn,ename,job,sal
no rows
emp10, emp11, emp12 from existing table emp with 4 columns empno,ename,job,sal

and without rows:

CREATE TABLE emp10


AS

ORACLE 2PM KPHB MAY 2024 Page 103


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

CREATE TABLE emp11 AS


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

CREATE TABLE emp12


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

Copy emp table 4 columns empn,ename,job,sal all rows to emp10, emp11, emp12 tables:

INSERT ALL
INTO emp10 VALUES(empno, ename, job, sal)
INTO emp11 VALUES(empno, ename, job, sal)
INTO emp12 VALUES(empno, ename, job, sal) SELECT empno, ename,
job, sal FROM emp;

Conditional INSERT ALL:

ORACLE 2PM KPHB MAY 2024 Page 104


Syntax:

Example on Conditional INSERT ALL:

EMP EMP_MGR
8 columns 4 cols empno,ename,job,sal

INSERT ALL
WHEN <condition> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>) WHEN
<condition> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>) WHEN
<condition> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
.
.
[ELSE
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)]
<SELECT QUERY>;

15 rows no rows
copy

MANAGER rows
CLERK rows copy EMP_CLERK
SALESMAN rows 4 cols empno,ename,job,sal
ANALYST rows no rows
PRESIDENT
copy
PRESIDENT
copy
EMP_OTHERS
4 cols empno,ename,job,sal
no rows

ORACLE 2PM KPHB MAY 2024 Page 105


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;

copy all managers recoords to emp_mgr all clerks records to emp_clerk other
than manager, clerk to emp_others:

INSERT ALL
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 empno,ename,job,sal FROM emp;

ORACLE 2PM KPHB MAY 2024 Page 106


MERGE
Monday, June 3, 2024 2:07 PM

S.cid = T.cid
Branch Office Head office

CID CNAME CCITY CID CNAME CCITY


MATCHED
1001 A ABC HYD BLR 1001 A HYD
UPDATE
1002 B MUM 1002 B MUM
1003 C DLH 1003 C DLH
1004 D CHN NOT MATCHED
1005 E HYD INSERT
CUSTOMER1 S CUSTOMER2 T=> Replica [duplicate copy]

MERGE:
• introduced in ORACLE 9i version.
• It is used to apply one table changes to it's replica.
• MERGE = UPSERT + INSERT
• MERGE is a combination of UPDATE and INSERT commands.
• It can be also called as UPSERT command.
• It avoids of writing a separate PL/SQL program.

Syntax:

MERGE INTO <target_table_name> <target_table_alias>


USING <source_table_name> <source_table_alias>
ON(<condition>)
S.cid = T.cid
WHEN matched THEN
UPDATE query
WHEN not matched THEN
INSERT query;

Example on MERGE:

CUSTOMER1 S CUSTOMER2 T Replica

ORACLE 2PM KPHB MAY 2024 Page 107


CID CNAME CCITY CID CNAME CCITY

1001 A ABC HYD BLR1001 A HYD

1002 B MUM 1002 B MUM

1003 C DLH
1003 C DLH

1004 D CHN

1005 E HYD
CREATE TABLE customer1
(
cid NUMBER(4), cname
VARCHAR2(10), ccity
CHAR(3)
);

INSERT INTO customer1 VALUES(1001,'A','HYD');


INSERT INTO customer1 VALUES(1002,'B','MUM');
INSERT INTO customer1 VALUES(1003,'C','DLH'); COMMIT;

create exact copy of customer1 with the name customer2:

CREATE TABLE customer2


AS
SELECT * FROM customer1;
1004 D CHN

1005 E HYD
INSERT INTO customer1 VALUES(1004,'D','CHN');
INSERT INTO customer1 VALUES(1005,'E','HYD');
COMMIT;

1001 A ABC HYD BLR


UPDATE customer1
SET cname='ABC', ccity='BLR'
WHERE cid=1001;
COMMIT;

Apply CUSTOMER1 table changes to CUSTOMER2:

ORACLE 2PM KPHB MAY 2024 Page 108


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.

ORACLE 2PM KPHB MAY 2024 Page 109


TRUNCATE and RENAME
Monday, June 3, 2024 3:04 PM

TRUNCATE:
• It is used to delete all rows from table with good performance.

• It does not delete table structure.


• Just, it deletes entire table data.

Example:
Table
CUSTOMER1 S
CID CNAME CCITY Table Structure [columns]
1001 ABC BLR
+
1002 B MUM
1003 C DLH Table Data [rows]
1004 D CHN
1005 E HYD

TRUNCATE = TRUNCATE + COMMIT

Syntax:
TRUNCATE TABLE <table_name>;

Example:
TRUNCATE TABLE customer1;

--all rows will be deleted permanently


--again we cannot recollect them

Using TRUNCATE command, we can delete all records.


Using DELETE command, we can delete all records.
What are the differences between TRUNCATE and DELETE?

TRUNCATE DELETE

• it is DDL command • it is DML command

• it is not auto committed


• It is auto committed.
TRUNCATE = TRUNCATE+COMMIT • it can delete single record or
specific group of records or all
records.
• it cannot delete single record or
specific group of records. Just it can
delete all records only. • WHERE clause can be used here.

• WHERE clause cannot be used here. • it can be rolled back. • slower

• It cannot be rolled back. • it deletes row by row

• faster

• it deletes block by block


[page by page]

DATABASE

ORACLE 2PM KPHB MAY 2024 Page 116


TABLESPACE

SEGMENT

EXTENT [64KB]

Block [8KB] Block [8KB]

--records --records

Block [8KB] Block [8KB]

--records --records

Block [8KB] Block [8KB]

--records --records

Block [8KB] Block [8KB]

--records --records

DATABASE
TABLESPACES
SEGMENTS
EXTENTS
BLOCKS
RECORDS

RENAME:
• It is used to rename the table.

Syntax:
RENAME <old_name> TO <new_name>;

Example:
RENAME emp TO e;
ORACLE 2PM KPHB MAY 2024 Page 117

DUAL
Tuesday, June 4, 2024 2:42 PM

DUAL:
• DUAL is a system table / readymade table / dummy table.
• It has 1 column and 1 row.

Example:
SQL> DESC dual Output:
NAME TYPE
--------------------------------
DUMMY VARCHAR2(1)

SQL> SELECT * FROM dual; Output:


DUAL
DUMMY
X
• when we want to work with non-table data or when we want to get 1
value as the result we use DUAL.

SELECT 100+200 FROM dual; Output:


300

SELECT 100+200 FROM emp;


Output: --15 300s => emp table has 15 rows

ORACLE 2PM KPHB MAY 2024 Page 118

300
300
300
..

In ORACLE 23ai, they made FROM clause as optional.

In ORACLE 23ai, we can write:

SQL> SELECT 100+200; Output:


300

SQL> SELECT lower('RAJU'); Output: raju

ORACLE 2PM KPHB MAY 2024 Page 119


Built-In Functions
Tuesday, June 4, 2024 2:12 PM

Built-In Functions / Predefined Functions / Readymade Functions:

• To make our actions easier ORACLE SOFTWARE DEVELOPERS already defined


some functions and placed them in ORACLE DB. These functions are called "Built-
In Functions".

• ORACLE SQL provides built-in functions. Those can be categorized as following:


○ String Functions
○ Conversion Functions
○ Aggregate Functions / Group Functions
○ Date Functions
○ Analytic Functions
○ Number Functions ○ Special Functions

String Functions:

Lpad()
Substr() Instr() Rpad()
lower() upper()
initcap() Replace()
Ltrim()
Rtrim() Translate()
length() concat()
Trim()

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

Syntax:
lower(<string>)
Examples:
lower('RAJU') raju

lower('RAJ KUMAR') raj kumar


SELECT lower('RAJU') FROM dual;

ORACLE 2PM KPHB MAY 2024 Page 114


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

Syntax: upper(<string>) Examples:


upper('raju') RAJU

upper('raj kumar') RAJ KUMAR


Initcap() [Initial Capital]:

It gives every word's starting letter as capital.

Syntax: initcap(<string>) Examples:


initcap('RAJU') Raju

initcap('RAJ KUMAR VARMA') Raj Kumar Varma


Examples:

Display all emp names and salaries. display emp names in lower case:

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


ENAME lower(ename)
---------- -----------------------
SMITH lower('SMITH') => smith
ALLEN lower('ALLEN') => allen
WARD lower('WARD') => ward
Modify all emp names to initcap case in emp table:

UPDATE emp
SET ename=initcap(ename);

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

SELECT * FROM emp


WHERE lower(ename)='blake';

ENAME WHERE lower(ename)='blake'


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

ORACLE 2PM KPHB MAY 2024 Page 115


• it is used to find length of the string.
• length of string => no of chars in string.

Syntax: length(<string>)

Examples:

length('RAJU') 4
length('RAVI TEJA') 9
Examples:

Display the emp records whose names are having 4 letters:

SELECT * FROM emp


WHERE length(ename)=4;

(or)

SELECT * FROM emp


WHERE ename LIKE '____';

Display the emp records whose names are having 14 letters:

SELECT * FROM emp


WHERE length(ename)=14;

Display the emp records whose names are having 6 or more letters:

SELECT * FROM emp


WHERE length(ename)>=6;

Concat():
• Concat => Concatenate / combine
• It is used to combine 2 strings

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

Examples:

ORACLE 2PM KPHB MAY 2024 Page 116


Concat('RAJ', 'KUMAR') RAJKUMAR

Concat('RAJ', 'KUMAR', 'VARMA') ERROR

Concat(Concat('RAJ', 'KUMAR'), 'VARMA') RAJKUMARVARMA


(or)
'RAJ' || 'KUMAR' || 'VARMA'
Example:

EMPLOYEE
EMPID FNAME MNAME LNAME

1001 RAJ KUMAR VARMA RAJ KUMAR VARMA


SACHIN RAMESH TENDULKAR
SACHIN RAMESH TENDULKAR

SELECT fname || ' ' || mname || ' ' || lname FROM employee;

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

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

Examples:
1 2 3 4 5 6 7 8 9
R A V I T E J A

Substr('RAVI TEJA', 6) TEJA

Substr('RAVI TEJA', 6, 3) TEJ

Substr('RAVI TEJA', 1, 4) RAVI

Substr('RAVI TEJA',3,4) VI T
2nd argument can be negative.
+ve from left side position number

-ve from right side position number


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

ORACLE 2PM KPHB MAY 2024 Page 117


1 2 3 4 5 6 7 8 9

substr('RAJ KUMAR',-4) UMAR

substr('RAJ KUMAR',-4,3) UMA

substr('RAJ KUMAR',-9,3) RAJ


Examples:

Display the emp records whose names are started with S:

SELECT ename, sal


FROM emp
WHERE substr(ename,1,1)='S';

(or)

SELECT ename, sal


FROM emp
WHERE ename LIKE 'S%';

Display the emp records whose names are started with VOWEL:

SELECT ename, sal


FROM emp
WHERE substr(ename,1,1) IN('A','E','I','O','U');
Display the emp records whose names are ended with RD:

SELECT ename, sal


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

(or)

SELECT ename, sal


FROM emp
WHERE ename LIKE '%RD';

Display the emp records whose names are started and ended with same letter:

SELECT ename, sal

ORACLE 2PM KPHB MAY 2024 Page 118


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

Display the emp records whose names are started and ended with
VOWEL:

SELECT ename,sal
FROM emp
WHERE substr(ename,1,1) IN('A','E','I','O','U') AND substr(ename,-1,1)
IN('A','E','I','O','U');

generate mail ids to all emps by taking emp name's first 3 chars and
empno's last 3 chars as username for the domain 'wipro.com':

EMPNO ENAMe MAIL_ID

7369 SMITH

7499 ALLEN
Add mail id column:

ALTER TABLE emp


ADD mail_id VARCHAR2(30);

generate mail ids:

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

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

Syntax:

ORACLE 2PM KPHB MAY 2024 Page 119


Instr(<string>, <sub_string>, [<search_position>, <occurrence>])
3rd argument search position default value is 1

4th arg occurrence default value is 1


Examples:
1 2 3 4 5 6 7 8 9 10 11
S A I K R I S H N A

Instr('SAI KRISHNA','KRISH') 5

Instr('SAI KRISHNA','RAMU') 0
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

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

Instr('THIS IS HIS WISH','IS',1,2) 6


Instr('THIS IS HIS WISH','IS',4,2) 10

Instr('THIS IS HIS WISH','IS',4,4) 0

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


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
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

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

Instr('THIS IS HIS WISH','IS',-1,3) 6

Instr('THIS IS HIS WISH','IS',-4) 10

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


Examples:

Display the emp records whose names are having AM letters:

SELECT ename, sal


FROm emp
WHERE Instr(ename,'AM')>0;

Example:

ORACLE 2PM KPHB MAY 2024 Page 120


EMPLOYEE17

EMPNO ENAME FNAME LNAME

1001 RAVI TEJA RAVI TEJA

1002 SAI KRISHNA SAI KRISHNA

1003 VIJAY KUMAR VIJAY KUMAR


CREATE TABLE employee17
(
empno NUMBER(4), ename VARCHAR2(20) );

INSERT INTO employee17 VALUES(1001,'RAVI TEJA');


INSERT INTO employee17 VALUES(1002,'SAI KRISHNA');
INSERT INTO employee17 VALUES(1003,'VIJAY KUMAR');
COMMIT;

ADD fname and lname columns:

ALTER TABLE employee17


ADD(fname VARCHAR2(10), lname VARCHAR2(10));

UPDATE employee17
SET fname=Substr(ename,1,Instr(ename,' ')-1),
lname=Substr(ename,Instr(ename,' ')+1);

Lpad() and Rpad():

• pad => fill

Lpad():
it is used to fill specified character set at left side

Syntax:
Lpad(<string>, <size> [, <char_set>]) char_set => char / chars
3rd arg default char => space
Rpad():
it is used to fill specified character set at right side

ORACLE 2PM KPHB MAY 2024 Page 121


Syntax:
Lpad(<string>, <size> [, <char_set>]) char_set => char / chars
3rd arg default char => space
Examples:
Lpad('RAJU',10,'*') ******RAJU

Rpad('RAJU',10,'*') RAJU******

Lpad('SAI',10,'@$') @$@$@$@SAI

Lpad('raju',8) 4spacesraju

Rpad('raju',8) raju4spaces

Lpad('A',6,'A') AAAAAA

Lpad('X',8,'X') XXXXXXXX
Example:
Display message as following:
amount debited from acno XXXXXX7890 acno => 1234567890

SELECT 'amount debited from acno ' || Lpad('X',6,'X') ||


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

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

• trim => remove

Ltrim():
• it is used to remove unwanted characters from left side.

Syntax:
Ltrim(<string> [, <char/chars>])
2nd arg default char => space
Rtrim():
• it is used to remove unwanted characters from right side.
Syntax:
Rtrim(<string> [, <char/chars>])
2nd arg default char => space
Examples:
Ltrim('@@@RAJU@@@','@') RAJU@@@

ORACLE 2PM KPHB MAY 2024 Page 122


Rtrim('@@@RAJU@@@','@') @@@RAJU

Ltrim(' RAJU ') RAJU3spaces

Rtrim(' RAJU ') 3spacesRAJU


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

Syntax:
Trim(Leading/Trailing/Both <char> FROM <string>) Examples:
Trim(Leading '*' FROM '***RAJU***') RAJU***

Trim(Trailing '*' FROM '***RAJU***') ***RAJU

Trim(Both '*' FROM '***RAJU***') RAJU


(or)
Trim('*' FROM '***RAJU***')
default side: BOTH default char: space
Trim(' RAJU ') RAJU
Replace() and Translate():

Replace():
• It is used to replace search string with replace string.
Syntax:
Replace(<string>, <search_string>, <replace_string>) Examples:
Replace('RAVI TEJA', 'TEJA', 'KUMAR') RAVI KUMAR

Replace('RAVI TEJA', 'RAVI', 'SAI') SAI TEJA

Replace('RAVI TEJA RAVI TEJA RAVI','RAVI','SAI') SAI TEJA SAI TEJA SAI
Translate():
• it is used replace search char with corresponding char in replace char set.

Syntax:
Translate(<string>, <search_char_set>, <replace_char_set>) Examples:
REPLACE('SAI KRISHNA','SAI','XYZ') XYZ KRISHNA

TRANSLATE('SAI KRISHNA','SAI','XYZ') XYZ KRZXHNY

S => X
A => Y
I => Z

Replace() it replaces the strings

Translate() it replaces the chars

ORACLE 2PM KPHB MAY 2024 Page 123


• translate() can be used to encrypt or decrypt the data.

cipher text normal text


normal text

hello @ZQQ$
hello
encryption

Display all emp names and salaries. encrypt salary as following:


0 1 2 3 4 5 6 7 8 9

@ Z W # $ Q ^ * B Y
SELECT ename,
translate(sal, '0123456789','@ZW#$Q^*BY') AS sal FROM emp;

Note:
There are 2 types of conversions. They are:
• Implicit Conversion
• Explicit Conversion

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

Example:
SELECT '100' + '200' FROM dual;
string string
implicit conversion
100 + 200 num num
Output:
300

Don't depend on Implicit Conversion. It degrades the performance.

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

ORACLE 2PM KPHB MAY 2024 Page 124


• to_char()
• to_date()

FORMAT PURPOSE EXAMPLE OUTPUT


sysdate: 7-JUN-24

YYYY year 4 digits to_char(sysdate,'YYYY') 2024

YY year last 2 digits to_char(sysdate,'YY') 24

YEAR / year in words to_char(sysdate,'YEAR') TWENTY TWENTY-FOUR


year to_char(sysdate,'year')
twenty twenty-four

MM month number to_char(sysdate,'MM') 06

ORACLE 2PM KPHB MAY 2024 Page 125


MON / short month name to_char(sysdate,'MON') JUN
mon to_char(sysdate,'mon')
jun

• to_number()
to_char()
to_char()

DATE CHAR NUMBER

to_date() to_number()

TO_Char() [date to char]:

• it can be used to convert date to char [string].

• to change date formats or to extract part of the date we need to convert date to char
[string].

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

ORACLE 2PM KPHB MAY 2024 Page 126


MONTH full month name to_char(sysdate,'MONTH') JUNE

D day num in week to_char(sysdate,'D') 6

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

DD day num in month to_char(sysdate,'DD') 07

DDD day num in year to_char(sysdate,'DDD') 159

31+29+31+30+31+7 = 159
DY short weekday name to_char(sysdate,'DY') FRI

SUN

DAY full weekday name to_char(sysdate,'DAY') FRIDAY

SUNDAY

Q quarter num to_char(sysdate,'Q') 2

1 => jan-mar
2 => apr-jun
3 => jul-sep
4 =>oct-dec

CC century num to_char(sysdate,'CC') 21

HH / HH12 hrs in 12hrs format

HH24 hrs in 24 hrs format

MI minutes part

ORACLE 2PM KPHB MAY 2024 Page 127


SS Seconds part

FF fractional seconds

ORACLE 2PM KPHB MAY 2024 Page 128


AM / PM AM or PM

Display current system date:

SELECT sysdate FROM dual;

Display today's date in INDIA date format:

SELECT to_char(sysdate,'DD/MM/YYYY') FROM dual; Display current system time

from sysdate:

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

Display current system time from sysdate in 24 hrs format:

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

Display all emp names and hiredates. Display hiredates in INDIA date format:

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

Display all emp names and hiredates. Display hiredates in US date format:

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

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

ORACLE 2PM KPHB MAY 2024 Page 129


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

Display the emp records who joined in 1980,1982, 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 to_char(hiredate,'MON')='DEC';

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

SELECT ename, hiredate


FROM emp
WHERE to_char(hiredate,'MM') IN(1,5,12);

Display the emp records who joined in 4th quarter:

SELECT ename, hiredate


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

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, DY, DAY

ORACLE 2PM KPHB MAY 2024 Page 130


1 SUN SUNDAY

SELECT ename, hiredate


FROM emp
WHERE to_char(hiredate,'D')=1; --displays who joined on SUNDAY

(or)
SELECT ename, hiredate
FROM emp
WHERE to_char(hiredate,'DY')='SUN'; ----displays who joined on SUNDAY

SELECT ename, hiredate


FROM emp
WHERE to_char(hiredate,'DAY')='SUNDAY'; --no rows selected
SUNDAY3spaces = SUNDAY FALSE

For every weekday 9 chars will be returned

SUNDAY3spaces
MONDAY3spaces
TUESDAY2spaces
WEDNESDAY max string length => 9
THURSDAY1space
FRIDAY3spaces
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 = SUNDAY3spaces T

Display the emp records who joined in DECEMBER month:

ORACLE 2PM KPHB MAY 2024 Page 131


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

SELECT ename, hiredate


FROM emp
WHERE to_char(hiredate,'MONTH')='DECEMBER'; DECEMBER1space =
DECEMBER FALSE no rows selected

SELECT ename, hiredate


FROM emp
WHERE RTRIM(to_char(hiredate,'MONTH'))='DECEMBER';
RTRIM(DECEMBER1space)
DECEMBER = DECEMBER TRUE

To_Char() [numbner to char]:

• It can be used to convert number to char [string].

• to apply currency symbol, thousand separator, decimal point, decimal places we need to
convert number to char.

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

L currency symbol
default currency symbol is: $
C currency name
default currency name is: USD

. (or) D decimal point

, (or) G Thousand separator

9 Digit

ORACLE 2PM KPHB MAY 2024 Page 132


Examples:
To_Char(123) '123'

To_Char(123.45) '123.45'

To_Char(5000, 'L9,999.99') '$5,000.00'

To_char(5000,'C9999.99') USD5000.00
Display all emp names and salaries.
Apply currency symbol $, thousand separator and 2 decimal places to all salaries:

SELECT ename, to_char(sal, 'L99999.99') AS sal FROM emp;

Display all emp names and salaries.


Apply currency sname USD and 2 decimal places to all salaries:

SELECT ename, to_char(sal, 'C99999.99') AS sal FROM emp;

Note:
NLS_CURRENCY $

NLS_ISO_CURRENCY AMERICA
Display all emp names and salaries.
Apply currency symbol ¥, thousand separator and 2 decimal places to all salaries:

SELECT ename, to_char(sal, 'L99,999.99', 'nls_currency=¥') AS sal


FROM emp;

Display all emp names and salaries.


Apply currency name JPY, thousand separator and 2 decimal places to all salaries:

SELECT ename, to_char(sal, 'C99,999.99', 'nls_iso_currency=JAPAN') AS sal FROM emp;

To_Date():

ORACLE 2PM KPHB MAY 2024 Page 133


• It is used to convert string to date.
• It is used to insert date values.

Syntax:
To_Date(<string> [, <format>]) Examples:
To_Date('25-DEC-2023') 25-DEC-23

To_Date('25 DECEMBER 2023') 25-DEC-23

To_Date('DECEMBER 25 2023') ERROR

To_Date('DECEMBER 25 2023','MONTH DD YYYY') 25-DEC-23

To_Date('25/12/2023') ERROR

TO_Date('25/12/2023','DD/MM/YYYY') 25-DEC-23
Example:

CREATE TABLE t1(f1 DATE);

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


string

F1 DATEimplicit conversion
---------
F1 DATEimplicit conversion
---------
25-DEC-23 date

INSERT INTO t1 VALUES(to_date('17-AUG-2022'));


string

F1 DATE
--------------- to_date()
17-AUG-22 date explicit
conversion

INSERT INTO t1 VALUES(to_date('27/10/2023')); --ERROR

INSERT INTO t1 VALUES(to_date('27/10/2023','DD/MM/YYYY'));


string

ORACLE 2PM KPHB MAY 2024 Page 134


F1
----------
27-OCT-23 date

INSERT INTO t1 VALUES(to_date('&d/&m/&y','DD/MM/YYYY')); Output:


enter value for d: 17 enter value for m:2 enter
value for y:2020

/
enter value for d: .. enter value for m:..
enter value for y:.. to_char(sysdate, 'YYYY') => 2024

date

to_char('25-DEC-2023','YYYY') => ERROR


string

to_char(to_date('25-DEC-2023'),'YYYY') => 2023


date

Find today's weekday:

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

Find the weekday on which INDIA got Independence?

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

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

Find the weekday on which SACHIN born if SACHIN DOB is: 24-APR-1973?

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

ORACLE 2PM KPHB MAY 2024 Page 135


To_Number():
• This function is used to convert string to number.
• string must be numeric string.

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

Examples:
To_Number('123') 123

To_Number('123.45') 123.45

To_Number('$5,000.00') ERROR

To_Number('$5,000.00','L9,999.99') 5000

To_Number('USD5000.00','C9999.99') 5000
Aggregate Functions / Group Functions / Multi Row Functions:

sum(f1) 10+20+30 = 60
F1
----- avg(f1) 60/3 = 20
10
max(f1) 30
20
30 min(f1) 10

count(f1) 3

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

Syntax: sum(<column>)

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 30:


SELECT sum(sal) FROM emp WHERE deptno=30;

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

ORACLE 2PM KPHB MAY 2024 Page 136


Syntax: avg(<column>)

Examples:
find avrg salary of all emps
SELECT avg(sal) FROM emp;

find avrg sal of all managers:


SELECT avg(sal) FROM emp
WHERE job='MANAGER';

find avrg salary of deptno 30:


SELECT avg(sal) FROM emp WHERE deptno=30;

max():
• it is 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 all managers:


SELECT max(sal) FROM emp WHERE job='MANAGER';

min():
• it is used to find min value in a set of values.

Syntax: min(<column>)

Examples:
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';

count():
• it is used to find number of records or number of column values.

Syntax:

ORACLE 2PM KPHB MAY 2024 Page 137


count(* / <column>)
Examples:
find no of records in emp table: SELECT count(*) FROM emp;

find number of managers in emp table:


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

find no of emps of deptno 30:


SELECT count(*) FROM emp WHERE deptno=30;

find how many emps are getting commission: SELECT count(comm) FROM emp;

what is the difference b/w count(*) and count(<column>):


count(*) finds no of records

count(<column>) finds no of column values


count(*) finds no of records count(<any_number> finds no of records what is the difference
b/w count(*) and count(<any_number>)?

count(*) => 18 count(8) => 18 count(25) => 18


count(100) => 18

count(*) counts number of records


slower

count(8) counts number of 8s faster

Note:
When we use GROUP FUNCTION, SELECT clause allows either group functions or group
columns
Example:
SELECT ename, max(sal) FROM emp; Output:
ERROR

Date Functions:

sysdate systimestamp Add_Months()


Last_Day()

ORACLE 2PM KPHB MAY 2024 Page 138


Next_Day()
Months_Between()

sysdate:
• it returns current system date

Example:
Display current system date:
SELECT sysdate FROM dual;

systimestamp:
• it returns current system date and time

Example:
Display current system date and time: SELECT systimestamp FROM dual;

Add_Months():
• it is used to add months to specific date.
• it can be also used to subtract months from date.

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

Examples:
Add 2 days to today's date:
SELECT sysdate+2 FROM dual;

Add 2 months to today's date:


SELECT Add_Months(sysdate,2) FROM dual;

Add 2 years to todays'date:


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

Subtract 2 days from today's date:


SELECT sysdate-2 FROM dual;

Subtract 2 months from today's date: SELECT Add_Months(sysdate,-2) FROM dual;

Subtract 2 years from todays'date:


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

ORACLE 2PM KPHB MAY 2024 Page 139


Examples:
ORDERS
ORDERID pid qty price Ordered_Date Delivery_Date

123456 1234 1 500.00 sysdate sysdate+5


PRODUCTS
PID PNAME MANUFACTURED_DATE EXPIRY_DATE

1234 XYZ sysdate Add_Months(sysdate,3)


CMS_LIST
STATE CM_NAME STARTDATE ENDDATE

TS RR 10-DEC-23 Add_Months(startdate,5*12)
EMP
EMPID ENAME DOB DOR

1234 A 25-DEC-2000 Add_Months(DOB,60*12)


Note:
INSERT INTO emp(empno,ename,hiredate) VALUES(9001,'AA',sysdate);

INSERT INTO emp(empno,ename,hiredate) VALUES(9002,'BB',sysdate-1);

INSERT INTO emp(empno,ename,hiredate)


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

INSERT INTO emp(empno,ename,hiredate) VALUES(9004,'DD',Add_Months(sysdate,-12));

Note: to remove time value from date and time we use TRUNC() function.

Example:
SELECT systimestamp FROM dual; Output:
10-JUN24 3:41:15.123456 PM

SELECT TRUNC(systimestamp) FROM dual; Output:


10-JUN24

Display the emp records who joined today:

SELECT ename, hiredate FROM emp


WHERE hiredate=sysdate;
10-JUN-24 3:34 PM = 10-JUN-24 3:43 PM FALSE Output: no rows selected

SELECT ename, hiredate FROM emp

ORACLE 2PM KPHB MAY 2024 Page 140


WHERE TRUNC(hiredate)=TRUNC(sysdate);
TRUNC(10-JUN-24 3:34 PM) = TRUNC(10-JUN-24 3:43 PM)
10-JUN-24 = 10-JUN-24 TRUE Output: displays emp
records who joined today:

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:

SELECT ename, hiredate


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

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

SELECT ename, hiredate


FROM emp
WHERE TRUNC(hiredate) = TRUNC(Add_Months(sysdate,-12));

Assignment:

GOLDRATES

ORACLE 2PM KPHB MAY 2024 Page 141


DATEID PRICE
find today's gold rate? find yesterday's gold rate? find 1
1-JAN-2020 50000 month ago gold rate? find 1 year ago gold rate?

2-JAN-2020 51000

..

..
SALES
11-JUN-2024 69000
DATEID AMOUNT find today's sales? find
yesterday's sales? find 1 month ago sales? find 1 year
1-JAN-2020 70000
ago sales?
Last_day(): 2-JAN-2020 90000
• it is used to get last date in the month.
..
Syntax:
..
Last_day(<date>)
Examples:
11-JUN-2024 86000

Last_Day(sysdate) 30-JUN-24

Last_Day('25-FEB-2023') 28-FEB-23

Last_Day('17-FEB-2024') 29-FEB-24
Find next month first date:

SELECT Last_day(sysdate)+1 FROM dual;


30-JUN-24+1
1-JUL-24

Find current month first date:

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


Last_day(11-MAY-24)
31-MAY-24+1 1-JAN-24

Next_day():
• it is next date based on weekday.
• for example, to find coming Sunday date, coming Friday date

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

Examples:

ORACLE 2PM KPHB MAY 2024 Page 142


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;

Find current month last Sunday date:


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

Months_Between():
• it is used to find difference between 2 date values.
• it returns no of months.

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

Examples:
SELECT Months_Between('11-JUN-2024','11-JUN-2023') FROM dual; Output:
12

Find experience of all emps:

SELECT ename, hiredate,


Trunc(months_between(sysdate,hiredate)/12) AS experience
FROM emp;

(or)

SELECT ename, hiredate,


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

Find experience in the form of years and months:


years months
15 months 12)15(1
1 3
30 months 12
2 6
--------------

ORACLE 2PM KPHB MAY 2024 Page 143


3
SELECT ename, hiredate,
TRUNC(months_between(sysdate,hiredate)/12) AS years,
MOD(trunc(months_between(sysdate,hiredate)),12) AS months
FROM emp;

calculate age of SACHIN if SACHIN date of birth is: 24-APR-1973

SELECT
TRUNC(months_between(sysdate,'24-APR-1973')/12) AS age FROM dual;

Analytic Functions / Window Functions:

RANK()
DENSE_RANK()
ROW_NUMBER()

RANK():
• it is used to apply ranks to records according to specific column order.

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

DENSE_RANK():
• it is used to apply ranks to records according to specific column order.

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

ORACLE 2PM KPHB MAY 2024 Page 144


560 950 1 1

780 950 1 1

950 840 3 2

840 840 3 2

400 780 5 3

950 780 5 3

780 780 5 3

840 600 8 4

600 560 9 5

780 400 10 6
difference b/w RANK() and DENSE_RANK():

RANK() does not follow sequence in ranking if multiple values are same. gaps may be
there in ranking.

DENSE_RANK() always follows sequence in ranking even if multiple values are same. gaps
will not be there in ranking

DENSE => NO GAPS

Examples:

Apply ranks to emp records according to salary descending order:

SELECT ename, sal,


Rank() OVER(ORDER BY sal DESC) AS rank FROM emp;

(or)

SELECT ename, sal,


Dense_Rank() OVER(ORDER BY sal DESC) AS rank
FROM emp;
Apply ranks to records according to seniority. give top rank to most
senior:

ORACLE 2PM KPHB MAY 2024 Page 145


hiredate ORDER BY hiredate ASC
---------------
25-DEC-2023 17-FEB-2020 1
17-FEB-2020 15-AUG-2022 2
15-AUG-2022 25-DEC-2023 3
SELECT ename, hiredate,
DENSE_RANK() OVER(ORDER BY hiredate ASC) AS rank
FROM emp;

Apply ranks to all emp records according to salary descending order. if salary is same don't
apply same rank. if salary is same apply rank according to seniority:

SELECT ename, sal, hiredate,


dense_rank() over(ORDER BY sal DESC, hiredate ASC) AS rank FROM emp;

Apply ranks to emp records according to salary descending order with in dept:

break on deptno skip 1 duplicates

SELECT ename,deptno,sal,
dense_rank() over(partition by deptno order by sal desc) as rank FROM emp;

clear breaks

PARTITION BY clause:
it is used to group the records according to specific column.
ORDER BY clause:
it is used to arrange the records in ascending or descending order.

Apply ranks to emp records according to salary descending order with in job:

break on job skip 1 duplicates

SELECT ename, job, sal,


dense_rank() over(partition by job order by sal desc) as rank FROM emp;

clear breaks

ORACLE 2PM KPHB MAY 2024 Page 146


Row_Number():
• it is used to apply row numbers to records.
• row numbers will be applied on result of select query.

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

Examples:
Display all empnos, emp names and salaries.
Apply row numbers to them according to empno ascending order:

SELECT row_number() over(order by empno asc) AS sno, empno, ename, sal


FROM emp;

Display all managers rercords. apply row numbers to them:

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


FROM emp
WHERE job='MANAGER';
Number Functions:

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

trunc() round()

power():
• it is used to find power value

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


power(2,3) 8

power(5,2) 25
sqrt():
• it is used to find square root value

ORACLE 2PM KPHB MAY 2024 Page 147


Syntax: sqrt(<number>) Examples:
sqrt(100) 10

sqrt(25) 5
abs():
• it is used to get absolute value
• absolute value => non-negative value Syntax: abs(<number>) Examples:
abs(25) 25

abs(-25) 25
sign():
• it is used to check whether the given number is +ve or -ve or 0.

Syntax: sign(<number>) Examples:


sign(20) 1

sign(-20) -1

sign(0) 0
Mod():
• it is used to get remainder value

Syntax:
Mod(<number>, <divisor>) Examples:
Mod(5,2) 1

Mod(10,7) 3
ceil():
• it is used to get round up value

Syntax: ceil(<number>)

floor():
• it is used to get round down value
Syntax: floor(<number>) Examples:
ceil(456.789) 457

floor(456.789) 456
Trunc():
• it is used to remove the decimal places

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

ORACLE 2PM KPHB MAY 2024 Page 148


Trunc(123.6789) 123

Trunc(123.6789, 1) 123.6

Trunc(123.6789, 2) 123.67

Trunc(123.6789, 3) 123.678
2nd argument can be -ve. if 2nd argument is -ve, it does not give decimal places.
-1 rounds in 10s 10 20 30 40 …. 100, 110, 120, ….

-2 rounds in 100s 100 200 300 ……

-3 rounds in 1000s 1000 2000 3000 4000 …..

TRUNC(567.789,-1) 560 and 570


560

TRUNC(785.4567,-1) 780 and 790


780

TRUNC(785.4567,-2) 700 and 800


700

TRUNC(5678.4567,-3) 5000 and 6000


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

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

ORACLE 2PM KPHB MAY 2024 Page 149


TRUNC(256.789) 256 and 257
256
256+257 = 513 513/2 = 256.5
ROUND(256.789) 256 and 257
avrg: 256.5
257

TRUNC(256.345) 256 and 257


256

ROUND(256.345) 256 and 257


avrg: 256.5
256

TRUNC(256.5) 256 and 257


256

ROUND(256.5) 256 and 257


avrg: 256.5
257
Difference b/w TRUNC and ROUND():
TRUNC() does not consider avrg it
always gives lower value

ROUND() it considers avrg if value is avrg or above avrg it gives


upper value. if value is below avrg, it gives lower value.

TRUNC(123.6789,1) 123.6

ROUND(123.6789,1) 123.7
TRUNC(123.6789,2) 123.67

ROUND(123.6789,2) 123.68

TRUNC(123.6749,2) 123.67

ROUND(123.6749,2) 123.67
2nd argument can be -ve. if 2nd arg is -ve, it does not give decimal places.
-1 rounds in 10s

-2 rounds in 100s

-3 rounds in
1000s
TRUNC(157.6789,- 150
1) and
160
150

ORACLE 2PM KPHB MAY 2024 Page 150


ROUND(157.6789,- 150
1) and
160
avrg:
155
160
TRUNC(157.6789,- 100
2) and
200
100
ROUND(157.6789,- 100
2) and
200
avrg:
150
200
TRUNC(127.6789,- 100
2) and
200
100
ROUND(127.6789,- 100
2) and
200
avrg:
150
100
Special Functions:

USER UID

NVL()
NVL2()

GREATEST()
LEAST()

DECODE()

USER:
• it returns current user name.

ORACLE 2PM KPHB MAY 2024 Page 151


UID:
• it returns user id.

Example: display current user name:

SELECT user FROM dual;


(or)
SHOW USER

display current user id and name:

SELECT uid, user FROM dual;

NVL():
• NVL() function is used to replace null with other value.
• If arg1 is not null, it returns arg1
• If arg1 is null, it returns arg2

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

Examples:
NVL(100,200) 100

NVL(null,200) 200
Calculate total salary of all emps:

SELECT ename, sal, comm, sal+NVL(comm,0) AS "TOTAL SALARY" FROM emp;

Display all emp ames, salaris and comm values.


If comm is null replace it with N/A

SELECT ename, sal,


NVL(to_char(comm),'N/A') AS comm
FROM emp;

Assignment:

ORACLE 2PM KPHB MAY 2024 Page 152


SID SNAME M1 replace nulls with ABSENT

1001 A 70

1002 B NVL(to_char(m1),'ABSENT')

1003 C 66

1004 D 50

1005 E

1006 F 0

Note:
NVL() can replace nulls only. it cannot replace not nulls.

NVL2():
• NVL2() function can replace nulls and not nulls.
• if arg1 is not null, returns arg2.
• if arg1 is null, it returns arg3.

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

Examples:
NVL2(100,200,300) 200

NVL2(null,200,300) 300
Differences b/w NVL() and NVL2():
NVL() •it can replace nulls only
•it can take 2 arguments

NVL2() •it can replace nulls and not nulls


•it can take 3 arguments
Modify commission values as following:
if emp is getting commission, increase 1000 rupees commission. if emp is not getting
commission, then set comm as 800.

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

ORACLE 2PM KPHB MAY 2024 Page 153


Max():
• it is used to find max value
• it is used to find max value in vertical values

Syntax: max(<column>)

Find max sal:


SELECT max(Sal) FROM emp;

Greatest():
• It is used to find max value in horizontal values.

Syntax:
Greatest(<value1>, <v2>, …………)

Examples:
Greatest(10,20,30) 30

Greatest(1,5,9,2,4,3) 9
Example:

T1
max is multi row function
F1 F2 F3
45 78 66
34 29 92 max(f3) => 92
71 50 81

greatest is single row function


T1
Greatest(f1,f2,f3)
F1 F2 F3
-----------------------------
45 78 66 Greatest(45,78,66) => 78
Greatest(34,29,92) => 92
34 29 92 Greatest(71,50,81) => 81
71 50 81

Differences between Max() and Greatest():

Max() Greatest()

ORACLE 2PM KPHB MAY 2024 Page 154


• is used to find max value in • is used to find max value in
vertical values. horizontal values.

• Multi Row Function • Single Row Function

• it can take 1 argument • it can take variable length arguments

Least():
• it is used to find minimum value in horizontal values.

Syntax:
Least(<value1>, <v2>, ……..)

Examples:
Least(10,20,30) 10

Least(1,6,5,8,7,2,3) 1
T1
F1 F2 F3
45 78 66
34 29 92
71 50 81
min(f3)

T1
Least(f1,f2,f3)
F1 F2 F3
------------------------
45 78 66 45
29
34 29 92
50
71 50 81

DECODE():
• it is used to implement "if" control structure in SQL.
• it can check equality condition only.

Syntax:
DECODE(<column>,
<value1>, <return_expression1>, <value2>, <return_Expression2>,

ORACLE 2PM KPHB MAY 2024 Page 155


.
.
<Else_Expression>);

Example:

Display all emp records along with job titles.


If job is PRESIDENT, display it as BIG BOSS.
If job is MANAGER, display it as BOSS. For others, display as EMPLOYEE.

SELECT ename,
DECODE(JOB,
'PRESIDENT','BIG BOSS',
'MANAGER', 'BOSS', 'EMPLOYEE') AS job, sal
FROM emp;
String lower() upper() initcap()
Substr() Instr() Lpad()
Rpad()
Ltrim() Rtrim() Trim() length()
concat()

Conversion to_char() to_number() to_date()

Aggregate / max() min() count() sum() avg()


Group /
Multi row

Date Add_Months() sysdate systimestamp


last_day() next_day() months_between()

Analytic rank() dense_rank() row_number()

Number ceil() floor() trunc() round() mod()

Special NVL() NVL2() Greatest() Least() user


Decode()

ORACLE 2PM KPHB MAY 2024 Page 156


Built -In Functions

Multi Row
Single Row
Functions
Functions

aggregate functions
String
Number
Analytic
Date
.
.

Single row function: if 1 function call is applied on 1 row then it is


called "Single row function"
Multi row function:
If 1 function call is applied on multiple rows then it is called multi row function

ENAME LOWER(ENAME)
---------------- ------------------------
SMITH LOWER('SMITH') => smith
ALLEN LOWER('ALLEN') => allen
WARD LOWER('WARD') => ward

SAL MAX(SAL)
--------
5000 9000
9000
8000

ORACLE 2PM KPHB MAY 2024 Page 157


CLAUSES
Thursday, June 13, 2024 3:31 PM

CLAUSES:

SQL ENGLISH
QUERIES SENTENCES CLAUSES WORDS

CLAUSE:
• CLAUSE is a part of query.
• Every query is made up of with clauses.
• Every clause has specific purpose.

Syntax of SELECT command:

SELECT [ALL/DISTINCT] <columns_list> / *


FROM <table_name>
[WHERE <condition>]
[GROUP BY <grouping_column_list>]
[HAVING <group_condition>]
[ORDER BY <column> ASC/DESC, <column> ASC/DESC, ….]
[OFFSET <number> ROW/ROWS]
[FETCH FIRST/NEXT <number> ROW/ROWS ONLY];

SELECT command clauses are:

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

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

SELECT ename, sal


FROM emp

ORACLE 2PM KPHB MAY 2024 Page 158


WHERE sal>2500;

SELECT clause It is used to specify columns list Example:


SELECT ename, sal

FROM clause It is used to specify table names Examples:


FROM emp
FROM emp, dept

WHERE clause It is used to specify filter condition.


WHERE condition will be applied on row.
It filters the rows.
Example:
WHERE sal>2500

ORDER BY clause:
• It is used to arrange the records in ascending or descending order.
• default order is: ASC

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

Example:
ORDER BY sal DESC

NUMBER CHAR DATE

ASC DESC ASC ASC


DESC DESC
1 10 A 1-JAN-24
2 9 B Z 2-JAN-24 31-DEC-24
3 8 . Y . 30-DEC-24
. . . . . .
. . Z . 31-DEC-24 .
10 1 A 1-JAN-24
Examples on ORDER BY:

Display all emp names and salaries. arrange them in descending order
according to salary:

SELECT ename, sal


FROM emp

ORACLE 2PM KPHB MAY 2024 Page 159


ORDER BY sal DESC;
(or) * All COlumns
SELECT ename, sal
FROM emp * = empno,ename,job,mgr,hiredate,sal,comm,deptno
ORDER BY 2 DESC;
(or)
SELECT *
FROM emp
ORDER BY 6 DESC;

Display all emp names and salaries. arrange them in alphabetical order
according to emp names:

SELECT ename, sal


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

Display all emp records.


arrange them according to seniority. display senior record first:

SELECT ename, hiredate


FROM emp
ORDER BY hiredate ASC;

Display all emp records.


arrange them in ascending order according to deptno:
break on deptno skip 1 duplicates

SELECT ename, deptno, sal


FROM emp
ORDER BY deptno ASC;

ORACLE 2PM KPHB MAY 2024 Page 160


Display all emp records.
Arrange them in ascending order according to deptno. Within dept arrange salaries in descending order:

SELECT ename, deptno, sal


FROM emp
ORDER BY deptno ASC, sal DESC;

CASE-1: deptnos are different if deptnos are different it will not check salary

20 10
10 20

CASE-2: deptnos are same if deptnos are same then only it checks salary

10 3000 10 4000
10 4000 10 3000

Display all emp records.


Arrange them in ascending order according to deptno. Within dept arrange them according to seniority. display
senior record first with in dept:

SELECT ename, deptno, sal, hiredate


FROM emp
ORDER BY deptno ASC, hiredate ASC;

Display all emp records.


Arrange them in ascending order according to deptno. Within dept arrange salaries in descending order.
if salary is same arrange according to seniority:

SELECT ename, deptno, sal, hiredate


FROM emp
ORDER BY deptno ASC, sal DESC, hiredate ASC;

ORACLE 2PM KPHB MAY 2024 Page 161


SAL ORDER BY sal ASC ORDER BY sal DESC
------- --------------------------------- --------------------------------
8000 5000 null
9000 null 6000 9000
5000 6000 8000 9000 8000 6000
null 5000

Display all emp names and salaries.


arrange then in descending order according to salary. Display nulls last:

SELECT ename, sal


FROM emp
ORDER BY sal DESC NULLS LAST;

Display all emp names and salaries.


arrange then in ascending order according to salary. Display nulls first:

SELECT ename, sal


FROM emp
ORDER BY sal ASC NULLS FIRST;

GROUP BY clause:
• It is used to group the records according to specific column or columns.
• On group of records we apply aggregate function.
• It is used to get summarized data from detailed data.
• It can be used for data analysis.

Example: GROUP BY deptno EMP detailed data summarized data

EMPNO ENAME SAL DEPTNO DEPTNO SUM_OF_SAL

1001 A 10000 20 10 50000

1002 B 20000 20 20 30000

1003 C 5000 30 30 15000

1004 D 10000 30

1005 E 30000 10

1005 F 20000 10
Examples on GROUP BY:

ORACLE 2PM KPHB MAY 2024 Page 162


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 deptno ASC;

Dept wise max salary and min sal:


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

Find dept wise avrg sal:


DEPTNO AVRG_SAL

10 ?

20 ?

30 ?
SELECT deptno, avg(sal) AS avrg_sal
FROM emp
GROUP BY deptno ORDER BY 1;

Find dept wise no of emps:


DEPTNO NO_OF_EMPS

10 ?

ORACLE 2PM KPHB MAY 2024 Page 163


20 ?

30 ?
SELECT deptno, count(*) AS no_of_emps
FROM emp
GROUP BY deptno ORDER BY 1;

Execution Order of Clauses:

• FROM
• WHERE
• GROUP BY
• HAVING
• SELECT
• DISTINCT
• ORDER BY
• OFFSET
• FETCH
Find dept wise sum of salaries. find it for deptno 10 and 20 only:
DEPTNO SUM_OF_SAL

10 ?

20 ?
SELECT deptno, sum(sal) AS sum_of_sal
FROM emp
WHERE deptno IN(10,20)
GROUP BY deptno
ORDER BY deptno ASC;

EMP
EMPNO ENAME SAL DEPTNO

1001 A 10000 20

1002 B 20000 20

1003 C 5000 30

1004 D 10000 30

1005 E 30000 10

1005 F 20000 10
FROM emp:
it selects entire table

EMP

ORACLE 2PM KPHB MAY 2024 Page 164


EMPNO ENAME SAL DEPTNO

1001 A 10000 20

1002 B 20000 20

1003 C 5000 30

1004 D 10000 30

1005 E 30000 10

1005 F 20000 10
WHERE deptno IN(10,20): it filters the rows
EMPNO ENAME SAL DEPTNO
1001 A 10000 20
1002 B 20000 20
1005 E 30000 10

1005 F 20000 10
GROUP BY deptno:
it groups the records according to specific column.
on these groups aggregate function will be applied,

20 group sum(Sal) => 30000


1001 A 10000 20

1002 B 20000 20

10 group sum(Sal) => 50000

1005 E 30000 10

1005 F 20000 10 SELECT deptno, sum(sal) AS sum_of_sal: it selects


specified columns.
DEPTNO SUM_OF_SAL

20 30000

10 50000
ORDER BY deptno ASC:
it arranges result in the specified order
DEPTNO SUM_OF_SAL

10 50000

20 30000
Find year wise no of emps joined in organization:
YEAR NO_OF_EMPS

ORACLE 2PM KPHB MAY 2024 Page 165


1980 ?

1981 ?

1982 ?

1983 ?
SELECT to_char(hiredate,'YYYY') AS year, count(*) AS no_of_emps FROM emp
GROUP BY to_char(hiredate,'YYYY') ORDER BY 1 ASC;

Find quarter wise no of emps joined organization:


QUARTER NO_OF_EMPS

1 ?

2 ?

3 ?

4 ?
SELECT to_char(hiredate,'Q') AS QUARTER, count(*) AS no_of_emps
FROM emp
GROUP BY to_char(hiredate,'Q') ORDER BY 1;

Find job wise sum of salaries:


JOB SUM_OF_SAL

CLERK ?

MANAGER ?

ANALYST ?

SALESMAN ?

PRESIDENT ?
SELECT job, sum(Sal) AS sum_of_sal
FROM emp
GROUP BY job;

Assignment:
Find job wise max sal and min sal

Find job wise avrg sal

Find job wise no of emps


Grouping records according to multiple columns:

ORACLE 2PM KPHB MAY 2024 Page 166


Find dept wise, with in dept job wise no of emps:
DEPTNO JOB NO_OF_EMPS

10 MANAGER ?

10 CLERK ?

20 MANAGER ?

20 CLERK ?
SELECT deptno, job, count(*) AS no_of_emps
FROM emp
GROUP BY deptno, job ORDER BY 1;

Rollup() and Cube():


• These 2 functions are used to calculate sub totals and grand total.
• We call these 2 functions from GROUP BY clause.
We pass grouping columns as arguments to these functions.

Rollup():

Syntax:
GROUP BY Rollup(<grouping_columns_list>)

Example:
GROUP BY Rollup(deptno, job) it calculates dept wise sub totals and grand total

Syntax:
GROUP BY Cube(<grouping_columns_list>)

Example:
GROUP BY Cube(deptno, job)
it calculates dept wise sub totals, job wise sub totals and grand total

Examples on Rollup() and Cube():

Find dept wise, within dept job wise no of emps.


Calculate subtotals according to deptno:
[Rollup()]
DEPTNO JOB NO_OF_EMPS

ORACLE 2PM KPHB MAY 2024 Page 167


10 CLERK ?

MANAGER ?

10th dept sub total ?

20 CLERK ?

20 MANAGER ?

20th dept sub total ?

GRAND TOTAL ?

SELECT deptno, job, count(*) AS no_of_emps


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

Find dept wise, within dept job wise no of emps.


Calculate subtotals according to deptno and job:
[Cube()]
DEPTNO JOB NO_OF_EMPS

10 CLERK ?

MANAGER ?

10th dept sub total ?

20 CLERK ?

20 MANAGER ?

20th dept sub total ?

CLERK subtotal ?

MANAGER sub total ?

GRAND TOTAL ?

SELECT deptno, job, count(*) AS no_of_emps


FROM emp
GROUP BY Cube(deptno, job)
ORDER BY 1;
Find year wise, quarter wise no of emps:
YEAR QUARTER NO_OF_EMPS

1980 1 ?

2 ?

ORACLE 2PM KPHB MAY 2024 Page 168


3 ?

4 ?

1981 1 ?

2 ?

3 ?

4 ?

SELECT to_char(hiredate,'YYYY') AS year, to_char(hiredate,'Q') AS quarter, count(*)


AS no_of_emps
FROM emp
GROUP BY to_char(hiredate,'YYYY'), to_char(hiredate,'Q') ORDER BY 1;

Find year wise, quarter wise no of emps. calculate sub totals according to year.
[Rollup()]
YEAR QUARTER NO_OF_EMPS

1980 1 ?

2 ?

3 ?

4 ?

1980 sub total ?

1981 1 ?

2 ?

3 ?

4 ?

1981 sub total ?

GRAND TOTAL ?

SELECT to_char(hiredate,'YYYY') AS year, to_char(hiredate,'Q') AS quarter, count(*)


AS no_of_emps
FROM emp
GROUP BY ROLLUP(to_char(hiredate,'YYYY'), to_char(hiredate,'Q'))
ORDER BY 1;
Find year wise, quarter wise no of emps.
calculate sub totals according to year and quarter.
[Cube()]

ORACLE 2PM KPHB MAY 2024 Page 169


YEAR QUARTER NO_OF_EMPS

1980 1 ?

2 ?

3 ?

4 ?

1980 sub total ?

1981 1 ?

2 ?

3 ?

4 ?

1981 sub total ?

1st qrtr sub total ?

2nd qrtr sub total ?

3rd qrtr sub total ?

4th qrtr sub total ?

GRAND TOTAL ?

SELECT to_char(hiredate,'YYYY') AS year, to_char(hiredate,'Q') AS quarter, count(*) AS


no_of_emps
FROM emp
GROUP BY CUBE(to_char(hiredate,'YYYY'), to_char(hiredate,'Q'))
ORDER BY 1;

Assignment:

SALES
DATEID AMOUNT

1-JAN-2020 50000

2-JAN-2020 70000

ORACLE 2PM KPHB MAY 2024 Page 170


..

..

15-JUN-2024 80000
calculate year wise, quarter wise sales:

GROUP BY to_char(dateid,'YYYY'), to_char(dateid,'Q')

YEAR QUARTER AMOUNT sum(amount)


2020 1 ?

2 ?

3 ?

4 ?

2021 1 ?

2 ?

3 ?
calculate year wise, quarter wise sales.
4 ? Also calculate sub totals according to year.

GROUP BY ROLLUP(to_char(dateid,'YYYY'), to_char(dateid,'Q'))


YEAR QUARTER AMOUNT

2020 1 ?

2 ?

3 ?

4 ?

2020 sub total ?

2021 1 ?

2 ?

3 ?

4 ?

2021 sub total ?

GRAND TOTAL ?

ORACLE 2PM KPHB MAY 2024 Page 171


calculate year wise, quarter wise sales.
Also calculate sub totals according to year and quarter.

GROUP BY CUBE(to_char(dateid,'YYYY'), to_char(dateid,'Q'))


YEAR QUARTER AMOUNT
2020 1 ?
2 ?

3 ?

4 ?

2020 sub total ?

2021 1 ?
2 ?

3 ?

4 ?

2021 sub total ?

1st quarter sub total ?

2nd quarter sub total ?

3rd quarter sub total ?

4th quarter sub total ?

GRAND TOTAL ?

HAVING:
• HAVING clause is used to write the condition on groups.
• This condition will be applied on result of GROUP BY.
• It cannot be used without GROUP BY.

Syntax:
HAVING <condition>

Display the depts which are spending more than 10000 rupees on their emps:

SELECT deptno, sum(Sal)


FROM emp
GROUP BY deptno

ORACLE 2PM KPHB MAY 2024 Page 172


HAVING sum(Sal)>10000 ORDER BY 1;

Display the depts which are having 5 or more emps:

SELECT deptno, count(*)


FROM emp
GROUP BY deptno
HAVING count(*)>=5 ORDER By 1;
Differences between WHERE and HAVING:

WHERE HAVING

• WHERE clause condition will be • HAVING clause condition will be


applied on rows. applied on groups.

• it filters the rows. • it filters the groups.

• Aggregate functions cannot be • Aggregate functions can be used in


used in WHERE clause HAVING clause.

• it gets executed before • it gets executed after GROUP BY


GROUP BY

• it can be used without • it cannot be used without GROUP BY


GROUP BY

OFFSET:
• introduced in ORACLE 12C version.
• OFFSET clause is used to specify no of rows to be skipped.

Syntax:
OFFSET <number> ROW/ROWS

FETCH:
• introduced in ORACLE 12C version.
• FETCH clause is used to specify no of rows to be displayed.

Syntax:
FETCH FIRST/NEXT <number> ROW/ROWS ONLY

ORACLE 2PM KPHB MAY 2024 Page 173


Examples:
Display all emp table records except first 5 rows:

SELECT * FROM emp OFFSET 5 ROWS;

Display first 5 rows only:

SELECT * FROM emp


FETCH FIRST 5 ROWS ONLY;

Display 6th row to 10th row:

SELECT * FROM emp


OFFSET 5 ROWS
FETCH NEXT 5 ROWS ONLY;

DISTINCT:
• It is used to eliminate the duplicate records.

Syntax:
SELECT DISTINCT <columns_list>

Examples:

Display the deptnos which are having emps:

SELECT ALL deptno FROM emp;

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

ORACLE 2PM KPHB MAY 2024 Page 174


Display the job titles offered by company:

SELECT ALL job FROM emp;


SELECT DISTINCT job FROM emp;

JOB
--------
JOB MANAGER
---------
CLERK
MANAGER
CLERK
CLERK
MANAGER
SALESMAN
SALESMAN
SALESMAN
MANAGER
CLERK

Display dept wise job titles offered by company:

SELECT DISTINCT deptno, job FROM emp


ORDER BY deptno;

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

Execution Order:

ORACLE 2PM KPHB MAY 2024 Page 175


FROM used to specify table names Examples:
FROM emp
FROM emp, dept

WHERE used to specify condition it will


be applied on every row it
filters the rows Examples:

WHERE job='MANAGER'
WHERE deptno=30
WHERE sal>2500

GROUP used to group the records according to specific column(s).


BY Examples:
GROUP BY deptno
GROUP BY deptno, job

HAVING used to write conditions on groups Examples:


HAVING count(*)>5
HAVING sum(sal)>10000

SELECT used to specify columns list Examples:


SELECT ename, sal

DISTINCT used to eliminate duplicate records Examples:


SELECT DISTINCT job

ORDER BY used to arrange the records in asc or desc order Examples:


ORDER BY sal DESC
ORDER BY ename ASC

OFFSET used to specify no of rows to be skipped Examples:


OFFSET 5 ROWS

FETCH used to specify no of rows to be fetched Example:


FETCH FIRST 5 ROWS ONLY

ORACLE 2PM KPHB MAY 2024 Page 176


Can we use column alias in GROUP BY?
NO.
because of execution order of clauses.
GROUP BY gets executed before SELECT.

Note:
We cannot use column aliases in GROUP BY, HAVING and WHERE. Because, all these 3 gets executed before
SELECT.
Can we use column alias in ORDER BY?
Yes.
because of execution order of clauses.
ORDER BY gets executed after SELECT.

Find year wise no of emps joined in organization:

SELECT to_char(hiredate,'YYYY') AS year, count(*)


AS no_of_emps
FROM emp
GROUP BY year; Output:
ERROR: 'YEAR' invalid identifier

SELECT to_char(hiredate,'YYYY') AS year, count(*)


AS no_of_emps
FROM emp
GROUP BY to_char(hiredate,'yyyy') ORDER BY year;

NOTE:

IN ORACLE 23AI, we can use column alias in GROUP BY and HAVING.

ORACLE 2PM KPHB MAY 2024 Page 177


JOINS
Tuesday, June 18, 2024 2:10 PM

JOINS:
GOAL:
JOINS concept is used to retrieve the data from multiple tables.

Example:

COLLEGE DB

STUDENT
MARKS
FEE
EMP

S.SID = M.SID Join Condition

STUDENT S MARKS M
SID SNAME SCITY SID MATHS PHY CHE
1001 A HYD 1001 70 50 65
1002 B MUM 1002 66 77 45
1003 C BLR 1003 88 90 60
1004 D HYD
JOINS

SID SNAME MATHS


STUDENT MARKS

JOINS:
• JOIN is an operation like filtering, sorting.

• JOIN => Combine / Connect / Link

• In JOIN Operation one table record will be combined with another table record based on some condition. This condition is called "Join
Condition".

• JOIN CONDITION decides which record in one table should be joined with which record in another table.

• JOINS concept is used to retrieve the data from multiple tables.

Types of Joins:

• Inner Join => matched records only


○ Equi Join
○ Non-Equi Join
• Outer Join => matched + unmatched records
○ Left Outer Join => matched + unmatched from left table
○ Right Outer Join => matched + unmatched from right table
○ Full Outer Join => matched + unmatched from left and right tables
• Self Join
• Cross Join
Inner Join:

ORACLE 2PM KPHB MAY 2024 Page 178


• Inner Join can give matched records only.
• It has 2 sub types. They are:
○ Equi Join
○ Non-Equi Join

Equi Join:
• If Join Operation is performed based on equality condition then it is called "Equi Join".

Examples:
WHERE S.SID = M.SID

Examples on Equi Join:

STUDENT.SID = MARKS.SID
STUDENT S
SID SNAME SCITY MARKS M
SID MATHS PHY CHE
1001 A HYD
Display 1001 70 50 65 student details along with maths subject marks:
1002 B MUM
SID SNAME MATHS
1002 66 77 45
1003 C BLR STUDENT S MARKS M
1003 88 90 60
1004 D HYD

CREATE TABLE student


(
sid NUMBER(4), sname VARCHAR2(10), scity CHAR(3)
);

INSERT INTO student VALUES(1001,'A','HYD');


INSERT INTO student VALUES(1002,'B','MUM');
INSERT INTO student VALUES(1003,'C','BLR');
INSERT INTO student VALUES(1004,'D','HYD'); COMMIT;

CREATE TABLE marks


(
sid NUMBER(4), maths NUMBER(3), phy NUMBER(3), che NUMBER(3)
);

INSERT INTO marks VALUES(1001,70,50,65); INSERT INTO marks VALUES(1002,66,77,45);


INSERT INTO marks VALUES(1003,88,90,60);
COMMIT;
SID SNAME MATHS
STUDENT S MARKS M

SELECT student.sid, sname, maths


FROM student, marks WHERE student.sid = marks.sid;

Above query degrades the performance. TO improve the performance of above query prefix every column name with table
name.

SELECT student.sid, student.sname, marks.maths


FROM student, marks WHERE student.sid = marks.sid;

above query improves the performance. To make table name short use table alias.

ORACLE 2PM KPHB MAY 2024 Page 179


SELECT s.sid, s.sname, m.maths
FROM student s, marks m WHERE s.sid = m.sid;

NOTE:
• From ORACLE 9i version onwards, we can write a join query in 2 styles.
They are:
○ ORACLE STYLE / NATIVE STYLE
○ ANSI STYLE => best way => portable

ORACLE SQL SERVER

we can run
portability
JOIN QUERY JOIN QUERY
[ ANSI STYLE ] [ ANSI STYLE ]

• ANSI STYLE is the best way. Because we get portability feature.

• For ORACLE STYLE we cannot give guarantee of portability.

NOTE:
• In ORACLE STYLE, to separate 2 table names we use , [comma].
• In ANSI STYLE, to separate 2 table names we use keyword.
• In ORACLE STYLE, we write join condition in WHERE clause.
• In ANSI STYLE, we write join condition in ON clause.

Display student details along with maths subject marks:


SID SNAME MATHS
STUDENT S MARKS M ORACLE STYLE:

SELECT s.sid, s.sname, m.maths


FROM student s, marks m
WHERE s.sid=m.sid; ANSI STYLE:

SELECT s.sid, s.sname, m.maths


FROM student s INNER JOIN marks m ON s.sid=m.sid;

Example:
e.deptno = d.deptno

ORACLE 2PM KPHB MAY 2024 Page 180


EMP e DEPT d
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
7369 SMITH 800 20 10 ACCOUNTS NEW YORK
7499 ALLEN 1600 30 20 RESEARCH DALLAS
7521 WARD 1250 30 30 SALES CHICAGO
7566 JONES 2975 20 40 OPERATIONS BOSTON
7782 CLARK 2450 10
7934 MILLER 1300 10
1001 A 1800
1002 B 2000

ENAME SAL DNAME LOC


EMP e DEPT d

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d
WHERE e.deptno=d.deptno; ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno;
Display the emp records who are working in NEW YORK:
ENAME DNAME LOC

NEW YORK

EMP e DEPT d ORACLE STYLE:

SELECT e.ename, d.dname, d.loc


FROM emp e, dept d
WHERE e.deptno=d.deptno AND d.loc='NEW YORK'; ANSI STYLE:

SELECT e.ename, d.dname, d.loc


FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno WHERE d.loc='NEW YORK';

NOTE:
• ON clause is used to specify Join Condition.
• WHERE clause is used to specify filter condition.

e.deptno=d.deptno
EMP e DEPT d
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
7369 SMITH 800 20 10 ACCOUNTS NEW YORK
7499 ALLEN 1600 30 20 RESEARCH DALLAS
7521 WARD 1250 30 30 SALES CHICAGO
7566 JONES 2975 20 40 OPERATIONS BOSTON
7782 CLARK 2450 10
7934 MILLER 1300 10
1001 A 1800
1002 B 2000

ORACLE 2PM KPHB MAY 2024 Page 181


Note:
• First, Filter Condition will be executed. The Join operation will be performed.

To see execution plan:

SET AUTOTRACE ON EXPLAIN

Display the emp records who are working in SALES dept:


ENAME DNAME

SALES

EMP e DEPT d ORACLE STYLE:

SELECT e.ename, d.dname


FROM emp e, dept d
WHERE e.deptno=d.deptno AND d.dname='SALES'; ANSI STYLE:

SELECT e.ename, d.dname


FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname='SALES';

EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
7369 SMITH 800 20 10 ACCOUNTS NEW YORK
7499 ALLEN 1600 30 20 RESEARCH DALLAS
7521 WARD 1250 30 30 SALES CHICAGO
7566 JONES 2975 20 40 OPERATIONS BOSTON
7782 CLARK 2450 10
7934 MILLER 1300 10
1001 A 1800
1002 B 2000

Display ALLEN RECORD along with dept details:


ENAME SAL DNAME LOC

ALLEN

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 AND e.ename='ALLEN'; ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e INNER JOIN dept d

ORACLE 2PM KPHB MAY 2024 Page 182


ON e.deptno=d.deptno
WHERE e.ename='ALLEN';
e.deptno = d.deptno
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
7369 SMITH 800 20 10 ACCOUNTS NEW YORK
7499 ALLEN 1600 30 20 RESEARCH DALLAS
7521 WARD 1250 30 30 SALES CHICAGO
7566 JONES 2975 20 40 OPERATIONS BOSTON
7782 CLARK 2450 10
7934 MILLER 1300 10
1001 A 1800
1002 B 2000
Equi Join:
• If Join operation is performed based on equality condition then it is called "Equi Join".

Example:
WHERE e.deptno = d.deptno

Non-Equi Join:
• If Join operation is performed based on other than equality condition then it is called "Non-Equi Join".

Examples:
Example:
WHERE e.deptno > d.deptno
WHERE e.deptno < d.deptno
WHERE e.deptno != d.deptno

e.sal BETWEEN s.losal AND s.hisal => Join Condition Example:


EMP e SALGRADE s
EMPNO ENAME SAL GRADE LOSAL HISAL
1001 A 6000 1 700 1200
1002 B 900 2 1201 1400
1003 C 1800 3 1401 2000
1004 D 2500 4 2001 3000
5 3001 9999

Display emp details with salary grades:


ENAME SAL GRADE
EMP e SALGRADE s

ORACLE STYLE:

SELECT e.ename, e.sal, s.grade


FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal; ANSI STYLE:

SELECT e.ename, e.sal, s.grade


FROM emp e INNER JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;

ORACLE 2PM KPHB MAY 2024 Page 183


Outer Join:
• Inner Join can give matched records only.

• Outer Join can give matched records and unmatched records also.
• Inner Join = matched records
• Outer Join = matched + unmatched records

• It has 3 sub types. They are:


○ Left Outer Join
○ Right Outer Join ○ Full Outer Join

Note:
• In ORACLE STYLE, based on join condition we can tell left table and right table.

Examples:
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


• In ANSI STYLE, based on keyword we can tell left table and right table.

Examples:
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


Note:
In ORACLE STYLE, for outer join we use outer join operator. symbol: (+)

Left Outer Join:

• Left outer Join = matched + unmatched from left table

• Left Outer Join can give matched records and unmatched records from left table.

• In ORACLE STYLE, for left outer join write (+) symbol at right side.

• In ANSI STYLE, use the keyword: LEFT [OUTER] JOIN

Example on Left Outer Join:


Display all emp details along with dept details:
Also display the emps to whom dept is not assigned:
ENAME SAL DNAME LOC
EMP e DEPT d

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


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

ORACLE 2PM KPHB MAY 2024 Page 184


ORACLE STLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d WHERE e.deptno=d.deptno(+); ANSI STLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e LEFT OUTER JOIN dept d ON e.deptno=d.deptno;

Right Outer Join:


• Right Outer Join = matched + unmatched from right table

• Right Outer Join can give matched records and unmatched records from right table.

• In ORACLE STYLE, write (+) symbol at left side.

• In ANSI STYLE, use the keyword: RIGHT [OUTER] JOIN

Example on Right Outer Join:

Display the emp details along with dept details.


Also display the depts which are not having emps:
ENAME SAL DNAME LOC
EMP e DEPT d

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d WHERE e.deptno(+)=d.deptno; ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno=d.deptno;
Full Outer Join:

• Full Outer Join = matched + unmatched from left and right tables

• Full Outer Join can give matched records, unmatched records from left table and
right table.

In ORACLE STYLE:
A = {1,2,3,4,5} B = {4,5,6,7,8}
Left Outer Join WHERE e.deptno = d.deptno(+)

Right Outer Join WHERE e.deptno(+) = d.deptno A U B = {1,2,3,4,5,6,7,8}

Full Outer Join WHERE e.deptno(+) = d.deptno(+)


ERROR
Left Outer Join = matched + unmatched from left
Full Outer Join Left Outer Join UNION
UNION Right Outer Join = matched +unmatched from right
Right Outer Join

Full Outer = matched + um from left + um from right


• In ANSI STYLE, we use the keyword: FULL OUTER JOIN.

ORACLE 2PM KPHB MAY 2024 Page 185


Example on Full Outer Join:

Display emp details along with dept details.


Also display the emps to whom dept is not assigned. Also display the
depts which are not having emps.

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d
WHERE e.deptno=d.deptno(+)
UNION
SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno; ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e FULL OUTER JOIN dept d ON
e.deptno=d.deptno;

Displaying unmatched records only:

Left Outer Join + Condition:

Left Outer Join + Condition = unmatched records from left table Example:

Display the emp records to whom dept is not assigned:


ename sal dname loc

A ..

B ..

ORACLE STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e, dept d
WHERE e.deptno = d.deptno(+) AND d.dname IS null; ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e LEFT JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS null;

Right Outer Join + Condition:

Right Outer Join + Condition = unmatched records from right table Example:

Display the depts which are not having emps:


ename sal dname loc

OPERATIONS BOSTON

ORACLE STYLE:

ORACLE 2PM KPHB MAY 2024 Page 186


SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno AND e.ename IS null; ANSI STYLE:

SELECT e.ename, e.sal, d.dname, d.loc


FROM emp e RIGHT JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename IS null;

Full Outer Join + Conditions:

Full Outer Join + Conditions = unmatched from left + unmatched from right Example:

Display the emps to whom dept is not assigned.


Also display the depts which are not having emps.
ENAME SAL DNAME LOC

A ..

B ..

OPERATIONS BOSTON

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:

Self Join / Recursive Join:

ORACLE 2PM KPHB MAY 2024 Page 187


• If a table is joined to itself then it is called "Self Join".
• It can be also called as "Recursive Join".

• In Self Join, one record in a table will be joined with another record in same table.

Example:
e.mgr = m.empno
EMP e EMP m

EMPNO ENAME JOB SAL MGR EMPNO ENAME JOB SAL MGR

1001 A MANAGER 20000 1001 A MANAGER 20000

1002 B CLERK 10000 1001 1002 B CLERK 10000 1001 1003 C ANALYST 8000 1001 1003 C ANALYST 8000 1001 1004 D MANAGER

25000 1004 D MANAGER 25000

1005 E SALESMAN 12000 1004 1005 E SALESMAN 12000 1004

1006 F CLERK 10000 1004 1006 F CLERK 10000 1004

Display emp details along with managers 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 AS mgr_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 AS mgr_sal


FROM emp e INNER JOIN emp m ON e.mgr = m.empno;

Display the emp records who are earning more than their manager:

ORACLE STYLE:

SELECT e.ename AS emp_name, e.sal AS emp_sal, m.ename AS mgr_name, m.sal AS mgr_sal


FROM emp e, emp m
WHERE e.mgr=m.empno AND e.sal>m.sal; ANSI STYLE:

SELECT e.ename AS emp_name, e.sal AS emp_sal, m.ename AS mgr_name, m.sal AS mgr_sal


FROM emp e INNER JOIN emp m
ON e.mgr=m.empno
WHERE e.sal>m.sal;

Display the emp records who are working under BLAKE:

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 m.ename='BLAKE'; 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 m.ename='BLAKE';

ORACLE 2PM KPHB MAY 2024 Page 188


x.cid < y.cid
Example:

GROUPA x GROUPA y
CID CNAME CID CNAME
10 IND 10 IND
20 AUS 20 AUS
30 WIN 30 WIN

20 AUS 20 AUS
30 WIN 30 WIN

IND VS AUS
IND VS WIN AUS VS WIN

create table groupa


(
cid number(2), cname varchar2(10)
);

insert into groupa values(10,'IND'); insert into groupa values(20,'AUS'); insert into groupa values(30,'WIN'); commit;

ORACLE STYLE:

SELECT x.cname || ' VS ' || y.cname


FROM groupa x, groupa y
WHERE x.cid<y.cid; ANSI STYLE:

SELECT x.cname || ' VS ' || y.cname


FROM groupa x INNER JOIN groupa y ON x.cid<y.cid;

Cross Join / Cartesian Join:

A = {1,2,3}
B = {4,5}
AXB = { (1,4)(1,5) (2,4) (2,5) (3,4) (3,5) }

A B

1
4
2
5
3

• In Cross Join, each record in one table will be joined with every record in another table.

• For Cross Join don't write any Join Condition.

• In ANSI STYLE we use the keyword: CROSS JOIN Example:

ORACLE 2PM KPHB MAY 2024 Page 189


GROUPA a GROUPB b

CID CNAME CID CNAME

10 IND 40 ENG

20 AUS 50 SL

30 WIN 60 NZ
create table groupa
(
cid number(2), cname varchar2(10)
);

insert into groupa values(10,'IND'); insert into groupa values(20,'AUS'); insert into groupa values(30,'WIN'); commit;

create table groupb


(
cid number(2), cname varchar2(10)
);

insert into groupb values(40,'ENG'); insert into groupb values(50,'SL'); insert into groupb values(60,'NZ'); commit; CROSS JOIN:

ORACLE STYLE:

SELECT a.cname || ' VS ' || b.cname


FROM groupA a, groupB b; ANSI STYLE:

SELECT a.cname || ' VS ' || b.cname


FROM groupA a CROSS JOIN groupB b; Output:

IND VS ENG
IND VS SL
IND VS NZ
AUS VS ENG
AUS VS SL
AUS VS NZ
WIN VS ENG
WIN VS SL
WIN VS NZ
JOINS:
• used to retrieve the data from multiple tables

Types Of Joins:
Inner Join matched records only

Equi based on =

Non-Equi based on other than =

Outer Join matched + unmatched

Left outer matched + um from left

Right outer matched + um from right

Full outer matched _ um from L & R

ORACLE 2PM KPHB MAY 2024 Page 190


Self join a table will be joined to itself

Cross join each record in one table will be joined with


every record in another table.

ORACLE 2PM KPHB MAY 2024 Page 191


Retrieving data from 4 tables
Friday, June 21, 2024 2:06 PM

Retrieving data from 4 tables:

e.deptno = d.deptno d.LocID = L.LocID L.cid = c.cid


EMP1 e DEPT1 d LOCATION1 L COUNTRY1 c

empno deptno LocID Cid


ename dname Lname Cname
deptno LocID CID

ENAME DNAME LNAME CNAME


EMP1 e DEPT1 d LOCATION1 L COUNTRY1 C

create table emp1


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

insert into emp1 values(1001,'A',10);

create table dept1


(
deptno number(2), dname
varchar2(10), locid
number(5)
);

insert into dept1 values(10,'SALES',12345); create table

location1

ORACLE 2PM KPHB MAY 2024 Page 192


(
locid number(5), lname varchar2(10), cid
number(3)
);

insert into location1 values(12345,'HYD',100);

create table country1


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

insert into country1 values(100,'INDIA'); commit;

ENAME DNAME LNAME CNAME


EMP1 e DEPT1 d LOCATION1 L COUNTRY1 C

ORACLE STYLE:

SELECT e.ename, d.dname, L.Lname, c.cname


FROM emp1 e, dept1 d, location1 L, country1 c WHERE e.deptno =
d.deptno AND d.LocID = L.LocID AND
L.cid = c.cid; ANSI STYLE:

SELECT e.ename, d.dname, L.Lname, c.cname


FROM emp1 e INNER JOIN dept1 d
ON e.deptno=d.deptno INNER JOIN Location1 L
ON d.LocID = L.LocID INNER JOIN COUNTRY1 C
ON L.cid = c.cid;

ORACLE 2PM KPHB MAY 2024 Page 193


Tuesday, June 18, 2024 3:36 PM

EMP DEPT

EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC

7369 SMITH 800 20 10 ACCOUNTS NEW YORK

7499 ALLEN 1600 30 20 RESEARCH DALLAS


7521 WARD 1250 30 30 SALES CHICAGO

7566 JONES 2975 20 40 OPERATIONS BOSTON

7782 CLARK 2450 10

7934 MILLER 1300 10

1001 A 1800

1002 B 2000
ORACLE 2PM KPHB MAY 2024 Page 209

Assignment
Wednesday, May 29, 2024 7:18 PM

Assignment:

EMPLOYEE e PROJECT p

EMPID ENAME PID PID PNAME


1001 A 30 10 X
1002 B 30 20 Y
1003 C 10 30 Z
1004 D 10
1005 E
1006 F
Display emp details along with project details => [Equi Join]
empid ename pname
Display emp details along with project details
Also display the employees who are on bench [emps who are not participating
in any project development]=> [Left Outer Join]
empid ename pname
Display emp details along with project details
Also display the projects which are not assigned to any employee =>
[Right Outer Join]
empid ename pname
display the employees who are on bench
empid ename pname
Left outer join + condition

ORACLE 2PM KPHB MAY 2024 Page 210

display the projects which are not assigned to any employee


empid ename pname
Right outer join + condition

display the employees who are on bench. display the projects which are
not assigned to any employee
empid ename pname
full outer join + conditions

Display emp details along with project details. also display the employees
who are on bench. also display the projects which are not assigned to any
employee
empid ename pname
full outer join
ORACLE 2PM KPHB MAY 2024 Page 211
SUB QUERIES
Friday, June 21, 2024 2:31 PM

SUB QUERIES / NESTED QUERIES:


Syntax:

SELECT <columns_list>
FROM <table_name>
WHERE <column_name> <operator> (< SELECT QUERY >) ;

Outer Query / Inner Query /


Main Query / Sub Query /
Parent Query Child Query
• A query which is written in another query is called "Sub Query".
• Outside query is called "Outer query / main query / parent query".
• Inside query is called "Inner query / sub query / child query".

• When we don't know filter condition value, to find it we write Sub Query.

• Sub query must be written parenthesis.

• First Inner query gets executed. Then outer query gets executed. Result of
inner query will become input for Outer query.

• Inner query must be SELECT query only. It cannot be INSERT / UPDATE /


DELETE. Because, inner query has to find some value. only SELECT can
find the value.

• Outer query can be SELECT / INSERT / UPDATE / DELETE.

• In WHERE clause we can write max of 254 sub queries.


Including main query we can write 255 levels of queries.

Types of Sub Queries:

2 types:
• Non-Correlated Sub Query INNER => OUTER
○ Single Row Sub Query
○ Multi Row Sub Query
○ Inline View / Inline Sub Query
○ Scalar Sub Query
• Correlated Sub Query OUTER => INNER
<=

ORACLE 2PM KPHB MAY 2024 Page 197


Non-Correlated Sub Query:
• In this, first inner query gets executed. Then outer query gets executed.
• Inner query gets executed only once.

It has following sub types:


○ Single Row Sub Query
○ Multi Row Sub Query
○ Inline View
○ Scalar Sub Query

Single Row Sub Query:


• if sub query returns 1 row then it is called "Single Row Sub Query".

Examples on Single Row Sub Queries:

Display the emp records who are earning more than BLAKE:

SELECT ename, sal


FROM emp
WHERE sal>(find BLAKE sal);

finding BLAKE sal:


SELECT sal FROM emp WHERE ename='BLAKE';

SELECT ename, sal


FROM emp
WHERE sal>(SELECT sal FROM emp WHERE ename='BLAKE');

Display the emp records whose job title is same as ALLEN:

SELECT ename, job,sal


FROM emp
WHERE job=(Find ALLEN job title);

Find ALLEN job title:


SELECT job FROM emp WHERE ename='ALLEN';

SELECT ename, job, sal


FROM emp
WHERE job=(SELECT job FROM emp WHERE ename='ALLEN');

ORACLE 2PM KPHB MAY 2024 Page 198


Find max sal:
SELECT max(sal) FROM emp; Find 2nd max

salary:

SAL SELECT max(sal)


--------- FROM emp
3000 WHERE sal<(find max sal);
2500 6000
40005000 3000
50002nd max sal 2500
4500 4000
5000
4500

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

Find 3rd max salary:

SAL
--------- SELECT max(sal) FROM emp
3000 WHERE sal<(find 2nd max sal);

2500 6000
4000max sal => 4000
3000
50003rd max sal
2500
4000

SELECT max(Sal) FROM emp


WHERE sal<(SELECT max(sal) FROM emp
WHERE sal<(SELECT max(Sal) FROM emp));
Display the emp name who is earning max sal:

SELECT ename
FROM emp
WHERE sal=(find max sal);

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

ORACLE 2PM KPHB MAY 2024 Page 199


Display the emp name who is earning 2nd max sal:

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

Assignment:
• find the emp name who is earning 3rd max sal
• find the emp name who is earning min sal

Display most senior's record:

SELECT ename, hiredate


FROM emp
WHERE hiredate=(find most senior's hiredate);

SELECT ename, hiredate


FROM emp
WHERE hiredate=(SELECT min(hiredate) FROM emp);

Display most junior's record:

SELECT ename, hiredate


FROM emp
WHERE hiredate=(find most junior's hiredate);

SELECT ename, hiredate


FROM emp
WHERE hiredate=(SELECT max(hiredate) FROM emp);

Display seniors of BLAKE:

SELECT ename, hiredate


FROM emp
WHERE hiredate<(find BLAKE hiredate);

SELECT ename, hiredate


FROM emp

ORACLE 2PM KPHB MAY 2024 Page 200


WHERE hiredate<(SELECT hiredate FROM emp WHERE ename='BLAKE');

Display juniors of BLAKE:

SELECT ename, hiredate


FROM emp
WHERE hiredate>(find BLAKE hiredate);

SELECT ename, hiredate


FROM emp
WHERE hiredate>(SELECT hiredate FROM emp WHERE ename='BLAKE');

Find the deptno which is spending max amount on their emps:

SELECT deptno
FROM emp
GROUP BY deptno
HAVING sum(Sal)=(find max amount in all depts sum of salaries);

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

Modify 7900 employee salary as 30th dept's max sal:

UPDATE emp
SET sal=(find 30th dept's max sal) WHERE
empno=7900;

UPDATE emp
SET sal=(SELECT max(sal) FROM emp WHERE deptno=30) WHERE empno=7900;

ORACLE 2PM KPHB MAY 2024 Page 201


Delete most senior's record:

DELETE FROM emp


WHERE hiredate=(find most senior's hiredate);

find most senior's hiredate:


SELECT min(hiredate) FROM emp;

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 Query".

• For multi row sub query we use operators such as IN, ANY, ALL.

Examples on multi row sub query:


Display the emp records whose job title is same as BLAKE and SMITH:

BLAKE => MANAGER


SMITH => CLERK

SELECT ename, job, sal


FROM emp
WHERE job IN(find BLAKE and SMITH job titles);

find BLAKE and SMITH job titles: SELECT job FROM emp
WHERE ename IN('BLAKE','SMITH');

SELECT ename, job, sal


FROM emp
WHERE job IN(SELECT job FROM emp WHERE ename
IN('BLAKE','SMITH'));

ALL:

Syntax:
<column> <relational_operator>ALL(<values_list>)
sal>2000 AND sal>3000 sal>ALL(2000,3000)
ANY:

Syntax:
<column> <relational_operator>ANY(<values_list>)

ORACLE 2PM KPHB MAY 2024 Page 202


Example:
sal>2000 OR sal>ANY(2000,3000)
sal>3000
SAL sal>ALL(2000,3000) sal>ANY(2000,3000)

if sal is > all list of if sal is > ANY 1 of the


values then list of values then
condition is TRUE condition is TRUE
6000 T T

2500 F T

5000 T T

2800 F T

1000 F F

sal=2000 sal sal=ANY(2000,3000)


OR IN(2000,3000)
sal=3000
Display the emp records who are earning more than all managers:

SELECT ename, sal


FROM emp
WHERE sal>ALL(find all managers sals);

SELECT ename, sal


FROM emp
WHERE sal>ALL(SELECT sal FROM emp multi row SQ WHERE job='MANAGER');

(or)

SELECT ename, sal


FROM emp
WHERE sal>(SELECT max(sal) FROM emp single row SQ
WHERE job='MANAGER');

Display the emp records who are earning more than any one of the managers:

SELECT ename, sal


FROM emp
WHERE sal>ANY(find all managers salaries);

SELECT ename, sal


FROM emp
WHERE sal>ANY(SELECT sal FROM emp multi row SQ WHERE job='MANAGER');

ORACLE 2PM KPHB MAY 2024 Page 203


(or)

SELECT ename, sal


FROM emp
WHERE sal>(SELECT min(sal) FROM emp single row SQ
WHERE job='MANAGER');
Inline View / Inline Sub Query:

• if Sub query is written in FROM clause then it is called "Inline


View".

• Sub query acts like table.

• To control execution order of clauses we need to write sub


query in FROM clause.

Examples on Inline View:

Find 3rd max sal:


Execution Order:
SELECT ename, sal,

dense_rank() over(order by sal desc) as rank FROM


FROM emp WHERE WHERE
rank=3; GROUP BY
HAVING
Output: SELECT
ERROR: RANK invalid identifier DISTINCT
ORDER BY
SELECT DISTINCT sal OFFSET
FROM (SELECT ename, sal, FETCH
dense_rank() over(order by sal desc) as rank
FROM emp)
WHERE rank=3;

Find 5th max sal:

SELECT DISTINCT sal


FROM (SELECT ename, sal, dense_rank() over(order
by sal desc) as rank
FROM emp)
WHERE rank=5; Find

nth max sal:

SELECT DISTINCT sal


FROM (SELECT ename, sal,
dense_rank() over(order by sal desc) as rank

ORACLE 2PM KPHB MAY 2024 Page 204


FROM emp) WHERE
rank=&n; Output:
enter .. n: 2
3000 => 2nd max sal
/
enter .. n: 3
2975 => 3rd max sal

Display top 3 salaries:

SELECT DISTINCT sal


FROM (SELECT ename, sal,
dense_rank() over(order by sal desc) as rank
FROM emp)
WHERE rank<=3;

Display top n salaries:

SELECT DISTINCT sal


FROM (SELECT ename, sal,
dense_rank() over(order by sal desc) as rank
FROM emp)
WHERE rank<=&n;

Pseudo Columns: pseudo => false

ROWNUM ROWID

ROWNUM:
• It is a pseudo column.
• It is used to apply row numbers to records.
• On select query result row numbers will be applied.

Examples on rownum:

Select all emp names and salaries. Apply row numbers to


them.

SELECT rownum, ename, sal

ORACLE 2PM KPHB MAY 2024 Page 205


FROM emp;
Display all managers records. Apply row numbers to them.

SELECT rownum AS sno, e.*


FROM emp e
WHERE job='MANAGER';

Display 3rd row from emp table:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn=3;

Display 3rd row, 7th row and 11th row from emp table:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn IN(3,7,11);

Display the row numbers between 6 to 10:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn BETWEEN 6 AND 10;

Display even numbered rows:

SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE MOD(rn,2)=0;

ROWID:
• it is used to get address of the row.

ORACLE 2PM KPHB MAY 2024 Page 206


Example:
Display all empnos, names and salaries along with row
addresses:

SELECT rowid, empno,ename,sal FROM emp;

Example:

EMPLOYEE
EMPID ENAME SAL ROWID

1001 A 12000 AAATevAAHAAAAF2AAA


AAATevAAHAAAAF2AAB
1001 A 12000
CREATE TABLE employee
(
empid NUMBER(4), ename
VARCHAR2(10), sal NUMBER(8,2)
);

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


VALUES(1001,'A',12000); COMMIT;

delete duplicate row:

DELETE FROM employee


WHERE rowid='<rowid>';

DELETE FROM employee


WHERE rowid='AAATevAAHAAAAF2AAB';

Scalar Sub Query:


• If sub query is written SELECT clause then it is called "Scalar Sub Query".

• It acts like column.

Examples on scalar sub query:

Find no of records in emp and dept tables:


SELECT (SELECT count(*) FROM emp) AS emp,
(SELECT count(*) FROM dept) AS dept
FROM dual;

Output:

ORACLE 2PM KPHB MAY 2024 Page 207


EMP DEPT
--------- -----------
14 4

Calculate each dept share:


DEPTNO SUM_OF_SAL TOTAL PER

10 8750 29025 8750*100/29025 = 30.1464

20 10875 29025 10875*100/29025 = 37.4677

30 9400 29025 9400*100/29025 = 32.3859


SELECT deptno, sum(Sal) AS sum_of_sal, (SELECT sum(sal) FROM
emp) AS total,
trunc(sum(Sal)*100/(SELECT sum(sal) FROM emp),2) AS per
FROM emp
GROUP BY deptno ORDER BY 1;

Non-Correlated Sub Query:


• In Non-Correlated Sub Query first inner query gets executed then outer query
executed.

• Inner query gets executed only once.

Correlated Sub Query:


• If Outer query passes value to inner query then it is called "Correlated Sub
Query".

• In this, inner query gets executed for multiple times.

• no of execution times of inner query = no of rows selected [passed] by outer


query

Execution process:
1. 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 selects the row.

Above 5 steps will be executed repeatedly for every row selected by outer query.

ORACLE 2PM KPHB MAY 2024 Page 208


1

selects a row 3
2 passes value

OUTER INNER
4 passes value

5 condition => T selects row

Example on Correlated Sub Query:

EMP e DEPTNO AVG(SAL)


EMPNO ENAME DEPTNO SAL
10 15000
1001 A 10 20000
1002 B 20 10000 20 25000
Display the
1003 C 30 15000 emps 30 10000 who are
1004 D 10 10000 earning more
than their dept's avrg sal:
1005 E 20 40000
1006 F 30 5000
SELECT ename, deptno, sal
FROM emp e
WHERE sal>(SELECT avg(Sal) FROM emp
WHERE deptno=e.deptno);

ENAME DEPTNO SAL

A 10 20000

C 30 15000

E 20 40000
Example:
Find the emps who are earning max sal in each dept:

EMP SAL = EMP DEPT'S MAX SAL

SELECT ename, deptno, sal


FROM emp e
WHERE sal = (SELECT max(Sal) FROM emp WHERE deptno=e.deptno);

ORACLE 2PM KPHB MAY 2024 Page 209


EMP e
EMPNO ENAME DEPTNO ENAME DEPTNO SAL
1001 A 10
A 10 20000
1002 B 20
1003 C 30 C 30 15000
1004 D 10 E 20 40000
1005 E 20
1006 F 30
Find the emps who are senior in each dept: emp hiredate = emp dept's

min hiredate

SELECT ename, deptno, hiredate


FROM emp e
WHERE hiredate = (SELECT min(hiredate) FROM emp WHERE
deptno=e.deptno);

EXISTS:
• it returns boolean value [true or false].

• If Sub query selects the rows, it returns TRUE.


• IF sub query does not select the rows, it return FALSE.
Syntax:
EXISTS(<sub query>) Example on exists:

Display the dept names which are having emps:

exists(select dept emp records)

SELECT dname FROM dept d


WHERE EXISTS(SELECT * FROM emp
WHERE deptno=d.deptno);

DEPT d EMP e

ORACLE 2PM KPHB MAY 2024 Page 210


DEPTNO DNAME LOC EMPNO ENAME DEPTNO SAL
10 ACCOUNTS NEW YORK 1001 A 10 20000
20 RESEARCH DALLAS
1002 B 20 10000
30 SALES CHICAGO
40 OPERATIONS BOSTON 1003 C 30 15000

1004 D 10 10000
ACCOUNTS
1005 E 20 40000
RESEARCH SALES
1006 F 30 5000

Non-Correlated first inner query gets executed inner


query gets executed 1 time
NOT
Single row SQ SQ returns 1 row

Multi Row SQ SQ returns multiple rows

Inline View SQ in FROM clause

Scalar SQ in SELECT clause

Correlated first outer query gets executed inner query gets


executed for multiple times
EXISTS:
• it returns boolean value [true or false].

• IF sub query does not select the rows, it return TRUE.


• If Sub query selects the rows, it returns FALSE.

Syntax:
NOT EXISTS(<sub query>)

Example on not exists:

Display the dept names which are not having emps:

not exists(select dept emp records)

SELECT dname FROM dept d


WHERE NOT EXISTS(SELECT * FROM emp
WHERE deptno=d.deptno);
SUB QUERY:
A query which is written in another query

2 Types:

WHERE max of 254 sub queries

ORACLE 2PM KPHB MAY 2024 Page 211


FROM unlimited

SELECT unlimited

ORACLE 2PM KPHB MAY 2024 Page 212


CONSTRAINTS
Tuesday, June 25, 2024 2:46 PM MAX MARKS: 100

0 TO 100

STUDENT CHECK(m1 BETWEEN 0 AND 100)


SID SNAME M1 NUMBER(3)

1001 A 56

1002 B 786 ERROR


CHECK(gender IN('M','F'))
GENDER
--------------------
M
F
Z ERROR Q ERROR

CONSTRAINTS:
• Constraint is a rule that is applied on column.
• Constraint => restrict
• CONSTRAINT is used to restrict the user from entering invalid data.
• Using CONSTRAINT, we can maintain accurate and quality data.
• Maintaining accurate and quality data is called "Data Integrity".
• To implement data integrity feature we use CONSTRAINTS.

ORACLE SQL provides following CONSTRAINTS:


○ PRIMARY KEY
○ UNIQUE
○ NOT NULL
○ CHECK
○ DEFAULT
○ REFERENCES [Foreign Key]

PRIMARY KEY:

ORACLE 2PM KPHB MAY 2024 Page 213


• It does not accept duplicates.
• It does not accept nulls.
• When value is MANDATORY and it should not be duplicated then use PK.
• A tale can have only one primary key.

EMPLOYEE
PK
EMPID ENAME JOB SAL

1234 RAJU CLERK 10000

1235 KIRAN CLERK 13000

1236 RAJU SALESMAN 10000

1234 ERROR: duplicate SAI MANAGER 25000

ERROR: null AMAR ANALYST 7000


Example on PRIMARY KEY:

T1
PK
F1
------
1234
1235

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

INSERT INTO t1 VALUES(1234); INSERT INTO t1


VALUES(1235);

INSERT INTO t1 VALUES(1234); Output:


ERROR: unique constraint violated

INSERT INTO t1 VALUES(null); Output:


ERROR: cannot insert NULL INTO c##batch2pm.T1.F1 column
UNIQUE:
• It does not accept duplicates.

ORACLE 2PM KPHB MAY 2024 Page 214


• It accepts the nulls.
• When value is OPTIONAL and it should not be duplicated then use UNIQUE.

Example:
CUSTOMER
UNIQUE
CID CNAME MOBILE_NUMBER

1234 A 9123456789

1235 B

1236 C 9123456789 ERROR: duplicate

1236 C 8987654321

1237 D
NOT NULL:
• It does not accept nulls.
• It accepts duplicates.
• When value is MANDATORY and it can be duplicated then use NOT NULL.

Example:
EMPLOYEE
NOT NULL
EMPNO ENAME SAL

1234 A 6000

1235 B 8000

1236 B 7000

1237 ERROR: null 12000

CONSTRAINT DUPLICATES NULLS

PRIMARY KEY NO NO
UNIQUE NO YES

NOT NULL YES NO


PK = UNIQUE + NOT NULL

PK = no dups + no nulls

ORACLE 2PM KPHB MAY 2024 Page 215


CHECK:
• CHECK constraint is used to apply our own condition on column.

Example:
STUDENT CHECK(gender IN('M','F'))
SID SNAME GENDER

1001 ABC M

1002 XYZ F

1003 AA Z ERROR
Default:
• To apply default value to column we use DEFAULT.

Example:
STUDENT
DEFAULT 'NARESH' DEFAULT 'HYD' DEFAULT 20000
SID SNAME CNAME CCITY FEE

1234 A NARESH HYD 20000

1235 B NARESH HYD 20000

1236 C NARESH HYD 10000


REFERENCES [Foreign Key]:
• Foreign Key accepts primary key values of another table.
• FK accepts duplicates.
• FK accepts NULLS.

Example:

COURSE STUDENT FK
PK REFERENCES COURSE(CID)
CID CNAME SID SNAME CID
10 JAVA 1234 A 20
20 PYTHON 1235 B 10
30 HTML 1236 C 10
1237 D
1238 E 90 ERROR

ORACLE 2PM KPHB MAY 2024 Page 216


Examples on Constraints:

STUDENT
SID SNAME M1

SID don't PK
accept
dups
and
nulls
SNAME don't NOT
accept NULL
nulls
m1 b/w 0 CHECK
to 100
CREATE TABLE student
(
sid NUMBER(4) PRIMARY KEY, sname VARCHAR2(10) NOT NULL,
m1 NUMBER(3) CHECK(m1 BETWEEN 0 AND 100)
);
Example:

USERS_LIST
USERID UNAME PWD

1234 raju kumar@12345

userid don't accept dups and PK


nulls
uname don't accept dups and unique
nulls not null
pwd min 8 chars CHECK
CREATE TABLE users_list
(
userid NUMBER(4) PRIMARY KEY, uname VARCHAR2(20) UNIQUE NOT NULL, pwd
VARCHAR2(30) CHECK(length(pwd)>=8)
);

Example:

EMPLOYEE11

ORACLE 2PM KPHB MAY 2024 Page 217


EMPID ENAME DOJ GENDER SAL

empid don't accept dups and PK


nulls
ename don't accept nulls NOT
NULL
doj default value as today's DEFAULT
date
gender M or F CHECK

SAL min 5000 CHECK


CREATE TABLE employee11
(
empid NUMBER(4) PRIMARY KEY, ename VARCHAR2(10) NOT NULL, doj DATE DEFAULT
sysdate, gender CHAR CHECK(gender IN('M','F')), sal NUMBER(8,2) CHECK(sal>=5000)
);
INSERT INTO employee11(empid, ename, gender, sal) VALUES(1234,'A','M',12000);

Example:

DEPT1 EMPLOYEE1
PK [parent key] FK [child key]
DEPTNO DNAME REFERENCES dept1(Deptno)
10 HR EMPNO ENAME DEPTNO

20 SALES 1001 A 30

30 ACCOUNTS 1002 B 30
1003 C 10
master table / 1004 D 10
parent table
1005 E
1006 F 80 ERROR

detailed table /
DEPT1 child table
PK
DEPTNO DNAME

ORACLE 2PM KPHB MAY 2024 Page 218


CREATE TABLE dept1
(
deptno NUMBER(2) PRIMARY KEY, dname VARCHAR2(10)
);

EMPLOYEE1
FK
PK REFERENCES dept1(Deptno)
EMPNO ENAME DEPTNO
CREATE TABLE employee1
(
empno NUMBER(4) PRIMARY KEY, ename VARCHAR2(10),
deptno NUMBER(2) REFERENCES dept1(deptno)
);

ORACLE 2PM KPHB MAY 2024 Page 219


Creating tables with constraint names
Tuesday, June 25, 2024 3:09 PM

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

Naming Constraints:
• We can give names to constraints.
• To identify constraint uniquely in database we use constraint name.
• When we define constraint it's better to give constraint name. If we don't
give constraint name implicitly ORACLE defines a constraint name.
• ORACLE DEFINED NAME IS: a six digit random number will be prefixed with
SYS_C Example: SYS_C002748

• To disable or enable or drop the constraints, constraint names are useful.

Example on creating table with constraint names:

STUDENT1
SID SNAME M1
don’t
accept
dups and
SID nulls PK c1

M1 0 t0 100 CHECK c2
CREATE TABLE student1
(
sid NUMBER(4) CONSTRAINT c1 PRIMARY KEY, sname VARCHAR2(10),

ORACLE 2PM KPHB MAY 2024 Page 220


m1 NUMBER(3) CONSTRAINT c2 CHECK(m1 BETWEEN 0 AND 100)
);

Note:
• We cannot give constraint name to DEFAULT constraint.

CREATE TABLE student1


(
sid NUMBER(4), sname
VARCHAR2(10), m1 NUMBER(3),
CONSTRAINT c3 PRIMARY KEY(Sid),
CONSTRAINT c4 CHECK(m1 BETWEEN 0 AND 100)
);

Wednesday, June 26, 2024 3:26 PM

We can apply constraints at 2 levels. They are:


• column level constraint
• table level constraint

Column Level Constraint:


ORACLE 2PM KPHB MAY 2024 Page 221
• If constraint is defined in column definition then it is called "Column Level
Constraint".

Example:

STUDENT2
SID SNAME M1
PK CHECK

CREATE TABLE student2


(
sid NUMBER(4) CONSTRAINT c3 PRIMARY KEY, sname VARCHAR2(10),
m1 NUMBER(3) CONSTRAINT c4 CHECK(m1 BETWEEN 0 AND 100)
);

Table Level Constraint:


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

Example:

STUDENT3
SID SNAME M1
PK CHECK
CREATE TABLE student3
(
sid NUMBER(4), sname
VARCHAR2(10), m1 NUMBER(3),
CONSTRAINT c5 PRIMARY KEY(sid),
CONSTRAINT c6 CHECK(m1 BETWEEN 0 AND 100)
);

Note:

ORACLE 2PM KPHB MAY 2024 Page 222


• All 6 constraints can be applied at column level. PK, UNIQUE, NOT
NULL, CHECK, DEFAULT, FK

• Only 4 constraints can be applied at table level. PK, UNIQUE,


CHECK, FK

NOT NULL and DEFAULT cannot be applied at table level.

Example:
COURSE1 STUDENT1
PK (c10) FK (c11)
CID CNAME references course1(Cid)
SID SNAME CID
10 JAVA
20 C# 1001 A 20

30 ORACLE 1002 B 90 ERROR

CREATE TABLE course1


(
cid NUMBER(2), cname
VARCHAR2(10),
CONSTRAINT c10 PRIMARY KEY(cid)
);
CREATE TABLE student1
(
sid NUMBER(4), sname
VARCHAr2(10), cid NUMBER(2),
CONSTRAINT c11 FOREIGN KEY(cid) REFERENCES course1(cid)
);

Why table level constraint?

2 reasons:

ORACLE 2PM KPHB MAY 2024 Page 223


• To apply combination of columns as constraint • To use another column
name in constraint

applying combination of columns as constraint:

STUDENT
PK(SID, SUBJECT) => composite primary key
SID SNAME SUBJECT MARKS
1001 A M1 70
1001 A M2 66
1001 A M3 70
1002 B M1 66
1002 B M2 50
1002 B M3 80
1001 M1 ERROR: duplicate
null ERROR
null ERROR
Composite primary key:
• If we set combination of columns as PK then it is called "Composite
Primary Key".
• It can be applied at table level only.

STUDENT
PK(SID, SUBJECT) => composite primary key
SID SNAME SUBJECT MARKS
CREATE TABLE student
(
sid NUMBER(4), sname
VARCHAR2(10), subject CHAR(2),
marks NUMBER(3),
CONSTRAINT c20 PRIMARY KEY(sid, subject)
);

ORACLE 2PM KPHB MAY 2024 Page 224


Using another column name in constraint:

PRODUCTS
PID PNAME MANUFACTURED_DATE EXPIRY_DATE
1001 A 27-JUN-24 25-DEC-23 ERROR
CREATE TABLE products
(
pid NUMBER(4), pname
VARCHAR2(10), manufactured_date
DATE,
expiry_date DATE,
CONSTRAINT c21 CHECK(expiry_Date>manufactured_date)
);

ORACLE 2PM KPHB MAY 2024 Page 225


Altering Constraints
Thursday, June 27, 2024 2:46 PM

ALTER:

• ALTER => Change

• It is used to change structure of the table.

• Using ALTER command we can:


○ Add the columns
○ Rename the columns
○ Drop the columns
○ Modify the field sizes
○ Modify the data types
○ Add the Constraints
○ Rename the Constraints
○ Disable the Constraints
○ Enable the Constraints ○
Drop the Constraints

Syntax:

ALTER TABLE <table_name> [ADD CONSTRAINT <con_name> <con_type>(<column>)]


[RENAME CONSTRAINT <old_name> TO <new_name>]
[DISABLE CONSTRAINT <con_name>]
[ENABLE CONSTRAINT <con_name>]
[DROP CONSTRAINT <con_name>];

Example:

STUDENT
SID SNAME M1
CREATE TABLE student
(
sid NUMBER(4), sname
VARCHAR2(10), m1
NUMBER(3)
);
Note:

ORACLE 2PM KPHB MAY 2024 Page 244

Using ADD keyword we can add Table Level Constraints only.


Using MODIFY keyword we can add Column Level Constraints.

Add PK to sid:
ALTER TABLE student ADD CONSTRAINT c30 PRIMARY KEY(sid);
(or)
ALTER TABLE student MODIFY sid CONSTRAINT c30 PRIMARY KEY;

Add Not Null to sname:


ALTER TABLE student MODIFY sname COSNTRAINT c31 NOT NULL;

Add CHECK constraint to m1:


ALTER TABLE student ADD CONSTRAINT c32 CHECK(m1 BETWEEN 0 AND 100);

Renaming constraint [PK name c30 to z]:


ALTER TABLE student RENAME CONSTRAINT c30 TO z;

Disabling Constraint [disable PK z]:


ALTER TABLE student DISABLE CONSTRAINT z;

Enabling Constraint [Enable PK z]:


ALTER TABLE student ENABLE CONSTRAINT z;

Dropping Constraint [drop PK z]:


ALTER TABLE student DROP CONSTRAINT z;

user_constraints:
• it is a system table / built-in table / readymade table. • It maintains all

constraints info to see list of constraints of specific table: column table_name

format a15

SELECT table_name, constraint_name, constraint_type


FROM user_constraints
WHERE table_name='EMPLOYEE1';
ORACLE 2PM KPHB MAY 2024 Page 245

SET OPERATORS
Thursday, June 27, 2024 3:29 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 A


A M B => it gives all elements from A except common elements

B M A = {6,7,8} => specific elements of B

SET OPERATORS:

Syntax:

<SELECT QUERY>
<SET OPERATOR>
<SELECT QUERY>;

SET OPERATOR is used to combine the result of 2 select queries.

ORACLE SQL provides following SET OPERATORS:


ORACLE 2PM KPHB MAY 2024 Page 228
• UNION
• UNION ALL
• INTERSECT
• MINUS

UNION:
It combines result of 2 select queries without duplicates.

UNION ALL:
It combines result of 2 select queries including duplicates.

INTERSECT:
It gives common records from result of 2 select queries.

MINUS:
It gives specific records from first select query result.

Example:

CRICKET FOOTBALL

SID SNAME SID SNAME


1001 A 5001 D
1002 B 1002 B
1003 C 5002 E
Display the students who are participating in CRICKET and
FOOTBALL:

SELECT sid, sname FROM cricket


UNION
SELECT sid, sname FROM football;

ORACLE 2PM KPHB MAY 2024 Page 230


SID SNAME
1001 A
1002 B
1003 C
5001 D
5002 E
Display the students who are participating in CRICKET and FOOTBALL
including duplicates:

SELECT sid, sname FROM cricket


UNION ALL
SELECT sid, sname FROM football;
SID SNAME
1001 A
1002 B
1003 C
5001 D
1002 B
5002 E
Differences b/w UNION and UNION ALL:

UNION •does not give duplicates


•slower

UNION ALL •it gives duplicates


•faster
Display the students who are participating in both CRICKET and
FOOTBALL:

SELECT sid, sname FROM cricket


INTERSECT
SELECT sid, sname FROM football;

ORACLE 2PM KPHB MAY 2024 Page 231


SID SNAME
1002 B
Display the students who are participating only in cricket and not
participating in football: [specific records of CRICKET]

SELECT sid,sname FROM cricket


MINUS
SELECT sid,sname FROM football;
SID SNAME
1001 A
1003 C
Display the students who are participating only in football and not
participating in cricket: [specific records of FOOTBALL]

SELECT sid,sname FROM football


MINUS
SELECT sid,sname FROM cricket;
SID SNAME
5001 D
5002 E
Rules of Set Operators:

• no of columns in both select queries must be same.

Example:
SELECT sid FROM cricket
UNION
SELECT sid, sname FROM football; Output:
ERROR

• Corresponding columns data types of both select queries must be


same.

Example:

ORACLE 2PM KPHB MAY 2024 Page 232


SELECT sid, sname FROM cricket
UNION
SELECT sname, sid FROM football; Output:
ERROR

deptno 10 deptno 20
deptno 10 deptno 20

CLERK CLERK
MANAGER MANAGER
PRESIDENT ANALYST
Display the job titles offered by 10 and 20 depts:

SELECT job FROM emp WHERE deptno=10


UNION
SELECT job FROM emp WHERE deptno=20;

CLERK
MANAGER
PRESIDENT ANALYST

Display the common job titles offered by deptno 10 and 20:

SELECT job FROM emp WHERE deptno=10


INTERSECT
SELECT job FROM emp WHERE deptno=20;

CLERK
MANAGER

Display the job titles offered by deptno 10 only and those should not be
offered by deptno 20:

ORACLE 2PM KPHB MAY 2024 Page 233


SELECT job FROM emp WHERE deptno=10
MINUS
SELECT job FROM emp WHERE deptno=20;

PRESIDENT

Display the job titles offered by deptno 20 only and those should not be
offered by deptno 10:

SELECT job FROM emp WHERE deptno=20


MINUS
SELECT job FROM emp WHERE deptno=10;

ANALYST

Example:

EMP_IND EMP_US

EMPID ENAME EMPID ENAME


1001 A 5001 C
1002 B 5002 D
Display the emp reocrd swho are working for INDIA and
US:

SELECT * FROM emp_ind


UNION
SELECT * FROM emp_us;
EMPID ENAME
1001 A
1002 B

ORACLE 2PM KPHB MAY 2024 Page 234


5001 C

5002 D
Differences b/w Joins and UNION:
JOINS •combines the columns
•it is used for vertical merging
•it is applied on dissimilar structures
UNION •combines the rows
•it is used for horizontal merging
•it is applied on similar structures
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME
ENAME DNAME
JOINS

EMP_IND EMP_US
EMPID ENAME EMPID ENAME
1001 A 5001 C
1002 B 5002 D
UNION
EMPID ENAME
1001 A
1002 B
5001 C
5002 D

ORACLE 2PM KPHB MAY 2024 Page 235


Friday, June 28, 2024 2:52 PM

TABLES

String lower() upper() initcap()


Ltrim() Trim() Trim()
Lpad() Rpad() length()
concat()

Conversion to_char() to_number() to_date()

Aggregate / Group sum() max() min() count() avg()

Analytic rank() dense_rank() row_number()

Number mod() ceil() floor() trunc() round()

ORACLE 2PM KPHB MAY 2024 Page 236


Date
Add_months() sysdate systimestamp
months_between() last_day() next_day()

Special NVL() NVL2() Decode()


SQL Commands

DDL DRL/DQL DML TCL DCL/ACL


metadata retrievals manipulations transactions accessibility
select insert update commit grant revoke
delete insert rollback
savepoint
create all

alter merge

drop
flashback
purge
truncate
rename
Built-In Functions:
Clauses:

FROM emp
WHERE sal>3000
GROUP BY deptno
HAVING count(*)>5
SELECT ename, sal
DISTINCT job
ORDER BY sal DESC
OFFSET 4 ROWS
FETCH FIRST 4 row only

ORACLE 2PM KPHB MAY 2024 Page 237


Joins: to retrieve data from multiple tables Types of

Joins:

Inner Join => matched


Equi => based on =
Non-Equi => based on other than =

Outer Join
Left outer = matched + um from L
Right outer = matched + um from R
Full outer = matched + um from L & R

Self Join => a table is joined to itself

Cross Join => each record in one table will be joined


with every record in another.

Sub Queries:

2 types:

non-correlated => inner then outer


single row SQ => returns 1 row multi row SQ => returns multiple
rows inline view => SQ in FROM scalar => SQ in SELECT
correlated => outer then inner

Constraints:

PK
UNIQUE

ORACLE 2PM KPHB MAY 2024 Page 238


NOT NULL
CHECK
DEFAULT
REFERENCES [FK]

SET OPERATORS:

UNION
UNION ALL
INTERSECT
MINUS

ORACLE 2PM KPHB MAY 2024 Page 239

You might also like