ORACLE4PM
ORACLE4PM
Day-1 https://youtu.be/UeMnnCqTY_o
Day-2 https://youtu.be/FpCHkGp4UMc
Day-3 https://youtu.be/pFX2pR8BFU0
Day-4 https://youtu.be/9AQQ4mNNafE
Day-5 https://youtu.be/epDMjhClQwE
Day-6 https://youtu.be/tyWq-ovCdac
Day-7 https://youtu.be/lwJuQjtwNF0
Day-8 https://youtu.be/UI1v8icChXk
Day-9 https://youtu.be/ZCPSOMlnHFQ
ORACLE4PM Page 1
Syllabus
Thursday, April 20, 2023 5:33 PM
SQL PL/SQL
Sequences Packages
Synonyms Triggers
Collections
Dynamic SQL
ORACLE4PM Page 2
ORACLE
Thursday, April 20, 2023 4:20 PM
ORACLE
SQL
PL/SQL
Database
DBMS
RDBMS
Metadata
Database:
Database:
• Database is a collection of interrelated data in an
organized form.
• database contains interrelated data.
• Database must be organized. Organized means,
arranging in systematic way. With this maintenance
will become easier.
• Database is complete details of an organization stored
in computer hard disk in meaningful format.
DBMS:
• DBMS stands for DataBase Management System /
Software.
• It is a software that is used to create & maintain the
database.
ORACLE4PM Page 3
1977 => ORACLE comapany established with the name
Software Development Laboratories => Larry Ellison
RDBMS:
• RDBMS is a kind of DBMS.
• RDBMS stands for Relational DataBase Management
System / Software.
• It is a software that is used to create & maintain the
database in the form of tables.
• Relation => Table
Example:
Examples:
ORACLE, SQL SERVER, MY SQL, DB2, Postgre SQL
DBMS
COMPUTER
RDBMS
LAPTOP
ORACLE => oracle company
DELL
SQL SERVER => microsoft company
MICROSOFT
DB2 => IBM
APPLE
MY SQL => Sun micro sys (ORACLE)
HP
Postgre SQL => postgre
number(4) int
money
to_char() datepart()
Metadata:
Metadata is the about the data.
Examples:
ORACLE4PM Page 4
Examples:
field names => empno, emp_name,salary
table name => employee
data type => number, varchar2, date
field size => 4, 10
EMPLOYEE
number(4) varchar2(10)
empno emp_name salary
1001 RAMU 6000
RAJU ERROR
9999
10000 ERROR
-9999 to
9999
DBMS is a software
create & maintain the database
RDBMS is a software
create & maintain the database in the form of tables
ORACLE
Exs:
ATM Bank DB Server
check balance
50000 customers
acno balance
ORACLE4PM Page 5
acno balance
1234 50000
1235 100000
online shopping
searching products
ORACLE
SQL DATABASE
PL/SQL TABLES
ROWS & COLUMNS
programming languages
SQL: software
• SQL stands Structured Query Language. programs
• SQL is a Query Language that is used to communicate with
ORACLE DB.
• In SQL we write the queries to communicate with DB.
• Query is a request that is sent to DB SERVER.
○ Ex: SELECT ename,sal FROM emp;
ATM Client
Bank DB Server
balance: 50000
OPENING ACCOUNT
Fill Form
firstname
lastname
city
mobile
mailid
DB SERVER
Submit => Request =>
INSERT INTO customer Customer
VALUES(…,…, … ….) cid fname lname city
QUERY
In C: sub programs
• SQL is Non-Procedural Language. It means, we Function:
will not write any set of statements or a set of statements
programs in SQL. Just we write the Queries.
In Java:
• SQL is unified language. It is common Method:
language to communicate with many RDBMSs. a set of statements
In PL/SQL:
Procedure:
a set of statements
ORACLE4PM Page 6
ORACLE SQL SERVER MY SQL
DATABASE DATABASE DATABASE
TABLES TABLES TABLES
SELECT
SELECT SELECT
INSERT
INSERT INSERT
SQL SQL SQL
1 month 2 days
number(4) numeric(4)
money
25-dec-2022
to_char() datepart()
ANSI standards
SQL
OOPS concepts
JAVA C# Python
EMP DEPT
1001 A 20 10 HR
1002 B 10 20 SALES
JOINS
ENAME DNAME
ORACLE
SQL DATABASE
PL/SQL TABLES
ROWS & COLUMNS
ORACLE4PM Page 7
SQL:
• Query Language that is used to communicate with DB
• Query => is a request => to DB SERVER
• Non-Procedural Language
• Unified Language
• readymade commands, functions, clauses, joins,
operators
DDL CREATE
• Data Definition Language ALTER
• Data Definition => metadata
• deals with metadata DROP
FLASHBACK [oracle 10g]
PURGE [oracle 10g]
TRUNCATE
RENAME
TCL: COMMIT
• Transaction Control Language ROLLBACK
• It deals with the transactions SAVEPOINT
DML: INSERT
• Data Manipulation Language UPDATE
• Manipulation => insert/ update/ DELETE
delete customer
• It deals with data manipulations INSERT ALL cid cname cust_city gender
MERGE
DCL: GRANT
• Data Control Language REVOKE
• It deals with data accessibility
ORACLE
DATABASE
DATABSE OBJECTS
DATABSE OBJECTS
• Tables
• Views
• Indexes
• Sequences
• Synonyms
• Materialized Views
• Stored procedures
• Stored Functions
• Packages
• Triggers
ORACLE4PM Page 8
DROP => used to drop the table => delete
FLASHBACK => restore the table => restore
PURGE => deletes from recyclebin => delete
EMPLOYEE
EMPNO ENAME SAL
1001 AA 6000
1002 BB 5000
DDL
DRL / DQL:
SELECT:
used to select the data from database
BANK DB SERVER
check balance
ACCOUNT
SELECT balance FROM account
acno balance
WHERE acno=1001;
1001 500000
1002 800000
TCL:
• It deals with transactions
ACCOUNT
withdraw
ACNO BALANCE
amount: 10000 1001 50000
gives money
UPDATE the balance
DML:
Manipulation => INSERT / UPDATE / DELETE
ORACLE4PM Page 9
DCL:
RAMU
emp table
GRANT
Revoke
SAI
SQL:
DDL Commands:
• Data Definition Language
• Data Definition => metadata
• It deals with metadata
ORACLE DB OBJECTS:
Tables
Views
CREATE Indexes
CREATE:
Synonyms
Syntax: Sequences
Materialized views
CREATE TABLE <table_name> [ ] Optional
( < > Any stored procedures
<field_name> <data_type> [, stored functions
<field_name> <data_type> , packages
STUDENT triggers
<field_name> <data_type>
sid sname dob
.
.] 1001 Ramu 25-DEC-1998
); 1002 Vijay 17-AUG-1995
ORACLE4PM Page 10
Data Types in ORACLE SQL:
nChar(n)
nVarchar2(n)
nCLOB
1001
Date & Time related Date
RAMU
Timestamp
1-2-123/A/B
25-DEC-1998
25-DEC-1998 9:30:00.00 PM
• nChar(n)
• nVarchar2(n)
• nCLOB
Char(n):
• n => max no of chars
• used to hold string [a set of chars] values.
• Fixed length char data type
Varchar2(n):
n => max no of chars
ORACLE4PM Page 11
• n => max no of chars
• used to hold string [a set of chars] values.
• Variable length char data type
Char(n):
• n => max no of chars
• used to hold string [a set of chars] values.
• Fixed length char data type
• Max size: 2000 Bytes [2000 chars]
• Default size: 1
• can accept alpha numerics.
Varchar2(n):
• n => max no of chars
• used to hold string [a set of chars] values.
• Variable length char data type
• Max size: 4000 Bytes [4000 chars]
• Default size: no default size [we must specify size]
• can accept alpha numerics.
Example:
Pan_Card_Number CHAR(10)
--------------------------
ABC1L34567
Vehicle_Number CHAR(10)
--------------------------
TS09AA1234
mail_id VARCHAR2(30)
--------------
[email protected]
[email protected]
ORACLE4PM Page 12
LONG:
• used to hold large amounts of chars
• It has some restrictions [limitations]:
○ we can take one column as LONG type per a table
○ Built-In Functions cannot be used on LONG type
CLOB:
• CLOB stands for Character Large Object
• used to hold large amounts of chars
Examples:
product_features CLOB
customer_feedback CLOB
experience_summary CLOB
ASCII:
• is a coding system
Char(n) • ASCII code char data types • American Standard Code for Information Interchange
Varchar2(n) • can hold english lang chars only • 256 chars are coded [code range: 0 to 255] [1 byte]
LONG • Single Byte Data types • A to Z => 65 to 90
CLOB • a to z => 97 to 122
• 0 to 9 => 48 to 57
nChar(n) • UNI code char data types • remaining codes are for special symbols like: @ # $ % + -
nVarchar2(n) • can hold english + other lang chars • English lang chars only
nCLOB • Multi Byte Data types
UNI:
n => national • is a coding system
• UNIVERSAL
• is extension of ASCII
• 65536 chars are coded [rang: 0 to 65535] [2 bytes]
• english lang chars +other lang chars [japanese, chinese, greek ]
In Java:
char ch; // 2 bytes => UNI
Varchar2(n) • variable length data type
• max size: 4000 bytes [4000 chars]
nVarchar2(n) • variable length data type
• max size: 4000 bytes [2000 chars]
Number(p) / Numeric(p):
• p => precision => max no of digits
• p valid range: 1 to 38
• It is used to hold integers.
• Integer means, number without decimal places
• Exs: 78, 1234, 897
Exs:
ORACLE4PM Page 13
Max marks: 100
Mobile_number NUMBER(10)
Aadhar_Number NUMBER(12)
CreditCard_Number NUMBER(16)
Integer = Number(38)
Int = Number(38)
Note:
• Integer and Int are alias names of Number(38)
Number(p,s) / Numeric(p,s):
• p => precision => max no of digits [total no of digits]
• s => scale => max no of decimal places
• It is used to hold floating point values.
• Floating point means, number with decimal places.
• Exs: 67.89, 123.45678
max salary:
100000.00
scale => 2
precision => 8
100.00
s=2
p=5
ORACLE4PM Page 14
123.453897 => 123.45
786.658342 => 786.66
786.654342 => 786.65
Float
Real
Binary_Float
Binary_Double
Date:
• It is used to hold date values.
• It can also hold time value.
• Default ORACLE DATE FORMAT: DD-MON-RR [26-APR-23]
• Default time: 12:00:00 AM [midnight time]
• It can hold day, month, year, hours, minutes and seconds.
• It cannot hold fractional seconds.
• Fixed length data type
• memory: 7 bytes
• Ex:
Date_Of_birth Date
Date_Of_Joining Date
Example:
create table t7
(
f1 date
);
String
t7
f1 Implicit Conversion
-------
25-DEC-19 Date
to_date():
can be used to convert string to date
Ex:
to_date('25-DEC-2019') => 25-DEC-19
Explicit conversion
Note:
ORACLE supports to Implicit conversion.
ORACLE4PM Page 15
• ORACLE supports to Implicit conversion.
• Don't depend on implicit conversion. Always do explicit
conversion due to 2 reasons:
○ performance will be degraded with implicit conversion
○ In future versions, implicit conversion programs may
be changed or removed
t7
to_date()
f1 explicit conversion
----------
17-AUG-22 => date
Note:
• to insert date value, use to_date() function.
• it improves the performance.
character related:
Char(n)
Statecode char(2)
PAN_CRAD_NUMBER char(10)
Varchar2(n)
ename VARCHAR2(10)
>4000 chars
CLOB
experience_summary CLOB
Integer related:
Number(p)
mopbile_number number(10)
aadhgar_num number(12)
100.00
Floating Point related:
Number(p,s)
avrg number(5,2)
Date:
used to hold date values
DOB DATE
DOJ DATE
DOR DATE
Timestamp:
• It is introduced in Oracle 9i version.
• It can hold day, month, year, hours, minutes,
seconds and fractional seconds.
• It is extension of DATE data type.
• Fixed Length data type.
memory: 11 bytes
ORACLE4PM Page 16
• memory: 11 bytes
Example
--------------
Transaction_date_time Timestamp
Session_strat_time Timestamp
STRING
to_timestamp()
Explicit conversion
F1
-------
22-DEC-2019 10:30:0.0 AM => timestamp
Note:
to insert date value, use to_date() function
to insert timestamp value, use to_timestamp() function
F1
-----
25-NOV-20 12:00:00.00 AM
timestamp format:
DD-MON-RR HH:MI:SS.FF AM
25-NOV-20 12:00:00.000000 AM
BFILE
BLOB
ORACLE4PM Page 17
Nowadays we are using BLOB data type instead
of RAW, LONG RAW
BFILE:
• BFILE stands for BINARY FILE LARGE OBJECT
• used to maintain multimedia objects [unstructured data]
like :
images, audios, videos, documents, animations
• External Large Object. Object will be stored out of the DB.
Just path of Object will be maintained in DB
• It is not secured
BLOB:
• BLOB stands for BINARY LARGE OBJECT
• used to maintain multimedia objects [unstructured data]
like :
images, audios, videos, documents, animations
• Multimedia object will be stored inside of the database. It
can be also called as "internal Large Object"
• It is secured
1234 CLOB
10001011110001 BLOB
DATABASE
D: DRIVE
EMP
EMPID ENAME EPHOTO [BFILE] EMPS Folder
1001 RAJU DIR1,raju.jpg
raju.jpg
DATABASE
D: DRIVE
EMPS Folder
EMP
EMPID ENAME EPHOTO [BLOB]
1001 RAJU 1456A523BFD385C raju.jpg
SQL
5 sub languages:
DDL:
CREATE:
ORACLE DB SERVER
Client
ORACLE4PM Page 18
ORACLE
SQL PLUS => CUI
Instance DB
CUI GUI
google account
username
password
15GB => memory
memory location
Note:
• ORACLE DB will be stored in tablespaces.
• built-in tablespaces are: sys, sysaux, users
• Open SQLplus
press windows+R => type "sqlplus" => OK
conn[ect]:
it is used to connect to DB server from SQL prompt.
ORACLE4PM Page 19
• it is used to connect to DB server from SQL prompt.
Syntax:
conn[ect] <username>/<password>
Ex:
conn batch4pm/naresh
DISC[ONNECT]:
• it is used to disconnect from db server
Syntax:
DISC[ONNECT]
Note:
• username is not case sensitive
• password is case sensitive
note:
if yopu invalid common user error, prefix user
name with c##
Changing password:
Login as DBA:
username: system
password: nareshit
ORACLE4PM Page 20
Syntax to create the table: STUDENT
sid sname avrg
CREATE TABLE <table_name>
(
<field_name> <data_type>[,
<field_name> <data_type>,
<field_name> <data_type>,
.
.]
);
Example-1:
STUDENT
sid sname avrg
1001 AA 67.89
100.00
1002 BB 56.92
Note:
• SQL is not case sensitive language
• Every SQL command end with ;
Inserting records:
1001 AA 67.89
1002 BB 56.92
COMMIT; DB SERVER
instance DB
Note: 1001 student
when we insert the record, it 1002
will be inserted in instance. it means,
RAM HD
it is temporary. To save it permanently
use COMMIT command
mobile num
SUBMIT
ORACLE
SQL SERVER
HTML
JavaScript
CSS
ORACLE4PM Page 21
ORACLE => RDBMS
SQL DATABASE
PL/SQL TABLES
SQL:
CREATE:
• It is used to create the DB Objects like Tables, Views,
Indexes, ….. etc.
INSERT:
• used to insert the records.
Syntax:
SELECT:
• It is used to retrieve the data from table/tables.
Syntax:
SELECT <column_list>/*
FROM <table_name>
[WHERE <condition>];
ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES
Exs of clauses:
ORACLE4PM Page 22
Examples on Creating tables & Inserting records:
Example-1:
STUDENT
SID SNAME GENDER AVRG
1001 AA M 78.96
1002 BB F 67.34
Creating table:
Inserting records:
1001 AA M 78.96
1002 BB F 67.34
INSTANCE DB
1001 student
1002 1001
1002
RAM HARD DISK
DESC[RIBE]:
It is used to see table structure.
Syntax:
DESC[RIBE] <table_name>;
ORACLE4PM Page 23
Example:
DESC student;
Output:
Name Type
sid NUMBER(4)
sname VARCHAR2(10)
.. ..
.. ..
user_tables:
• It is a Built-In Table / System Table.
• It maintains all tables information which are created by
the user.
DESC user_tables;
Output:
Name Type
Table_name ..
.. ..
user_tables
table_name .. ..
SELECT table_name FROM user_tables;
Output:
T1
STUDENT
create
insert
commit
desc
user_tables
/ (or) Run:
It is used to run recent command which is in memory.
/
Output:
1 row inserted. [1003 record inserted]
/
Output:
1 row inserted. [1003 record inserted]
parameter:
• parameter concept is used to read the value at runtime.
• parameter text need not be column name
Syntax:
&<text>
Ex:
ORACLE4PM Page 24
enter value for sid: 1004
enter value for sname: ABC
enter value for gender: M
enter value for avrg: 45.66
these values will be substituted in place of parameters.
oracle rewrites query as following:
INSERT INTO student VALUES(1004,'ABC','M',45.66);
1 row created.
/
enter value for sid: 1005
enter value for sname: XYZ
enter value for gender: F
enter value for avrg: 66.23
/
enter value for sid: ..
enter value for sname: ..
enter value for gender: ..
enter value for avrg: ..
STUDENT
sid sname gender avrg
XYZ 55.44
null
null INSERT INTO student VALUES('XYZ',55.44);
Output:
ERROR: not enough values
ORACLE is expecting 4. we are passing 2
5001 AAAA
INSERT INTO student(sid,sname) VALUES(5001,'AAAA');
Output:
1 row created.
create
commit
desc
user_tables
select
Pages[ize]:
• default page size is 14
ORACLE4PM Page 25
we can change pagesize as following:
Lines[ize]:
• default line size is 80
Note:
lines 200
1 1234…………200
200 chars => 1 line
2
3
pages 200
Example-2:
DOJ => Date Of Joining
EMPLOYEE
EMPNO ENAME JOB SAL DOJ 100000.00
5001 SAI CLERK
5002 KIRAN MANAGER
empno NUMBER(4)
ename VARCHAR2(10)
job VARCHAR2(10)
sal NUMBER(8,2)
doj DATE
Inserting records:
STRING STRING
implicit conversion
ename
DOJ
=========
========
KIRAN => string
ORACLE4PM Page 26
STRING STRING
implicit conversion
ename
DOJ
=========
========
KIRAN => string
30-APR-23 => date
DD-MON-RR
to_date()
DOJ explicit conversion
--------
25-NOV-21 => date
Example-3:
TRANSACTIONS
TID T_DATE_TIME TTYPE ACNO Amount
123456 2-may-2023 10:30:0.0 AM deposit 1001 10000
123457 30-apr-2023 5:30:0.0 PM withdraw 4567 15000
tid number(6)
t_date_time timestamp
ttype varchar2(10)
acno number(4)
amount number(9,2)
implicit conversion
t_date_time
---------------
30-APR-2023 10:30:0.0 AM => timestamp
ORACLE4PM Page 27
INSERT INTO transactions
VALUES(123458, to_timestamp('24-APR-2023 5:30:0.0 PM'), 'deposit',
5123, 25000); string
to_timestamp()
Explicit Conversion
t_date_time
----------------------
24-APR-2023 5:30:0.0 PM => timestamp
Integer NUMBER(p)
Float NUMBER(p,s)
Date DATE
DATE & Time TIMESTAMP
fixed length chars CHAR(n)
variable length chars VARCHAR2(n)
ALTER:
• ALTER => change
• ALTER command is used to change structure of table.
• Using this command we can:
○ Add the columns => ADD
○ Rename the Columns => RENAME COLUMN
○ Drop the Columns => DROP
○ Modify the field sizes => MODIFY
○ Modify the data types => MODIFY
STUDENT
sid sname
DESC student;
Output:
sid
sname
DESC student;
Output:
sid
ORACLE4PM Page 28
sid
sname
m1
DESC student;
Output:
sid
sname
m1
m2
m3
DESC student;
Output:
sid
sname
m1
m2
maths
DESC student;
Output:
sid
sname
m1
m2
DESC student;
Output:
sid
sname varchar2(10)
DESC student;
Output:
sid
sname varchar2(20)
ORACLE4PM Page 29
20 to 6 => valid
VIJAY
SAI
RAMESH => 6 => max string length
DESC student;
Output:
sid char(8)
NOTE:
To modify the data type of a column, column must be empty
DROP
FLASHBACK
PURGE
Note:
• "RecycleBin" concept added to ORACLE in ORACLE 10g version
• FLASHBACK & PURGE are related to recyclebin. These 2
commands are introduced in ORACLE 10g version.
DROP:
• is used to delete the entire table.
• Table = Structure + Data
EMPLOYEE Table
EMPNO ENAME SAL Structure
1001 AA 6000 +
1002 BB 8000 Data
Syntax:
DROP TABLE <table_name> [PURGE];
Ex:
DROP TABLE employee;
to see recyclebin:
show recyclebin;
Output:
Object_name
-----------------------
Employee
FLASHBACK:
ORACLE4PM Page 30
FLASHBACK:
• used to restore the dropped table from recyclebin
Syntax:
Example:
FLASHBACK TABLE employee
TO BEFORE DROP;
PURGE:
• used to delete the table from recyclebin
• Once table is deleted from recyclebin, it will be
deleted permanently. it cannot be restored.
Syntax:
PURGE TABLE <table_name>;
Ex:
PURGE TABLE employee;
username: system
4-MAY-23
-------------------
DDL:
CREATE
ALTER
DROP
FLASHBACK
PURGE
CASE-1:
RBIN
RBINNAME
CREATED T1
T1 4:15 …..
T1 DROPPED => 4:10 PM
T1 4:10 ……
CREATED T1
T1 DROPPED => 4:15 PM
FLASHBACK TABLE t1
TO BEFORE DROP;
restores recently dropped one
T1 => 4:15 PM
ORACLE4PM Page 31
To restore older one [t1 table dropped at 4:10 PM]:
Note:
Table name must be unique with in the schema [user => c##batch4pm]
CASE-2:
RBIN
CREATE TABLE T2
T2 DROPPED T2
CREATE TABLE T2
Restore
with another name
TRUNCATE:
• used to delete all records from the table with good
performance.
• These records will be deleted permanently. We cannot
recollect them.
Table = Structure + Data
CUSTOMER Table
TRUNCATE
Syntax:
Example:
TRUNCATE TABLE customer;
ORACLE4PM Page 32
DROP TRUNCATE
RENAME:
used to change table name
Syntax:
Ex:
RENAME t2_old TO xyz;
DDL:
Alter:
create:
used to change structure of table
used to create the table
add the columns
drop the columns
syntax:
rename the columns
create table <tn>
modify the data types & field sizes
(
<fn> <dt>[,
ALTER TABLE <tn> ADD(..)
.
DROP COLUMN
.]
DROP(..)
);
MODIFY(..)
Drop: Flashback:
to delete entire table used to restore the table
Syn: Syn:
DROP TABLE <tn> [PURGE]; FLASHBACK TABLE <tn>
TO BEFORE DROP
[RENAME TO <name>];
truncate:
PURGE:
TO DELETE ALL ROWS
to delete from rbin
Syn:
Syn:
TRUNCATE TABLE <tn>;
PURGE TABLE <tn>;
Rename:
used to rename the table
Syn:
RENAME <old_name> TO <new_name>;
ORACLE4PM Page 33
Emptying Recyclebin:
Recyclebin
T1
PURGE RECYCLEBIN;
T2
T3
-- it empties recyclebin
.
.
T10
ORACLE4PM Page 34
DRL
Thursday, May 4, 2023 5:00 PM
DRL / DQL:
• DRL stands for Data Retrieval Language
• DQL stands for Data Query Language
• Retrieve => get back => opening existing data
• Query => request that is sent to DB SERVER
• Example:
○ check balance
○ searching for products in online shopping
SELECT:
Syntax:
ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES
CLAUSE:
• CLAUSE is a part of query
Every CLAUSE has specific purpose
SELECT:
• SELECT command is used to select the data from
table.
• Using SELECT command we can SELECT:
• all rows and all columns
• specific rows and all columns
• all rows and specific columns
specific rows and specific columns
ORACLE4PM Page 35
• specific rows and specific columns
SELECT ename,sal
FROM emp
WHERE sal>2500;
Execution Order:
FROM
WHERE
SELECT
EMP
EMPNO ENAME JOB SAL
1001 AA CLERK 6000
1002 BB SALESMAN 2000
1003 CC MANAGER 8000
FROM emp:
It selects entire table
EMP
EMPNO ENAME JOB SAL
1001 AA CLERK 6000
1002 BB SALESMAN 2000
1003 CC MANAGER 8000
WHERE sal>2500:
• It filters the rows.
WHERE clause condition will be
ORACLE4PM Page 36
• WHERE clause condition will be
applied on every row.
EMP
EMPNO ENAME JOB SAL
1001 AA CLERK 6000
1003 CC MANAGER 8000
SELECT ename,sal:
It selects the columns
EMP
EMPNO ENAME JOB SAL ENAME SAL
1001 AA CLERK 6000 AA 6000
1003 CC MANAGER 8000 CC 8000
final result
SELECT *
FROM emp;
* All Columns
SELECT *
FROM emp
WHERE sal=3000;
SELECT ename,sal
FROM emp
WHERE sal=3000;
* All Columns
SELECT ename,sal Specific Columns
Not wrting WHERE condition All rows
WHERE sal=3000 Specific rows
5-may-23:
-------------------
OPERATORS in SQL:
OPERATOR:
OPERATOR is a symbol that is used to perform operations like
arithmetic or logical operations.
Arithmetic + - * /
Special IN
BETWEEN AND
LIKE
IS NULL
ORACLE4PM Page 38
ANY
ALL
EXISTS
SET UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||
Arithmetic Operators:
In SQL:
5/2 = 2.5 [accurate]
mod(5,2) = 1
mod(10,7) = 3
Output:
ENAME SAL SAL*12
----------- -------- ----------
SMITH 800 9600
ALLEN 1600 19200
Output:
Output:
Output:
Output:
ERROR: alias name has space
Output:
ENAME SAL annual sal
ORACLE4PM Page 40
Column Alias:
• Alias => Alternative name / another name
• Column Alias is used to change column heading in
output.
• "AS" keyword is used to give column alias.
• Using "AS" keyword is optional.
• To maintain the case or to give column alias in
multiple words we must specify alias name in
double quotes.
Syntax:
<column> [AS] <column_alias>
Exs:
sal AS salary => SALARY
sal salary => SALARY
sal AS "salary" => salary
sal AS monthly sal => ERROR
sal AS "monthly sal" => monthly sal
NOTE:
Select query calculation is temporary. it will not be
stores in table
Add a Column TA
UPDATE query calculation is stored in table.
ORACLE4PM Page 41
UPDATE query calculation is stored in table.
Assignment:
Display the emp records whose experience is
more than 41 years:
Exs:
sal > 3000
sal > 3000,4000 --Invalid
ORACLE4PM Page 42
sal > 3000,4000 --Invalid
SELECT ename,sal
FROM emp
WHERE sal=3000;
SELECT ename,sal
FROM emp
WHERE sal>=3000;
SELECT ename,sal
FROM emp
WHERE sal<=3000;
SELECT ename,sal
FROM emp
WHERE sal<1000;
6-may-23
------------------
no rows selected
ORACLE4PM Page 43
job
----------
CLERK
MANAGER = manager => F
SALESMAN
MANAGER
NOTE:
• SQL is not case sensitive language.
• String comparison is case sensitive.
• Case sensitive means, upper case and lower
case will be treated as different.
Ex:
MANAGER = MANAGER => T
MANAGER = manager => F
SELECT *
FROM emp
WHERE empno=7521;
SELECT ename,deptno
FROM emp
WHERE deptno=10;
Display the emp records who are working in other than 10th
dept:
SELECT ename,deptno
FROM emp
WHERE deptno!=10; [deptno<>10] [deptno^=10]
ORACLE4PM Page 44
Display the emp record whose name is BLAKE:
SELECT ename,sal
FROM emp
WHERE ename='BLAKE';
2019
2020
2021 25-JUN-2019 > 15-AUG-2017
2023 calendar
18-SEP-2020 < 23-NOV-2022
1-jan-2023
2-jan-2023
3-jan-2023
.
.
31-dec-2023
hiredate
hiredate
ORACLE4PM Page 45
WHERE hiredate<'1-jan-1981';
hiredate
31-dec-1980 1-jan-1981
<
30-dec-1980
.
.
Logical Operators:
Logical Operators are used to perform logical operations
like logical AND, logical OR, logical NOT operations.
Truth Table:
SELECT ename,job
FROM emp
WHERE job='MANAGER' OR job='CLERK';
job
-------
SALESMAN F F => F
ORACLE4PM Page 46
SALESMAN F F => F
MANAGER T F => T
CLERK F T => T
SELECT ename,job,sal
FROM emp
WHERE job='MANAGER' AND sal>2500;
Display all managers records whose salary is more than 2500 and who
joined after april 1981:
SELECT ename,sal
FROM emp
WHERE sal>=2000 AND sal<=3000;
sal
-------
6000 => F
1000 => F
2000 => T
3000 => T
2500 => T
SELECT *
FROM emp
WHERE empno=7369 OR empno=7521 OR empno=7900;
ORACLE4PM Page 47
Display the emp records who are working in 10 and 30
depts:
SELECT ename,deptno
FROM emp
WHERE deptno=10 OR deptno=30;
Condn NOT(condn)
T Not(T) => F
F Not(F) => T
SELECT ename,job
FROM emp
WHERE NOT(job='MANAGER');
(or)
SELECT ename,job
FROM emp
WHERE job!='MANAGER';
job
------
CLERK NOT(F) => T
MANAGER NOT(T) => F
ANALYST NOT(F) => T
MANAGER NOT(T) => F
Amazon
WHERE pname='LAPTOP' AND cname='DELL' AND price between 50000 and 60000
ORACLE4PM Page 48
WHERE pname='LAPTOP' AND cname='DELL' AND price between 50000 and 60000
Example:
max marks: 100
min marks: 40 for pass in each sub
STUDENT
sid sname M1 M2 M3
1001 A 70 90 80
1002 B 60 30 55
SELECT *
FROM student
WHERE m1>=40 AND m2>=40 AND m3>=40;
SELECT *
FROM student
WHERE m1<40 OR m2<40 OR m3<40;
Special Operators:
IN:
sal
---------
2500 => F
4000 => T
6000 => F
5000 => T
IN:
used to compare column value with a list of values.
ORACLE4PM Page 49
• used to compare column value with a list of values.
• it avoids of writing multi equality conditions using OR
• It checks column value is in the list or not. If it is in list,
condition is TRUE. otherwise condition is FALSE.
Syntax:
<column> IN(<value_list>)
Ex:
WHERE sal IN(3000,4000,5000)
Examples on IN Operator:
SELECT *
FROM emp
WHERE job='MANAGER' OR job='CLERK';
(or)
SELECT *
FROM emp
WHERE job IN('MANAGER','CLERK');
job
-------
SALESMAN => F
MANAGER => T
ANALYST => F
CLERK => T
SELECT *
FROM emp
WHERE ename IN('BLAKE','WARD','SCOTT');
ename
---------
SMITH => F
WARD => T
BLAKE => T
ALLEN => F
SCOTT => T
ORACLE4PM Page 50
Display the emp records who are
working in deptno 10 and 30:
SELECT ename,deptno
FROM emp
WHERE deptno IN(10,30);
SELECT *
FROM emp
WHERE job NOT IN('MANAGER','CLERK');
job
--------
CLERK => F
ANALYST => T
MANAGER => F
SALESMAN => T
SELECT *
FROM emp
WHERE empno IN(7499,7521,7900);
BETWEEN AND:
• used to compare column value with a range values
Syntax:
<column> BETWEEN <lower> AND <upper>
Ex:
WHERE sal BETWEEN 2000 AND 3000
ORACLE4PM Page 51
Display the emp records whose salary is
between 2000 and 3000:
SELECT *
FROM emp
WHERE sal BETWEEN 2000 AND 3000;
(or)
SELECT *
FROM emp
WHERE sal>=2000 AND sal<=3000;
SELECT *
FROM emp
WHERE sal BETWEEN 3000 AND 2000;
Answer: C
SELECT ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-jan-1981' AND '31-dec-1981';
(or)
SELECT ename,hiredate
FROM emp
WHERE hiredate>='1-jan-1981' AND hiredate<='31-dec-1981';
ORACLE4PM Page 52
Display all emp records except the emps who joined 1981:
SELECT ename,hiredate
FROM emp
WHERE hiredate NOT BETWEEN '1-jan-1981' AND '31-dec-1981';
In Windows OS,
to search for all jpg files *.jpg
to search for all jpg files s*.jpg
which are started with S
to search for files in which ?a*.jpg
2nd char is A
srinu.jpg
james.jpg
ramu.jpg
aa.jpg
sravan.jpg
allen.jpg
symonds.jpg
scott.jpg
s.jpg
LIKE:
• used to compare column value with text pattern
Syntax:
<column> LIKE <text_pattern>
_ replaces 1 char
% replaces 0 or any no of chars
SELECT *
FROM emp
WHERE ename LIKE 'S%';
ename
-----------
SMITH => T
ORACLE4PM Page 53
SMITH => T
ALLEN => F
SCOTT => T
WARD => F
SYMONDS => T
S => T
SELECT *
FROM emp
WHERE ename LIKE '%S';
ename
-----------
ALLEN => F
SMITH => F
SYMONDS => T => % replaces 6 chars
JAMES => T => % replaces 4 chars
SS => T => % replaces 1 char
S => T => % replaces 0 char
SELECT *
FROM emp
WHERE ename LIKE '%RD';
SELECT *
FROM emp
WHERE ename LIKE '_A%';
SELECT *
FROM emp
WHERE ename LIKE '__M%';
ORACLE4PM Page 54
Display the emp records whose name is
having A char:
SELECT *
FROM emp
WHERE ename LIKE '%A%';
ename
-----------
SMITH
ALLEN
JAMES
ADAMS
SRAVAN
SELECT *
FROM emp
WHERE ename LIKE '____';
SELECT *
FROM emp
WHERE hiredate LIKE '%DEC%';
SELECT *
FROM emp
WHERE hiredate LIKE '%JAN%' OR hiredate LIKE '%DEC%';
SELECT ename,sal
FROM emp
WHERE sal LIKE '___';
sal
-------
1600
12000
800
ORACLE4PM Page 55
800
SELECT *
FROM emp
WHERE ename NOT LIKE 'S%';
SELECT *
FROM emp
WHERE ename LIKE 'S%S';
ename
---------
SMITH
SYMONDS
SS
SRINIVAS
SCOTT
NULL:
• NULL means empty or blank
STUDENT
AB Error
EMPLOYEE
EMPNO ENAME SAL DOJ
1001 A 8000 17-aug-2019
1002 B 7000 null
null != 0
ORACLE4PM Page 56
null != 0
Note:
• In first oracle 6 versions we were using
"varchar" data type
• varchar data type was not showing difference
between space and null.
• Oracle 7 version varchar2 data type introduced
to avoid drawback of varchar.
• Later they modified meaning of varchar also. In
latest versions varchar and varchar2 both acts
as same.
NULL:
• NULL means empty or blank
• NULL is not equals to 0 or space.
• When we don't know the value or when we are unable to
insert the value then we insert NULL.
• If NULL is participated in operation then result will be
NULL.
○ Exs:
100+200 = 300
100+200+ null = null
Example:
EMPLOYEE
EMPNO ENAME SAL HIREDATE
1001 A 8000
1001 A 8000
1002 B
IS NULL:
• It used to compare column value with NULL.
• For null comparison we must use IS NULL operator.
We cannot use = operator.
Syntax:
<column> IS NULL
Examples:
SELECT ename,sal,comm
FROM emp
WHERE comm IS NULL;
SELECT ename,sal,comm
ORACLE4PM Page 58
SELECT ename,sal,comm
FROM emp
WHERE comm IS NOT NULL;
comm
--------
500 => not null => T
=> null => F
Concatenation operator:
Symbol: ||
It used to concatenate [combine] 2 strings
Example:
EMPLOYEE
EMPNO FNAME LNAME
1001 RAJ KUMAR
1002 SAI TEJA
name
-------------
RAJKUMAR
SAITEJA
name
-------------
RAJ KUMAR
SAI TEJA
Output:
SMITH is earning 800
ALLEN is earning 1600
ORACLE4PM Page 59
SQL
ORACLE4PM Page 60
TCL
Tuesday, May 9, 2023 5:19 PM
TCL:
• TCL stands for Transaction Control Language.
• It deals with transactions
• Transaction Rule:
A Transaction must be successfully completed or
aborted [cancelled].
ORACLE DB SERVER
instance DB
INSERT => 1001
emp
ORACLE4PM Page 61
instance DB
INSERT => 1001
emp
1001
dept
Hard Disk
RAM
COMMIT:
• COMMIT command is used to save the transaction.
Syntax:
COMMIT;
ROLLBACK:
• used to cancel uncommitted actions.
• After COMMIT, we cannot use ROLLBACK.
Syntax:
ROLLBACK [TO <savepoint_name>];
Note:
All DDL commands are auto committed
Exs:
CREATE = CREATE + COMMIT
ALTER = ALTER + COMMIT
SAVEPOINT:
• Used to set specific point for rollback.
Syntax:
SAVEPOINT <savepoint_name>;
ORACLE4PM Page 63
Example-1:
Example-2:
SAVEPOINT p1;
INSERT INTO t1 VALUES(1001);
INSERT INTO t1 VALUES(1002);
SAVEPOINT p2
INSERT INTO t1 VALUES(1003)
INSERT INTO t1 VALUES(1004);
SAVEPOINT p3;
INSERT INTO t1 VALUES(1005);
ORACLE4PM Page 64
INSERT INTO t1 VALUES(1005);
INSERT INTO t1 VALUES(1006);
ROLLBACK TO p3;
ROLLBACK TO p2;
ROLLBACK TO p1;
SQL:
ORACLE4PM Page 65
DDL DRL / DQL TCL DML DCL
create select commit insert
alter rollback update
drop savepoint delete
flashback
purge insert all
truncate merge
rename
ORACLE4PM Page 66
Wednesday, May 10, 2023 4:40 PM
note:
• To modify table structure, use ALTER
• To modify table data, use UPDATE
UPDATE:
• Update command is used to change [modify] table data.
• Using this command we can modify:
○ single value of single record
○ multiple values of single record
○ specific records
○ all records
○ using parameters
Syntax:
UPDATE <table_name>
SET <column> = <new_value> [,<column> = <new_value>, ..]
[WHERE <condition>];
Examples on UPDATE:
UPDATE emp
SET sal=6000
WHERE empno=7499;
Output:
1 row updated
COMMIT;
UPDATE emp
SET job='MANAGER', sal=sal+2000
WHERE empno=7369;
UPDATE emp
SET sal=sal+sal*0.1
WHERE job='MANAGER';
UPDATE emp
SET sal=sal+2000;
Output:
enter value for per:10
enter value for empno:7499
/
enter value for per:20
enter value for empno:74521
/
enter value for per:15
enter value for empno:7900
Examples:
ORACLE4PM Page 67
ORACLE4PM Page 68
ORACLE4PM Page 69
Transfer all 10th dept emps emps to 20th dept:
UPDATE emp
SET deptno=20
WHERE deptno=10;
increase 20% on sal to the emps who are not getting commission:
UPDATE emp
SET sal=sal+sal*0.2
WHERE comm is null;
UPDATE emp
SET sal=sal+sal*0.2, comm=comm+comm*0.1
WHERE comm is not null;
UPDATE emp
SET comm=1000
WHERE comm is null;
UPDATE emp
SET comm=null
WHERE empno=7521;
NOTE:
= operator cannot be used for null comparison
= operator can be used for null assignment
UPDATE emp
SET sal=sal+sal*0.1
WHERE hiredate BETWEEN '1-jan-1982' AND '31-dec-1982';
Increase 10% on sal to the emps who are having more than
41years experience:
UPDATE emp
SET sal=sal+sal*0.1
WHERE trunc((sysdate-hiredate)/365)>41;
Assignment:
Increase 10% on sal to the emps who are working in deptno 20 and 30
DELETE:
• used to delete the records from table.
• Using it we can delete:
○ single record
○ specific records
○ all records
○ using parameters
Syntax:
Output:
1 row deleted.
ORACLE4PM Page 70
ORACLE4PM Page 71
ORACLE4PM Page 72
Deleting specific records:
/
enter .. empno: 7934
TRUNCATE DELETE
• It is faster • It is slower
Tablespace
ORACLE4PM Page 73
ORACLE4PM Page 74
ORACLE4PM Page 75
block / page block / page block / page block / page
------------------- ------------------- ------------------- -------------------
------------------- ------------------- ------------------- -------------------
------------------- ------------------- ------------------- -------------------
extent extent
segment
segment segment
Tablespace-2 Tablespace-3
ORACLE DB
ORACLE DB
TABLE SPACES
SEGMENTS
EXTENTS
BLOCKS
RECORDS
ORACLE4PM Page 76
ORACLE4PM Page 77
ORACLE4PM Page 78
Built-In Functions
Thursday, May 11, 2023 4:59 PM
Built-In Functions:
• To make our tasks / actions easier ORACLE DEVELOPERS already
defined some functions & placed them in ORACLE DB. These
functions are called "Built-In Functions / Predefined Functions /
System-Defined Functions".
Built-In Functions
String Functions
Conversion Functions
Date Functions
Math / Number Functions
Analytical Functions
Miscellaneous Functions
Ex:
lower(ename)
ename
------------
SMITH lower('SMITH') => smith
ALLEN lower('ALLEN') => allen
WARD lower('WARD') => ward
ORACLE4PM Page 79
Ex:
Sum(Sal)
String Functions:
lower():
• used to convert the string to lower case
Syntax:
lower(<string>)
Examples:
Output:
ramu
upper():
used to convert the string to upper case.
Syntax:
upper(<string>)
Exs:
ORACLE4PM Page 80
Exs:
upper('ramu') RAMU
upper('raj kumar') RAJ KUMAR
initcap():
used to get every word's starting letter as capital.
Syntax:
initcap(<string>)
Exs:
initcap('RAJU') Raju
initcap('RAJ KUMAR VARMA') Raj Kumar Varma
length():
• used to find length of the string
• length of the string => no of chars in string
Syntax:
length(<string>)
Exs:
length('RAMU') 4
length('RAVI TEJA') 9
concat():
• used to concatenate [combine] 2 strings
Syntax:
concat(<string1>, <string2>)
Exs:
concat('RAJ', 'KUMAR') RAJKUMAR
concat('RAJ','KUMAR','VARMA') ERROR
concat(concat('RAJ', 'KUMAR'),'VARMA') RAJKUMARVARMA
(or)
'RAJ' || 'KUMAR' || 'VARMA'
UPDATE emp
ORACLE4PM Page 81
UPDATE emp
SET ename = initcap(ename);
SELECT *
FROM emp BLAKE = blake => F
WHERE ename = 'blake';
Output:
no rows selected
(or)
SELECT *
FROM emp
WHERE upper(ename) = 'BLAKE';
(or)
SELECT *
FROM emp
WHERE length(ename)=4;
(or)
SELECT *
FROM emp
WHERE ename LIKE '____';
ename length(ename)
----------
SMITH 5
ORACLE4PM Page 82
ename length(ename)
----------
SMITH 5
WARD 4
MILLER 6
SCOTT 5
KING 4
SELECT *
FROM emp
WHERE length(ename)=14;
SELECT *
FROM emp
WHERE length(ename)>14;
ASSIGNMENT:
PLAYER
PID FNAME LNAME PNAME
1001 ROHIT SHARMA ----------
1002 VIRAT KOHLI null Rohit Sharma
null Virat Kohli
DUAL:
Calculate 10+20:
ORACLE4PM Page 83
SELECT 10+20 FROM dual;
10+20
-----------
30
DUAL:
• DUAL is a readymade table / system table / predefined table.
• DUAL table created in "SYS" schema.
• This table has one column and one row.
• column name is: DUMMY varchar2(1)
○ DESC dual;
○ SELECT * FROM dual;
Output:
D
--
X
Example:
Substr():
• It is used to get sub string from the string.
• Sub String => part of string
Syntax:
Substr(<string>, <position>[, <no_of_chars>])
Exs:
ORACLE4PM Page 84
Exs:
1 2 3 4 5 6 7 8 9
R A J K U M A R
Note:
In Substr(), 2nd argument can be given as -ve also.
+ve means, from left side position number
-ve means, from right sider position number
R A J K U M A R
-9 -8 -7 -6 -5 -4 -3 -2 -1
Generate mail ids to all emps by taking emp name's first 3 chars
and empno's last 3 chars as user id for the domain '@tcs.com':
UPDATE emp
SET mail_id = Substr(ename,1,3) || Substr(empno,-3,3) || '@tcs.com';
SELECT *
FROM emp
ORACLE4PM Page 85
FROM emp
WHERE Substr(ename,1,1)='S';
(or)
SELECT *
FROM emp
WHERE ename LIKE 'S%';
SELECT *
FROM emp
WHERE Substr(ename,-2,2)='RD';
(or)
SELECT *
FROM emp
WHERE ename LIKE '%RD';
ename
----------- WHERE ename LIKE 'A%A' OR
SMITH ename LIKE 'B%B' OR
SYMONDS ename LIKE 'C%C' OR
ALLEN .
DAVID .
26 conditions
SELECT *
FROM emp
WHERE Substr(ename,1,1) = Substr(ename,-1,1);
Assignment:
AEIOU
ORACLE4PM Page 86
WHERE ename LIKE 'A%' OR
ename LIKE 'E%' OR
ename LIKE 'I%' OR
ename LIKE 'O%' OR
ename LIKE 'U%';
(or)
Lpad():
used to fill specified char set at left side.
Syntax:
Lpad(<string>, <size> [, <char/chars>])
Rpad():
used to fill specified char set at right side.
Syntax:
Rpad(<string>, <size> [, <char/chars>])
Examples:
LPAD('RAJU',10,'*')
LPAD('RAJU',10,'*') ******RAJU
RPAD('RAJU',10,'*') RAJU******
LPAD('RAVI',12,'@') @@@@@@@@RAVI
RPAD('RAVI',12,'@') RAVI@@@@@@@@
LPAD('SAI',10,'#$') #$#$#$#SAI
ORACLE4PM Page 87
LPAD('SAI',10,'#$') #$#$#$#SAI
LPAD('A',8,'A') AAAAAAAA
LPAD('X',6,'X') XXXXXX
LPAD('*',5,'*') *****
RPAD('X',6,'X') XXXXXX
LPAD('KIRAN',10) 5spacesKITAN
RPAD('KIRAN',10) KIRAN5spaces
LTRIM():
• 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>])
Examples:
LTRIM('***RAJU***','*') RAJU***
RTRIM('***RAJU***','*') ***RAJU
LTRIM('3spacesRAJU3spaces') RAJU3spaces
ORACLE4PM Page 88
LTRIM('3spacesRAJU3spaces') RAJU3spaces
RTRIM('3spacesRAJU3spaces') 3spacesRAJU
TRIM():
it can be used to remove unwanted chars from left side or right
side or both
Syntax:
TRIM(LEADING / TRAILING / BOTH <char> FROM <string>)
gmail.com
username: ravi
password: kumar
REVERSE():
used to get reverse string
Syntax:
REVERSE(<string>)
Exs:
REVERSE('RAJU') UJAR
ASCII():
used to get ASCII value of specified char.
Syntax:
ASCII(<char>)
Exs:
ORACLE4PM Page 89
Exs:
ASCII('A') 65
ASCII('Z') 90
ASCII('a') 97
ASCII('z') 122
ASCII('0') 48
ASCII('9') 57
CHR():
It returns char of specified ASCII value
Syntax:
CHR(<ASCII_value>)
Exs:
CHR(65) A
CHR(97) a
Replace():
used to replace search string with replace string.
Syntax:
REPLACE(<string>, <serach_string>, <replace_string>)
Exs:
REPLACE('SAI KRISHNA', 'KRISHNA', 'TEJA') SAI TEJA
REPLACE('SAI TEJA SAI TEJA','SAI','RAVI') RAVI TEJA RAVI TEJA
Translate():
• used to replace search char with corresponding char in replace char set.
Syntax:
Translate(<string>, <search_char_set>, <replace_char_set>)
Exs:
Replace('HELLO WELCOME HELLO WELCOME','LO','ab') HELab WELCOME HELab WELCOME
ORACLE4PM Page 90
REPLACE('abcabcaabbccabcaa','abc','XYZ') XYZXYZaabbccXYZaa
TRANSLATE('abcabcaabbccabcaa','abc','XYZ') XYZXYZXXYYZZXYZXX
0 1 2 3 4 5 6 7 8 9
A @ # Z Y % * H G ^
SELECT ename,
TRANSLATE(sal,'0123456789','A@#ZY%*HG^') AS sal
FROM emp; => encrypt
Instr():
• It is used to check whether substring is existed in string or not.
• If sub string is existed in string, it returns position number.
• If sub string is not existed in string, it returns 0
Syntax:
Instr(<string>, <sub_string>[, <search_position>, <occurrence>])
Exs:
Instr('SAI TEJA','TEJA') 5
Instr('SAI TEJA','RAMU') 0
Instr('SAI TEJA RAVI TEJA','TEJA',1,2) 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
T H I S I S H I S W I S H
ORACLE4PM Page 91
T H I S I S H I S W I S H
T H I S I S H I S W I S H
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
SELECT *
FROM emp
WHERE Instr(ename,'AM')>0;
ename
-----------
SMITH => 0
ADAMS => 3
JAMES => 2
ALLEN => 0
AMAR => 1
SELECT *
FROM emp
WHERE Instr(ename,'_')>0;
(or)
SELECT *
FROM emp
WHERE ename LIKE '%\_%' ESCAPE '\';
(or)
ORACLE4PM Page 92
SELECT *
FROM emp
WHERE ename LIKE '%$_%' ESCAPE '$';
(or)
SELECT *
FROM emp
WHERE ename LIKE '%#_%' ESCAPE '#';
ename
------------
SAI TEJA
RAVI_TEJA
SELECT *
FROM emp
WHERE instr(ename,'%')>0;
(or)
SELECT *
FROM emp
WHERE ename LIKE '%\%%' ESCAPE '\';
Soundex():
• When we don't the exact spelling, based on sounds [pronunciation]
if we want to retrieve the records, we can use it.
Syntax:
Soundex(<string1>) = Soundex(<string2>)
Examples:
SELECT *
FROM emp
WHERE ename='BLEK';
Output:
ORACLE4PM Page 93
Output:
no rows selected
SELECT *
FROM emp
WHERE soundex(ename)=soundex('BLEK');
Output:
displays blake record
SELECT *
FROM emp
WHERE soundex(ename) = soundex('skat');
Output:
displays scott record
Conversion Functions:
number number
100 + 200
Output:
300
SELECT *
FROM emp
WHERE empno='7499'; '7499'
Output: string
displays 7499 emp record implicit conversion
number
7499
implicit conversion:
ORACLE4PM Page 94
implicit conversion:
• If conversion is done implicitly by ORACLE then it is called
"Implicit Conversion".
NOTE:
• ORACLE supports to implicit conversion.
• Don't depend on implicit conversion. It degrades the performance.
Explicit Conversion:
• If conversion is done explicitly using Built-In Function then it is
called "Explicit Conversion".
• to_Char()
• to_Date()
• to_Number()
to_Char() to_Char()
CHAR
DATE NUMBER
[STRING]
to_Date() to_Number()
• It can be used to change date formats [IND date format: DD/MM/YYYY, US date format:
MM/DD/YYYY].
• It can be used to get part of the date date, month, year, weekday, hours, minutes, seconds …etc
Syntax:
To_Char(<Date> , <Format>)
1 => sun
2 => mon
3 => tue
.
.
7 => sat
31+28+31+30+16 = 136
jan-mar => 1
apr-jun => 2
jul-sep => 3
oct-dec => 4
CC Century number to_char(sysdate,'CC') => 21
ORACLE4PM Page 96
HH12 format
to_char(sysdate,'HH') => 4
2:00 PM => 14
MI minutes part to_char(sysdate,'MI') => 58
SS seconds part to_char(sysdate,'SS') => 15
FF fractional seconds to_char(systimestamp,'FF')
AM / PM AM or PM to_char(sysdate,'AM') => PM
SELECT ename,hiredate
FROM emp
WHERE to_Char(hiredate,'YYYY') = 1982;
(or)
SELECT ename,hiredate
FROM emp
WHERE HIREDATE BETWEEN '1-jan-1982' AND '31-dec-1982';
Display the emp records who joined in 1980, 1982 and 1984:
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'MM') = 12;
(or)
SELECT ename,hiredate
FROM emp
WHERE hiredate LIKE '%DEC%';
SELECT ename,hiredate
ORACLE4PM Page 97
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'MM') IN(1,5,12);
Display the emp records who joined in 1st and 4th quarters:
D => 1
DY => SUN
DAY => SUNDAY
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'D')=1;
(or)
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'DY')='SUN';
(or)
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'DAY')='SUNDAY';
SUNDAY3spaces = SUNDAY => F
Output:
no rows selected
SUNDAY3spaces
MONDAY3spaces
TUESDAY2spaces
WEDNESDAY => 9 => max string length in all weekday names
THURSDAY1space
FRIDAY3space
SATURDAY1space
SELECT ename,hiredate
FROM emp
WHERE RTRIM(to_char(hiredate,'DAY')) = 'SUNDAY';
RTRIM('SUNDAY3spaces')
SUNDAY = SUNDAY => T
(or)
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'DAY')= 'SUNDAY ';
SUNDAY3spaces
ORACLE4PM Page 98
Display the emp records who joined in JANUARY:
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'MONTH') = 'JANUARY';
JANUARY2spaces = JANUARY => F
Output:
No rows selected
SELECT ename,hiredate
FROM emp
WHERE RTRIM(to_char(hiredate,'MONTH')) = 'JANUARY';
SELECT ename,
to_char(hiredate,'DD/MM/YYYY') as hiredate
FROM emp;
Assignment:
Syntax:
To_Char(<number> [, <format> , <nls_parameters>])
ORACLE4PM Page 99
FORMAT PURPOSE
L Currency Symbol
Default currency symbol: $
C Currency Name
Default currency name: USD
$5000.00
L9999.99
USD5,000.00
C9,999.99
NLS_Parameters:
JPY5000.00
Login as DBA:
username: system
password: nareshit
show parameters
--displays all parameters
Session altered.
Session altered.
TO_CHAR(5000,'L999
------------------
¥5000.00
TO_CHAR(5000,'C
---------------
JPY5000.00
To_Date():
• It can be used to convert string to date.
• To insert date values, we can use it.
• To get part of specific date, we can use it.
Syntax:
To_Date(<string> [, <format>])
Exs:
To_Date('25-DEC-2022') 25-DEC-22
To_Date('25 December 2022') 25-DEC-22
To_Date('25/12/2022') ERROR
To_Date('25/12/2022','DD/MM/YYYY') 25-DEC-22
to_date('DECEMBER 25 2022','MONTH DD YYYY') 25-DEC-22
Example:
CREATE TABLE t1
(
f1 DATE
);
T1 string
F1
-------- Implicit conversion
25-DEC_22 date
Note:
• Don't depend on implicit conversion. It degrades the performance.
• to insert date value, use to_date() function.
T1 string
F1
-------
to_Date()
25-DEC-22
date Explicit conversion
/
enter value for DD: 18
enter value for MM: 10
enter value for YYYY:2021
SELECT to_char(to_date('17-AUG-2022'),'YYYY')
FROM dual;
Output:
2022
15-AUG-1947
To_Number():
• It can be used to convert string to number.
• String must be numeric string.
Syntax:
To_Number(<string> [, <format>])
Exs:
To_Number('123') 123 Number
string
To_Number('ABC') ERROR
To_Number('123.45') 123.45
To_Number('$5000.00') ERROR
TO_Number('$5000.00','L9999.99') 5000
To_Number('USD5,000.00','C9,999.99') 5000
Date Functions:
sysdate
systimestamp
Add_Months()
Last_Day()
Next_Day()
Months_Between()
sysdate:
• it us used to get current system date
systimestamp:
• it is used to get system date & time
Add_Months():
• used to add months to specific date (or)
subtract months from specific date
Syntax:
Add_Months(<date>, <no_of_months>)
Examples:
sysdate: 18-MAY-23
Assignment:
ORDERS
ORDERID PID PRICE QTY AMOUNT ORDERED_DATE DELIVERY_DATE
123456 1001 10000 1 10000 sysdate sysdate+5
EMPLOYEE
EMPNO ENAME DOB DOR
1001 A 23-NOV-1998 Add_Months(DOB,12*60)
Product
Manufacturing_date Expiry_date
sysdate Add_Months(sysdate,3)
CM_LIST
STATE_CODE CM_NAME START_DATE END_DATE
TS KCR 18-JUN-2019 Add_Months(start_date,5*12)
SALES
DATEID AMOUNT Find today's sales:
1-JAN-2020 600000
Find yesterday sales:
2-JAN-2020 1200000
.. Find 1 month ago sales:
..
18-MAY-2023 900000 Find 1 year ago sales:
GOLD_RATE
find today's gold rate
DATEID PRICE [10gms]
1-JAN-2020 30000 find yesterday's gold rate
2-JAN-2020 30300
COMMIT;
SELECT ename,hiredate
FROM emp
WHERE hiredate = sysdate;
18-MAY-23 5:00PM = 18-MAY-23 5:05PM => F
Output:
No rows selected
NOTE:
TRUNC() function can be used to remove time value from
DATE TIME.
SELECT ename,hiredate
FROM emp
WHERE TRUNC(hiredate) = TRUNC(sysdate);
TRUNC(hiredate) = TRUNC(sysdate)
TRUNC(18-MAY-23 5:00PM) = TRUNC(18-MAY-23 5:09PM)
(or)
SELECT ename,hiredate
FROM emp
WHERE to_char(hiredate,'DD/MM/YYYY') = to_char(sysdate,'DD/MM/YYYY');
SELECT ename,hiredate
FROM emp
WHERE TRUNC(hiredate) = TRUNC(sysdate-1);
Display the emp records who joined 1 month ago from today's date:
SELECT ename,hiredate
FROM emp
WHERE TRUNC(hiredate) = TRUNC(Add_Months(sysdate,-1));
Display the emp records who joined 1 year ago from today's date:
SELECT ename,hiredate
FROM emp
WHERE TRUNC(hiredate) = TRUNC(Add_Months(sysdate,-12));
Last_day():
• used to get last date in the month
Syntax:
Last_day(<date>)
Examples:
Last_day(sysdate) 31-MAY-23
Last_day('20-FEB-2023') 28-FEB-23
Last_day('20-FEB-2020') 29-FEB-23
31-MAY-23+1
1-JUN-23
Next_Day():
• used to get coming date based on weekday
• Example: find next Sunday date, next Friday date
Syntax:
2nd arg:
Next_day(<date>,<weekday>)
sun
Sunday
1
Assignment:
Find current month last Sunday date
Find current month first Sunday date
Months_Between():
used to get no of months between 2 dates.
Syntax:
Months_Between(<date1>, <date2>)
Example:
Months_Between('1-JAN-2023','1-JAN-2022') 12
(or)
Calculate age:
sqrt() ceil()
power() floor()
sign() trunc()
abs() round()
mod()
sqrt():
used to find square root value
Syntax:
sqrt(<number>)
Exs:
sqrt(100) 10
sqrt(25) 5
power():
used to find power value
Syntax:
power(<number>, <power>)
Exs:
power(2,4) 16
power(5,3) 125
sign():
• can be used to check whether the given
number is +ve or -ve or zero.
• if number is +ve, it returns 1
• if number is -ve, it returns -1
• if number is 0, it returns 0
Syntax:
sign(<number>)
Exs:
sign(25) 1
sign(-25) -1
sign(0) 0
abs():
• used to get absolute value
• absolute => non-negative
Syntax:
abs(<number>)
Exs:
abs(15) 15
abs(-15) 15
ceil():
is used to get round up value
Syntax:
ceil(<number>)
floor():
is used to get round down value
Syntax:
floor(<number>)
Examples:
ceil(123.4567) 123 => 123.4567 => 124
124
floor(123.4567) 123 => 123.4567 => 124
123
Syntax:
Trunc(<number> [, <number_of_decimal_places>])
Exs:
Trunc(123.45678) 123
Trunc(123.45678,1) 123.4
Trunc(123.45678,2) 123.45
Trunc(123.45678,3) 123.456
-1 rounds in 10s
10,20,30,40,…..
-2 rounds in 100s
100,200,300,400,…..
-3 rounds in 1000s
1000, 2000, 3000, 4000,…..
-4 rounds in 10000s
10000, 20000, 30000, …..
Note:
Trunc() always gives lower value
Round():
• if value is avrg or above avrg, it returns upper value
• if value is below avrg, it returns lower value
Syntax:
Round(<number> [, <no_of_decimal_places>])
Exs:
percentage round(percentage)
67.8 67 & 68
avrg: 67.5
TRUNC(123.45678) 123
ROUND(123.45678) 123
TRUNC(123.65678) 123
ROUND(123.65678) 124
ROUND(123.45678,2) 123.46
ROUND(123.45378,2) 123.45
ROUND(567.8923782,3) 567.892
ROUND(567.8928782,3) 567.893
-1 rounds in 10s
-2 rounds in 100s
-3 rounds in 1000s
CREATE TABLE t1
NUMBER(5,2)
(
f1 NUMBER(5,2)
-999.99 TO 999.99
);
CREATE TABLE t2
(
f1 NUMBER(5,-2)
);
Mod():
used to get remainder value
Syntax:
Mod(<number>, <divisor>)
Exs:
Mod(10,7) 3
Mod(5,2) 1
Rank()
Dense_Rank()
ORACLE4PM Page 114
Dense_Rank()
Row_Number()
Rank():
• is used to apply ranks to records according to specific
column order
• If multiple values are same, it does not follow sequence
in ranking. Gaps will be there in ranking.
Syntax:
Rank() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/DESC)
Dense_Rank():
• is used to apply ranks to records according to specific
column order
• It follows sequence in ranking even if multiple values
are same. No Gaps will be there in ranking.
Syntax:
Dense_Rank() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/DESC)
SELECT ename,sal,
RANK() OVER(ORDER BY sal DESC) as RNK
FROM emp;
(or)
SELECT ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as RNK
FROM emp;
EMP
EMPNO ENAME HIREDATE rank
1001 A 25-AUG-2019 1002 B 17-DEC-2018 1
1002 B 17-DEC-2018 1001 A 25-AUG-2019 2
SELECT empno,ename,hiredate,
DENSE_RANK() OVER(ORDER BY hiredate ASC) as rnk
FROM emp;
EMP
EMPNO ENAME SAL HIREDATE 1001 A 7000 17-MAR-1982 1
1001 A 7000 17-MAR-1982 1004 D 6000 25-JAN-1983 2
1002 B 5000 23-JUL-1981 1003 C 5000 20-DEC-1980 3
1003 C 5000 20-DEC-1980 1002 B 5000 23-JUL-1981 4
1004 D 6000 25-JAN-1983
SELECT empno,ename,sal,hiredate,
DENSE_RANK() OVER(ORDER BY sal DESC, hiredate ASC) as rnk
FROM emp;
PARTITION BY clause:
It is used to apply ranks within groups.
Note:
By default ranks will be applied on entire table [all records]
To apply ranking within group, use PARTITION BY clause
Assignment:
MANAGER 6000 3
MANAGER 8000 1
MANAGER 7000 2
CLERK 4000 1
CLERK 3000 2
Row_Number():
It is used to apply row numbers to records
Syntax:
Row_Number() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/DESC)
Miscellaneous Functions:
NVL()
NVL2()
COALESCE()
GREATEST()
LEAST()
USER
UID
NVL():
• It is used to replace with other value.
Syntax:
NVL(<arg1>, <arg2>)
Exs:
NVL(100,200) 100
NVL(null,200) 200
SELECT ename,sal,comm,
sal+NVL(comm,0) as "total salary"
FROM emp;
SELECT ename,sal,
NVL(comm,'N/A') as comm
FROM emp;
Output:
ORACLE4PM Page 118
Output:
Error: Data types are mismatching
comm => number
N/A => char [string]
SELECT ename,sal,
NVL(TO_CHAR(comm),'N/A') as comm
FROM emp;
Assignment:
STUDENT
SID SNAME M1
1001 A 78
1002 B
Display nulls as AB
1003 C 66
1004 D
1005 E
1006 F 88
NVL2():
• It can be used to replace nulls and not nulls.
Syntax:
NVL2(<arg1>, <arg2>, <arg3>)
Examples:
NVL2(100,200,300) 200
NVL2(null,200,300) 300
NVL():
• NVL() can be used to replace nulls only
• It takes 2 arguments
NVL2():
• NVL2() can be used to replace nulls and not nulls
• It takes 3 arguments
UPDATE emp
USER:
it is use to get current user name
Syntax:
USER
UID:
it is used to get user id.
Syntax:
UID
Examples:
MAX():
It is used to find max value in vertical values
Syntax:
MAX(<column>)
Ex:
SAL
-----------
5000 SELECT max(sal) FROM emp;
8000 Output:
7000 8000
6000
GREATEST():
It is used to find max value in horizontal values
Syntax:
GREATEST(<value1>,<v2>,<v3>,…..<v-n>)
demo
F1 F2 F3 SELECT greatest(f1,f2,f3) FROM demo;
10 80 70
50 30 90 greatest(10,80,70) => 80
greatest(50,30,90) => 90
100 70 40
greatest(100,70,40) => 100
F1 F2 F3
10 80 70 greatest(f1,f2,f3) => 80
50 30 90
100 70 40
max(f3) => 90
GREATEST() MAX()
LEAST():
used to find minimum value in horizontal values
Syntax:
LEAST(<value1>,<v2>,…..,<v-n>)
MIN():
used to fin min value in vertical values
ORACLE4PM Page 121
used to fin min value in vertical values
Syntax:
SELECT least(f1,f2,f3) FROM demo;
MIN(<column>)
Output:
10
demo 30
F1 F2 F3 40
10 80 70
50 30 90
SELECT min(f3) FROM demo;
100 70 40
Output:
40
Coalesce():
used to get first not null value
Syntax:
Coalesce(<arg1>,<arg2>,a3,a4…..,an)
Exs:
Coalesce(null,null,null,300,500) 300
Coalesce(null,null,'XYZ','AAA') XYZ
CUSTOMER
cid cname mobile1 mobile2
1001 AA 91234 56789
1002 BB 89123 45678
sum():
used to find sum of a set of values.
Syntax:
sum(<column_name>)
Examples:
avg():
used to find average of a set of values
Syntax:
avg(<column>)
Examples:
ORACLE4PM Page 123
Examples:
Find average salary of all emps:
min():
used to find minimum value in a set of values:
Syntax:
min(<column>)
Exs:
Find min salary in all emps:
max():
used to find max value in a set of values
Syntax:
max(<column>)
Examples:
Find max salary in all emps:
count():
• used to count number of records or number of column
values
Syntax:
count(<column> / *)
Examples:
count(*) count(20)
slower faster
Built-In Function:
A function which is already defined & placed in
oracle db is called "Built-In Functions".
demo
81
23
78
51
Syntax of SELECT:
ENGLISH SQL
SENTENCES QUERIES
WORDS CLAUSES
• SELECT
• FROM
• WHERE
• ORDER BY
• DISTINCT
• GROUP BY
• HAVING
• FETCH
SELECT ename,sal
FROM emp
WHERE sal>=3000;
ORDER BY:
• used to arrange the records in ascending or descending order.
• default order is: ASC
Syntax:
ORDER BY <column> ASC/DESC [, <column> ASC/DESC, ….]
NUMBER CHAR
Date
1-JAN-22 31-DEC-23
2-JAN-22 30-DEC-23
. .
. .
31-DEC-22 1-JAN-23
1-JAN-23 31-DEC-22
. .
. .
31-DEC-23 1-JAN-22
SELECT ename,sal
FROM emp
ORDER BY ename ASC;
(or)
SELECT ename,sal
FROM emp
ORDER BY ename;
(or)
SELECT ename,sal
FROM emp
ORDER BY 1 ASC;
1 ename
2 sal
SELECT ename,sal
FROM emp
ORDER By sal DESC;
(or)
SELECT ename,sal
SELECT ename,hiredate
FROM emp
ORDER BY hiredate ASC;
27-DEC-2019
17-SEP-2017
17-SEP-2017
25-AUG-2022
27-DEC-2019
25-AUG-2022
SELECT ename,deptno,sal
FROM emp
ORDER BY deptno ASC;
SELECT empno,ename,deptno,sal
FROM emp
ORDER BY deptno ASC, sal DESC;
20 10
10 20
10 6000 10 9000
10 9000 10 6000
SELECT empno,ename,deptno,sal
FROM emp
ORDER BY deptno ASC, sal DESC, empno ASC;
20 10
10 20
10 6000 10 9000
10 9000 10 6000
SELECT empno,ename,deptno,hiredate
FROM emp
ORDER BY deptno ASC, hiredate ASC;
Note:
if a column has null values,
in ascending order, nulls will be displayed last
in descending order, nulls will be displayed first
SELECT ename,sal
FROM emp
ORDER BY sal DESC nulls last;
SELECT ename,sal,hiredate
FROM emp
ORDER BY hiredate ASC nulls first;
GROUP BY:
• used to group the records according to specific
column or columns.
• We can apply aggregate (group) functions on group of
records.
• It can be used for data analysis.
• It gives summarized data from detailed data.
Example:
GROUP BY deptno
EMP => detailed data
EMPNO ENAME DEPTNO SAL summarized data
deptno sum_of_sal
10 ?
20 ?
30 ?
deptno no_of_emps
10 ?
20 ?
30 ?
JOB SUM_OF_SAL
CLERK ?
GROUP BY job
MANAGER ? sum(Sal)
ANALYST ?
YEAR NO_OF_EMPS
1980 ?
1981 ?
1982 ?
1983 ?
QUARTER NO_OF_EMPS
1 ?
2 ?
3 ?
4 ?
HAVING:
• HAVING clause is used to write condition on groups.
• It filters the groups.
• It must be followed by GROUP BY.
• It cannot be used without GROUP BY.
HAVING clause condition will be applied on result of
ORACLE4PM Page 135
• HAVING clause condition will be applied on result of
GROUP BY.
• Aggregate functions can be used in HAVING clause.
SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno
HAVING sum(sal)>10000
ORDER BY deptno;
Assignment:
Display the job titles which are having more than 3 emps:
GROUP BY job
GROUP BY job
HAVING sum(sal)<10000
10 MANAGER
10 10 group MANAGER MANAGER group
10 MANAGER
20 CLERK
20 20 group CLERK CLERK group
20 CLERK
10 MANAGER group
10 MANAGER
20 ANALYST
20 ANALYST 20 ANALYST group
30 SALESMAN
30 SALESMAN 30 SALESMAN group
30 SALESMAN
30 SALESMAN 30 SALESMAN group
30 SALESMAN
Assignment:
… .. 2 ?
.. .. 3 ?
24-MAY-2023 4 ?
2021 1 ?
2 ?
3 ?
4 ?
Rollup():
used to calculate sub totals & grand total according to first
Syntax:
GROUP BY Rollup(<grouping_column_list>)
Ex:
GROUP BY Rollup(deptno,job)
Cube():
Cube():
• used to calculate sub totals & grand total according to all
columns specified in CUBE() function.
Syntax:
GROUP BY Cube(<grouping_column_list>)
Ex:
GROUP BY Cube(deptno,job)
Assignment:
SALES
DATE_ID AMOUNT
1-JAN-2020 1600000
2-JAN-2020 1000000
… ..
.. ..
24-MAY-2023 ..
ASSIGNMENT:
PERSON
PID PNAME STATE_CODE GENDER AADHAR
DISTINCT clause:
• used to avoid duplicate rows.
• It avoids duplicates. It means, it gives distinct values.
Examples:
job
---------- SELECT DISTINCT job FROM emp;
CLERK
SALESMAN job
SALESMAN -------
MANAGER CLERK
CLERK SALESMAN
MANAGER MANAGER
ANALYST ANALYST
ANALYST
MANAGER
deptno job
FETCH clause:
• it was introduced in ORACLE 12c version
• used to get top n records.
Syntax:
[OFFSET <n> row/rows] [FETCH FIRST/NEXT <n> row/rows only]
n => no of rows
SELECT ename,hiredate
FROM emp
ORDER BY hiredate ASC
FETCH FIRST 3 ROWS ONLY;
Ex:
GROUP BY deptno
HAVING sum(sal)>10000
GOAL:
JOINS concept is used to retrieve the data
from multiple tables.
COLLEGE DATABASE
STUDENT
MARKS
FEE
STAFF
.
.
STUDENT MARKS
SID SNAME SCITY SID Maths Phy Che
1001 A HYD 1001 60 80 70
1002 B MUMBAI 1002 56 45 82
1003 C DELHI 1003 55 77 66
JOINS
JOINS:
• JOIN => connect / combine
Types of Joins:
Equi Join:
matched records
Emp e Dept d
empno ename sal deptno Deptno Dname Loc
1001 A 20 10 Accounting DALLAS
1002 B 30 20 Research CHICAGO
1003 C 10 30 SALES BOSTON
1004 D 10 40 OPERATIONS NEW YORK
1005 E 20
1006 F 30
unmatched record from dept
1007 G
1008 H
In above example,
e is table alias. it is alias name of emp table
d is table alias. it is alias name of dept table
Note:
Table alias makes table name short
ANSI standards
SQL
• In ANSI STYLE,
to separate 2 table names we use keyword
we write Join condition in ON clause / USING clause
ORACLE STYLE:
ANSI STYLE:
(or)
NOTE:
For USING clause, common column name must be same in 2 tables.
Otherwise, we cannot use USING clause.
oracle rewrites as
USING(deptno) ON e.deptno=d.deptno
ORACLE STYLE:
Emp
Dept
empno ename sal deptno
Deptno Dname Loc
1001 A 20
10 Accounting DALLAS
ANSI STYLE:
Assignment:
Display BLAKE and ALLEN records along with dept details
Note:
Inner Join = matched records only
Inner Join can give matched records only
Outer Join:
• Outer Join = matched +unmatched records
Note:
In ORACLE STYLE, Join Condition decides left table & right table
Exs:
Exs:
FROM emp e JOIN dept d
emp e Left table
dept d Right Table
COMMIT;
ORACLE STYLE:
ANSI STYLE:
• Right outer Join can give matched records and unmatched records
from right side table.
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 = matched + unmatched from left + unmatched from right table
• Full Outer Join can give matched records, unmatched records from left table
and unmatched records from right table.
• In ORACLE STYLE, apply UNION OPERATOR between Left Outer Join and
A = {1,2,3,4,5}
Right Outer Join
B = {4,5,6,7,8}
ORACLE STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno(+)
UNION
ANSI STYLE:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL OUTER JOIN dept d
ON e.deptno = d.deptno;
Example:
Display the emp records to whom dept is not assigned:
[unmatched records only from emp]
ORACLE STYLE:
ANSI STYLE:
ORACLE 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:
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;
Equi Join
Outer Join
Left Outer
Right outer
Full Outer
Self Join
Cross Join
Exs:
WHERE e.deptno = d.deptno
WHERE s.sid = m.sid
Non-Equi Join:
Exs:
WHERE e.deptno > d.deptno
WHERE e.deptno < d.deptno
WHERE e.deptno >= d.deptno
ORACLE STYLE:
ANSI STYLE:
Self Join:
• If a table is joined to itself then it is called "Self Join /
Recursive Join".
• IN this, one record in a table will be joined with another
record in same table.
• In this, physically one table is there. logically take it as 2
tables and join them based on some condition
e.mgr = m.empno
EMP e EMP m
EMPNO ENAME JOB SAL MGR EMPNO ENAME JOB SAL MGR
ORACLE STYLE:
ANSI STYLE:
Display the emp records who are earning more than their
manager:
ORACLE STYLE:
ANSI STYLE:
Example:
TEAMS
CID CNAME Display the output as following:
10 IND
IND VS AUS
20 AUS
IND VS WIN
30 WIN
AUS VS WIN
TEAMS x TEAMS y
CID CNAME CID CNAME
10 IND 10 IND
20 AUS 20 AUS
30 WIN 30 WIN
ORACLE STYLE:
ANSI STYLE:
1
A = {1,2,3} 4
2
B = {4,5} 5
3
AXB = ?
{ (1,4)(1,5)
3 X 2 = 6 pairs
(2,4)(2,5)
(3,4)(3,5) }
Example:
EMP e DEPT d
EMPNO ENAME DEPTNO DNAME
1001 A 10 ACCOUNTS
1002 B 20 RESEARCH
1003 C 30 SALES
ORACLE STYLE:
ANSI STYLE:
GROUPA a GROUPB b
cid cname cid cname
10 IND 40 ENG
20 AUS 50 NZ
30 WIN 60 BAN
ORACLE STYLE:
Output:
IND VS ENG
SELECT a.cname || ' VS ' || b.cname
IND VS NZ
FROM groupa a, groupb b;
IND VS BAN
ANSI STYLE:
AUS VS ENG
AUS VS NZ
SELECT a.cname || ' VS ' || b.cname
AUS VS BAN
FROM groupa a CROSS JOIN groupb b;
WIN VS ENG
WIN VS NZ
WIN VS BAN
JOINS:
• used to retrieve the data from multiple tables
Types of Joins:
Cross Join => each record in one table will be joined with every record in another
dname sum(Sal)
Accounting ?
Research ?
Sales ?
LOC no_of_emps
NEW YORK ?
CHICAGO ?
DALLAS ?
ORACLE STYLE:
ANSI STYLE:
e.deptno = d.deptno
Emp Dept
empno ename sal deptno Deptno Dname Loc
1001 A 20 10 Accounting DALLAS
1002 B 30 20 Research CHICAGO
1003 C 10 30 SALES BOSTON
1004 D 10 40 OPERATIONS NEW YORK
1005 E 20
1006 F 30
1007 G
1008 H
Example-1:
PROJECTS
EMPLOYEE
PROJECT_ID PNAME DURATION
EMPNO ENAME PROJECT_ID
10 X 6
1001 A 10
20 Y 12
1002 B 40
30 Z 8
1003 C
40 W 15
1004 D 20
50 N 10
1005 E 10
1006 F 40
1007 G
1008 H 20 duration in months
1009 I
Display emp records with project details. Also display the emps who are on bench. Bench means,
not assigned to project. [Left Outer Join]
Display emp records with project details. Also display the projects which are not assigned to any
employee.
Display emp records with project details. Also display the emps who are on bench. Also display the
projects which are not assigned to any employee.
Display the emp records who are on bench. [Left Outer Join + Condition]
Display the projects which are not assigned to any employee. [Right Outer Join + Condn]
Display the emp records who are on bench. Also display the projects which are not assigned to any
employee. [Full Outer Join + Condns]
Example-2:
STUDENT COURSE
SID SNAME CID CID CNAME
1 A 20 10 MCA
2 B 30 20 MBA
3 C 10 30 MSC
4 D 10 40 MA
5 E 30
6 F
7 G
• Display student details with course details. Also display the students who are not
joined in any course.
• Display the student details with course details. Also display the courses in which
students are not joined.
• Display the student details with course details. Also display the students who are
not joined in any course. Also display the courses in which students are not joined.
• Display the students who are not joined in any course. Display the courses in which
students are not joined.
Example-3:
CUSTOMER
PRODUCTS
ORDERS
Display the customer details, product details and order details as following:
OID, PID, PNAME, QTY, PRICE, AMOUNT, CNAME, STREET, CITY, STATE, MOBILE
Example:
Display the emp records who are earning more than BLAKE:
SELECT ename,sal
FROM emp
WHERE sal>(find BLAKE sal);
SELECT ename,sal
FROM emp
WHERE sal>(SELECT sal FROM emp WHERE ename='BLAKE');
Syntax:
SELECT <column_list>
FROM <table_name>
WHERE <column> <operator> (<SELECT query>);
5 Types:
• A sub query which returns one value is called "Single Row Sub
Query".
• For this, we use operators such as: > < >= <= = !=
SELECT ename,job,sal
FROM emp
WHERE job=(Find BLAKE'S JOB title);
SELECT ename,job,sal
FROM emp
WHERE job=(SELECT job FROM emp WHERE ename='BLAKE');
SELECT max(sal)
FROM emp
WHERE sal<(Find max sal);
SELECT max(sal)
FROM emp
WHERE sal<(SELECT max(sal) FROM emp);
sal
------ SELECT max(sal)
4000 FROM emp
6000 WHERE sal<6000;
5000
7000
3000 4000 max sal => 5000
5000 3rd max salary
3000
SELECT max(sal)
FROM emp
WHERE sal<(Find 2nd max sal);
SELECT max(sal)
FROM emp
WHERE sal<(SELECT max(sal) FROM emp
WHERE sal<(SELECT max(Sal) FROM emp));
SELECT ename
FROM emp
WHERE sal=(Find max sal);
SELECT ename,hiredate
FROM emp
WHERE hiredate<(find BLAKE's hiredate);
SELECT ename,hiredate
FROM emp
WHERE hiredate<(SELECT hiredate FROM emp
WHERE ename='BLAKE');
Find the dept name which is spending max amount on their emps:
3oth dept is spending max amount. But we don't know deptno. find it
SELECT deptno
FROM emp
GROUP BY deptno
HAVING count(*) = (find max no of emps in all depts);
SELECT deptno
FROM emp
GROUP BY deptno
HAVING count(*) = (SELECT max(count(*)) FROM emp
GROUP BY deptno);
UPDATE emp
SET sal=(find 10th dept max sal)
WHERE empno=7934;
UPDATE emp
SET sal=(SELECT max(sal) FROM emp WHERE deptno=10)
WHERE empno=7934;
Examples:
BLAKE MANAGER
SMITH CLERK
SELECT ename,job,sal
FROM emp
WHERE job IN(Find BLAKE and SMITH job titles);
SELECT ename,job,sal
FROM emp
7934 MILLER 10
7900 JAMES 30
ALL:
Syntax:
<column> <relational_operator> ALL(<value_list>)
Example:
SELECT ename,sal
FROM emp
WHERE sal>2000 AND sal>3000;
sal
--------
6000
2500
1800
4000
Display the emp records whose salary is less than 2000 and
3000:
SELECT ename,sal
FROM emp
WHERE sal<2000 AND sal<3000;
SELECT ename,job,sal
ORACLE4PM Page 175
SELECT ename,job,sal
FROM emp
WHERE sal>ALL(find all managers sals);
SELECT ename,job,sal
FROM emp
WHERE sal>ALL(SELECT sal FROM emp
WHERE job='MANAGER');
SELECT ename,job,sal
FROM emp
WHERE sal<ALL(SELECT sal FROM emp
WHERE job='MANAGER');
ANY:
Syntax:
<column> <relational_operator> ANY(<value_list>)
Examples:
SELECT ename,sal
FROM emp
WHERE sal>2000 OR sal>3000;
(or)
SELECT ename,sal
FROM emp
WHERE sal>ANY(2000,3000);
sal
-------
OR AND
ANY ALL
5000 => T T
1500 => F F
2500 => T F
4000 => T T
SELECT ename,sal
FROM emp
WHERE sal=2000 OR sal=3000 OR sal=4000;
SELECT ename,sal
FROM emp
WHERE sal>ANY(find all managers sals);
SELECT ename,sal
FROM emp
WHERE sal>ANY(SELECT sal FROM emp
WHERE job='MANAGER');
SELECT max(sal)
FROM emp
WHERE sal<(SELECT max(Sal) FROM emp);
1 2 passes value 3
OUTER INNER
4 passes value
These 5 steps will be executed for every row selected by outer query.
If outer query selects 5 rows, inner query gets executed for 5 times.
Steps:
1. First outer query gets executed. It selects a row.
ORACLE4PM Page 178
1. First outer query gets executed. It selects a row.
2. Outer query passes value to inner query.
3. Inner query gets executed.
4. Inner query passes value to Outer query.
5. Outer query condition will be tested. If condition is TRUE,
it selects the row. Otherwise, row will not be selected.
Display the emp records who are earning more than their
dept's avrg salary:
EMP
EMPNO ENAME DEPTNO SAL deptno avg_sal
1001 A 10 15000 10 20000
1002 B 10 25000 20 7500
1003 C 20 10000
1004 D 20 5000
Assignment:
Display most senior record in each dept:
EXISTS:
SYNTAX:
EXISTS(<SELECT query>)
SELECT d.dname
FROM dept d
WHERE EXISTS(SELECT * FROM emp
WHERE deptno=d.deptno);
DEPT d EMP
DEPTNO DNAME LOC EMPNO ENAME DEPTNO
10 ACCOUNTING 1001 A 10
20 RESEARCH 1002 B 10
30 SALES 1003 C 20
40 OPERATIONS 1004 D 20
1005 E 30
DNAME
ACCOUNTING
RESEARCH
SALES
If rows are not selected by sub query, NOT EXISTS returns TRUE
If rows are selected by sub query, NOT EXISTS returns FALSE
SELECT d.dname
FROM dept d
WHERE NOT EXISTS(SELECT * FROM emp
WHERE deptno=d.deptno);
DEPT d EMP
DEPTNO DNAME LOC EMPNO ENAME DEPTNO
10 ACCOUNTING 1001 A 10
20 RESEARCH 1002 B 10
30 SALES 1003 C 20
40 OPERATIONS 1004 D 20
SELECT sal
DENSE_RANK() OVER(ORDER BY sal DESC) as rnk
FROM emp
WHERE rnk=3;
SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal DESC) as rnk
FROM emp)
WHERE rnk=3;
SELECT *
SELECT *
* All columns of sub query FROM emp
empno, ename, sal, rnk
SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk=5;
SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk=10;
SELECT sal
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk=&n;
SELECT *
FROM (SELECT empno,ename,sal,
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk<=5;
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER(ORDER BY sal
DESC) as rnk
FROM emp)
WHERE rnk<=&n;
ROWNUM:
• ROWNUM is a pseudo column.
• It is used to apply row numbers.
• Row Number will be applied on result of SELECT QUERY.
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn=3;
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn IN(1,9,12);
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn BETWEEN 5 AND 10;
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE MOD(rn,2)=0;
Mod(2,2) =0
0=0 T
Mod(3,2) = 0
1=0 F
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE MOD(rn,2)=1;
Examples:
Output:
EMP DEPT
-------- --------
14 4
Types:
ROWID:
• ROWID is a pseudo column.
ROWID returns row address.
Example:
STUDENT
sid sname m1
1 A 70
2 B 70
1 A 70
SELECT f1, f2
FROM t1
GROUP BY f1,f2
HAVING count(*)>=2;
T1
F1 F2 rowid
1 A AAA <> AAA F => will not be deleted
2 B AAB <> AAB F => will not be deleted
3 C AAC <> AAC F => will not be deleted
AAD <> AAA => T => row will be deleted
1 A AAD
AAE <> AAB => T => row will be deleted
2 B AAE
3 C AAF AAF <> AAC => T => row will be deleted
ORACLE4PM Page 189
AAD <> AAA => T => row will be deleted
1 A AAD
AAE <> AAB => T => row will be deleted
2 B AAE
3 C AAF AAF <> AAC => T => row will be deleted
4 D AAG AAG <> AAG F => will not be deleted
1 A AAH AAH <> AAA T => will be deleted
DELETE FROM t1 t
WHERE rowid <> (SELECT min(rowid)
FROM t1 WHERE f1=t.f1 and f2=t.f2);
Field Definition:
CONSTRAINTS in SQL:
Max Marks: 100
• CONSTRAINT => Restrict / Limit / Control 0 TO 100
STUDENT
check(m1>=0 AND m1<=100)
SID SNAME M1
1 A 78
2 B 56
3 C 82
4 D 567 ERROR: check constraint violated
• Primary Key
• Not Null
• Unique
• Check
• Default
• References [Foreign Key]
Primary Key:
• Primary Key does not accept duplicates.
• Primary Key does not accept nulls.
EMP
PK
EMPNO ENAME JOB SAL
1001 RAVI CLERK 6000
1002 SAI CLERK 7000
1003 RAVI SALESMAN 6000
1004 SAI SALESMAN 7000 Null
KIRAN MANAGER 10000 ERROR: PK does not accept null
1001 SRAVAN CLERK 5000
Duplicate
Error: PK does not accept duplicate
Example:
CREATE TABLE t1
(
f1 NUMBER(4) PRIMARY KEY
ORACLE4PM Page 192
f1 NUMBER(4) PRIMARY KEY
);
NOT NULL:
Example:
EMP
NOT NULL
EMPNO ENAME SAL
1001 RAJU 5000 NULL
1002 8000 ERROR: cannot insert null
1003 RAJU 7000
DUPLICATE
Accepts duplicate value
Example:
CREATE TABLE t2
(
f1 NUMBER(4) NOT NULL
);
Unique:
Example:
CUSTOMER
UNIQUE
cid cname mail_id
1001 AA [email protected] NULL
1002 BB accepts null
1003 AA [email protected]
DUPLICATE
ERROR
Example:
CREATE TABLE t3
(
f1 NUMBER(4) UNIQUE
);
Check:
sal CHECK(sal>=10000)
---------
5000 => ERROR
4000 => ERROR
9000 => ERROR
15000
20000
25000
7000 => ERROR
Example:
CREATE TABLE t4
(
f1 NUMBER(3) CHECK(f1 BETWEEN 0 AND 100)
);
DEFAULT:
Example:
CREATE TABLE t5
(
f1 NUMBER(4),
f2 NUMBER(5) DEFAULT 20000
);
REFERENCES DEPT(DEPTNO)
REFERENCES [FOREIGN KEY]:
Child Table / Detailed Table
Parent Table / Master table
EMP Foreign Key
DEPT
EMPNO ENAME DEPTNO
PK
1001 A 30
DEPTNO DNAME
1002 B 10
10 HR
1003 C 30
20 SALES
1004 D 10
30 ACCOUNTS
1005 E 90 ERROR
1006 F 20
1007 G null
accepts null
Example:
CREATE TABLE t7
(
f1 NUMBER(4) REFERENCES T6(F1)
);
Examples on Constraints:
STUDENT1
SID SNAME M1
Example-2:
USER_LIST
userid uname pwd
Example-3:
EMPLOYEE
EMPNO ENAME GENDER SAL HIREDATE CNAME CCITY
Example:
CUSTOMER
cid cname mobilenum mailid
Example:
DEPT1 EMP1 FK
PK EMPNO ENAME DEPTNO
DEPTNO DNAME 1001 A 30
10 ACCOUNTS 1002 B 10
20 SALES 1003 C 30
30 HR 1004 D 20
1005 E 70 =>ERROR
Naming Constraints:
• When we want to drop the constraints or enable the constraints or disable the
constraints these names are useful.
NOTE:
Constraint name must be unique with in the SCHEMA [user]
user_tables:
it maintains all tables information
user_constraints:
• it is a built-in table
• it maintains all constraints information.
DESC user_constraints;
STUDENT
sid sname mail_id m1
COURSE STUDENT FK
ORACLE4PM Page 206
REFERENCES course(cid)
COURSE STUDENT FK
PK sid sname cid
cid cname 1001 A 30
10 JAVA 1002 B 10
20 PYTHON 1003 C 10
30 C# 1004 D 30
1005 E 20
1006 F 80 => ERROR
COURSE
PK
cid cname
STUDENT FK
sid sname cid
CM_LIST
CMID CM_NAME STATE_CODE START_DATE END_DATE
1001 KCR TS 18-MAY-2018 27-DEC-2015 => ERROR
NOTE:
If we want to use another column name in constraint
we must apply it at table level only. It cannot be applied
at column level.
Example:
STUDENT
ERROR:
PK does not accept null
ALTERING TABLE:
Adding Constraints:
• Using ADD CONSTRAINT we can add 4 constraints only. Those are: PK,
UNIQUE, CHECK, FK
Example:
STUDENT
sid sname mail_id fee m1
Example:
DEPT EMP
DEPTNO DNAME EMPNO ENAME DEPTNO
Renaming Constraint:
In student
sid => constraint name is con1 => rename it as "z"
PK FK
F1 F1
10 10
20 10
20
20
parent table:
child table:
ON DELETE clause:
Syntax:
ON DELETE cascade:
parent table:
child table:
CREATE TABLE t2
(
f1 NUMBER(2) REFERENCES t1(f1) ON DELETE CASCADE
);
parent table:
child table:
CREATE TABLE t2
(
f1 NUMBER(2) REFERENCES t1(f1) ON DELETE SET NULL
);
ON DELETE CASCADE
CUSTOMER TRANSACTIONS
cid[PK] cname ac_type ac_opened CID[FK] TID T_TYPE AMOUNT DOT
_date 1001 .. W 10000 ..
1001 A S -- 1001 .. D 30000 ..
1001 .. D 50000 ..
1001 .. W 20000 .
PROJECT EMP
FK
PK
PROJID PNAME DURATION EMPNO ENAME PROJID
10 X 8 1001 A 20 NULL
20 Y 12 1002 B 20 NULL
30 Z 10 1003 C 30
1004 D 30
1006 E 10
1007 F 10
SQL:
TRUNCATE
RENAME
DCL:
• Data Control Language
• It deals with data accessibility.
• It is used to implement table level security
Security:
Syntax:
privilege = permission
GRANT <privileges_list>
ON <db_object_name>
TO <user_list>;
Ex:
GRANT select
ON emp
TO c##batch11am;
GRANT all
ON emp
TO c##batch6pm;
GRANT select
ON emp
TO c##batch9am, c##batch2pm;
GRANT select
ON emp
TO public;
REVOKE:
ORACLE4PM Page 219
REVOKE:
• used to can cancel the permissions on
DB Objects from users.
Syntax:
REVOKE <priviliges_list>
ON <db_obj_name>
FROM <user_list>;
Examples:
REVOKE all
ON emp
FROM c##batch11am;
creating userA:
[Log in as DBA]
CREATE USER c##userA
IDENTIFIED BY usera
DEFAULT TABLESPACE users
QUOTA unlimited ON users;
creating userB:
T1
F1 F2
1 A
2 B
CREATE TABLE t1
(
f1 NUMBER(4),
f2 VARCHAR2(10)
);
GRANT select
ON t1
ORACLE4PM Page 221
GRANT select
ON t1
TO c##userB;
UPDATE c##userA.t1
SET f2='SAI' WHERE f1=1;
ERROR: insufficient privileges
UPDATE c##userA.t1
SET f2='SAI' WHERE f1=1;
Output: 1 row updated
COMMIT;
F1 F2
2 B
3 C
GRANT all
ON t1
TO c##userB
WITH GRANT OPTION;
REVOKE all
ON t1
FROM c##userB;
select * from c##userA.t1;
ERROR:
USER_TAB_PRIVS_MADE:
• is a system table
• It maintains list of privileges made by the GRANTOR.
Log in as c##userA:
DESC user_tab_privs_made;
Log in as c##userB:
DESC user_tab_privs_recd;
Copying Table:
• Copying table means, creating table from existing table
Syntax:
Examples:
create a new table with the name employee1 from existing table
emp with all rows and all columns:
[create exact copy of emp]
1=2
'A'='B'
100=500
Syntax:
INSERT INTO <table_name>
<SELECT query>;
Example:
EMP EMPLOYEE4
EMPNO ENAME JOB SAL .. EMPNO ENAME JOB SAL
1001 A MANAGER .. ..
copy manager records
1002 B CLERK .. ..
1003 C SALESMAN .. ..
1004 D MANAGER .. ..
INSERT ALL:
• Introduced in ORACLE 9i version.
• used to copy one table data to multiple tables.
• It avoids of writing multiple INSERT commands.
EMP1
EMP
EMPNO ENAME SAL
EMPNO ENAME SAL copy 10 rows
1001 A ..
1002 B .. EMP2
.. .. ..
copy 10 rowsEMPNO ENAME SAL
.. .. ..
1010 .. ..
EMP3
EMPNO ENAME SAL
copy 10 rows
INSERT ALL
Syntax:
INSERT ALL
INTO <table_name>[(column_list>)] VALUES(<value_list>)
ORACLE4PM Page 229
INSERT ALL
INTO <table_name>[(column_list>)] VALUES(<value_list>)
INTO <table_name>[(column_list>)] VALUES(<value_list>)
INTO <table_name>[(column_list>)] VALUES(<value_list>)
.
.
<SELECT QUERY>;
EMP EMP1
EMPNO ENAME SAL EMPNO ENAME SAL
1001 A .. copy emp table all records
1002 B ..
EMP2
.. .. ..
EMPNO ENAME SAL
.. .. ..
copy emp table all records
1010 .. ..
EMP3
EMPNO ENAME SAL
copy emp table all records
INSERT ALL
INTO emp1 VALUES(empno,ename,sal)
INTO emp2 VALUES(empno,ename,sal)
INTO emp3 VALUES(empno,ename,sal)
SELECT empno,ename,sal FROM emp;
Output:
42 rows created
Note:
SELECT query result will be copied into emp1, emp2 and emp3
Syntax:
INSERT ALL
WHEN <condition-1> THEN
INTO <table_name>[(column_list>)] VALUES(<value_list>)
WHEN <condition-2> THEN
INTO <table_name>[(column_list>)] VALUES(<value_list>)
.
.
[ELSE]
INTO <table_name>[(column_list>)] VALUES(<value_list>)
<SELECT QUERY>;
INSERT FIRST
WHEN <condition-1> THEN
INTO <table_name>[(column_list>)] VALUES(<value_list>)
WHEN <condition-2> THEN
INTO <table_name>[(column_list>)] VALUES(<value_list>)
.
.
[ELSE]
INTO <table_name>[(column_list>)] VALUES(<value_list>)
<SELECT QUERY>;
INSERT FIRST
WHEN job='MANAGER' THEN
INTO emp_mgr VALUES(empno,ename,job,sal)
WHEN job='CLERK' THEN
INTO emp_clerk VALUES(empno,ename,job,sal)
ELSE
INTO emp_others VALUES(empno,ename,job,sal)
SELECT * FROM emp;
Output:
14 rows created.
Assignment:
dept10
EMP
EMPNO ENAME DEPTNo
EMPNO ENAME DEPTNo copy 10th dept records
1001 A 10
1002 B 10 dept20
1003 C 20 copy 20
EMPNO ENAME DEPTNo
1004 D 20
1005 E 30
dept_others
1006 F 40 copy
EMPNO ENAME DEPTNo
other
than
ORACLE4PM Page 234
dept_others
1006 F 40 copy
EMPNO ENAME DEPTNo
other
than
10,20
Assignment-2
to_char(hiredate, 'YYYY')
EMP1980
EMP
copy 1980 emp records
1980
EMP1981
1981
copy 1981 emp records
1982
1983
EMP_OTHERS
copy other than 1980, 1981
MERGE:
• Introduced in Oracle 9i version.
• It is used to apply one table changes to its replica [duplicate copy].
• It avoids of writing a separate PL/SQL program.
• MERGE = UPDATE + INSERT
• MERGE is a combination of UPDATE and INSERT commands.
• It can be also called as "UPSERT" command.
Syntax:
1 A HYD
2 B MUMBAI
3 C PUNE
4 D CHENNAI
5 E KOLKATA
Output:
5 rows merged
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
SET OPERATORS:
Syntax:
SELECT query
<SET OPERATOR>
SELECT query;
UNION:
• UNION gives result of 2 select queries without
duplicate records.
UNION ALL:
• UNION gives result of 2 select queries including
duplicate records.
INTERSECT:
• INTERSECT gives common records from the result of
2 select queries.
MINUS:
• It gives specific records of 1st SELECT query.
Example:
HomeLoan GoldLoan
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5002 F
cid cname
1001 A
1002 B
cid cname
1001 A
1002 B
1003 C
5001 D
1002 B
5002 F
• Slower • Faster
cid cname
1002 B
cid cname
1001 A
1003 C
cid cname
5001 D
5002 F
10 20
-------- --------
CLERK CLERK
MANAGER MANAGER
PRESIDENT ANALYST
DEPT
EMP_IND
DEPTNO DNAME
EMPNO ENAME Sal DEPTNO
10 HR
1001 A 8000 20
20 SALES
1002 B 10000 10
30 ACCOUNTS
..
..
EMP_US
EMPNO ENAME Sal DEPTNO
5001 XYZ 5000 20
5002 ABC 4000 10
Assignment:
Display the employees details along with dept details who
are working for INDIA & US:
Rules:
Example:
SELECT cid FROM HomeLoan
UNION
SELECT cid,cname FROM GoldLoan;
ERROR
Example:
SELECT cid,cname FROM homeLoan
UNION
SELECT cname,cid FROM GoldLoan;
ERROR
Tables
VIEWS
INDEXES
SEQUENCES
SYNONYMS
MATERIALIZED VIEWS
ORACLE
SQL DATABASE
PL/SQL TABLES
ROWS & COLUMNS
SQL:
• Non-Procedural Language.
• We will not any set of statements [programs]
• We write Queries
• Query => is a request that is sent to DB SERVER
command, purpose
5 Sub Languages:
syntax, example
TRUNCATE
RENAME
Built-In Functions:
ORACLE4PM Page 246
Built-In Functions:
Clauses:
Execution Order:
GROUP BY deptno
FROM
WHERE 10
GROUP BY 10 10 group
HAVING 10
SELECT
DISTINCT
ORDER BY
ORACLE4PM Page 247
ORDER BY
FETCH
Joins:
Self Join
Cross Join
Sub Queries:
A query written in another
Types:
Constraints:
PK
Not Null
Unique
Check
Default
References [Foreign Key]
SET operators:
UNION
UNION ALL
INTERSECT
MINUS