Professional Documents
Culture Documents
Sandeep Sir:
Whatsapp:
Notes Link:
799 799 7809
https://bit.ly/oracle7am
send fee receipt, batch details
&gmail id
Data
Information
Database
DBMS
RDBMS
Metadata
Data:
People Places
Things
1234 nareshit
smartphone
Ravi 3 floors samsung
Oracle 8 classrooms
A71
567 200 30000
78.9 Black
manager 56.4
8000
Data Information
Tyre
Bike
Engine connecting
handle
break
Information:
• If data is arranged in meaningful form then it is
called "Information".
• It is processed one.
• It is in meaningful form.
Types of data:
Letters audios
Digits videos
Special Symbols images
animations
Ex: documents
25
Ravi
H.NO. 1-2-123/A
Database:
College DB
Student field
Marks
sid M1 M2 M3 Total
1001 60 80 70 …
Fee
sid total fee paid fee balance
1001 15000 10000 5000
Online Shopping DB
Products
pid pname price qty
Customers
cid cname ccity
Orders
oid pid ord_date qty del_date cid
DBMS:
• DataBase Management Software.
• It is a software that is used to create & maintain the
database.
• This software allows us to store, manipulate &
retrieve the data of Database.
• Manipulate => add [insert], delete & modify [update]
• retrieve => opening existing data
RDBMS:
• RDBMS => Relational DataBase Management Software.
• Relation => Table
• In RDBMS, we create & maintain the database in the
form of tables.
column / field /
attribute / property
RDBMS Exs:
ORACLE SQL SERVER My SQL DB2 Postgre SQL
ORACLE 21c
-----------------------
duration: 3 months 7.00 AM to 8.30 AM
SQL
PL/SQL
SQL
PL/SQL
------------
----------------
5 sub languages
Introduction
DDL
Control Structures
DML
Cursors
DRL
Exception Handling
DCL
Procedures
TCL
Functions
Built-In Functions
Packages
Clauses in SQL
Triggers
SET Operators
Working with LOBs
Joins
Dynamic SQL
Sub Queries
Collections
VIEWS
INDEXES
Materialized Views
Sequences
Metadata:
• is Data about the data.
• It describes about the data
Customers
Ex:
Table Name => Customers
Column Name => cid, cname, ccity
Data Type => Number(4), Varchar2(20)
Field size => Number(4) => 4 => field size
ORACLE
Larry Ellison
In C: In Java:
Function Method
-set of statements -set of statements
In PL/SQL:
SQL:
• Stands for Structured Query Language.
• SQL is used to write the queries.
• We write the queries to communicate with
the database.
• Query is a request that is sent to database
server.
• SQL is Non-Procedural Language. It means,
we cannot write a set of statements.
• SQL is 4GL [4th Generation Language]. In
4GL, we much concentrate on what to do
rather than how to do.
• SQL is Unified Language. It means, It is
common language for Relational Database
Management Softwares.
Ex:
emp e Dept d
empno ename job sal deptno deptno dname
1234 Ravi clerk 5000 20 10 Accounts
1235 .. .. .. 10 20 Research
30 Sales
emp dept
DDL Create
[Data Definition Language] Alter
ORACLE 7AM Page 8
[Data Definition Language] Alter
Drop
Truncate
Rename
Flashback [Oracle 10g]
Purge [Oracle 10g]
DML Insert
[Data Manipulation Language] Update
Delete
Insert All [Oracle 9i]
Merge [Oracle 9i]
DDL:
• Data Definition Language.
• It deals with metadata.
student
sid sname
DML:
• Data Manipulation Language.
• It deals with data.
• Manipulation => add [insert], delete & modify [update]
• student joined => insert
• student left => delete
• student mobile num changed => update
DCL:
• Data Control Language.
• It deals with data accessibility.
C##Raju
DRL:
• Data Retrieval Language.
• It deals with data retrievals.
• Retrieval => Opening existing data.
TCL:
• Transaction Control Language.
• It deals with Transactions.
ORACLE:
• It is RDBMS.
• used to create & maintain the database.
• we maintain DB in the form of tables.
SQL:
is a Query Language.
5 Sub Languages:
• DDL
• DML
• DCL
• DRL
• TCL
DDL:
• Data Definition Language.
• It deals with metadata.
CREATE:
• used to create the Database Objects like
tables, views …etc.
DB OBJECTS:
• Table
• View
• Index
• Materialized View
• Sequence
• Synonym
• Procedure
• Trigger
• Function
• Package
[ ] Optional
< > Any
Number(p,s)
float
real
binary_float
binary_double
Number(p):
• It is used to hold integers.
• Integer => number without decimal places Ex: 23 567 1234
• p => Precision => Max Number of digits
• Max Precision is 38
• Precision => valid range => 1 to 38
• -9999…..99 [38 digits] to 9999..999 [38 digits]
Ex:
Debit_card_num Number(16)
Aadhar_Num Number(12)
Avrg
(100+100+100)/3 = 100
------------
100.00
67.89
76.54 Avrg Number(5,2)
-999.99 to 999.99
-9.9 to 9.9
Number(p):
• Precision => Max no of digits
Char(n)
Varchar2(n)
Long
CLOB
nChar(n)
nVarchar2(n)
nCLOB
Char(n):
• used to hold a set of characters [string]
• It is Fixed length Character Data Type.
• n => Max no of characters
• Default size: 1
• Max Size: 2000 Bytes
Ex:
Country_Code Char(3)
-----------------------
IND
AUS
USA
PAK
Vehicle_Num Char(10)
------------------------
TS09AA1234
PAN_NUM Char(10)
---------------- sid Number(4)
ABC1D12345 ----
4567
1234
1A23 //Error
1#@2 //Error
Gender
ORACLE 7AM Page 15
Gender
Char
---------------
M
F
Note:
Number Data Type can accept digits only. It
cannot accept letters or special symbols.
Varchar2(n):
• it is used to hold a set of characters [string].
• it is variable length character data type.
• n => max no of characters.
• Default size: No default size. We must specify
the size
Ex:
sname Varchar2(10)
------------
Raju => 4
Sai => 3
naresh => 6
vijay => 5
f1 Char(10) f2 Varchar2(10)
sai sai
naresh4spaces naresh
Raju Raju
Rule:
There should be difference b/w space and null
There should be difference b/w 0 and null
m1
--------
45
56
24
89
0
Note:
Varchar data type was not following one of the
In latest versions,
Varchar & Varchar2 both are same.
Long:
• is used to hold a set of characters [string].
• Max size: 2GB
• is used to hold large amounts of data.
• It is outdated.
• Some limitations are there on this data type:
○ We cannot use built-in functions on Long
Type Column.
○ We can create only one column as Long type
per a table.
CLOB:
• Character Large Object.
• It is used to hold a set of characters (String).
• It is used to hold large amounts of data.
• Max size: 4GB
Ex:
Experience_Summary CLOB
100
height Number(2,1)
----------
5.9
6.0
5.5
5.7
5.3
experience_summary CLOB
-----------------------------------
feedback CLOB
complaints CLOB
n => National
A = 65 a = 97
B = 66 b = 98
. .
. .
Z = 90 z = 12
256
Date:
• is used to hold date values.
• It can hold time values also.
• It can hold date, month, year, hour, minute &
second.
• It cannot hold fractional seconds.
• Default Date Format: dd-mon-rr
• to insert date value use to_date() function
• default time value is: 12:00:00 AM [mid night]
• Fixed length data type
• memory: 7 Bytes Ex:
DOB
DOJ
DOR
Ord_Date
Del_Date
In C / Java : In SQL:
"hello" 'hello'
RR
2022 2070
Timestamp:
• introduced in Oracle 9i version.
• used to hold date & time values.
• It can hold date, month, year, hour,
minute, second & fractional seconds.
• memory: 11 Bytes
• fixed length data type
7 Bytes 11 Bytes
• BFILE
• BLOB
emp BFILE d:
empno ename ephoto emps
1234 Ravi d:\emps\ravi.jpg ravi.jpg
emp BLOB
empno ename ephoto
1234 Ravi 12AD34F66abcd6575
BFILE:
• BFILE => binary file
• used to maintain multimedia objects
• It is a pointer to multimedia object.
• It can be also called as "External Large Object".
• Because, multimedia object will be stored out of
the Database.
• It maintains path [locator] inside of Database.
• It is not secured one.
• max size: 4 GB
bfilename() function is used to maintain the path
BLOB:
• BLOB => Binary Large Object
• it is used to maintain multimedia objects.
• It can be also called as "Internal Large Object".
Because, multimedia object will be stored
inside of Database.
• It is secured one.
• max size: 4GB
• we need to write a separate program to store
multimedia object
www.oracle.com
RAM => 2GB
ORACLE 19c, 21c ORACLE 11g
CREATING USER:
Log in as DBA:
username: system
password: nareshit
2 users:
ramu
CREATE USER c##batch7am c##ramu
IDENTIFIED BY nareshit
DEFAULT TABLESPACE users
QUOTA unlimited ON users;
Log in as DBA:
user name: system
password: naresh
Dropping user:
student
sid sname scity
Creating Table:
Desc Student;
Output:
sid Number(4)
sname Varchar(10)
desc user_tables;
* All COlumns
1 row created
Run /
/
enter value for sid: 1004
enter value for sname: Ramu
enter value for m1:50
1 row created
student
sid sname m1
1010 45
1011 Srinu
Ex-2:
EMPLOYEE
empno ename job sal gender doj
7001 A clerk 6000 M 25-jan-20
empno Number(4)
ename Varchar2(15)
job varchar2(10)
sal Number(8,2)
gender Char
doj date
/
enter value for empno: …
enter value for ename: ..
…
..
..
/
enter value for empno: …
enter value for ename: ..
…
..
..
passenger
ORACLE 7AM Page 28
• Data Integrity means,
flight => 500 seats
maintaining accurate & quality
1 to 500
data.
passenger
pid pname seatnum
1001 A 68
1002 B 794
Primary Key:
• should not accept duplicate values
• should not accept null values
Ex:
student
PK
sid sname M1
1001 Ravi 45
1002 Sai 50
1003 Ravi 50
Arun 80
1002 Vijay 60
Not Null:
• accepts duplicate values.
• does not accept null values.
• It demands for the value.
student
sid sname M1
1001 Ravi 45
1002 78
1003 Ravi 78
Customer
cid cname mobile_num mail_id aadhar
1001 A ….. …
1002 B .. .. 1234
1003 C .. .. 1234
1004 D .. abcd@gmail
1005 E .. abcd@gmail
1006 F .. 5678
Check:
• It is used to apply our own conditions
student
Max marks: 100
sid sname M1 0 to 100
101 A 78
102 B 55
103 C 674
103 D 100
104 E 101
Gender
--------------
M
F
Default:
It is used to apply default value to a column.
student
Course Student
cid cname sid sname cid
10 Java 5001 A 20
20 Python 5002 B 50
30 HTML 5003 C 90
40 Oracle 5004 D 30
50 C#.Net 5005 E 100
dept employee
deptno dname empno ename deptno
10 sales 7001 A 30
20 accounts 7002 B 40
30 HR 7003 C 80
40 Research
Ex-2:
std1
Ex-3:
COURSE STD2
cid cname sid sname cid
10 JAVA 9001 A 20
20 PYTHON 9002 B 30
30 ORACLE 9003 C 80
Note:
• Primary Key column data type & foreign key
column data type must be same.
Assignment:
dept empoyee
deptno dname empno ename deptno
10 SALES 1001 Srinu 20
20 ACCOUNTS 1002 Kiran 30
30 RESEARCH 1003 Sai 70
Naming Constraints:
• Giving names to constraints is called "Naming
Constraints".
• When we define a field with constraint we can
give constraint name. If we don't give
constraint name implicitly ORACLE gives
constraint name. This name will be prefixed
with "sys_c".
• To disable or enable or rename or drop the
constraint this name is useful.
• "USER_CONSTRAINTS" maintain all
constraints information.
• Constraint name must be unique with in the
schema [user => c##batch7am]
SELECT
CONSTRAINT_NAME,CONSTRAINT_TYPE,
TABLE_NAME FROM user_constraints;
Ex-1:
std5
sid sname m1
sid Number(4) PK x
sname Varchar2(10) Not Null y
m1 Number(3) Check => 0 to z
100
Column Level:
If constraint is defined in field definition then it is
called "Column level constraint"
Ex:
create table std6
(
sid number(4) primary key,
sname varchar2(10)
);
Table Level:
• If constraint is defined after defining all columns then
it is called "Table Level".
EX:
CREATE TABLE std7
(
sid number(4),
sname varchar2(10),
primary key(sid)
);
Note:
All 6 constraints can be created at column level.
[PK, U, NN, C, D, R]
std8
sid sname m1
sid PK a
sname Not Null b
m1 Check c
unique(sid)
course1 std9
cid cname sid sname cid
cid PK p cid FK q
cname
DDL Commands:
CREATE
ORACLE 7AM Page 37
CREATE
ALTER
DROP
TRUNCATE
RENAME
FLASHBACK
PURGE
ALTER: emp
• ALTER => Change empno ename job
• ALTER command is used to change 1001 A clerk
structure of table.
• Using ALTER command we can:
○ add the columns
○ rename the columns
○ drop the columns
○ add the constraint
○ disable the constraint
○ enable the constraint
○ rename the constraint
○ drop the constraint
○ modify the field size
○ modify the data type
Ex on ALTER:
Adding M1 column:
desc std11;
sid
sname
m1
Rename M3 to Maths:
15
ORACLE 7AM Page 39
15
sname
-----------
raju
naresh
kiran
sai
sid
----
H-1001
H-1002
H-1003
D-2001
D-2002
P-3001
P-3003
NOTE:
Using ADD CONSTRAINT we can add 4 constraints only.
PK, Unique, Check & Foreign key
Disabling constraint:
Enabling Constraint:
Renaming constraint:
Dropping Constraint:
DROP
FLASHBACK [Oracle 10g]
PURGE [Oracle 10g]
DROP:
• It is used to drop the database objects like tables,
views, indexes …etc,
Ex:
DROP TABLE employee;
show recyclebin
FLASHBACK:
It is used to recollect the dropped DB Objects
from recycle bin.
Syntax:
FLASHBACK TABLE <table_name> TO
BEFOR DROP [RENAME TO <new_name>];
Ex:
FLASHBACK TABLE employee TO BEFORE DROP;
STUDENT Recyclebin
DROP STUDENT STUDENT
Purge:
• It is used to remove dropped
objects from recycle bin.
Syntax:
Purge Table <Table_name>;
Ex:
Purge Table employee;
Emptying recyclebin:
Purge recyclebin;
TRUNCATE:
• used to delete all records from the table.
• It clears the memory.
• It deletes block by block.
• It works faster.
• When we want to delete all records then use it.
Syntax:
TRUNCATE TABLE <table_name>;
Ex:
TRUNCATE TABLE student;
ORACLE DB
TALESPACE
SEGMENT
Extent
Block => Oracle page [set of records]
RENAME:
• used to rename the DB Objects
like tables, views, indexes…etc.
Syntax:
RENAME <old_name> TO <new_name>;
Ex:
RENAME employee TO emp;
DDL Commands:
• Data Definition Language
• deals with metadata
DRL / DQL:
• DRL => Data Retrieval Language
• DQL => Data Query Language
• Retrieval => opening existing data.
• Query => is a request.
It deals with data retrievals.
SELECT:
• is used to retrieve the data from existing database.
• Ex: Check Balance, Online shopping
• Using this command we can retrieve:
○ All columns & All rows
○ Limited Columns
○ Limited Rows
○ Limited Rows & Columns
Syntax:
emp
empno ename job mgr hiredate sal comm deptno
7369 SMITH CLERK .. .. .. … ..
.. ..
SELECT empno,ename,sal
FROM emp;
Execution Order:
FROM => selects all rows & all columns
SELECT => selects empno,ename & sal
* All Columns
* empno,ename,job,sal,mgr,comm,hiredate,deptno
Limited Rows:
SELECT ename,sal
FROM emp
WHERE sal>2500;
Operators in SQL:
Operator: is a symbol that is used to perform
operations like arithmetic or logical operations.
Ex:
sal>2500
m1+m2+m3
Logical
Arithmetic
Arithmetic + - * /
Relational / Comparison > >= < <= = <> / != / ^=
equals not equals
Logical AND OR NOT
SET UNION
UNION ALL
MINUS
INTERSECT
ORACLE 7AM Page 45
INTERSECT
Special IN NOT IN
Between And Not Between And
IS NULL IS NOT NULL
LIKE NOT LIKE
ANY
ALL
EXISTS
Others PIVOT
UNPIVOT
|| (Concatenation)
Arithmetic Operators:
• are used to perform Arithmetic
operations: IN C/JAVA
+ Addition 5/2 = 2
- Subtraction
* Multiplication
/ Division In SQL:
5/2 = 2.5
Calculate 10+20+30:
Dual:
SELECT 10+20+30 FROM dual;
• is a system table
• is created in "SYS" schema[user]
10+20+30
• Oracle Developers created DUAL table with
-----------------
one column & one row.
60
• For temporary calculations we can use this
table.
Changing column name:
• It is used to work with the non-Database
values
SELECT 10+20+30 AS total FROM
dual;
TOTAL
-----------------
60
Column Alias:
• We can change column headings by giving column
alias (another name / alternative name).
• "AS" keyword is used to give alias name for a column.
Using "AS" keyword is optional.
○ Ex:
SELECT 10+20+30 AS total FROM dual;
[or]
SELECT 10+20+30 total FROM dual;
• To maintain case & to give alias name in the form of
multiple words specify column alias in double quotes.
• Ex:
SELECT 10+20+30 total marks FROM dual;
total marks
----------------
60
+ - * /
student
sid sname M1 M2 M3
1001 A 50 80 70
1002 B 66 35 71
SELECT sid,sname,
M1+M2+M3 as TOTAL,
(M1+M2+M3)/3 as AVRG
FROM student;
emp
empno ename job sal mgr hiredate comm deptno
1001 A 6000
1002 B 5000
SELECT empno,ename,sal,
sal*0.1 as TA,
sal*0.2 as HRA,
sal*0.05 as TAX,
sal+sal*0.1+sal*0.2-sal*0.05 as GROSS
FROM emp;
SELECT empno,ename,sal,
sal*12 AS "Annual Salary"
FROM emp;
Calculate experience:
SELECT empno,ename,hiredate,
trunc((sysdate-hiredate)/365) as experience
FROM emp;
SELECT empno,ename,deptno
FROm emp
SELECT empno,ename,deptno
FROM emp
WHERE deptno!=20;
SELECT empno,ename,job
FROM emp
WHERE job='manager';
no rows selected
Note:
SQL is not case sensitive.
But, in string comparison it is case sensitive.
'MANAGER'='manager' => FALSE
'MANAGER' = 'MANAGER' => TRUE
SELECT empno,ename,job
FROM emp
WHERE job='MANAGER';
Logical Operators:
• are used to perform logical operations.
• Oracle SQL provides following Logical Operators:
○ AND
○ OR
○ NOT
c1 c2 c1 AND c2 c1 OR c2
T T T T
T F F T
F T F T
F F F F
C1 Not(C1)
T F
F T
emp
empno ename job sal hiredate mgr comm deptno
SELECT empno,ename,job
FROm emp
WHERE job='MANAGER' OR job='CLERK';
SELECT empno,ename,job,sal,hiredate
FROM emp
WHERE job='MANAGER' AND sal>2500 AND
hiredate>'30-apr-1981';
Special Operators:
Special operators are also comparison operators.
IN:
IN:
• is used to compare column value with list of values.
• It avoids of writing multi equality conditions using
OR.
Syntax:
<column_name> IN(<value_list>)
SELECT empno,ename,deptno
FROM emp
WHERE deptno IN(10,20);
job
----
CLERK
ANALYST
MANAGER
SALESMAN
Between And:
• It is used to compare column value with a range of
values.
Syntax:
SELECT empno,ename,sal
FROM emp
SELECT empno,ename,sal
FROM emp
WHERE sal BETWEEN 3000 AND 1600;
No rows selected
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-JAN-1981' AND '31-DEC-1981';
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate BETWEEN '1-JAN-1981' AND '31-DEC-1983';
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate NOT BETWEEN '1-JAN-1981' AND
'31-DEC-1981';
SELECT empno,ename,job
FROM emp
WHERE empno BETWEEN 7300 AND 7600;
Bank DB
Home loan
ORACLE 7AM Page 55
Home loan
previous 6 months transactions
IS NULL:
NULL:
• NULL means empty or blank. Ex:
• When the value is unknown we insert NULL value.
• NULL is not equals to 0 or space. sid sname M1
• If Null is participated in operation then result will 1001 A 55
be null.
1002 B 0
• Ex: M1+M2+M3 => 50+40+NULL => NULL
1003 C
○ something + null = null
○ something-null = null
• For NULL comparison we cannot use = OPERATOR.
FOR NULL comparison use "IS NULL" OPERATOR.
student5
sid sname M1
1001 Ramu 45
1002 Kiran
1003 Sai
IS NULL:
• It is used to compare column value with NULL.
Syntax:
<column_name> IS NULL;
SELECT empno,ename,comm
FROM emp
WHERE comm IS null;
SELECT empno,ename,comm
FROM emp
WHERE comm IS NOT NULL;
LIKE:
• It is used to compare column with text pattern
Syntax:
_ replaces 1 character
% replaces 0 or any number of characters
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE 'S%';
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%S';
SELECT empno,ename,sal
FROM emp
WHERE ename LIKE '%A%';
SELECT empno,ename,sal
FROM emp
WHERE sal LIKE '___';
Concatenation Operator:
Symbol: ||
to concatenate [combine] 2
strings, we use it
RAJKUMAR
SQL
• DDL
• DRL
• DML
• DCL
• TCL
DML:
• Data Manipulation Language
• It deals with Data.
• Manipulation => INSERT / UPDATE / DELETE
• Ex:
○ employee joined => INSERT
○ employee got promotion => UPDATE
○ employee left => DELETE
• ORACLE SQL provides following DML
commands:
▪ INSERT
▪ UPDATE
▪ DELETE
▪ INSERT ALL [Oracle 9i]
▪ MERGE [Oracle 9i]
TCL Commands:
COMMIT [SAVE]:
• is used to save the transaction.
• When we perform DML operations like INSERT,
UPDATE & DELETE, these will be applied on
ORACLE INSTANCE [RAM]. To apply the changes of
Oracle Instance to Database, use COMMIT.
• When COMMIT is executed, it applies all changes of
ORACLE INSTANCE to ORACLE DATABASE.
INSERT:
• is used to insert the records.
• Using this command we can:
○ insert single record
○ insert multiple records using parameters
○ Inserting limited column values
○ Inserting limited column values by changing the order
○ Copying records from existing table.
Syntax:
Example On INSERT:
Customer
cid cname ccity
5001 A Hyd cid Number(4)
5002 B Delhi cname Varchar2(15)
5003 C Mumbai ccity Varchar2(10)
Creating Table:
/
Enter value for cid: 5004
Enter value for cname: D
Enter value for ccity: Pune
emp Customer
empno ename job sal cid cname ccity
clerk 7782 CLARK
clerk 7566 JONES
7782 CLARK manager 7698 BLAKE
7566 JONES manager
7698 BLAKE manager
DML:
• All DMLs are not auto-committed.
• COMMIT => to save the transaction
• ROLLBACK => to cancel the transaction
Update:
• This command is used to modify the data. emp
• Using this command, we can perform empno ename job sal
calculations. 1001 A clerk 6000
• Using this command we can update: 1002 B Manager 9000
○ single value of single record
○ multiple values of single record
○ a set of records
○ all records
○ using parameters
Syntax:
UPDATE <table_name>
SET <column_name>=<value>,
<column_name>=<value>, …..
[WHERE <condition>];
UPDATE emp
SET job='MANAGER', sal=9000
WHERE empno=7369;
UPDATE emp
SET sal=sal+sal*0.1
WHERE job='MANAGER';
/
enter value for per: 20
enter value for empno: 7499
/
enter value for per:
enter value for empno:
student9
sid sname M1 M2 M3 Total Avrg
1001 A 60 80 50
1002 B 35 75 64
UPDATE student9
SET total=m1+m2+m3,avrg=(m1+m2+m3)/3;
(or)
UPDATE student9
SET total=m1+m2+m3;
UPDATE student9
SET avrg=total/3;
Ex-2:
employee12
empno ename job sal TA HRA TAX GROSS
1001 A clerk 10000
1002 B manager 15000
10% on sal as TA
20% on sal as HRA
5% on sal as TAX
GROSS = sal+ta+hra-tax
UPDATE employee12
SET TA=sal*0.1,
HRA=sal*0.2,
TAX=sal*0.05,
GROSS=sal+sal*0.1+sal*0.2-sal*0.05;
UPDATE emp
SET sal=sal+0.15, comm=comm+comm*0.05
WHERE comm is not null;
UPDATE emp
SET sal=sal+2000
WHERE hiredate like '%82';
(or)
UPDATE emp
SET sal=sal+2000
WHERE hiredate BETWEEN '1-jan-1982' AND '31-dec-1982';
DELETE:
• used to delete the records.
• using delete command we can delete:
○ single record
○ a set of records
○ all records
○ using parameters
Syntax:
TRUNCATE DELETE
• It is faster • It is slower
emp
empno ename sal
1001 A 5000
1002 B 7000
COMMIT [SAVE]:
• It is used to save the transaction.
• When 'COMMIT' command is executed, ORACLE
INSTANCE changes will be applied to ORACLE
DATABASE.
Syntax:
COMMIT;
Syntax:
ROLLBACK [TO <savepoint_name>];
Ex:
ROLLBACK;
SAVEPOINT:
• used to set margin for rollback
• Syntax:
Savepoint <savepoint_name>;
Ex: Savepoint aaa;
Ex on savepoint:
Create Table t1
(
f1 number(4),
f2 varchar2(10)
);
SAVEPOINT aaa;
SAVEPOINT bbb;
SAVEPOINT ccc;
Rollback to ccc;
Rollback to bbb;
Rollback to aaa;
SQL
DDL DRL DML TCL DCL
DCL / ACL:
• DCL => Data Control Language
• ACL => Accessing Control Language
It deals with data accessibility.
ORACLE 7AM Page 70
• It deals with data accessibility.
• Using DCL commands, we can implement the
security.
GRANT:
• is used to grant the permissions
to other users c##batch7am c##batch6pm
emp
Syntax: GRANT
GRANT <privileges_list> REVOKE
ON <DB_Object_name>
TO <user_names>;
REVOKE:
• is used to cancel the
permissions from other users
Syntax:
REVOKE <privileges_list>
ON <Db_Object_Name>
FROM <user_names>;
c##userA c##userB
GRANT select ON t1
GRANT select ON t1
TO c##userB;
SELECT * FROM c##userA.t1;
f1 f2
-----------
1 A
2 B
GRANT insert,update
ON t1 TO c##userB;
GRANT all ON t1
TO c##userB;
GRANT all ON t1
TO c##userB
WITH GRANT OPTION;
REVOKE all ON t1
TO c##userB;
SQL
C S I C G
A U R R
D D S
T IA
R M
F
P
INSERT ALL:
• is used to insert multiple records in multiple
tables or single table.
• It avoids of writing multiple INSERT commands
emp emp1
empno ename job sal empno ename job sal
1001 .. .. ..
..
emp2
1010
empno ename job sal
emp3
empno ename job sal
Copying Table
Copying records
Copying Table:
Syntax:
Copying records:
Syntax:
emp employee2
managers
Syntax:
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 job sal empno ename job sal
1001
..
1010 emp2
empno ename job sal
emp3
empno ename job sal
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>)
WHEN <condition-3> THEN
into <table_name>(<column_list>) VALUES(<value_list>)
.
.
[ELSE
into <table_name>(<column_list>) VALUES(<value_list>)]
<SELECT query>;
emp emp1
empno ename job sal empno ename job sal
1001 MANAGER
CLERK
CLERK
emp2
MANAGER
empno ename job sal
SALESMAN
emp3
empno ename job sal
INSERT ALL
WHEN job='MANAGER' THEN
into emp1 VALUES(empno,ename,job,sal)
Assignment-1:
emp1 => 1980
emp
empno ename hiredate sal
emp2 => 1981
Assignment-2:
emp emp1 deptno 10
emp2 deptno 20
empno ename deptno sal
emp3 others
empno ename deptno sal
2022-23 2020
2021 transactions
2015 sales
C => CREATE 2016
R => READ
U => Update
READ operations only
D => Delete
Merge:
• is used to apply the changes of table to its Replica.
• It is a combination of Update & Insert Commands
• It can be also called as UPSERT command.
OLTP
OLAP
Customer1 Customer2
cid cname ccity cid cname ccity
1 A Bangalore 1 A Hyd
2 B Delhi 2 B Delhi
3 C Mumbai 3 C Mumbai
4 D Pune
Syntax:
SQL:
• Structured Query Language
• It is used to write the queries.
• To communicate with database we write queries
• query => is a request sent to database
5 Sub Languages:
Built-In Function:
• Function is a set of statements that gets
executed on calling.
• Function => Task / Action / Job
• Every function is defined to perform particular
task.
• Function ca take arguments & function can
return the result.
• Built-In Function can be also called as
"Predefined Function".
Upper():
Used to convert the string to upper case.
Syntax:
Upper(<string>)
EX:
Upper('ramu') RAMU
Upper('sai') SAI
ARUN
lower():
used to convert the string to lower
case.
Syntax:
Lower(<string>)
Ex:
Lower('RAMU') ramu
LOWER('SAI') sai
arun
Initcap():
used to get every word starting letter as
capital.
Syntax:
Initcap(<string>)
Ex:
Initcap('RAMU') Ramu
Initcap('SAI TEJA') Sai Teja
Length():
used to find length of the string.
Syntax:
Length(<string>)
Ex:
Length('Arun') 4
Length('sai') 3
concat():
• concatenate => combine
• used to combine 2 strings
Syntax:
concat(<string-1>,<string-2>)
Ex:
concat('sai','teja') saiteja
concat('sai',' ','teja') ERROR
rajkumar
Example:
Player
pid fname lname name
1001 rohit sharma ----------
1002 virat kohli Rohit Sharma
Virat Kohli
ORACLE 7AM Page 82
pid fname lname name
1001 rohit sharma ----------
1002 virat kohli Rohit Sharma
Virat Kohli
Substr():
• is used to get sub string from the string.
• sub string => part of the string
Syntax:
Substr(<string>,<position>[,no_of_chars])
1 2 3 4 5 6 7 8 9
R a j K u m a r
Ex:
Substr('Raj Kumar',5) Kumar
Substr('Raj Kumar',6) umar
Substr('Raj Kumar',1,3) Raj
Substr('Raj Kumar',1,5) Raj K
Substr('Raj Kumar',6,3) uma
Substr('Raj Kumar,-4) umar
Substr('Raj Kumar',-4,3) uma
Substr('Raj Kumar',-5) Kumar
SubStr('Raj Kumar',-5,3) Kum
emp
empno ename job sal hiredate comm mgr deptno
7369 SMITH
7499 ALLEN
Instr():
used to get position of the sub string.
Syntax:
Instr(<string>,<sub_string>[,<position>,<occurrence>]
T h i s i s h i s w i s h
Ex:
Instr('This is his wish','is') 3
Instr('This is his wish','is',4) 6
Note:
If sub string is not found in the string it returns 0
If sub string is found in the string it returns position
number of the sub string.
ALLEN
SMITH
ename
----------
SMITH
DAVID
SRINIVAS
Lpad():
• pad => fill
• used to fill specified chars from left side.
Syntax:
Lpad(<string>,<max_size>[,<char_set>])
max_size-no_of_chars
10-4 = 6
Ex:
Lpad('Ramu',10,'*') ******Ramu
Lpad('Naresh',10,'@') @@@@Naresh
Lpad('Sai',12','#$') #$#$#$#$#Sai
Lpad('Raju',10) 6spacesRaju
Lpad('*',10,'*') **********
Lpad('X',10,'X') XXXXXXXXXX
Rpad():
• used to fill specified chars from right side.
• default char is: space
Syntax:
Rpad(<string>,<max_size>[,<char_set>])
Ltrim():
• trim => remove
• used to remove unwanted characters from left
side.
• default char is: space
Syntax:
Ltrim(<string>[,<char_set>])
Exs:
Ltrim('***Raju***','*') Raju***
Ltrim(' Raju ') Raju3spaces
Rtrim():
used to remove unwanted chars from
right side.
default char is: space
Syntax:
Rtrim(<string>[,<char_set>])
Exs:
Rtrim('***Ramu***','*') ***Ramu
Rtrim(' Ramu ') 3spacesRamu
Trim():
used to remove unwanted chars from left side or right side
or both sides.
Ex: @@@Raju@@@
Replace():
used to replace search string with replace string.
Syntax:
Replace(<string>,<serach_string>,<replace_string>)
EX:
Replace('Rama Krishna','Rama','Sai') Sai Krishna
Replace('abcdefabctseabc','abc','XYZ' XYZdefXYZtseXY
) Z
Transalte():
used to replace search char with corresponding
replace char.
Syntax:
Translate(<string>,<search_chars>,<replace_chars>)
Exs:
Translate('hello','lo','ab') heaab
Replace('hello','lo','ab') helab
all l chars replaced with a
all o chars replaced with b
Translate('abcaaabbbcccabcaaabbabc','abc','XYZ') XYZXXXYYYZZZXYZXXXYYXYZ
Replace('abcaaabbbcccabcaaabbabc','abc','XYZ') XYZaaabbbcccXYZaaabbXYZ
Translate(sal,'0123456789',')!@#$%^&**(')
sal
-------
8000
ORACLE 7AM Page 88
8000
9500
4600
Revrse():
used to get reverse string.
Syntax:
Reverse(<string>)
Ex:
Reverse('ramu') umar
Reverse(sai') ias
ASCII():
used to get ascii value of specific
char.
Syntax:
ASCII(<char>)
Ex: 0-255
ASCII('A') 65
ASCCI('B') 66
ASCCI('Z') 90
ASCII('a') 97
ASCII('b') 98
ASCII('z') 122
ASCII('0') 48
Chr():
used to get char of specified ASCII
value.
Syntax:
Chr(<ASCII_value>)
Ex:
Chr(65) A
Chr(97) a
Soundex():
• it used to display the records based on
sounds [pronunciation].
• When we don't know exact spelling, it is
useful.
Syntax:
Soundex(String)
Ex:
Soundex('SMYT')
Soundex('BLEK')
ORACLE 7AM Page 89
Soundex('BLEK')
Sum()
Avg()
Min()
Max()
Count()
Sum():
used to find sum of a set of values.
Syntax:
Sum(<column_name>)
Ex:
Sum(sal)
Sum(amount) amount
--------------
20000
30000
50000
Ex:
calculating sum of salaries of all emps:
Avg():
used to find average of a set of values.
Syntax:
Avg(<column_name>
Ex:
Calculate average salary:
Max():
used to get maximum value in a
set of values.
Syntax:
max(<column_name>
Ex:
Find Maximum salary in all emps:
Min():
used to get minimum value in a set of values.
Syntax:
Min(<column_name>)
Ex:
calculate min salary in all emps:
count():
used to count number of records or no of column values.
Syntax:
Count(<column_name> / *)
Ex:
Find how many emps are getting commission:
Note:
If we specify column name, it will not count null
values.
Find no of clerks:
emp
empno ename job sal
SELECT max(sal) FROM emp
8000
WHERE sal<9000;
6000
9000 8000
7000 6000
7000
Sub Query:
• Writing query in another query is called "Sub
Query".
• First inner query gets executed. then outer query
gets executed.
• Inner query result will become input for the outer
query.
8000
9000
7000
Conversion Functions:
• are used to convert the data from one type
to another.
• There are 2 types of conversions:
○ Implicit Conversion
○ Explicit Conversion
○ Implicit Conversion:
This conversion will be done by the ORACLE
implicitly.
Ex:
SELECT '100'+'200' FROM dual;
300
Explicit Conversion:
If conversion is done explicitly by using built-in function
then it is called "Explicit Conversion".
Char
Date
Number
Syntax:
to_char(<date>,<format>)
2022
Display emp records with hiredates. Display
hiredate in IND date format [dd/mm/yyyy]: 1-jan-2022 1st day
31-dec-2022 365th day
SELECT ename, 19-may-2022 139th day
to_char(hiredate,'dd/mm/yyyy') as hiredate
FROM emp;
SELECT empno,ename,
to_char(hiredate,'mm/dd/yyyy') as hiredate
FROM emp;
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'yyyy')=1982;
SELECT empno,ename,
to_Char(hiredate,'dd/mm/yyyy') as hiredate
FROM emp
WHERE to_char(hiredate,'yyyy') IN(1980,1982,1983);
SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'q')=4;
Display the emp records who joined in 1st & 4th quarters:
SELECT empno,ename,hiredate
FROM emp
WHERE to_char(hiredate,'q') IN(1,4);
SELECT empno,ename,hiredate
FROM emp
WHERE to_Char(hiredate,'day')='sunday';
no rows selected
SELECT empno,ename,hiredate
FROM emp
WHERE Rtrim(to_Char(hiredate,'day'))='sunday';
sal
------------
5000 $5,000.00
9000
6000 USD5,000.00
4000
Syntax:
to_char(<number>[,<format>])
Ex:
to_char(123) '123'
to_char(123.45) '123.45'
5000.00
$5000.00
USD5000.00
$5,000.00
SELECT empno,ename,
to_char(sal,'L99,999.99') as SALARY
FROM emp; sal Number(7,2)
99999.99
sal Number(8,2)
999999.99
JAPAN => ¥
UK => £
NLS_TERRITORY AMERICA
NLS_CURRENCY $
Log in as DBA:
username: system
password: nareshit
to_date():
used to convert the string to date.
Syntax:
to_date(<string>[,<format>])
Ex:
to_date('23-DEC-2019') 23-DEC-2019
to_date('23 december, 2019') 23-DEC-2019
to_Date('23/12/2019') ERROR
to_Date('23/12/2019','dd/mm/yyyy') 23-DEC-2019
to_Date('12/23/2019') ERROR
to_Date('12/23/2019',mm/dd/yyyy') 23-DEC-2019
20
ERROR
SELECT to_Char(to_date('23-dec-2019'),'yyyy')
FROM dual;
2019
SELECT to_char(to_Date('15-AUG-1947'),'day')
FROM dual;
to_number():
• used to convert string to number.
Syntax:
to_number(<string>[,<format>])
Note:
string must be numeric string
Ex:
to_number('123') 123
to_number('123.45') 123.45
to_number('Ramu') ERROR
to_number('$5000.00') ERROR
to_number('$5000.00','L9999.99') 5000
to_number('USD5,000.00','C9,999.99') 5000
Math Functions:
power():
used to find power values
Syntax:
power(number,power)
Ex:
power(2,3) 8
power(5,3) 125
sqrt():
used to find square root value.
Syntax:
sqrt(number)
Ex:
sqrt(100) 10
sqrt(81) 9
Syntax:
sin(angle)
Ex:
sin(90*3.14/180)
Syntax:
Ex:
cos(0*3.14/180)
Syntax:
tan(Angle)
Ex:
tan(45*3.14/180)
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 the number is +ve
or -ve or zero.
Syntax:
sign(number)
Ex:
sign(20) 1
sign(-20) -1
sign(0) 0
mod():
used to get remainder values
Syntax:
mod(number,dvisor)
Ex:
mod(5,2) 1
mod(20,7) 6
log():
used to get logarithmic values.
Syntax:
log(number,base)
Ex:
ln():
used to find natural logarithmic values.
Syntax:
ln(number)
Ex:
ln(7)
Ceil():
used to get upper integer value.
Syntax:
Ceil(number) 123 124
Exs:
Ceil(123.45) 124
Ceil(5678.234) 5679
Floor():
used to get lower integer value.
Syntax:
Floor(number)
Ex:
Floor(123.45) 123
Floor(786.457) 786
Trunc():
used to remove decimal places.
Syntax:
Trunc(number,no_of_decimal_places)
Trunc(123.4567) 123
Trunc(123.456789,2) 123.45
Trunc(123.456789,3) 123.456
10,20,30,….100,110,120,130
Trunc(456.789,-2) 400
400 to 500
Round():
• used to get rounded values.
• if value is >= avrg value, it takes upper
• if value < avrg value, it takes lower
Syntax:
Round(number,no_of_Decimal_places)
Exs:
Round(123.45) 123
Round(123.678) 124
Round(123.5678) 124
Round(123.5567,2) 123.56
Round(123.5547,2) 123.55
Round(45.67893,3) 45.679
Round(45.67833,3) 45.678
Round(123.4567,-1) 120
120 to 130
Round(127.456,-1) 130
120 to 130
Round(1234.5678,-2) 1200
1200 to 1300
Round(1284.5678,-2) 1300
1200 to 1300
percentage
------------------ 78.69 78 & 79
78.69
65.45
56.52 78+79 = 157 /2 = 78.5
82.37
72.89
Date Functions:
• sysdate
• systimestamp
• add_months()
• last_day()
• next_day()
• months_between()
sysdate:
• is used to get current system date.
Ex:
display current system date:
23-may-22
7:29:11 AM
systimestamp:
used to get current system date & time
Add_Months():
used to add / subtract months to/from a date.
Syntax:
Add_months(<date>,<no_of_months>)
no_of_months,
+ve adds the months
Ex: 60 YEARS
employee
empno ename DOB DOR
1001 A 25-MAY-2000
1002 b 17-DEC-1998
UPDATE employee
SET DOR=Add_Months(DOB,12*60);
Ex:
India_CMs
state_id state_name CM_name start_date end_date
10 TS KCR 15-dec-2018
20 AP YS JAGAN 20-may-2019
UPDATE india_Cms
SET end_date=Add_Months(start_date,12*5);
Ex:
Trunc():
can be used to remove time value
from date value.
SELECT Trunc(systimestamp)
FROM dual;
Display the emp record who joined 1 month ago from sysdate:
Display the emp records who joined 1 year ago from sysdate:
Ex:
Sales
dateid amount
1-jan-2019 30000
2-jan-2019 50000
23-may-22 75000
22-may-22 60000
23-apr-22 80000
23-may21 50000
Last_day():
is used to get last day in the month.
Syntax:
Last_day(<date>)
Exs:
31-may-22
31-dec-18
SELECT
Last_day(add_months(sysdate,-2))+1
FROM dual;
SELECT
Last_Day(add_months(sysdate,-1))+1
FROM dual;
23-apr-22
30-apr-22 + 1 = 1-may-22
Next_Day():
used to get next date based on weekday.
If we want to find next Sunday date,
next Monday date we can use Next_Day() function.
Syntax:
Next_Day(<date>,<week_Day_name>)
<week_Day_name>
Ex: sun
Sunday
find next Friday's date from sysdate: 1
SELECT Next_day(last_day(sysdate),'sun')
FROM dual;
SELECT
Next_day(Last_day(Add_Months(sysdate,-1)),'sun')
FROM dual;
23-apr-22
30-apr-22
31-may-22 - 7 = 24-may-22
Months_Between():
used to get months between 2 dates.
Syntax:
Months_Between(date1,date2)
SELECT empno,ename,
Round(Months_Between(sysdate,hiredate)/12) as
experience
FROM emp;
SELECT
Months_Between(sysdate,'24-APR-1973')/12 as AGE
FROM dual;
Miscellaneous Functions:
• User
• UID
• Greatest()
• Least()
NVL()
ORACLE 7AM Page 111
• NVL()
• NVL2()
• Rank()
• Dense_Rank()
User:
used to get current user name.
Ex:
SELECT user FROM dual;
c##batch7am
UID:
used to get user ID
Ex:
SELECT UID,USER FROM dual;
Desc All_Users;
GREATEST():
used to find max [greatest] value in
specified list.
Syntax:
GREATEST(<value_list>)
EX:
SELECT
GREATEST(10,20,50,90,40,30)
FROM dual;
90
LEAST():
used to get min [least] value in specified
list.
Syntax:
LEAST(<value_list>)
Ex:
SELECT LEAST(10,90,80,5,80,4)
FROM dual;
Min() Least()
NVL():
something+null = null
something-null = null
Syntax:
NVL(value1,value2)
Ex:
SELECT NVL(100,200) FROM dual;
100
SELECT empno,ename,sal,comm,
sal+NVL(comm,0) as "total salary"
FROM emp;
SELECT empno,ename,
NVL(comm,'N/A') as comm
FROM emp;
ERROR: data type mismatch
comm => number
N/A => string
SELECT empno,ename,
NVL(to_char(comm),'N/A') as comm
FROM emp;
Ex:
student
sid sname M1
101 Ramu 56
102 Kiran
103 AA 45
104 BB
SELECT sid,sname,
NVL(m1,'AB') FROM student;
SELECT sid,sname,
NVL(to_char(m1),'AB') FROM student;
NVL2():
used to replace null and not null values.
Syntax:
NVL2(value1,value2,value3)
Ex:
NVL2(100,200,300) 200
NVL2(null,200,300) 300
SELECT empno,ename,comm,
NVL2(comm,comm+500,300) as comm
FROM emp;
Rank():
used to apply ranks to records according specific
column.
Syntax:
Rank() Over(ORDER BY column_name DESC/ASC)
Dense_Rank():
used to apply ranks to records according specific column.
Syntax:
Dense_Rank() Over(ORDER BY column_name DESC/ASC)
SELECT empno,ename,sal,
Rank() Over(ORDER BY sal DESC) as Rnk
FROM emp;
SELECT empno,ename,sal,
Dense_Rank() Over(ORDER BY sal DESC) as Rnk
FROM emp;
SELECT empno,ename,sal,hiredate,
Dense_Rank() Over(Order BY sal Desc, hiredate Asc) as Rnk
FROM emp;
CASE Expression:
• Introduced in Oracle 9i.
• used to implement 'If..Then..Else' in SQL.
• It avoids of writing PL/SQL program.
• can be used in 2 ways:
○ Simple CASE [like switch in C / JAVA]
○ Searched CASE [like if else if in C / JAVA]
CASE <column_name>
WHEN <value-1> THEN <return_expression>
WHEN <value-2> THEN <return_expression>
..
..
[ELSE <return_expression>]
END
SELECT empno,ename,
CASE job
WHEN 'MANAGER' THEN 'BOSS'
WHEN 'PRESIDENT' THEN 'BIG BOSS'
WHEN 'CLERK' THEN 'WORKER'
ELSE 'EMPLOYEE'
END as JOB
ORACLE 7AM Page 117
END as JOB
FROM emp;
SEARCHED CASE:
Syntax:
CASE
WHEN <Condition-1> THEN <return_expression>
WHEN <Condition-2> THEN <return_expression>
..
..
[ELSE <return_expression]
END
SELECT empno,ename,sal,
CASE
WHEN sal>4000 THEN 'HiSal'
WHEN sal<4000 THEN 'LoSal'
WHEN sal=4000 THEN 'AvrgSal'
END as "Salary Range"
FROM emp;
NOTE:
If all conditions are FALSE, if we
don't specify ELSE, by default it
returns NULL.
SELECT sid,sname,
CASE
WHEN m1>=40 AND m2>=40 AND m3>=40 THEN 'PASS'
ELSE 'FAIL'
END as RESULT
FROM student;
In ORACLE SQL,
'IF..THEN..ELSE' can be implemented using 2 ways:
• using CASE expression [From Oracle 9i version onwards]
• using Decode() Function [Before Oracle 9i version]
Decode():
• it is used to implement 'IF..THEN..ELSE'.
• It can check equality condition only.
It is same as SIMPLE CASE.
ORACLE 7AM Page 120
• It is same as SIMPLE CASE.
Syntax:
decode(<column_name>,
<value1>,<return_expression>,
<value2>,<return_expression>,
………… , …………………………… ,
<else_Return_expression>)
SELECT empno,ename,
decode(job,
'MANAGER','BOSS',
'CLERK','WORKER',
'PRESIDENT','BIG BOSS',
'EMPLOYEE') as JOB
FROM emp;
decode() decode()
CASE CASE
Interval Expression:
• introduced in Oracle 9i.
• using it, we can add/ subtract days, months,
years to/from a date.
• We can also add/subtract hours, minutes and
seconds to/from a time also.
sales
dateid amount
1-jan-2019 60000
2-jan-2019 90000
3-jan-2019 80000
..
..
Clause:
• Clause is a part of query.
ENGLISH SQL
Sentences Queries
Words Clauses
• SELECT
• FROM
• WHERE
• DISTINCT
• GROUP BY
• HAVING
• ORDER BY
SELECT:
is used to specify the column list.
Ex:
SELECT ename,sal
SELECT sid,sname,scity
SELECT * => * = all columns
FROM:
used to specify table list.
Ex:
FROM emp
FROM emp,dept
WHERE:
• is used to specify the condition.
• this condition will be applied on every row.
Ex:
WHERE job='MANAGER'
WHERE sal>3000
DISTINCT:
is used to avoid duplicate rows.
emp
empno ename job deptno
MANAGER 10
CLERK 30
CLERK 30
MANAGER 10
ANALYST 20
ANALYST 20
CLERK 30
MANAGER
CLERK
ANALYST
Ex:
STUDENT
sid sname course
1001 Ramu JAVA
1002 ORACLE
1003 ORACLE
1004 JAVA
ORACLE 7AM Page 130
1004 JAVA
1005 PYTHON
1006 PYTHON
JAVA
ORACLE
PYTHON
ORDER BY:
is used to arrange the records in ascending
order or descending order according to
specific column / columns.
Numbers:
1 to 10 => Asc
10 to 1 => Desc
Characters:
A to Z => Asc
Z to A => Desc
Date:
Asc Desc
1-jan-2022 31-dec-2022
2-jan-2022 30-dec-2022
. .
. .
31-dec-2022 1-jan-2022
1-jan-2023 31-dec-2021
desc emp;
empno
ename
job
sal desc
----- sal
6000 -------
5000 8000
8000 6000
4000 5000
4000
Ascending Descending
sal
---------------- -----------------
5000 4000 null
8000 5000 null
7000 8000
4000 8000 7000
null 5000
null 4000
7000
deptno job
10 clerk
10 clerk
20 clerk
20 clerk
10 clerk
20 clerk
ORACLE 7AM Page 133
20 clerk
emp
empno ename deptno sal
1001 A 30 8000 1002 B 10 9000
1002 B 10 9000 1003 C 10 12000
1003 C 10 12000 1006 F 10 6500
1004 D 30 11000 1001 A 30 8000
1005 E 30 7000 1004 D 30 11000
1006 F 10 6500 1005 E 30 7000
SELECT empno,ename,deptno,sal
FROM emp
ORDER BY deptno Asc,sal desc;
20 10
10 20
10 5000 10 6000
10 6000 10 5000
SELECT empno,ename,deptno,sal,hiredate
FROM emp
ORDER BY deptno asc,sal desc,hiredate asc;
GROUP BY:
• used to group the records according to particular
column/columns.
• It is used to get summarized data from detailed data.
• It can be used to apply aggregate functions on group
of records.
emp
empno ename deptno sal deptno sum(sal)
1001 A 30 5000 10 13000
1002 B 30 8000 20 13000
1003 C 10 7000 30 13000
1004 D 10 6000
1005 E 20 9000
1006 F 20 4000
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
SELECT deptno,sum(Sal)
FROM emp
WHERE deptno IN(10,30)
GROUP BY deptno
ORDER BY deptno;
FROM emp:
selects entire table
emp
empno ename deptno sal
1001 A 30 5000
1002 B 30 8000
1003 C 10 7000
1004 D 10 6000
1005 E 20 9000
1006 F 20 4000
GROUP BY deptno:
groups the records according to deptno
1001 A 30 5000
1002 B 30 8000
1003 C 10 7000
1004 D 10 6000
SELECT deptno,sum(Sal):
selects deptnos and sum of salaries
deptno sum(sal)
30 13000
10 13000
ORDER BY deptno:
arranges result in ascending order according to
deptno.
deptno sum(sal)
10 13000
ORACLE 7AM Page 137
10 13000
30 13000
emp
empno ename deptno sal
1001 A 30 5000
1002 B 30 8000
deptno no_of_emps
1003 C 10 7000
10 2
1004 D 10 6000
20 2
1005 E 20 9000
30 2
1006 F 20 4000
SELECT deptno,count(8)
FROM emp
GROUP BY deptno
ORDER BY 1;
year no_of_emps
1980 3
ORACLE 7AM Page 138
1980 3
1981 5
1982 4
1983 7
quarter no_of_emps
1 3
2 5
3 2
4 6
aggregate functions:
emp
empno ename job deptno sal
clerk 10000
clerk 15000
manager 20000
manager 15000
clerk 25000
manager 35000
SELECT job,avg(sal)
FROM emp
GROUP BY job;
SELECT job,count(8)
FROM emp
GROUP BY job;
sal_range no_of_emps
hisal 3
losal 5
avrgsal 2
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
ORACLE 7AM Page 141
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;
HAVING clause:
• used to write the conditions on groups.
• We can use aggregate functions in HAVING
clause.
• It cannot be used without GROUP BY.
• On result of GROUP BY, HAVING condition will be
applied.
• After GROUP BY, HAVING will be executed.
SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno
HAVING sum(Sal)>10000;
SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno
ORACLE 7AM Page 142
GROUP BY deptno
HAVING sum(Sal)=9400;
SELECT deptno,count(*)
FROM emp
GROUP BY deptno
HAVING count(*)>5;
SELECT deptno,max(Sal)
FROM emp
GROUP BY deptno
HAVING max(sal)>3000;
SELECT job,count(*)
FROM emp
GROUP BY job
HAVING count(*)>3;
SELECT job,count(*)
FROM emp
GROUP BY job
HAVING count(*)=3;
SELECT job,sum(Sal)
FROM emp
GROUP BY job
HAVING sum(Sal)>5000;
WHERE HAVING
Execution Order:
FROM
WHERE
GROUP BY
HAVING
SELECT
ORACLE 7AM Page 144
SELECT
DISTINCT
ORDER BY
emp
empno ename job deptno sal
1001 clerk 10 10000
clerk 20 12000
manager 20 8000
clerk 10 7000
salesman 10 15000
salesman 10 20000
manager 10 25000
clerk 20
10 clerk
20 clerk
10 manager
20 manager
10 salesman
SELECT deptno,job,sum(Sal)
FROM emp
GROUP BY deptno,job
ORDER BY deptno;
1980 1 3
2 7
3 4
4 9
1981 1 5
2 6
3 2
4 8
SALES
dateid amount
1-jan-2015 50000
2-jan-2015 75000
ORACLE 7AM Page 146
2-jan-2015 75000
..
..
28-MAY-2022 60000
Rollup():
• used to calculate sub totals & grand totals
• calculates sub totals & grand total according to
first column in GROUP BY list.
Cube():
• used to calculate sub totals & grand total
• calculates sub totals & grand totals according to
all columns in GROUP BY list.
SELECT deptno,job,sum(Sal)
FROM emp
GROUP BY Rollup(deptno,job)
ORDER BY 1;
SELECT deptno,job,sum(Sal)
FROM emp
GROUP BY deptno,job
ORDER BY deptno;
20 CLERK 8
20 MANAGER 4
Find year wise, quarter wise sales. Calculate sub totals &
grand total according to year:
2018 1 300000
2 100000
3 500000
4 400000
Person
ORACLE 7AM Page 150
Person
pid pname state gender age aadhar
state no_of_people
TS ..
MR ..
AP ..
SETS
A = {1,2,3,4,5}
B = {6,7,1,2,3}
A UB = {1,2,3,4,5,6,7}
A IB = {1,2,3}
A MB = {4,5}
B MA = {6,7}
SET OPERATORS:
• are used to combine the rows from multiple tables.
• ORACLE SQL provides following SET operators:
○ UNION
○ UNION ALL
○ INTERSECT
○ MINUS
Syntax:
Customer1 Customer2
cid cname cid cname
1001 Ramu 5001 Vijay
1002 Kiran 5002 Sravan
1003 Sai 1002 Kiran
UNION:
is used to get all records from two tables uniquely
ORACLE 7AM Page 153
• is used to get all records from two tables uniquely
[without duplicate records].
• gives result in the order.
cid cname
1001 Ramu
1002 Kiran
1003 Sai
5001 Vijay
5002 Sravan
UNION ALL:
used to combine the rows from two tables including
duplicates.
cid cname
1001 Ramu
1002 Kiran
1003 Sai
5001 Vijay
5002 Sravan
1002 Kiran
INTERSECT:
ORACLE 7AM Page 154
INTERSECT:
used to common records from 2 tables.
cid cname
1002 Kiran
MINUS:
• used to get specific records of a table.
• It gives all records from first table except common
records.
Customer1
cid cname
1001 Ramu
1003 Sai
Customer2
cid cname
5001 Vijay
ORACLE 7AM Page 155
5001 Vijay
5002 Sravan
Rules:
• Corresponding column data types should be
matched in both SELECT queries.
ERROR:
ERROR:
JOB
---------
MANAGER
PRESIDENT
CLERK
JOB
---------
CLERK
MANAGER
ANALYST
CLERK
ANALYST
job
-----------
ANALYST
CLERK
MANAGER
PRESIDENT
PRESIDENT
ANALYST
College DB
STUDENT
MARKS
FEE
STAFF
LIBRARY
STUDENT MARKS
sid sname scity sid Maths Phy Che
JOINS:
• Join => Connect / Link / Combine
• Joins concept is used to retrieve the data from
multiple tables.
• JOIN is an operation that combines one table
records with another based on JOIN CONDITION.
• JOIN CONDITION decides which record one table
should be joined with which record in another
table.
STUDENT MARKS
sid sname scity sid Maths Phy Che
1001 A Hyd 1001 50 80 60
1002 B Delhi 1002 40 60 30
1003 C Mumbai 1003 55 78 36
emp dept
empno ename job sal deptno deptno dname loc
SELECT ename,sal,dname,loc
FROM emp, dept
WHERE emp.deptno=dept.deptno;
(or)
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;
emp dept
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno;
Note:
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno;
ORACLE 7AM Page 162
ON e.deptno=d.deptno;
(or)
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
USING(deptno);
emp e dept d
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno AND d.loc='CHICAGO';
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE d.loc='CHICAGO';
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
ORACLE 7AM Page 163
FROM emp e,dept d
WHERE e.deptno=d.deptno AND e.ename='BLAKE';
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename='BLAKE';
emp e
dept d
empno ename sal deptno
deptno dname loc
1001 A .. 20
10 ACCOUNT NEW YORK
1002 B .. 20
20 RESEARCH DALLAS
1003 BLAKE .. 30
30 SALES CHICAGO
1004 D 10
40 OPERATIONs BOSTON
1005 E 10
1006 F 30
ORACLE style:
ANSI style:
SELECT e.ename,d.dname,l.lname,c.cname
FROM emp1 e INNER JOIN dept1 d
ON e.deptno=d.deptno
INNER JOIN location1 l
ON d.locid=l.locid
INNER JOIN country1 c
ON l.cid=c.cid;
Outer Join:
• Inner Join can give matched records only. It
cannot give unmatched records.
• Outer Join is used to get matched & unmatched
records.
• For outer join we use Outer Join Operator in
ORACLE style.
• Outer Join Operator symbol: (+)
• There are 3 sub types in Outer Join:
○ Left Outer Join
○ Right Outer Join
○ Full Outer Join
emp dept
empno ename sal deptno dept dname loc
1001 A .. 20 no
1002 B .. 20 10 ACCOUNT NEW
1003 C .. 30 YORK
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno(+);
Note:
For left outer join write (+) symbol at right side
In ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno=d.deptno;
dept.deptno=emp.deptno
dept => left table
emp => right 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;
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno;
emp dept
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30
1007 G
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno(+) AND
d.dname IS null;
ANSI style:
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e,dept d
WHERE e.deptno(+)=d.deptno AND
e.ename IS null;
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename IS null;
Full outer+conditions =
left outer + condition
UNION
right outer + condition
ORACLE style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno(+) AND
d.dname is null
UNION
SELECT e.ename,e.sal,d.dname,d.loc
ORACLE 7AM Page 169
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno AND
e.ename is null;
ANSI style:
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e FULL OUTER JOIN dept d
ON e.deptno=d.deptno
WHERE d.dname IS null OR e.ename IS null;
Non-Equi Join:
If join operation is performed based on other than
equality condition then it is called "Non-Equi Join"
Ex:
e.deptno>d.deptno
e.deptno<d.deptno
emp salgrade
empno ename sal grade losal hisal
1234 5000 1 700 1200
1235 2000 2 1201 1400
1236 1200 3 1401 2000
1237 1800 4 2001 3000
1238 3000 5 3001 5000
ORACLE style:
SELECT e.empno,e.ename,e.sal,s.grade
ORACLE 7AM Page 170
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 INNER JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;
Self Join:
• If a table is joined to itself then it is called "Self Join".
• It can be also called as "Recursive Join".
• a record in one table joined with another record in same
table here.
emp emp
empno ename job sal mgr empno ename job sal mgr
1001 A manager 1001 A manager
1002 B clerk 1001 1002 B clerk 1001
1003 C SALESMAN 1001 1003 C SALESMAN 1001
1004 d MANAGER 1004 d MANAGER
1005 E CLERK 1004 1005 E CLERK 1004
1006 f analyst 1004 1006 f analyst 1004
ORACLE style:
ANSI style:
ORACLE 7AM Page 171
ANSI style:
ORACLE style:
ANSI style:
A = {1,2,3}
B = {4,5}
AXB =
GroupA GroupB
cid cname cid cname
10 IND 40 PAK
20 AUS 50 ENG
30 WIN 60 NZ
3X3=9
IND PAK
IND ENG 10 X 5 = 50
IND NZ
AUS PAK
AUS ENG
AUS NZ
WIN PAK
WIN ENG
WIN NZ
ORACLE style:
SELECT a.cname,b.cname
FROM groupA a,groupB b;
ANSI style:
SELECT a.cname,b.cname
FROM groupA a CROSS JOIN groupB b;
emp dept
empno ename sal deptno deptno dname loc
1001 A .. 20 10 ACCOUNT NEW YORK
1002 B .. 20 20 RESEARCH DALLAS
1003 C .. 30 30 SALES CHICAGO
1004 D 10 40 OPERATIONs BOSTON
1005 E 10
1006 F 30
1007 G
Syntax:
SELECT <column_list>
FROM <table_list>
WHERE <column_name> <operator> (<SELECT query>);
SELECT
• Inside query is called "inner query / sub query / child
WHERE .. (SELECT …
query".
(SELECT …
• Outside query is called "outer query / main query / parent
(SELECT …
query"
• Normally, first inner query gets executed. Then outer
255 levels
query will be executed.
• The result of inner query becomes input for the outer
query.
• Normally, when WHERE condition value is unknown then
write Sub Query.
• We can write maximum of 255 sub queries in WHERE
clause.
• Sub query must be written in parenthesis. [ (<sub
query>) ].
• Sub Query must be SELECT query only.
• Sub Query cannot be INSERT / UPDATE / DELETE
• Main query can be INSERT / UPDATE / DELETE / SELECT.
BLAKE 5000
ORACLE 7AM Page 176
BLAKE 5000
sal
----
5000 SELECT sal FROM emp
7000 WHERE sal<7000;
4000
8000 5000
6000 4000
6000
Swapping 2 salaries:
emp
empno ename deptno sal
deptno sum(Sal)
10 10000
10 25000
10 15000
20 15000
20 5000
30 35000
20 10000
30 20000
30000 15000
30 35000
30
Examples:
Display the emp names who are earning max sal in their
dept:
Execution Process:
• Outer query gets executed. It selects the row.
• Outer query passes value to inner query.
• Inner query gets executed.
• Inner query passes value to outer query.
• Outer query condition will be tested. If condition
is TRUE, row will be selected.
• Above process will be executed repeatedly for
every row.
emp e
empno ename sal deptno deptno avg_sal
1 A 10000 20 10 15000
2 B 15000 20 20 12500
3 C 20000 10
4 D 10000 10
SELECT empno,ename,sal,deptno
FROM emp e
WHERE sal>(SELECT avg(sal) FROM emp
WHERE deptno=e.deptno);
emp
SELECT empno,ename,sal,deptno
FROM emp e
WHERE 2 = (SELECT count(DISTINCT sal)
FROM emp WHERE sal>e.sal);
4 D 12000 10
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 4 = (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);
emp
empno ename sal deptno no_of_sals>emp sal 0 max sal
1 A 10000 20 no_of_sals>emp sal 1 2nd max sal
2 B 15000 20 no_of_sals>emp sal 2 3rd max sal
3 C 20000 10 no_of_sals>emp sal 3 4th max sal
4 D 12000 10 no_of_sals>emp sal 4 5th max 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 5 > (SELECT count(distinct sal)
FROM emp WHERE sal>e.sal);
SELECT empno,ename,sal,deptno
FROM emp e
WHERE &n > (SELECT count(distinct sal)
FROM emp WHERE sal>e.sal);
dept emp
deptno dname empno ename sal deptno
10 Accounting 1 A 10000 20
20 Research 2 B 15000 20
30 Sales 3 C 20000 10
4 D 12000 10
Inline View:
• Writing sub query in FROM clause is In WHERE clause, we can write
called "Inline View". maximum of 255 sub queries
• It acts like table. In FROM clause, no limit is there.
• Used to change the execution order.
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
RowNum:
• is a pseudo column.
• It is used to get record numbers.
• Row number will be applied on result of
SELECT query.
emp dept
------- ------
16 4
deptno per
10 30
20 50
30 20
ORACLE
Database
Tables
SQL
PL/SQL
Views:
Virtual => not real
• View is a DB Object.
• View is a Virtual Table.
• Virtual Table means, it does not contain
physical data & does not occupy the memory.
• View holds SELECT query.
• When we retrieve data through VIEW, implicitly
ORACLE runs SELECT query & retrieve data
from table.
• A VIEW is created on table. This table is called
"Base Table".
• Without Table we cannot create the VIEW.
• Some views can be updated. These are called
"Updatable views / simple views".
• Some views cannot be updated. These are
called "Read-Only views / Complex Views".
Ex:
emp
empno ename job sal comm deptno hiredate mgr
V1
empno ename job
Log In as DBA:
username: system
password: nareshit
Advantages:
• provides security for the data.
• reduces the complexity & simplifies queries.
emp
empno ename job sal mgr comm hiredate deptno
V1
empno ename job
emp
empno ename job sal mgr comm hiredate deptno
1001 10
1002 10
1003 10
1004 20
1005 20
1006 20
CREATE VIEW v2
ORACLE 7AM Page 189
CREATE VIEW v2
AS
Join query
Disadvantage:
• Less Performance
Log in as DBA:
username: system
password: nareshit
CREATING USER:
Log in as c##oracle7am:
CREATE VIEW v2
AS
SELECT empno,ename,job FROM emp;
Log in as c##ramu:
username: c##ramu
password: ramu
Types of Views:
2 types:
• Simple VIEW
• Complex VIEW
Simple VIEW:
emp
empno ename job sal comm mgr hiredate deptno
10
10
20
20
emp
30
empno ename sal gender
30
c##batch7am:
CREATE VIEW v3
AS
SELECT * FROM emp WHERE deptno=20;
Log in as c##Ramu:
Note:
• We cannot use ALTER command on View.
• To make changes in existing view, we use
CREATE OR REPLACE
c##batch7am:
c##ramu:
Complex View:
• If view is created based on multiple tables
(joins) or group by or having or set operators
or sub queries or group functions or
expressions then it is called "Complex View"
CREATE VIEW v4
AS
SELECT deptno,sum(Sal) as sum_of_sal
FROM emp
GROUP BY deptno
ORDER BY 1;
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:
If view is created forcibly with some errors then it is
called "FORCE VIEW".
Ex:
• If we want to create view without base table then
use FORCE VIEW.
• This view will not work until we create the base
table.
Dropping View:
Syntax:
DROP VIEW <view_name>;
Ex:
DROP VIEW v9;
User_views:
It maintains all views information of specific user.
View:
Virtual does not contain physical data & does not
Table occupy the memory.
View holds SELECT query
ORACLE
Indexes:
• Index is a DB Object.
• Index is used to improve the performance INDEX
of data retrieval.
• To refer a chapter in book, we use index. Chapter Name Page Num
With this, we can refer the chapter quickly.
DDL 5
• If index is created on column of table, we
DML 10
can retrieve the record quickly.
• Index will be created on column. Built-in fun 20
• The columns which are frequently in WHERE Joins 50
condition or Join Condition, on them create
the Index to improve the performance.
Advantage:
• It improves performance of data retrieval.
Table Scan:
If Index is not created, ORACLE performs Table Scan.
It is slower than Index scan
Index Scan:
If index is created, ORACLE performs Index Scan.
It is faster than table scan.
Table scan
Types of Indexes:
2 Types:
Simple Index:
If index is created on one column then it is
called "Simple Index".
Ex:
Composite Index:
If index is created on multiple columns then it is called
"Composite Index".
deptno job
10 clerk
20 manager
Unique Index:
If index is created on the column which is having
unique values then it is called "Unique Index".
Function-Based Index:
If index is created based on function (or) expression
then it is called "Function-Based Index".
B-TREE INDEX:
• In this, B-TREE will be created.
• It stores data & rowids.
○ Ex: sal => 3000 * *
5000 *
BITMAP INDEX:
• In this B-TREE will not be created.
• It stores the bits => 0s and 1s.
• Every bit is associated with Row IDs. Bit will be
converted to Row ID, goes to that Row ID & picks
the record.
• On low cardinality columns create bitmap index.
Ex:
Gender
------------
ORACLE 7AM Page 201
------------
M
M
F
F
F
M
M
F
M
M
M
F
deptno
-----------
10
30 10
30 20
20 30
20
10
10
20
30
emp2
Yes
No
Yes
User_indexes:
Desc user_indexes;
Dropping Index:
Syntax:
DROP INDEX <index_name>;
EX:
DROP INDEX i1;
SEQUENCES:
• SEQUENCE is a DB Object.
• It is used to create sequential integers.
• It is independent of the table.
Ex:
Order_id cust_id Transaction_id
------------- ------------ -----------------------------
12345678 123456 1234567890
12345679 123457 1234567891
12345680 123458
Syntax:
Syntax:
sequence_name.pseudo_column
Ex:
s1.nextval
s1.currval
CUSTOMER
cid cname
1 A
2 B
/
enter value for cname: B
/
enter value for cname: C
/
enter value for cname: D
/
ORACLE 7AM Page 208
/
enter value for cname: E
/
enter value for cname: F
ERROR: sequence reached max value
Assignment:
course
CREATE SEQUENCE s3
cid cname START WITH 10
10 Java INCREMENT BY 10
20 C# MINVALUE 10
30 Python MAXVALUE 50;
40 C
50 Oracle
Cycle / NoCycle:
• Default => NoCycle
NoCycle:
When we create a sequence with nocycle,
When we call the sequence, it can generate next
value up to max value. After reaching max value, it
will be stopped.
Cycle:
If sequence is created with Cycle,
Sequence will be started with START WITH value,
generates next value up to max value. After
reaching max value, it will be reset to min value.
CREATE SEQUENCE s6
START WITH 300
INCREMENT BY 1
MINVALUE 100
MAXVALUE 500
Cycle;
CREATE SEQUENCE s5
CREATE SEQUENCE s6
START WITH 5
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
Cycle
Cache 9;
NoCache:
If sequence is created with NoCache,
When we call the sequence, ORACLE goes to
DB, identifies current value, adss increment
by value, returns sequential number.
CREATE SEQUENCE s8
ORACLE 7AM Page 211
CREATE SEQUENCE s8
START WITH 300
MINVALUE 100
MAXVALUE 500
INCREMENT BY 1
NoCache;
Cache <size>:
• If sequence is created using cache, every time it
will not go to database. Sequential Values will be
preloaded into cache memory. When we call the
sequence, sequential number will be returned
from cache.
• It improves the performance.
• Cache size must be less than one cycle.
• Default Cache size: 20
CREATE SEQUENCE s8
START WITH 300
MINVALUE 100
MAXVALUE 500
INCREMENT BY 1
Cache 100;
ALTERING SEQUENCE:
Syntax:
DROP SEQUENCE <seq_name>;
Ex:
DROP SEQUENCE s1;
user_sequences:
• It maintains all sequences information.
Desc user_sequences;
Materialized View:
• Materialized View is a DB object.
• M.View is not Virtual Table. It contains physical
data. It occupies the memory.
• M.VIEW holds result of SELECT query Whereas
VIEW holds SELECT query.
• It is used to improve the performance.
• It holds precomputed result.
• In DWH (DataWare Housing), to maintain
summarized tables physically, we use M.VIEW.
• VIEW gives recent data. Because, It holds
SELECT query. Materialized View gives
precomputed result. M.View does not give
recent data. That's why we need to refresh
M.View.
VIEW
Disadvantage:
• Less Performance
PERSON
CREATE VIEW v1
AS
SELECT state,count(*) FROM person
GROUP BY state;
v1
Advantages of M.View:
• Improves the performance.
• We can maintain a local copy of remote database.
V1 MV1
On DEMAND:
In this way, we need to call "refresh()" procedure
explicitly to refresh the m.view.
"refresh()" procedure defined in"dbms_mview" package.
Ex:
exec dbms_mview.refresh('MV2');
exec dbms_mview.refresh('MV2');
On COMMIT:
• In this way, when COMMIT is executed Materialized
view will be refreshed.
After 2 minutes:
SELECT * FROM mv4; --gives refreshed data
3 Refresh Types:
• Complete
• Fast
• Force
Complete:
deptno sum(sal)
10 10000
20 30000
30 15000
Fast:
• Only recent changes of base table will be
applied to m.view.
emp
mv2
empno ename deptno sal
10 6000 deptno sum(sal)
10 4000 10 10000
20 20000 20 30000
20 10000 30 15000
30 10000
30 5000 fast
10 20000 materialized view log
20 10000
user_mviews:
It maintains all materialized view
info.
DESC user_mviews;
Java Developer:
Synonyms:
• Synonym is a DB Object.
• Synonym is used to give alias name (alternative
name) to the database object.
• Synonym is permanent whereas Table alias or
column alias are temporary. Scope of Table alias or
column alias is limited to that query only. In another
query we cannot use those names.
Advantages:
• It makes table name short.
• It avoids of writing schema name.
Syntax:
Login as DBA:
Ex:
CREATE SYNONYM e FOR emp;
SELECT * FROM e;
Types of Synonyms:
2 Types:
• Private Synonym
• Public Synonym
Private Synonym:
Private Synonym is created by the user.
Syntax:
Ex:
CREATE SYNONYM d FOR dept;
Public Synonym:
It is created by DBA [DataBase Administrator]
Syntax:
c##batch2pm:
SELECT * FROM c##batch7am.emp;
c##batch6pm:
SELECT * FROM c##batch7am.emp;
c##ramu:
DBA:
DROP SYNONYM e;
user_synonyms:
It maintains all synonyms information
SQL
Tables
Views
Indexes
Sequences
Materialized Views
Synonyms