R SQL
R SQL
Oracle 6 PM Page 1
ORACLE
Monday, January 24, 2022 6:20 PM
ORACLE 19c
SQL
PL/SQL
Data
Information
Database
DBMS
RDBMS
Metadata
Data:
is a raw collection of facts about people or
places or things.
nareshit smartphone
1234
4 samsung
Ravi
2nd floor 20000
500
2 room no
100
raw material
engine Bike
seat Connecting
handle
Information
Data
sid sname marks
1234
Ravi Data Processing 1234 Ravi 500
500
processed one
unprocessed one
is in meaningful form
not in meaningful form
increases knowledge
does not increase knowledge of
of person
person
Micro Processor
Mother board Computer
Hard disk
RAM
.
.
Types of Data:
2 Types:
• Structured Data
• Unstructured Data
Structured Data:
data is made up of with letters, digits & special symbols
Oracle 6 PM Page 2
data is made up of with letters, digits & special symbols
Ex: 1234 Kiran Clerk 6000.00 H.NO.1-2-123
Unstructured Data:
data is in the form of audios, videos, images or documents
Ex: emp_photo emp_voice
Information:
If data is arranged in meaningful form then it is called
"Information"
Database:
• is a collection of interrelated data in an organized
form.
• Complete details about an organization.
College DB
Student
sid sname scity mobile
101 Srinu Hyd …
Marks
sid M1 M2 M3 tot avrg result
101 70 80 60 .. .. ..
Fee
sid total paid balanc
fee amount e
101 15000 10000 5000
DBMS:
• DataBase Management System/ Software.
• is a software that is used to create &
maintain the database.
Oracle 6 PM Page 3
maintain the database.
• allows us to store, manipulate & retrieve the
data of database.
• manipulate => INSERT / UPDATE / DELETE
• emp is joining in organization => INSERT
• emp got promotion => UPDATE [modify]
• emp left the organization => DELETE
• Retrieve => opening existing data [Read]
SQL PL/SQL
SQL Basics
=> DDL DML DCL Control Structures
TCL DRL Cursors
Operators Functions
Built-In Functions Procedures
Clauses in SQL Packages
SET Operators Triggers
Joins Exception Handling
Sub Queries Dynamic SQL
Views Collections
Indexes Working with LOBs
Synonyms
Sequences
Materialized views
RDBMS:
• Relational DataBase Management System / Software.
Before 1960s => manually in the books [papers]
• It is the software which is used to create & maintain
the database.
1960s => FMS => data in files
• Relation => Table 1976 => E.F.Codd
• We create & maintain database in the form of tables.
1970s => HDBMS [Hierarchical]
• Table => is a collection of rows & columns. RDBMS
NDBMS [Network]
Relation => Table
12 Rules
Examples:
Oracle, SQL Server, My SQL, DB2, Postgre SQL
Metadata:
• It is the data about the data.
• It describes about the data.
Marks
Oracle 6 PM Page 4
Marks
Ex:
Table Name => Marks Varchar2
Field Name => sid, sname, marks Number
Data Type => 25 => Number
kiran => varchar2
Field Size => Number(4) => max 4 digits => 9999
4 => field size
Varchar2(20) => max 20 chars
20 => field size
ORACLE:
• is a Relational DataBase Management Software
[RDBMS].
• Using Oracle database software, we create &
maintain the database in the form of tables. Oracle company established in
• It allows us to store, manipulate & retrieve the 1977 with the name "Software Development
data of database. Laboratories".
• manipulate => add / delete / modify
• retrieve => opening existing data [read] Larry Ellison => 1977
• second version introduced in 1979. 1977 => Software Development Laboratories
• latest version is Oracle 21c. 1979 => Relational Software Inc.
1983 => Oracle Corp.
SQL:
• Structured Query Language.
• we write the queries.
• we write these queries to communicate
with the database.
• query => is a request that is sent to DB C
Server. Java => Programming Languages
• Non-Procedural Language. It means, we
will not write any set of statements Software =>
here. Just we write the queries. => programs
• is a 4GL [4th generation language]. => instructions
In 4GLs, we much concentrate on what
to do rather than how to do.
• is a Unified Language. It means, it is
common for many relational database
management softwares.
Oracle 6 PM Page 5
SQL provides 5 sub languages. They are:
DDL Create
[Data Definition Language] Alter
Drop
Truncate
Rename
DDL:
• Data Definition Language.
• It deals with metadata. customer
cid cname cust_city
Create
1001
Alter
1002
Drop
Truncate
Rename cid => number
DRL / DQL:
• Data Retrieval Language
• Data Query Language
• Retrieval => opening existing data [read]
• Query => request
• It deals with data retrievals
SELECT
DML:
• Data Manipulation Language.
• deal with data manipulations
• Manipulation = add / delete / modify opening account => INSERT
• emp joined => add {INSERT} closing account => DELETE
• emp left => delete {DELETE} withdraw / deposit => UPDATE
• emp got promotion => modify {UPDATE}
Insert
Delete
Update
Insert All
Merge
Oracle 6 PM Page 6
Merge
DCL / ACL :
• Data Control Language
• Accessing Control language
• It deals with data accessibility.
Example:
manager
user: ravi
emp
empno ename job sal clerk
5001
user: kiran
5002
TCL:
• Transaction Control language.
• It deals with transactions.
• Transaction => is a series of commands
• series of SELECT commands
• series of INSERT / UPDATE / DELETE commands
Oracle 6 PM Page 7
DDL:
• Data Definition Language.
• It deals with the metadata.
Create:
• is used to create the database objects like tables,
view, indexes …etc.
Oracle Server
Schema [User]
Tables
Views
Indexes
Sequences
Synonyms
Materialized views
Procedures
Functions
Packages
Triggers
student
sid sname Number(4) => 9999
1001 Ravi 10000 => 5digits ERROR
Oracle 6 PM Page 8
Data Types in SQL:
• Data Type tells the type of data colln of facts
which a column can hold.
• It also tells the valid range. 25
Ravi
A
67.89
Number(p,s)
float
binary_float
binary_double
Character Related char(n)
varchar2(n)
long Raju
CLOB mobile
clerk
nChar(n)
nVarchar2(n)
nCLOB
Date & time Related Date
Timestamp
Binary Related BFILE
BLOB
Number(p) Number(p,s)
int float
integer binary_float
binary_double
Number(p):
• It is Integer related data type.
• It is used to hold integers.
• p => precision => max no of digits
• valid range of p: 1 to 38
• max value: 99999…..999 [9 38digits]
• min value: -99999…..999 [-9 38digits]
cid
--------
Example: 123456
rno Number(2) => -99 to 99 123457
123458
sub1_marks Number(3) => -999 to 999
Mobilenum Number(10)
creditcard_num Number(16)
aadhar_num Number(12)
Oracle 6 PM Page 9
Number(p,s):
• used to hold floating point values.
• p => precision => max no of digits
• s => scale => max number of decimal places
• p => valid range => 1 to 38
• s => valid range => -84 to 127
p=8 p=5
s=2 s=2
char(n)
varchar2(n)
long
CLOB
nchar(n)
nvarchar2(n)
nCLOB => N => National
Char(n):
• it is used to hold a set of characters.
• It is fixed length char data type.
• n => max no of chars
Varchar2(n):
• it is used to hold a set of characters.
• it is variable length char data type.
• n => max no of chars
CharDemo
f1 char(10) f2 varchar2(10)
sai7spaces sai
arun6spaces arun
naresh4spaces naresh
Oracle 6 PM Page 10
Gender char(1) ename varchar2(10)
---------- -----------
M sai
F vijay
ramu
STATE_CODE char(2)
--------------------- job varchar2(20)
AP -----------
TS programmer
WB DBA
UP team leader
manager
Country_code char(3) CEO
------------------------
IND
AUS prod_name
USA ----------------
hard disk
VEHICLE_NUM char(10) RAM
------------------------ keyboard
TS09EY1234 mouse
PAN_CARD_NUM char(10)
----------------------
ABC 56 WE123
Char(n):
• it is used to hold a set of characters.
• It is fixed length char data type.
• n => max no of chars
• max size: 2000 Bytes
• Default size: 1
• Ex: Gender char => char(1)
• Ex: state_Code country_Code gender
pan_num veh_num
Varchar2(n):
• it is used to hold a set of characters.
• it is variable length char data type.
• n => max no of chars
• max size: 4000 Bytes
• Default size: no default size
• Ex: Gender varchar2 => ERROR
• Gender varchar2(1) => valid
• Exs: ename job product_name cust_name
Char Varchar2
• Fixed length char data type • variable length char data type
Why Varchar2?
Oracle 6 PM Page 11
Oracle 2, 3, 4, 5, 6 => Varchar Data type
There was no Varchar2 data type in above
versions.
According to E.F.Codd,
there should be difference b/w null and space
This rule not followed by varchar data type
eid comm
------ -----
1234 2000
1235 0
1236 null
Long:
• is used to hold a set of characters. char(n)
• max size: 2 GB 2000 bytes
• It's better to avoid of using Long data type.
Because some restrictions are there on
Long data type. varchar2(n)
• We can create only one column as long 4000 bytes
type for a table. We cannot take many
columns as long type for a table.
• We cannot use built-in functions on Long
type
Example:
Cust_Feedback
Experience_summary
Complaints
CLOB:
• Character Large Object
• It is used to hold large amounts of text.
• max size: 4GB
• We can create many columns as CLOB type
in a table
• We can use built-in functions on CLOB type.
Examples:
Cust_Feedback
Complaints
Experience_summary
Oracle 6 PM Page 12
char(n) => 2000 bytes Single Byte Char Data types
varchar2(n) => 4000 bytes ASCII Code Char data types
long => 2GB English only
clob => 4GB
n => National
In C In Java
A to Z
a to z
, @ #$
Date
Timestamp [Oracle 9i]
Date:
• is used to hold date values.
• default date format: DD-MON-RR
• it can hold date, month, year, hour, minute and
second
• Fixed length data type.
• memory: 7 Bytes
• default time value: 12:00:00 AM [mid night time]
Examples:
Date_Of_Bith
Date_Of_Joining
Order_date
Deliver_date
Timestamp:
• can hold date, month, year, hour, minute,
second and fractional seconds.
• fixed length data type
• memory: 11 bytes
Ex:
Transaction_date_time
Oracle 6 PM Page 13
Binary Related Data Types: Structured data
letters
BFILE
digits
BLOB
symbols
These 2 data types are used to maintain
multimedia objects like audios, videos, images …etc. Unstructured Data
audios
videos
BFILE: images
• Binary File Large Object data type.
• It maintains the path of the file.
• External Large Object.
• It is not secured one. Because multimedia object
will be stored out of the database.
• bfilename() function is used to maintain the file
path.
BFILE
BLOB:
• Binary Large Object.
• Multimedia Object will be stored
inside of the database.
• Internal Large Object.
• we need to write PL/SQL program
to store binary data.
Database
4 categories: 100.00
CLOB
Timestamp
Create:
Syntax:
Oracle 6 PM Page 14
Syntax:
Insert:
Syntax:
EX-1:
student
sid sname marks
1001 Ramu 75
1002 Kiran 56
max marks: 100
Creating table:
Output:
sid number(4)
sname varchar(10)
marks number(3)
output:
Table_name
-----------------
student
emp
dept
..
Oracle 6 PM Page 15
Inserting records: 1001 Ramu 75
1002 Kiran 56
Insert into student
values(1001,'Ramu',75);
output:
1 row created.
output:
enter value for sid:1003
enter value for sname: vijay
run (or) / => runs recent command
enter value for marks: 55
1 row created
/
enter value for sid:1004
enter value for sname: sai
enter value for marks: 88
/
enter value for sid:1005
enter value for sname: sravan
enter value for marks: 67
Log in as DBA:
user name: system
password: nareshit
[during s/w installation u have
given password. i.e DBA password]
Oracle 6 PM Page 16
c## => common user
Ex on creating table:
employee
empno ename job sal doj
1001 Ravi clerk 8000 23-nov-2019
/
enter value for empno: ….
enter value for ename: …
…
..
Oracle 6 PM Page 17
Inserting limited column values:
Insert into
employee(empno,ename,job)
values(1006,'A','manager');
Insert into
employee(ename,job,empno)
values('B','clerk',1007);
Null:
• Null value means empty / blank.
• Null is not equals to 0 or space.
• When the value is unknown we insert null value.
emp
empno ename job sal
1001 AA CLERK
1002 BB manager 12000
student
sid sname M1
1001 AA 70
1002 BB
1003 CC 0
Null:
• Null value means empty / blank.
• Null is not equals to 0 or space.
• When the value is unknown we
insert null value.
• when null is participated in
expression then result will be
null only.
• Ex:
set pages 200 lines 200
○ 10+20 = 30
○ 10 + null = null
pages 200:
○ 10-null = null
in one page it
• Null comparison is not possible
can display 200 records
using = [equals to] operator.
• "IS NULL" operator is used
lines 200:
to compare with null value.
in one line it
Ex:
can display 200 chars
comm=300 //valid
comm=1400 //valid
comm=null //invalid => no rows
selected empno Number(4) ename doj
comm is null //valid => null -----------
comparing comm value with null 1234 => valid
value A-1234
• Null can be accepted by any data null
type column. number data type can accept only
digits
Oracle 6 PM Page 18
Example:
Customer
cid cname ccity mobile
1001 A Hyd 90123……..
1002 B null null
IMPLICIT:
1002 B
total 4 values
we are passing 2 values
remaining 2 values will be inserted as NULL implicitly
1004 D 9012389764
Insert into
customer(cid,cname,mobile)
values(1004,'D',9045678923);
2nd way:
1005 E
Oracle 6 PM Page 19
Constraints:
Field Definition
Constraints:
• Constraint is a rule that is applied on a column.
• It restricts the user from entering invalid data. Ex:
• It is used to maintain data integrity. max marks: 100
• Data Integrity means, maintaining accurate & student
quality data. sid sname M1 min=> 0
1 A 56 max => 100
Oracle SQL provides following constraints:
2 B 786
• Primary Key
• Unique
500 seats
• Not Null
flight
• Check
• Default pid pname seatnum
• References [Foreign Key] 101 Ravi 754
Gender
------------
Primary Key:
M
• should not accept duplicate values.
F
• should not accept null values.
Ex:
student
customer
sid sname M1
1001 Ravi 56 cid cname ccity
1002 Raju 78 Ravi Hyd
Vijay 93 Raju Hyd
1003 Ravi 78 Ravi Mumbai
1001 Kiran 66 Raju Mumbai
Duplicate
Unique:
• It does not accept duplicate values.
• It accepts the null values.
• to maintain null or unique values, use it
Example:
Customer
Oracle 6 PM Page 20
1001 Ravi 90123… [email protected] 1234…..
1002 Srinu qwer@gmail
1003 Ramu 89123… [email protected]
Not Null:
• should not accept null values.
• it accepts duplicate values.
• when we want to demand for a
value & accept the duplicate the
value, use it.
Ex:
emp
Check:
• is used to apply our own rules on a column.
Ex:
Max Marks: 100
sid sname M1
min marks: 0
1 A 78 max marks: 100
2 B 123
emp
Default:
• It is used to apply default value to a column.
Oracle 6 PM Page 21
103 C 5000 XYZ Hyd
Ex:
course student
Dept emp
Examples on constraints:
Ex-1:
student1
sid sname M1
sid => PK
sname => Not Null
M1 => b/w 0 to 100
Oracle 6 PM Page 22
Insert into Student1 values(null,'B',55); --ERROR
Note:
When we define the constraint we have to give
constraint name. If we don't give constraint
name ORACLE gives constraint name implicitly
by prefixing it with "sys_c"
Ex: sys_c001234
Ex-2:
Student2
sid sname FEE cname ccity
Ex on Foreign Key:
Course Student3
Oracle 6 PM Page 23
Ex on Foreign Key:
Course Student3
PK
cid cname sid sname cid
10 Python 5001 A 30
20 Java 5002 B 20
30 C# 5003 C 70
Assignment:
Dept Emp
deptno dname empno ename deptno
10 HR 1001 A 30
20 Sales 1002 B 10
30 Accounts 1003 C 90
Naming Constraints:
Oracle 6 PM Page 24
Ex on naming constraints:
Student5
sid sname M1
User_Constraints:
It maintains all constraints information.
Desc User_Constraints;
Column definition:
Oracle 6 PM Page 25
References
PK => sid
Check => M1
Create Table student7
(
sid number(4),
sname Varchar2(10),
M1 Number(3),
constraint ccc1 Primary Key(sid),
constraint ccc2 Check(M1>=0 and M1<=100)
);
Dept1 Emp1
deptno dname empno ename deptno
10 Sales 1001 A 30
20 HR 1002 B 10
30 Research 1003 C 90
DDL Commands:
Create
Alter
Drop
Truncate
Rename
Flashback
Purge
Alter:
• Alter => Change
is used to change the structure of table.
Oracle 6 PM Page 26
• is used to change the structure of table.
add:
is used to add the columns
Ex:
student8
sid sname
sid sname M1
adding a column [M1]:
Alter Table student8 add M1 Number(3);
desc student8;
sid
sname
M1
Rename Column:
[rename m3 column to maths]
sid sname M1 M2 M3
student8
sid sname M1 M2 Maths
Oracle 6 PM Page 27
Alter table student8 drop(Maths);
student8
sid sname M1 M2
modify:
is used to modify the field sizes or data types.
student8
sid sname
sname
-----------
Raju
Kiran
Vijay
Naresh
sid
--------
Example on Alter:
emp11
empno ename
100000.00
Oracle 6 PM Page 28
Add job & sal columns:
Disabling constraint:
Enabling Constraint:
Renaming Constraint:
Dropping Constraint:
ADD CONSTRAINT:
• we can add table level constraints only.
• table level constraints => 4
○ Primary Key
○ Unique
○ Check
○ References [Foreign Key]
Customer
Oracle 6 PM Page 29
Adding default constraint to State column:
std
sid sname M1
Course Student
cid cname sid sname cid
DDL Commands:
Create
Alter
Truncate
Drop
Flashback
Purge
Rename
TRUNCATE:
• is used to delete all records from
the table.
• It clears the memory.
customer
cid cname ccity
5001 A Hyd
5002 B Chennai
Syntax:
Oracle 6 PM Page 30
Truncate Table <table_name>;
Example:
Truncate table emp11;
DROP
FLASHBACK => Oracle 10g
PURGE => Oracle 10g
DROP:
• is used to drop the tables.
• Dropped tables will be stored in recycle
bin.
• If we want to recollect it in future, we can
recollect it from recycle bin
• Before Oracle 10g version "RecycleBin"
concept was not available.
• "RecycleBin" concept introduced in Oracle
10g version
Syntax:
Dropping a Table:
show recyclebin;
Flashback:
• used to recollect the dropped tables from recycle
bin.
Syntax:
For Ex:
Oracle 6 PM Page 31
name "student1"
• Now, we are Flashbacking the table
"student1". It will give ERROR
• Within the schema, table name must be
unique. That's why it gives ERROR
• In this situation, recollect dropped table
with new name. For this we use
"RENAME TO <NEW_NAME>".
Purge:
is used to delete the dropped table
from recycle bin.
Syntax:
(OR)
Emptying Recyclebin:
DDL Commands:
Create
Alter
Truncate
Drop
Flashback
Purge
Rename
Rename:
used to rename the database objects
Syntax:
SQL:
5 sub languages:
Oracle 6 PM Page 32
DDL Create
Alter
Drop
Truncate
Flashback
Purge
Rename
DRL / DQL SELECT
DML
DCL
TCL
DRL / DQL :
• DRL => Data Retrieval Language
• DQL => Data Query Language
• Retrieval => opening existing data
• Query => is a request that is sent to DB Server
• SELECT command comes under DRL.
• It is used to retrieve the data from the table.
Syntax of SELECT:
Select ename,sal
From emp
SELECT [DISTINCT] <column_list> / *
Where sal>3000;
FROM <table_list>
[WHERE <condition>]
[GROUP BY <grouping_column_list>]
[HAVING <group_condition>]
[ORDER BY <column_list> Asc / Desc] ;
ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES - are part of query
limited rows:
limited columns:
Oracle 6 PM Page 33
OPERATORS in SQL:
Operator:
is a symbol that is used to perform operations
like arithmetic or logical operations.
Ex: sal*12 sal>5000
Arithmetic + - * /
Relational (or) < <= > >= = <> (or) != (or) ^=
Comparison equals not equals
Logical And Or Not
Special IN NOT IN
BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL
SET UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||
Miscellaneous EXISTS
ANY
ALL
PIVOT
UNPIVOT
Arithmetic Operators:
Arithmetic operators are used to perform
Arithmetic Operations.
+ Addition 5+2 = 7
- Subtraction 5-2 = 3
* Multiplication 5*2 = 10
/ Division 5/2 = 2.5
DUAL:
• is a dummy table.
• It is used to work with non-database
values temporarily.
Calculate 2+3+4:
2+3+4
------------
9
TOTAL
----------
9
TOTAL
----------
9
Oracle 6 PM Page 34
SELECT 2+3+4 as total value FROM dual; --ERROR
total value
-----------------
9
SELECT ename,sal,
sal*0.1 as TA,
sal*0.2 as HRA,
sal*0.15 as DA,
sal*0.05 as TAX,
sal+sal*0.1+sal*0.2+sal*0.15-sal*0.05 as GROSS
FROM emp;
student
sid sname M1 M2 M3
1 A 50 80 70
2 B 70 30 90
SELECT sname,
M1+M2+M3 as TOTAL,
(M1+M2+M3)/3 as AVRG
Oracle 6 PM Page 35
(M1+M2+M3)/3 as AVRG
FROM student;
NOTE:
SQL not case sensitive language. But for string
comparison, it is case sensitive.
Oracle 6 PM Page 36
Display the emp records who are working in deptno 20:
Display the emp records who are not working in deptno 30:
Logical Operators:
are used to perform logical operations
student
sid sname M1 M2 M3
1001 A 60 80 70
1002 B 50 35 80
Oracle 6 PM Page 37
WHERE M1>=40 and M2>=40 and M3>=40;
(or)
Oracle 6 PM Page 38
WHERE deptno!=30;
Special Operators:
• are also comparison operators
IN NOT IN
BETWEEN AND NOT BETWEEN AND
IS NULL IS NOT NULL
LIKE NOT LIKE
IN:
Syntax:
<column_name> IN(<val1>,<val2>,………);
(or)
Oracle 6 PM Page 39
Display all emps records except SCOTT and WARD:
BETWEEN AND:
Syntax:
Display the emp records whose sal is between 2000 and 3000:
[OR]
Display the emp records who joined in the years 1982,1983 &
1984:
IS NULL:
• It is used for null comparison.
• To compare a column value with NULL, use IS NULL.
We cannot use = [equals operator] for null comparison.
Oracle 6 PM Page 40
• We cannot use = [equals operator] for null comparison.
Syntax:
<column_name> IS NULL
Like Operator:
• used to compare column value with text pattern.
_ replaces 1 character
% replaces 0 or any number of characters
Syntax:
Oracle 6 PM Page 41
4 chars:
SMITH
SELECT * FROM emp WARD
WHERE ename LIKE '____';
SELECT empno,ename,hiredate
FROM emp
WHERE
hiredate LIKE '%80'
Or
hiredate LIKE '%83';
Oracle 6 PM Page 42
mail_id
-----------
[email protected]
[email protected]
Concatenation Operator ( || ):
• concatenate => combine
• is used to combine the strings.
Syntax:
string1 || string2 || string3
Oracle 6 PM Page 43
DML
Thursday, February 17, 2022 6:24 PM
DML Commands:
• Data Manipulation Language.
• Manipulation = INSERT + UPDATE[modify] +DELETE
• For Ex, emp joined in Organization => INSERT
• emp got promotion => UPDATE
• emp left from org => DELETE
• DML deals with data.
• All DML commands are not auto-committed. Where as
DDL commands are auto-committed.
• After using DML command to save the transaction use
COMMIT command.
• After using DML command to cancel the transaction use
ROLLBACK command.
COMMIT
ROLLBACK
SAVEPOINT
COMMIT [SAVE]:
• is used to make the changes the permanent.
It means, it is used to save the transactions.
• When COMMIT command is executed, All the
changes of Oracle Instance [RAM] will be
applied to Oracle Database [Hard Disk].
INSERT:
• used to insert the records.
• Using INSERT command, we can
○ insert single record
○ insert the record using parameter
○ insert limited column values
○ insert limited column values by changing order
○ insert the records from existing table [copying records]
Syntax:
Example:
Customer
cid cname ccity
Oracle 6 PM Page 45
Create Table Customer
(
cid number(4),
cname varchar2(10),
ccity varchar2(10)
);
Inserting a record:
/
enter value for cid:
enter value for cname:
enter value for ccity:
Oracle 6 PM Page 46
Inserting records from existing table:
[Copying the records from one table to another]
Customer Emp
cid cname ccity empno ename job sal
1001 5001 ..
1002 5002 ..
5003 ..
5004 ..
Syntax:
Ex:
INSERT INTO customer(cid,cname)
SELECT empno,ename FROM emp;
Update Command:
• is used to modify [update] the data.
• Using this command we can:
○ update single column value of single record
○ update multiple column values of single record
○ update a set of records
○ update all records
○ update the records using parameters
Oracle 6 PM Page 47
Syntax:
UPDATE <table_name>
SET <column1>=<value1>[,<column2>=<value2>,….]
[WHERE <condition>];
Ex:
Increase 2000 rupees salary to the emp whose
empno is 7499:
UPDATE emp
SET sal=sal+2000
WHERE empno=7499;
Exs:
Set sal value as 4000 to the employees whose sal is
null:
UPDATE emp
SET sal=4000
WHERE sal IS NULL;
UPDATE emp
SET sal=sal+2000
WHERE job='CLERK';
Ex:
Update job value as manager and salary value as
5000 to the emp whose empno is 7369:
Oracle 6 PM Page 48
UPDATE emp
SET job='MANAGER', sal=5000
WHERE empno=7369;
Ex:
Increase sal as following:
7369 => increase 1500
7499 => increase 2000
7900 => increase 1000
UPDATE emp
SET sal=sal+&amount
WHERE empno=&empno;
/
Enter amount: 2000
Enter empno: 7499
UPDATE emp
SET sal=sal+sal*0.1
WHERE job IN('MANAGER','CLERK');
Oracle 6 PM Page 49
WHERE job IN('MANAGER','CLERK');
UPDATE emp
SET sal=sal+sal*0.2
WHERE comm is not null;
UPDATE emp
SET sal=sal+sal*0.15
WHERE (sysdate-hiredate)/365>40;
UPDATE emp
SET sal=sal+sal*0.2, comm=comm+comm*0.1
WHERE comm is not null;
UPDATE emp
SET deptno=10
WHERE deptno=20;
UPDATE emp
SET comm=null
WHERE comm is null;
Oracle 6 PM Page 50
IN C, JAVA: IN SQL:
== equals = equals
= Assignment
= Assignment
WHERE <condition>
x=50
WHERE sal=3000 => comparison
x==50
SET sal=3000 => Assignment
UPDATE emp
SET comm=null
WHERE comm is not null;
Note:
FOR null comparison use "IS NULL"
FOR null null assignment use " = " [Assignment operator]
UPDATE emp
SET sal=sal+sal*0.1, comm=500;
Oracle 6 PM Page 51
SET sal=sal+sal*0.1, comm=500;
Delete:
• is used to delete the records.
• Using this command we can:
○ delete single record
○ delete a set of records
○ delete all records
○ delete records using parameters
Syntax:
Delete From <table_name> [WHERE <condition>];
Ex:
Delete the emp record whose empno is 7902:
Ex:
Delete the emp records whose job title is
'SALESMAN':
Oracle 6 PM Page 52
DELETE FROM emp
WHERE (sysdate-hiredate)/365 > 40;
Ex:
Delete all emp records from emp table:
/
enter value fro empno: 7499
Oracle 6 PM Page 53
DELETE FROM emp;
(or)
TRUNCATE TABLE emp;
DELETE TRUNCATE
ORACLE SERVER
INSTANCE DB
Oracle 6 PM Page 54
Block => default size => 8KB
1 Block = 8 KB
1 Extent = 8 Blocks (64 KB)
DB
TABLESPACE [USERS]
SCHEMA [USER => c##batch6pm]
Segments
Extents
Blocks [pages]
Data
TRUNCATE VS DROP:
TRUNCATE =>
deletes entire table data. But does not delete the
structure of table
Oracle 6 PM Page 55
DROP =>
deletes entire table. It deletes table data & table
structure also.
SQL:
DDL
DRL
DML
TCL
DCL
DCL:
• Data Control Language.
• It deals with Data Accessibility.
• SQL provides 2 DCL commands:
○ Grant
○ Revoke
Grant:
• is used to give permissions on DB Objects
[Tables,Views] to other users.
• Owner of DB Object Or DBA can grant the
permissions to other users.
Syntax:
Oracle 6 PM Page 56
c##raju c##ravi
emp
empno ename job sal
1001 A
1002 B
GRANT
Revoke:
• is used to cancel the permissions on DB objects from
users.
Syntax:
Log In as DBA:
username: system
password: nareshit
Oracle 6 PM Page 57
Grant connect,resource to c##usera;
Note:
connect => is permission for logging in
resource => is permission for creating table
c##userA c##userB
std
sid sname
1 A
2 B
Oracle 6 PM Page 58
WHERE sid=1;
ERROR: insufficient privileges
GRANT insert,update
ON std to c##userB;
GRANT select ON
c##userA.std TO c##batch6pm;
Allowing the user to grant
ERROR
permissions to other users:
Syntax:
emp
empno ename job sal mgr comm deptno hiredate
1001
1002
employee
empno ename job sal
1001
1002
emp
empno ename job sal comm hiredate deptno
1001
1002
employee2
empno ename job sal
INSERT ALL:
• introduced in Oracle 9i version
• Used to insert multiple records in multiple
tables or in single table
Oracle 6 PM Page 61
emp1
emp
empno ename job sal
empno ename job sal deptno
1001 ..
1002 emp2
.. empno ename job sal
1010
emp3
empno ename job sal
emp employee3
empno ename job sal deptno empno ename job sal
1001
1002
Oracle 6 PM Page 62
records into multiple records or single table.
• It avoids of writing multiple INSERT commands.
Syntax:
INSERT ALL
into <table-1>(<column_list>) values(<value_list>)
into <table-2>(<column_list>) values(<value_list>)
into <table-3>(<column_list>) values(<value_list>)
….
….
<SELECT query>;
emp emp1
empno ename job sal deptno empno ename job sal
1001
1002
emp2
empno ename job sal
emp3
empno ename job sal
INSERT ALL
into emp1 values(empno,ename,job,sal)
into emp2 values(empno,ename,job,sal)
into emp3 values(empno,ename,job,sal)
SELECT empno,ename,job,sal FROM emp;
Syntax:
INSERT ALL
When <condition-1> Then
into <table-1>(<column_list>) values(<value_list>)
When <condition-2> Then
Oracle 6 PM Page 64
When <condition-1> Then
into <table-1>(<column_list>) values(<value_list>)
When <condition-2> Then
into <table-2>(<column_list>) values(<value_list>)
When <condition-3> Then
into <table-3>(<column_list>) values(<value_list>)
..
..
ELSE
into <table-n>(column_list>) values(<value_list>)
<SELECT query>;
dept10
emp
empno ename job sal deptno
empno ename job sal deptno
1001 10
1002 10 dept20
1003 20 empno ename job sal deptno
1004 20
1005 30
1006 40 dept_others
empno ename job sal deptno
Oracle 6 PM Page 65
Copy deptno 10 emps into dept10,
deptno 20 emps into dept20
other depts emps into dept_others:
INSERT ALL
WHEN deptno=10 THEN
into dept10 values(empno,ename,deptno)
WHEN deptno=20 THEN
into dept20 values(empno,ename,deptno)
ELSE
into dept_others values(empno,ename,deptno)
SELECT empno,ename,deptno FROM emp;
Assignment:
emp_clerk
emp empno ename job
empno ename job
CLERK
CLERK emp_manager
MANAGER empno ename job
MANAGER
SALESMAN
emp_others
ANALYST
empno ename job
INSERT ALL
WHEN job='CLERK' THEN
into emp_clerk
emp
emp1980
empno ename hiredate
empno ename hiredate
Oracle 6 PM Page 66
emp
emp1980
empno ename hiredate
empno ename hiredate
17-JAN-80
13-OCT-80
emp1981
25-DEC-81 empno ename hiredate
12-FEB-81
17-MAR-82
28-APR-83 emp_others
empno ename hiredate
INSERT ALL
WHEN hiredate like '%80' THEN
into emp1980
MERGE:
• is introduced in Oracle 9i version.
• MERGE = UPDATE + INSERT
• MERGE is a combination of UPDATE & INSERT
commands.
• It can be also called as "UPSERT" Command.
• This command used to apply changes of a table
to its replica [duplicate copy].
Replication:
The process of making duplicate copies.
Oracle 6 PM Page 67
OLTP OLAP [DWH]
Cust2
Cust1
cid cname ccity
cid cname ccity
1 A Hyd
1 A Bangalore
2 B Chennai
2 B Chennai
3 C Delhi
3 C Delhi
4 D Bangalore
5 E Kolkata
Syntax:
Cust1 Cust2
Oracle 6 PM Page 68
Cust1 Cust2
cid cname ccity cid cname ccity
1 A Bangalore 1 A Hyd
2 B Chennai 2 B Chennai
3 C Delhi 3 C Delhi
4 D Bangalore
5 E Kolkata
INSERT
UPDATE
DELETE
Rollback;
SavePoint aaa;
INSERT
Savepoint bbb;
INSERT
Savepoint ccc;
INSERT
Rollback to ccc; --1 action will be cancelled
Oracle 6 PM Page 69
Rollback to bbb; --2 actions will be cancelled
SQL =>
• query language
• used to write the queries
• By writing queries we can communicate with
oracle DB
5 Sub Languages
DML INSERT
UPDATE
DELETE
INSERT ALL
MERGE
DRL SELECT
TCL COMMIT [SAVE]
ROLLBACK [ROLLBACK]
SAVEPOINT [to set margin for rollback
DCL GRANT
REVOKE
Oracle 6 PM Page 70
Built-In Functions
Thursday, February 24, 2022 7:21 PM
Built-In Functions:
• SQL provides several built-in functions to make
our tasks easier.
• Function => Task / Action
• Every function is defined to perform particular
task. power(2,3) => 8
• Oracle developers already defined some functions
& placed in Oracle Database. These functions are 2,3 => arguments
called "Built-In Functions / Predefined Functions". Function performs process
• Function can take Arguments [Input] & returns 8 => returned value [result]
the result.
Lower()
Upper()
Initcap()
length()
concat()
reverse()
ASCII()
Chr()
substr()
instr()
lpad()
rpad()
ltrim()
rtrim()
trim()
replace()
translate()
soundex()
Lower():
is used to convert the string to lower case.
Syntax:
Lower(<string>)
Ex:
Lower('RAJU') => raju
UPPER():
used to convert the string to upper case.
Syntax:
UPPER(<string>)
Ex:
UPPER('raju') => RAJU
Oracle 6 PM Page 71
Initcap():
used to get each word's starting letter as capital.
Syntax:
Initcap(<string>)
Exs:
Initcap('RAJU') => Raju
Initcap('RAJ KUMAR') => Raj Kumar
Concat():
concatenate => combine
used to combine 2 strings
Syntax:
Concat(<string1>,<string2>)
Ex:
Concat('Raj','Kumar') => RajKumar
Length():
used to find length of the string. It means, number
of chars in string.
Syntax:
Length(<string>)
Exs:
Length('Sai') => 3
Length('Ramu') => 4
Length('Ravi Teja') => 9
DUAL:
• is a table created in oracle database.
• created in 'SYS' user.
• It can be used by any user.
• It is created with 1 column. that column
name is 'dummy'.
• Dummy column can hold only one char i.e. X
• Only one row is available in 'dual' table.
• To get one value from the expressions or
built-in functions we use it.
DUAL
DUMMY
-------------
X
Oracle 6 PM Page 72
concatenation operator:
Symbol: ||
_ 1 char
% any no of chars
Player
pid fname lname
1001 sachin tendulkar
1002 rahul dravid
1003 rohit sharma
1004 virat kohli
Oracle 6 PM Page 73
INSERT INTO player
values(1003,'ROHIT','SHARMA');
UPDATE player
SET pname = Initcap(fname || ' ' || lname);
drop fname,lname:
Reverse():
is used to get reverse string
Syntax:
Reverse(<string>)
Ex:
A=65
Reverse('raju') => ujar
B=66
.
.
ASCII():
Z=90
Used to get ASCII value of specified char.
Syntax: a=97
ASCII(<char>) b=98
.
Ex: .
ASCII('A') => 65 z=122
ASCII('a') => 97
SELECT
ASCII('A'), ASCII('a'),ASCII('1'),ASCII('#')
FROM dual;
CHR():
used to get character of specified ASCII value.
Syntax:
CHR(<ascii_value>)
Ex:
CHR(65) => A
CHR(97) => a
Substr():
• is used to get sub string from the string.
• sub string => part of the string.
Syntax:
substr(<string>,<position>[,<no_of_chars])
Oracle 6 PM Page 74
substr(<string>,<position>[,<no_of_chars])
Exs:
R a j K u m a r
R A V I T E J A
emp
empno ename job sal mailid
7369 SMITH .. .. [email protected]
7499 ALLEN .. .. [email protected]
UPDATE emp
SET mailid=substr(ename,1,3) || substr(empno,-3,3)
|| '@nareshit.com';
Oracle 6 PM Page 75
Display the emp records whose name's second
char is 'A':
instr():
• used to get position of sub string.
• if sub string is existed in string, it returns sub string
position value.
• if sub string is not existed in string , it returns 0.
Syntax:
instr(<string>,<sub_string>
[,<search_position>,<occurrence>])
Exs:
t h i s i s h i s w i s h
ename
-----------
ALLEN
JAMES
SMITH
Soundex:
• This Function is used to retrieve the data
based on pronunciation.
• When we don't know exact spelling of string
we can search with the sound.
Syntax:
Soundex(string)
substr()
instr()
soundex()
Lpad():
Oracle 6 PM Page 76
Lpad():
• pad => fill
• used to fill specified char set from left side.
• Default char is 'space'.
Syntax:
Lpad(<string>,<max_size>[,<char_Set>])
Ex:
Lpad('raju',10,'*') => ******raju
Lpad('naresh',10,'#') => ####naresh
Lpad('sai',10,'#$') => #$#$#$#sai
Lpad('sai',10) => 7spacessai
Rpad():
• used to fill specified char set from right side
• default char is 'space'.
Syntax:
Rpad(<string>,<max_size>[,<char_set>])
EX:
Rpad('Ravi',10,'*') => Ravi******
Rpad('Sai',10) => Sai7spaces
Ltrim():
• trim => remove
• used to remove unwanted chars from left side.
Syntax:
Ltrim(<string>[,<char/chars>])
Rtrim():
• used to remove unwanted chars from right side.
Syntax:
Rtrim(<string>[,<char/chars>])
Exs:
Ltrim('*****RAJU*****','*') => RAJU*****
Rtrim('*****RAJU*****','*') => *****RAJU
Oracle 6 PM Page 77
mailid
------------
[email protected]
[email protected]
[email protected]
SELECT Rtrim(mailid,'@nareshit.com')
FROM emp;
Model
-------------
OPPO-A72
OPPO-A12
OPPO-A51
Trim():
• used to remove unwanted chars from left side
/ right side / both sides.
Syntax:
Trim(leading / trailing / both <char> FROM <string>)
Ex:
Trim(Leading '@' FROM '@@@raju@@@') => raju@@@
Trim(Trailing '@' FROM '@@@raju@@@') => @@@raju
Trim(Both '@' FROM '@@@raju@@@') => raju
gmail.com
username ravi
password
Replace():
used to replace search string with replace string
Syntax:
Replace(<string>,<search_string>,<replace_string>)
Ex:
Replace('sai krishna','sai','rama') => rama krishna
Replace('sai krishna','krishna','teja') => sai teja
Translate():
Oracle 6 PM Page 78
Translate():
used to translate corresponding chars
Syntax:
Translate(<string>,<char_set1>,<char_set2>)
Translate('hello','leo','xyz') =>
REPLACE('abcaabbccabcabcaabbcc','abc','XYZ')
Conversion Functions:
Implicit Conversion:
This conversion will be done implicitly by the ORACLE
Ex:
SELECT '100' + '200' FROM dual;
300
Explicit Conversion:
This conversion will be done explicitly by using
built-in function.
CHAR
Oracle 6 PM Page 79
CHAR
DATE
NUMBER
to_char(sysdate,'q') 1
cc century num
to_char(sysdate,'cc') 21
AD / BC to_char(sysdate,'BC') AD
hh / hh12 to_char(sysdate,'hh') 07
to_char(sysdate,'hh12') 07
hh24 to_char(sysdate,'hh24') 19
mi to_char(sysdate,'mi') 10
ss seconds value
ff fractional seconds value
AM / PM AM / PM format
7:11 PM
Oracle 6 PM Page 80
19:11:15
SELECT empno,ename,sal,
to_char(hiredate,'mm/dd/yyyy') hiredate,
hiredate
FROM emp;
SELECT empno,ename,sal,
to_char(hiredate,'dd/mm/yyyy') hiredate,
hiredate
FROM emp;
Display the emp records who joined in 1st & 4th quarters:
ASSIGNMENT:
Oracle 6 PM Page 81
So, it displays no rows selected
To remove unwanted spaces from right side use Rtrim()
Ex:
sal
------
5000 $5,000.00
5000 USD5,000.00
Syntax:
to_char(<number>[,<format>])
Format Purpose
L Currency Symbol ($)
C Currency name (USD)
9 digit
, thousand separator
. decimal point
Exs:
to_char(123) => 123
Log in as DBA:
username: system
password: nareshit
to_date():
Oracle 6 PM Page 82
to_date():
• used to convert string to date.
Syntax:
to_date(<string>[,<format>])
Exs:
to_date('22 DEC 2019') => 22-DEC-19
to_Date('22-DEC-2019') =>
to_date('22 DECEMBER, 2019') => 22-DEC-19
SELECT to_char(to_date('25-SEP-2018'),'yyyy')
FROM dual;
2018
SELECT to_char(to_date('25-SEP-2018'),'mm')
FROM dual;
09
15-AUG-1947
SELECT
to_char(to_date('24-APR-1973'),'day')
FROm dual;
to_number():
• used to convert string to number.
• string must be numeric string.
Syntax:
to_number(<string>[,<format>])
Ex:
Oracle 6 PM Page 83
Ex:
to_number('123') => 123
to_number('123.45') => 123.45
SELECT ename,
to_char(sal,'L99,999.99') as salary desc emp;
FROM emp;
sal number(7,2)
SELECT ename,
to_char(sal,'C99,999.99') as salary
FROM emp;
to_char()
to_date()
to_number()
String Functions
Conversion Functions => Single Row Functions
Sum()
Avg()
Max()
Min()
Count()
Sum():
used to find sum of a set of values
Syntax:
sum(<column_name>)
Ex:
sum(sal)
Oracle 6 PM Page 84
Find sum of salaries of all clerks:
avg():
This function is used to average of a set of values.
Syntax:
avg(<column_name>)
Ex:
avg(sal)
avg(runs)
Max():
used to find maximum value in a set of values.
Syntax:
max(<column_name>
Ex:
max(sal)
max(marks)
Min():
This function is used to find
minimum value in a set of numbers.
Syntax:
min(<column_name>)
Ex:
min(sal)
min(marks)
Oracle 6 PM Page 85
Find min salary in all employees:
count():
used to count specific column values or
number of records.
Syntax:
count(<column_name>/*)
Ex:
count(Sal)
count(comm)
count(*) => counts number of records
Note:
count(comm) => it will not count null values
Oracle 6 PM Page 86
Find second max salary:
Assignment:
sqrt()
power()
mod()
sin()
cos()
tan()
abs()
sign()
log()
ln()
ceil()
floor()
trunc()
round()
sqrt():
used to find square root value
Syntax:
sqrt(<number>)
Ex:
sqrt(100) => 10
power():
used to find power value
Oracle 6 PM Page 87
Syntax:
power(number,power)
Ex:
power(2,3) => 8
mod():
used to get remainder value.
Syntax:
mod(<number>,<divisor>)
Ex:
mod(5,2) => 1
sin():
used to find sine values
Syntax:
sin(angle)
cos():
used to find cosine values
Syntax:
cos(angle)
tan():
used to tangent values
Syntax:
tan(angle)
Note:
specify angle value in the form of
radians
Ex:
sin 90 => sin(90*3.14/180) => 1
cos 0 => cos(0*3.14/180) => 1
tan 45 => tan(45*3.14/180) => 1
abs():
used to get absolute value.
absolute value => non-negative
Syntax:
abs(<number>)
Ex:
abs(5) => 5
abs(-5) => 5
sign():
used to check whether a number is +ve
or -ve or zero.
it returns 1 when number is +ve
it returns -1 when number is -ve
it returns 0 when number is ZERO
Syntax:
sign(<number>)
Ex:
sign(8) => 1
sign(-8) => -1
sign(0) => 0
log():
used to find logarithmic values
Syntax:
log(number,base)
Oracle 6 PM Page 88
Ex:
log(10,10) => 1
ln():
used to get natural logarithmic values
Syntax:
ln(<number>)
Ex:
ln(7)
ceil():
used to get upper integer value
Syntax:
ceil(<number>) 123 => 123.4567 => 124
Ex:
ceil(123.4567) => 124
ceil(167.8923) => 168
floor():
used to get lower integer value.
Syntax:
floor(<number>)
123 => 123.4567 => 124
Ex:
floor(123.4567) => 123
floor(167.8923) => 167
trunc():
it truncates [removes] decimal places
Syntax:
trunc(<number>[,<decimal_places>])
Ex:
trunc(123.45678) => 123
trunc(123.45678,2) => 123.45
Note:
Always it takes lower integer value
Oracle 6 PM Page 89
Round():
used to get rounded values.
if value is .5 or > .5 => it takes upper value
if value is <.5 => it takes lower value
Syntax:
Round(<number>,<decimal_places>) percentage
-------------
Ex: 56.78 => 57
Round(123.45678) => 123 78.34 => 78
Round(123.7896) => 124 67.53 => 68
Round(123.54321) => 124
Date Functions:
• sysdate
• systimestamp
• add_months()
• last_day()
• next_day()
• months_between()
sysdate:
• used to current system date
• Date value also contains time value.
Oracle 6 PM Page 90
SELECT systimestamp FROM dual;
Add_Months():
used to add months to a date (or)
subtract months from a date.
Syntax:
Add_Months(<date>,<number_of_months>)
Ex:
SALES
DateId Amount
1-JAN-2018 25000
2-JAN-2018 35000
.
.
Oracle 6 PM Page 91
WHERE dateid = sysdate;
no rows selected
Employee
60 years age
Update employee
SET DOR=Add_Months(DOB,12*60);
IndiaCMs
State CM_NAME B_O_TERM_DATE E_O_TERM_date
TS .. 23-MAY-2018 After 5 years?
AP .. 15-OCT-2019 After 5 years?
Last_Day():
It is used to get last day in the specified month.
Syntax:
Last_day(<date>)
Ex:
Oracle 6 PM Page 92
SELECT last_day(sysdate) FROM dual;
SELECT last_day(add_months(sysdate,1))
FROM dual;
SELECT last_day(add_months(sysdate,-1))
FROM dual;
Next_day():
Used to coming date based on weekday.
Syntax:
Next_day(<date>,<weekday_format>) weekday_format:
d
dy
day
Find next Friday's date:
SELECT next_day(last_day(sysdate),'sun')
FROM dual;
SELECT
Next_day(last_day(sysdate)-7,'sun')
FROM dual;
Months_Between():
used to find months b/w two dates.
Syntax:
Months_Between(<date-1>,<date-2>)
SELECT ename,
trunc(Months_Between(sysdate,hiredate)/12) experience
FROM emp;
Miscellaneous Functions:
Greatest()
Oracle 6 PM Page 93
Greatest()
Least()
NVL()
NVL2()
Rank()
Dense_Rank()
User
UID
Greatest():
is used to get maximum value in the specified values.
Syntax:
Greatest(<value1>,<value2>,……<value-n>)
Ex:
Greatest(500,400,800,300,600) => 800
STUDENT
SID SNAME M1 M2 M3
1001 A 60 50 90
1002 B 70 80 40
90 70
80
Functions
greatest() max()
Syntax:
Least(<val1>,<val2>,……,<val-n>)
EX:
Least(50,70,30,80,75) => 30
NVL():
• used to replace NULL value with some other value.
• Something + NULL = NULL
• Something - NULL = NULL
1002 B 8000
1003 C 6000 300
1004 D 4000
Oracle 6 PM Page 94
1004 D 4000
1005 E 7000
Syntax:
NVL(<first>,<second>)
EX:
NVL(600,700) => 600
NVL(null,700) => 700
SELECT ename,sal,comm,
sal+NVL(comm,0) as "total sal"
FROM emp;
SELECT ename,sal,
NVL(comm,'N/A')
FROM emp;
ERROR: data type mismatch
comm => number
'N/A' => string
SELECT ename,sal,
NVL(to_char(comm),'N/A') as "comm"
FROM emp;
Ex:
STUDENT
SELECT sname,
sid sname M1 M2 M3
NVL(M1,'AB')
1001 A 60 80 70
FROM student;
1002 B 55 90 ERROR
1003 C 70 66 44
1004 D 35 82 SELECT sname,
NVL(to_char(M1),'AB') as M1
FROM student;
NVL2():
is used to replace NULL values and NOT NULL values.
Whereas NVL() Function can replace only NULL values.
Syntax:
NVL2(<first>,<second>,<third>)
Ex:
NVL2(500,600,700) => 600
NVL2(null,600,700) => 700
comm
-----------
null => 750
Oracle 6 PM Page 95
null => 750
1000 => 1250 => comm+250
UPDATE emp
SET comm = NVL2(comm,comm+250,750);
NVL() NVL2()
USER:
used to get current user name
UID:
used to get current user ID
Ex:
SELECT user FROM dual; (or) show user
--gives current user name
All_Users:
It maintains all users information
Rank():
• Used to apply ranks to records according to specific
column or columns.
• does not follow the sequence
Syntax:
Rank() over(order by <column> Asc/Desc)
Dense_Rank():
• Used to apply ranks to records according to specific
column or columns.
• follows the sequence.
Syntax:
Dense_Rank() over(order by <column> Asc/Desc)
SELECT ename,sal,
Oracle 6 PM Page 96
SELECT ename,sal,
Rank() Over(Order BY sal Desc) as "RANK"
FROM emp;
SELECT ename,sal,
Dense_Rank() Over(Order BY sal Desc) as "RANK"
FROM emp;
SELECT ename,sal,hiredate,
DENSE_RANK() Over(Order By sal Desc, hiredate Asc) as RANK
FROM emp;
Oracle 6 PM Page 97
Case Expressions
Thursday, March 10, 2022 6:52 PM
Case Expressions:
• This concept introduced in Oracle 9i version.
• used to implement "If..Then..Else" in
Oracle SQL.
It avoids of writing a separate PL/SQL program
or Procedure.
Simple Case:
can check equality condition only.
Syntax: switch(exprn)
{
CASE <expression> case <const>:
WHEN <value> THEN <return_value> …
WHEN <value> THEN <return_value> break;
. case <const>:
. ….
[Else <return_value>] break;
End .
.
default:
..
}
Increase the salary to the employees as
following:
If deptno is 10 => Increase 10% sal
Oracle 6 PM Page 98
If deptno is 10 => Increase 10% sal
If deptno is 20 => Increase 20% sal
If deptno is 30 => Increase 15% sal
Others => Increase 5% sal
Display
CLERK as WORKER
MANAGER as BOSS
PRESIDENT as BIG BOSS
OTHERS as EMPLOYEE
in job column:
SELECT ename,sal,
CASE job
WHEN 'CLERK' THEN 'WORKER'
WHEN 'MANAGER' THEN 'BOSS'
WHEN 'PRESIDENT' THEN 'BIG BOSS'
ELSE 'EMPLOYEE'
END AS JOB
FROM emp;
Oracle 6 PM Page 99
Simple CASE [like switch]:
can check equality condition only
Syntax:
CASE
WHEN <condition-1> THEN <return_value>
WHEN <condition-2> THEN <return_value>
.
.
ELSE <return_value>
END
SELECT empno,ename,sal,
CASE
WHEN sal>3000 THEN 'HiSal'
WHEN sal<3000 THEN 'LoSal'
WHEN sal=3000 THEN 'AvrgSal'
END as "salary range"
FROM emp;
Ex:
SELECT sname,M1,M2,M3,
CASE
WHEN m1>=40 AND m2>=40 AND m3>=40 THEN 'PASS'
ELSE 'FAIL'
END as Result
FROM student;
Decode():
• is used implement 'IF..THEN..ELSE' in
SQL.
• It can check equality condition only. It
cannot check other conditions like > <
Ex:
Display job titles as following:
PRESIDENT as Big Boss
CLERK as Worker
MANAGER as Boss
Others as Employee;
SELECT ename,
DECODE(Job,
'PRESIDENT','Big Boss',
'CLERK', 'Worker',
'MANAGER','Boss',
'Employee') as Job
FROM emp;
In SQL,
we can implement IF..THEN..ELSE
using 2 ways:
• CASE Expression
• Decode() Function
• It is ANSI standard
• It is portable
CASE CASE
Decode Decode
Interval Expressions:
• introduced in Oracle 9i version.
• used to add or subtract days, months or years
to particular date or from particular date.
• can be also used to add or subtract hours,
minutes or seconds to a time or from a time.
SALES
dateid amount
1-jan-2018 25000
2-jan-2018 30000
Flashbacking Data:
• Flashback concept in Oracle 10g version.
• Before Oracle 10g,
○ If we delete all records from table &
committed then we cannot recollect it.
To recollect the data they were using backup
Oracle 6 PM Page 107
To recollect the data they were using backup
copies.
• From Oracle 10g version onwards.
○ If we delete all records from table &
committed then also we can recollect it by
using the "FLASHBACK query".
• By default we can recollect upto 15 minutes
[900 seconds].
• We can change this time using the parameter
"undo_retention".
Syntax:
Log in as DBA:
user name: system
password: nareshit
Syntax:
SQL English
Queries Sentences
Clauses Words
Clauses:
• Clause is a part of query.
SELECT ename,sal
FROM emp
WHERE sal>2500;
• SELECT:
SELECT clause is used to specify
the column list.
Ex:
SELECT ename,sal
• FROM clause:
FROM clause is used to specify the table list.
Ex:
FROM emp
FROM emp,dept
• WHERE clause:
○ WHERE clause is used to write the
conditions on rows.
○ This condition is applied on every row.
Ex:
WHERE sal>3000
WHERE sal between 3000 and 5000
ORDER BY:
• ORDER BY clause is used to arrange the
records in ascending or descending
according to specific column / columns.
• Default Order is Ascending Order. We have
no need to specify "Asc". By default it will be
taken.
• For Descending Order we must write "DESC".
1 to 10 => Ascending
10 to 1 => Descending
A to Z => Ascending
Z to A => Descending
SELECT ename,sal
FROM emp
ORDER BY ename;
(or)
SELECT ename,sal
FROM emp
ORDER BY ename Asc;
SELECT ename,sal
FROM emp
ORDER BY sal DESC;
SELECT ename,sal
FROM emp
ORDER BY sal DESC, ename ;
(or)
SELECT ename,sal
FROM emp
ORDER BY sal DESC, ename Asc;
SELECT empno,ename,sal,deptno
FROM emp
ORDER BY deptno;
GROUP BY clause:
• is used group the records according to
specific column or columns.
SELECT sum(Sal)
emp
FROM emp
empno ename job sal deptno GROPU BY deptno;
1001 A CLERK 3000 20 10 13000
1002 B MANAGER 5000 20 20 8000
1003 C MANAGER 4000 30 30 10000
1004 D CLERK 6000 30
1005 E MANAGER 8000 10 SELECT sum(Sal)
1006 F CLERK 5000 10 FROM emp
GROPU BY job;
CLERK 14000
MANAGER 17000
GROUP BY:
• It is used to group the records according to specific
column / columns.
○ GROUP BY deptno => 10, 20, 30
○ GROUP BY Job => CLERK, MANAGER
○ GROUP BY deptno,job => 10 MANAGER, 10 CLERK
• When column values are same it will be treated as one
group.
SELECT deptno,sum(Sal)
SELECT deptno,sum(Sal)
FROM emp
WHERE deptno IN(10,30)
GROUP BY deptno
ORDER BY deptno;
1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. DISTINCT
7. ORDER BY
SELECT deptno,sum(Sal)
FROM emp
WHERE deptno IN(10,30)
GROUP BY deptno
ORDER BY deptno;
FROM emp:
GROUP BY deptno:
SELECT deptno,sum(Sal):
deptno sum(Sal)
30 10000
10 13000
ORDER BY deptno:
deptno sum(Sal)
10 13000
30 10000
deptno num_of_emps
sum()
10 5
avg()
20 7 count()
30 6 max()
min()
SELECT deptno, count(*) no_of_emps
FROM emp
GROUP BY deptno
ORDER BY deptno;
SELECT deptno,
max(Sal) max_Sal,
min(Sal) min_Sal
FROM emp
GROUP BY deptno
ORDER BY 1;
Year No_Of_Emps
1980 2
1981 5
1982 3
1983 4
Note:
Can we use alias name in GROUP BY?
No. Because After GROUP BY, SELECT
will be executed. GROUP BY cannot
identify alias name.
quarter no_of_emps
1 5
2 3
3 7
4 4
sal_range no_of_emps
Hisal 1
LoSal 5
AvrgSal 8
SELECT
CASE
WHEN sal>3000 THEN 'HiSal'
WHEN sal<3000 THEN 'LoSal'
WHEN sal=3000 THEN 'AvrgSal'
End as "salary range",
count(*) as "no of emps"
FROM emp
GROUP BY
CASE
WHEN sal>3000 THEN 'HiSal'
WHEN sal<3000 THEN 'LoSal'
WHEN sal=3000 THEN 'AvrgSal'
End;
job sum(sal)
CLERK …
ANALYST …
Job no_of_emps
CLERK 3
MANAGER 2
HAVING clause:
• HAVING clause is used to write the conditions
on Groups [Group of records]. Display dept wise no of emps:
• It will be applied on result of GROUP BY. Display the depts which are having
• It cannot be used without GROUP BY. more than 5 emps:
SELECT deptno,count(*)
• It filters the groups. FROM emp
SELECT deptno,count(*)
GROUP BY deptno;
Display the deptnos which are spending more FROM emp
than 10000 amount on their employees: GROUP BY deptno
deptno count(*)
HAVING count(*)>5;
10 3
SELECT deptno,Sum(Sal) FROM emp
20 6 deptno count(*)
GROUP BY deptno
HAVING sum(sal)>10000; 30 8 20 6
40 4 30 8
WHERE HAVING
Note:
When we use GROUP BY or Aggregate Functions,
In SELECT clause we can write group column or
group function.
We cannot write single row column.
SELECT deptno,ename,sum(Sal)
SELECT deptno,ename,sum(Sal)
FROM emp
GROUP BY deptno;
ERROR:
ename is not GROUP BY expression
emp
Rollup():
Syntax:
Rollup(grouping_column_list)
Ex:
Rollup(deptno,job)
It calculates sub totals & grand total
according to "deptno"
SALES
dateid amount
Year quarter amount
1-JAN-2017 20000
2017 1 100000
2-JAN-2017 30000
2 2000000
.
3 …
.
4 …
.
2017 sub total
.
2018 1
2
3
4
2018 sub total
grand total
Person
pid pname state gender age aadhar
SELECT state,
CASE
WHEN age<18 THEN 'MINOR'
WHEN age between 18 and 60 THEN 'MidAge'
WHEN age>60 THEN 'S.CITIZEN'
END as age_group,
gender,
count(*) no_of_people
FROM person
GROUP BY state,
CASE
WHEN age<18 THEN 'MINOR'
WHEN age between 18 and 60 THEN 'MidAge'
WHEN age>60 THEN 'S.CITIZEN'
END,
gender
ORDER BY 1;
DISTINCT:
used to avoid the duplicate rows
job Job
MANAGER ---------
CLERK MANAGER
CLERK CLERK
SALESMAN
MANAGER
SALESMAN
SALESMAN
Ex:
GROUP BY deptno => 10 20 30
GROUP BY job => CLERK MANAGER
GROUP BY deptno,job => 10 MANAGER
10 CLERK
20 MANAGER
20 CLERK
Execution Order:
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
A = {1,2,3,4,5,6}
B = {2,3,4,7,8}
A U B = {1,2,3,4,5,6,7,8}
A I B = {2,3,4}
A M B = {1,5,6}
B M A = {7,8}
Syntax:
SELECT query
SET OPERATOR
SELECT query;
UNION:
• used to combine records from multiple
tables without duplicates.
cust1 cust2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
cid cname
1001 A
1002 B
1003 C
5001 D
5003 E
UNION ALL:
• used to combine records from 2 tables
including duplicates.
cust1 cust2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
cid cname
1001 A
1002 B
1003 C
5001 D
1002 B
5003 E
INTERSECT:
used to common records from multiple tables.
cust1 cust2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
cid cname
1002 B
SET Operators:
cust1 [Branch1] cust2 [Branch2]
UNION cid cname cid cname
UNION ALL 1001 A 5001 D
INTERSECT
1002 B 1002 B
MINUS
1003 C 5003 E
cid cname
1001 A
1003 C
Minus:
It is used to get specific records
from first table.
It gives all records from first table
except common records.
CID CNAME
---------- ----------
1001 A
1003 C
CID CNAME
---------- ----------
5001 D
5003 E
SELECT query1
SET OPERATOR
SELECT query1
Rules:
• Corresponding columns data types in both
SELECT queries should be matched.
Ex:
SELECT cid,cname FROM cust1
UNION
SELECT cname,cid FROM cust2;
Output:
ERROR at line 1:
ORA-01790: expression must have same
datatype as corresponding expression
cust_id cust_name
1001 A
1002 B
1003 C
5001 D
5003 E
JOB
---------
CLERK
ANALYST
MANAGER
JOB
---------
CLERK
MANAGER
PRESIDENT
JOB JOB
--------- ---------
CLERK CLERK
ANALYST MANAGER
MANAGER PRESIDENT
CLERK
MANAGER
PRESIDENT
ANALYST
ANALYST
CLERK
MANAGER
PRESIDENT
emp_us
empno ename job sal
5001 Display all emp records who are working
5002 in india & us.
5003
Display common emps who are working
5004
for india & us.
5005
Display the emp records who are
emp_ind working only for us.
empno ename job sal
2001 Display the emp records who are
2002 working only for ind.
5002
5004
2003
2004
Oracle 6 PM Page 127
2004
Joins:
Goal => Retrieve data from multiple tables
College DB
Student
Orders
Orderid Ord_Date Cid Del_date Pid Qty Price
1001 15-FEB-22 2001 20-FEB-22 3001 2 5000
Customers
cid cname ccity
Products
pid pname cid cname pid pname orderid ord_Date del_Date
Joins:
• Join => Connect / Link / Combine College DB
• Join is an operation that is used to combine
one table records with another based on Student
Join Condition. Marks
• Join condition decides one record in one table Fee
should be joined with which record in another Staff
table.
• Goal: Joins are used to retrieve the data from
multiple tables.
STUDENT.sid = MARKS.sid Join Condition
• Normally, for Join operation common column is
required.
• Common column names need not to be same. STUDENT MARKS
• Ex: STUDENT.stdid = MARKS.sid sid sname scity sid M1 M2 M3
1001 A Hyd 1001 60 90 70
1002 B Mumbai 1002 66 88 44
1003 C Pune 1003 45 72 49
Types of Joins:
• Equi Join / Inner Join
Emp e
empno ename sal deptno Dept d
1006 30
Table Alias:
• We can give alias(alternative)
names to tables.
Advantages:
• It makes table name short.
• improves the performance.
ORACLE Style:
ANSI STYLE:
• To separate two table names we use comma
[,] in Oracle Style. In ANSI style, to separate
two table names use keyword.
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;
e.deptno=d.deptno
SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e INNER JOIN dept d
USING(deptno);
ON e.deptno=d.deptno
(or)
USING(deptno)
e.deptno = d.deptno
Oracle 6 PM Page 131
e.deptno = d.deptno
emp e dept d
empno ename sal deptno deptno dname loc
ORACLE STYLE:
ANSI STYLE:
Outer Join:
• Equi Join [Inner Join] can display matching records
only. Outer Join is used to get matching records &
unmatching records.
• Equi Join / Inner Join = matching records only
Emp Dept
empno ename sal deptno Deptno Dname Loc
1001 A 20 10 Accounting DALLAS
1002 B 30 20 Research CHICAGO
1003 C 10 30 SALES BOSTON
1004 D 10 40 OPERATIONS NEW YORK
1005 E 20
1006 F 30
1007 G
1008 H
ORACLE STYLE:
ANSI STYLE:
Note:
IN ANSI STYLE , based on table list in
FROM clause which one left & right will
be decided.
Ex:
FROM emp e LEFT OUTER JOIN dept d
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
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:
Equi Join:
If join operation is performed based on equality condition
then it is called "Equi Join".
Non-Equi Join:
If join operation is performed based on other than equality
emp salgrade
empno ename sal
1001 5000 grade losal hisal
1002 8000 1 700 1200
1003 4000 2 1201 1400
1004 1800 3 1401 2000
4 2001 3000
5 3001 6000
6 6001 9000
ORACLE STYLE:
SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;
ANSI STYLE:
SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;
Self Join:
• Self Join can be also called as "Recursive Join".
• If a table is joined to itself then it is called "Self Join"
Emp e1 [employee]
Emp e2 [manager]
empno ename job sal mgr
empno ename job sal mgr
1001 A clerk 5000 1003
1001 A clerk 5000 1003
1002 B analyst 7000 1003
1002 B analyst 7000 1003
1003 C manager 10000
1003 C manager 10000
1004 D clerk 6000 1005
1004 D clerk 6000 1005
1005 E manager 12000
1005 E manager 12000
A = {1,2,3} 1 2 3
B = {4,5,6}
4 5 6
AXB = ?
GROUPA GROUPB
----------------- ----------------
IND NZ
AUS ENG
WI PAK
3 3 9
Natural Join:
emp
empno ename job sal hiredate comm mgr deptno
dept
deptno dname loc
empno ename job sal hiredate comm mgr deptno dname loc
Equi Join:
SELECT * FROM emp e, dept d
WHERE e.deptno=d.deptno;
Natural join:
ORACLE STYLE:
SELECT e.*,d.dname,d.loc FROM emp e, dept d
WHERE e.deptno=d.deptno;
ANSI style:
SELECT * FROM emp Natural Join dept;
Join:
• Join => connect / link / combine
• used to combine one table records with another
based on join condition.
• join condition decides which record in one table
should be joined with which record in another table
• used to retrieve the data from multiple tables
Types of joins:
student course
sid sname cid cid cname
101 A 20 10 Java
102 B 30 20 Python
103 C 30 30 HTML
104 D 10 40 CPP
105 E
SELECT ………
……..(SELECT ……
(SELECT …. ) );
SELECT <column_list>
FROM <table_name>
WHERE <column_name> <operator> (SELECT query);
Inner Query /
Sub Query /
Child Query
Note:
When value is unknown in WHERE clause
ALLEN 25-DEC-1983
SMITH 17-oct-1980
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate > '23-NOV-1981';
25-MAR-2022
24-NOV-1981 onwards => juniors
26-MAR-2022
1
SELECT hiredate FROM emp 1-jan-2022
2
WHERE ename='FORD'; 2-jan-2022
3
.
4
.
5
SELECT empno, ename, hiredate 31-jan-2022
6
FROM emp
7
WHERE hiredate > (SELECT hiredate
8
FROM emp
9
WHERE ename='FORD');
10
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate = (SELECT hiredate FROM emp
WHERE ename='FORD');
sal
--------
select min(sal) from emp
4000
where sal>(select min(Sal) from
5000
emp);
2000
3000
select ename FROM emp
WHERE sal = (
select min(sal) from emp
where sal>(select min(Sal) from
emp)
);
10 10000
20 15000
30 12000
SELECT deptno,count(*)
FROM emp
GROUP BY deptno;
SELECT deptno
FROM emp
GROUP BY deptno
HAVING count(*) = (SELECT max(count(*))
FROM emp
GROUP BY deptno);
SELECT empno,ename,job,sal,deptno
FROM emp
WHERE job IN('MANAGER','CLERK');
SELECT empno,ename,sal
FROM emp WHERE sal IN(SELECT sal
FROM emp
WHERE ename IN('WARD','FORD') );
sal>1500 or sal>2850
SELECT empno,ename,sal
FROM emp
WHERE sal>ALL(SELECT sal
FROM emp
WHERE ename IN('TURNER','BLAKE'));
SELECT empno,ename,sal
FROM emp
WHERE sal>ANY(SELECT sal
FROM emp
WHERE ename IN('TURNER','BLAKE'));
Display the emp records who are max salary in their depts:
SELECT empno,ename,sal,deptno
FROM emp
WHERE (deptno,sal) IN(
SELECT deptno,max(Sal) FROM emp
GROUP BY deptno);
10 senior hiredate
20 senior hiredate
30 senior hiredate
SELECT deptno,min(hiredate)
FROM emp
GROUP BY deptno;
SELECT empno,ename,hiredate,deptno
FROM emp
WHERE (deptno,hiredate) IN(SELECT deptno,min(hiredate)
FROM emp
GROUP BY deptno);
emp
deptno avrg_sal
empno ename sal deptno
10 6000
1001 A 4000 10
20 8000
1002 B 8000 10
1003 C 6000 20
1004 D 10000 20
1002 B 8000 10
1004 D 10000 20
SELECT empno,ename,sal,deptno
FROM emp e
WHERE sal>(SELECT avg(Sal) FROM emp
WHERE deptno=e.deptno);
emp
deptno avrg_sal
empno ename sal deptno
10 6000
1001 A 4000 10
20 8000
1002 B 8000 10
1003 C 6000 20
1004 D 10000 20
1002 B 8000 10
1004 D 10000 20
emp
empno ename sal deptno
deptno max(Sal)
1001 A 4000 10
10 8000
1002 B 8000 10
20 10000
1003 C 6000 20
1004 D 10000 20
SELECT empno,ename,sal,deptno
FROM emp e
WHERE sal = (SELECT max(Sal) FROM emp
WHERE deptno=e.deptno);
1002 B 8000 10
1004 D 10000 20
highest sal 0
2nd max sal 1
3rd max sal 2
4th max sal 3
SELECT empno,ename,sal,deptno
FROM emp e
WHERE 2 = (SELECT count(sal)
FROM emp WHERE sal>e.sal);
emp
empno ename job sal
1001 5000
1002 8000
1003 6000
1004 7000
SELECT empno,ename,sal,deptno
FROM emp e
WHERE 0 = (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);
SELECT empno,ename,sal,deptno
FROM emp e
WHERE 1= (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);
SELECT empno,ename,sal,deptno
FROM emp e
WHERE 2 = (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);
SELECT empno,ename,sal,deptno
FROM emp e
WHERE 3 = (SELECT count(distinct sal) FROM
emp WHERE sal>e.sal);
SELECT empno,ename,sal,deptno
FROM emp e
WHERE &n-1 = (SELECT count(distinct sal)
FROM emp WHERE sal>e.sal);
Inline View:
• If sub query is written in FROM clause then FROM
it is called "Inline View". WHERE
• This sub query acts like Table. GROUP BY
• It is used to change execution order of HAVING
clauses. SELECT
DISTINCT
ORDER BY
SELECT * FROM
(SELECT empno,ename,sal,sal*12 An_Sal
FROM emp)
WHERE An_Sal>30000;
SELECT * FROM
(SELECT empno,ename,sal,
Dense_Rank() over(order by sal desc) Rnk
FROM emp)
WHERE Rnk<=3;
Rownum:
• It is a pseudo column. pseudo => false
• It is used to apply row numbers to the
result of select query.
SELECT * FROM
(SELECT rownum rn,
empno,ename,sal
FROM emp)
WHERE rn=3;
mod(6,2) => 0
mod(7,2) => 1
SELECT * FROM
(SELECT rownum rn,empno,ename,sal
FROM emp)
WHERE mod(rn,2)=0;
SELECT * FROM
(SELECT rownum
rn,empno,ename,sal
FROM emp)
WHERE mod(rn,2)=1;
SELECT * FROM
(SELECT rownum rn,empno,ename,sal
FROM emp)
WHERE rn BETWEEN 6 AND 10;
SELECT * FROM
(SELECT rownum rn,empno,ename,sal
FROM emp)
WHERE rn IN(3,7,12,14);
ROWID:
• ROWID is a pseudo column.
• It displays row address.
emp dept
-------- ……….
14 4
10 30
20 50
30 20
Sub Queries
writing query in another query
SQL
Table
5 sub languages => DDL DML DRL DCL TCL
Built-In Functions
Clauses => SELECT FROM WHERE GB H D OB
Joins => Equi, Outer => LO, RO, FO Non-equi self cross natural
Sub Queries
SET operators
Emp
empno ename sal deptno
Dept
1001 A 20
Deptno Dname Loc
1002 B 30
10 Accounting DALLAS
1003 C 10
20 Research CHICAGO
1004 D 10
30 SALES BOSTON
1005 E 20
40 OPERATIONS NEW YORK
1006 F 30
1007 G
1008 H
View:
• is a Database Object.
• View is a Virtual table.
• It means, View does not contain physical data & it does
not occupy the memory.
• VIEW holds SELECT query. It does not hold result of
query.
• When we retrieve data through view, implicitly oracle runs
SELECT query.
• A view is created on Table. Without Table we cannot
create the view.
• A table on which view is created is called "Base Table".
• View always gives recent data [committed data].
• Some views can be updated. These are called "Updatable
Views / Simple Views".
• Some view cannot be updated. These are called "Read-
Only Views / Complex Views".
Advantages:
• Provides Security
• Reduces Complexity & Simplifies queries
Disadvantages:
• Low performance
CREATE VIEW v1
AS
SELECT empno eno,ename en,job ejob FROM
emp;
emp table
empno ename job sal deptno mgr comm hiredate
v1 View
empno ename job hiredate
emp Table
empno ename job sal comm deptno hiredate mgr
1001 A .. .. .. 10 .. ..
1002 10 .. ..
1003 10
1004 20
1005 20
SELECT ………………….
FROM …………….
………………….
………………..
CREATE VIEW v1
AS
SELECT deptno, sum(Sal) FROM
emp
GROUP BY deptno;
Log in as c##batch6pm:
username: c##batch6pm
password: nareshit
CREATE VIEW v1
AS
SELECT empno,ename,job,hiredate FROM emp;
Log in as DBA:
username: system
password: nareshit
Log in as c##batch6pm:
CREATE VIEW v1
AS
SELECT empno,ename,job,hiredate FROM emp;
Log in as c##ramu:
Types of Views:
2 types:
emp
empno ename job sal hiredate mgr comm deptno
1001 A .. .. .. .. .. 10
1002 10
1003 20
1004 20
1005 20
1006 30
1007 30
Log in as c##batch6pm:
CREATE VIEW v2
AS
SELECT * FROM emp WHERE deptno=20;
log in as c##ramu:
INSERT INTO
c##batch6pm.v2(empno,ename,deptno)
VALUES(2345,'A',20);
CREATE VIEW v3
AS
SELECT * FROM emp WHERE deptno=20
WITH CHECK OPTION;
ERROR:
ORA-01402: view WITH CHECK OPTION
where-clause violation
1 row created
Complex View:
• If a view is created based on multiple tables then it
is called "Complex View".
• If a view is created based on joins (or) group by (or)
having (or) sub queries (or) set operators (or)
group functions (or) expressions then it is called
"Complex View".
• We cannot perform DML operations on complex view.
• Just we can read the data. That's why it can be also
called as "Read-Only View".
CREATE VIEW v5
AS
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;
FORCE VIEW:
A view which is created forcibly with some
errors is called "FORCE VIEW".
Ex: without base table existence we can
create FORCE VIEW. This view will not work
until we create the base table.
CREATE VIEW v8
AS
SELECT empno,ename,job FROM emp;
CREATE VIEW v9
AS
SELECT * FROM v8;
* empno,ename,job,sal,hiredate,comm,mgr,deptno
User_Views:
• "User_Views" maintains all views information.
Dropping views:
Syntax:
Drop View <view_name>;
Ex:
Drop View v10;
View:
Virtual Table
SELECT query
Advantages:
• SECURITY
• REDUCES COMPLEXITY
Disadvantage:
• Low performance
2 types of views:
SEQUENCE:
• SEQUENCE is a DB Object.
• SEQUENCE is independent from the table.
• It is used to generate sequential integers.
Ex:
cid productid
------- ------------
10 1000
20 1100
30 1200
40 1300
50
Example:
Clause Default
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10 power 28
Cycle NoCycle
Cache 20
Syntax:
<seq_name>.<pseudo_column>
Ex:
s1.NEXTVAL
s1.CURRVAL
Example:
1 row inserted
/
enter value for cname:Vijay
Assignment:
Course
cid cname
10 JAVA CREATE SEQUENCE s3
20 PYTHON START WITH 10
30 C# INCREMENT BY 10
MINVALUE 10
40 ORACLE
MAXVALUE 50;
50 C
/
Enter value for cname:
Oracle 6 PM Page 164
Enter value for cname:
CREATE SEQUENCE s4
START WITH 1001
INCREMENT BY 1
MINVALUE 1001
MAXVALUE 1020;
CREATE SEQUENCE s5
START WITH 101
INCREMENT BY 1
MINVALUE 101
MAXVALUE 500;
cycle / nocycle:
• default => nocycle
cycle:
CREATE SEQUENCE s6
START WITH 300 s6.nextval 300
INCREMENT BY 1 301
MAXVALUE 310 302
MINVALUE 100
cycle;
310
100
310
100
CREATE SEQUENCE s7
START WITH 300
INCREMENT BY 1
MAXVALUE 500
MINVALUE 100
cycle;
CREATE SEQUENCE s7
START WITH 300
INCREMENT BY 1
MAXVALUE 500
MINVALUE 100
nocycle;
CREATE SEQUENCE s9
START WITH 301
s9.nextval =>
• goes to DB.
• identifies current value
• to the current value increment by value will added
• returns sequence number
cache 100:
CREATE SEQUENCE s9
START WITH 301
INCREMENT BY 1
MINVALUE 300
MAXVALUE 500
cache 100;
s9.nextval =>
s9.nextval =>
it collects next value from CACHE
memory
cache:
• Default size: 20
• It improves the performance.
• When we call the sequence, next number
will be collected from cache.
• Cache holds preloaded values.
• Cache size must be < one cycle.
Altering Sequence:
using IDENTITY:
• Introduced in Oracle 12c version.
• It is used to generate sequential integers.
• Always it starts from 1 only.
• "GENERATED ALWAYS AS IDENTITY" keyword is
used to generate sequential integers for a column.
Dropping SEQUENCE:
Syntax:
Drop Sequence <seq_name>;
Ex:
Drop Sequence s1;
USER_SEQUENCES:
It maintains all sequences information
PERSON
Disadvantage of VIEW:
• Less Performance
Advantages:
• It improves performance.
• We can maintain local copy physically of remote
database.
emp emp
empno ename job sal deptno empno ename job sal deptno
1001 10 1001 10
1002 10 1002 10
.. 20 .. 20
1005 30 1005 30
v1 mv1
deptno sum(Sal)
SELECT ..
10 50000
20 100000
emp
empno ename job sal deptno
Oracle 6 PM Page 171
empno ename job sal deptno
1001 10
1002 10
.. 20
1005 30
2001 A 20000 10
mv1
deptno sum(Sal)
deptno sum(Sal)
10 70000
10 50000
20 100000
20 100000
mv1
deptno sum(Sal)
10 70000
20 100000
Log in as DBA:
GRANT create materialized view TO c##batch6pm;
ON DEMAND:
Ex:
SQL> Execute dbms_mview.refresh('MV1');
Execute dbms_mview.refresh('MV3');
On commit:
Ex:
weekly collection on every week
monthly collection on every month
year collection on every year
Refresh Types:
3 refresh types:
• Complete
• Fast
• Force
Complete refresh:
• In "complete" refresh, truncates complete data
from materialized view. Again it calculates &
fills the result in materialized view.
BASE TABLE
MV6
emp
deptno sum(sal)
empno ename deptno sal
10 7000
1001 10 3000
20 15000
1002 10 4000
1003 20 6000
1004 20 5000
1005 20 4000
FAST refresh:
• In fast refresh, only recent changes made on base
table will be applied to materialized view.
• For FAST refresh, "materialized view log" file is
required. In this file, recent changes of base table
will be recorded here.
BASE TABLE
emp
MV6
empno ename deptno sal
deptno sum(sal)
1001 10 3000
10 7000
1002 10 4000
20 11000
1003 20 6000
1004 20 5000
1005 20 4000
1006 10 2000
1005 20 4000
1006 10 2000
Note:
If materialized view log file is not there, FAST refresh
will be failed.
FORCE refresh:
• IN FORCE refresh, ORACLE gives first
priority for FAST refresh. If "materialized
view log" file is not available, then ORACLE
performs COMPLETE refresh.
Note:
to create m.view log file, the table must have primary key
DBA creates it
Log in as DBA:
improves performance
Java Developer:
user_mviews:
It maintains all m.views information
ORACLE
Index:
Joins
• Index is DB Object.
• Index improves the performance
of data retrieval. INDEX
• To refer particular topic in BOOK, we
use INDEX. With this quickly we can DDL
refer particular topic. DML
• If index is created on column quickly
access the records. Joins 50
• Index will be created on columns.
• Index will be created on the columns
which are frequently used in WHERE
clause Or in JOIN condition.
Advantage:
• improves performance of data retrieval.
Table Scan:
If index is not created "TABLE SCAN" will be
performed.
Index Scan:
If index is created "INDEX SCAN" will be
performed
sal
------- 3000
3000
5000
1500
1800 2000 4000
4000
4000
1200 1000 * 2500 * 4000 ** 5000 *
1000 1200 * 3000 **
3000 1500 *
2500 1800 *
sal
------- SELECT * FROM emp WHERE sal>3500;
3000
5000 If index is not created 10 comparisons
1500 will be done
1800
4000
Oracle 6 PM Page 180
5000 If index is not created 10 comparisons
1500 will be done
1800
4000
4000
1200
1000
3000
2500
Types of Indexes:
2 Types:
B-TREE Index:
If B-TREE is created when we create the INDEX then it
is called "B-TREE INDEX"
Simple Index:
If index is created on one column
then it is called "Simple Index".
Ex:
emp
empno ename deptno job
10 MANAGER 20
10 CLERK
20 MANAGER 10 30
10 CLERK
20 CLERK
10 man * 20 man * 30 man *
30 MANAGER
10 cler ** 20 cle 8 30 cl *
30 CLERK
dept
deptno dname
10 sales
20 accounts
30 research
40 operations
Note:
When we create a table with primary key an index will be
created implicitly on primary key column.
Function-Based Index:
If index is created based on function or expression
then it is called "Function-Based Index".
Ex:
sal*12 (sysdate-hiredare)/365
BITMAP INDEX:
• 0,1 are the bits. B-TREE INDEX value, row iid
• An Index which can store bits only is called
Bitmap Index bits
"Bitmap Index".
• For this B-Tree will not be created.
1 Row ID
• Every bit is associated with row id.
• In this, bits will be converted to ROW IDs.
• Low Cardinality => A column which is having
less distinct values
• Create Bit map index on low cardinality Low Cardinality:
columns
deptno
-----------
10
20 10
job
10 20
------
CLERK 10 30
CLERK 20
MANAGER 20
SALESMAN 30
MANAGER 30
CLERK 20
SALESMAN 30
10
Gender
-----------
M
Oracle 6 PM Page 184
M
M M
F F
F
F
M
F
M
F
ename
------------
SMITH
ALLEN
BLAKE
SMITH
JOHN
MILLER
.
gender
Oracle 6 PM Page 185
gender
-----------
M M F
F 1 0
F 0 1
M 0 1
M 1 0
F
1 0
0 1
User_Indexes:
• "User_Indexes" maintains all indexes information.