SQL Notes
SQL Notes
Notes Link:
https://bit.ly/oracle7am
Mahesh:
Whatsapp num: 81436 16558
Oracle7AM Page 2
Oracle
Wednesday, December 22, 2021 7:21 AM
Oracle:
SQL
PL/SQL
Data
Information
Database
DBMS
RDBMS
Metadata
Data:
• Data is a raw collection of facts about
people, places & things …etc.
• Raw => unordered [Not in Order]
Engine
Tyres
Connecting Bike
Seat
..
..
4567
1234
Srinu
Ravi
8000
500
MANAGER
Smartphone
nareshit
20000
floor 3
Samsung
room no 1
30.5
20.4
Data:
• Data is a raw collection of facts about people,
places & things …etc.
• Data is unprocessed one.
• Data is not in meaningful form.
Information
Data
Information:
Oracle7AM Page 3
Information:
If data is arranged in meaningful form then it is
called "information".
Data Information
Types of Data:
2 Types:
• Structured Data
• Unstructured Data
• Structured Data:
If data is in the form of letters, digits & special
symbols.
• Unstructured Data:
• Multimedia objects are comes under unstructured Data.
Database:
• Database is a collection of interrelated data in an
organized form.
• You can understand like complete details about
an organization.
Ex:
College DB
Student
sid sname city
Marks
sid M1 M2 M3 Tot Avrg Result
Fee
sid Fee Balance Total Fee
Amazon DB
Oracle7AM Page 4
Amazon DB
Customer
cid cname ccity mobile
Product
pid pname QIH Price
Orders
cid pid qty amount orddate deldate
Types of databases:
2 Types:
• OLTP
• OLAP
DBMS:
• DataBase Management System / Software.
• It is a software that is used to create &
maintain the Database.
• It allows us to store, manipulate & retrieve
the data of Database.
○ Manipulate = Insert + Update + Delete
○ Retrieve => Opening existing data
RDBMS:
• Relational DataBase management System
• Relation => Table FMS / FPS => 1960s
• In RDBMS, we maintain database in the form
of tables. Hierarchical => 1970s
Network
Ex:
Oracle => Oracle RDBMS => 1976 => E.F.Codd
SQL Server => Microsoft
Postgre SQL => PostGre 1979 => Oracle
DB2 => IBM
MySQL => Oracle
Oracle7AM Page 5
tables.
• Relation => Table
Table:
Table is a collection of rows & columns
where rows are the records & columns are
the fields.
Customer
cid cname ccity Table => Relation / Entity
1001 Raju Hyd
1002 Kiran Mumbai row => record / entity instance / tuple
Metadata:
•
Marks
Metadata:
• It is the data about the data.
• It describes about the data.
Ex:
Table Name
Field Name
Data Type
Field Size
Data
Information
Database
DBMS
RDBMS
Metadata
Oracle7AM Page 6
Metadata
ORACLE:
• is a Relational Database Management Software.
• Relation => Table
• In this, we create & maintain database in the form of
tables.
• It allows us to store, manipulate & retrieve the data of Larry Ellison
database.
• Manipulate = Insert + Update + Delete 1977 => Software Development Laboratories
• Retrieval => Opening existing data [Reading data] 1979 => Relational Software Inc.
• Oracle Database software's second version introduced in 1983 => Oracle Corp.
1979.
• Oracle Database latest version is Oracle 21C.
SQL:
• SQL stands for Structured Query Language.
a=10 fact
b=5
power
print a+b
print a-b sqrt
print a*b
SQL:
SQL stands for Structured Query Language.
Oracle7AM Page 7
• SQL stands for Structured Query Language.
• It is a Query Language. Oracle Server
• It is used to write the queries.
• Query is a request which is sent to Database
Server. request Instance DB
select
emp
empno,ename response
from emp; [query]
RAM Hard Disk
Client
SQL:
• Structured Query Language.
• It is a query language that is used to write the queries.
• Query is a request that is sent to DB Server.
• Ex: Select empno, ename from emp;
• Queries are written to communicate with Database. Procedure
• SQL is a Non-Procedural Language. We will not write any
set of statements. In C =>
• SQL is a 4GL [Generation Language]. We much Function => is a set of statements
concentrate on what to do rather than how to do.
• Ex: sqrt(100) In Java:
• SQL is a unified language. It is common for many Method => is a set of statements
relational databases like SQL Server, Postgre SQL,
MySQL ..etc.
• Ex:
SQL Server MYSQL Postgre SQL Oracle
+ >
SQL SQL SQL SQL
- >=
• SQL provides built-in [predefined] functions.
* <
• SQL provides operators to perform operations.
<=
• SQL provides Joins to work with multiple tables
• SQL provides Sub Queries.
SQL:
DDL
DML
DCL
TCL
DRL
DDL:
• stands for Data Definition Language
• It deals with metadata.
Create
Alter
Drop
Truncate
Rename
Flashback [Oracle 10g]
Purge [Oracle 10g]
metadata:
data about the data
emp
Ex: empno ename sal job
Table name 1234 Ravi 8000 manager
Field name
Data Type
Field size
Oracle7AM Page 9
Alter : change the structure of table
emp
empno ENAME job sal
DML:
• stands for Data Manipulation Language.
• Manipulation = Insert + Update +Delete
• It deals with the data.
emp
empno ename job sal
1001 Raju manager 10000
Insert
Update
Delete
Insert All [Oracle 9i]
Merge [Oracle 9i]
DRL / DQL:
• Data Retrieval Language / Data Query Language
• It deals with data retrievals
• Retrieval = opening existing data [reading the data]
SELECT
DCL / ACL:
• Data Control Language / Accessing Control Language
• It deals with data accessibility.
Grant
Revoke
GRANT
REVOKE
Oracle7AM Page 10
REVOKE
TCL:
• Transaction Control Language
• It deals with transactions.
Ex:
Transaction => a series of actions
Withdraw =>
read pin
check validity
sufficient bal
read amount
update bal
Deposit
Order
COMMIT
ROLLBACK
SAVEPOINT
DDL Commands:
Create:
• is used to create the database Database
objects like tables, views, Schema [user]
indexes ..etc. DB Objects
Table
View
Index
Sequence
Synonym
materialized view
< > => Any
function
[ ] => Optional
procedure
trigger
package
Oracle7AM Page 11
SQL provides following data types:
Number Related number(p) [Integer] Ex: 123
int
integer
nChar(n)
nVarchar2(n)
nCLOB
Date & Time related Date
Timestamp [Oracle 9i]
Binary related BFILE
BLOB
Number(p):
• It is used to hold integer type data.
• p => precision => Max number of digits
• p => valid range => 1 to 38
age empno
Examples:
------ -------------
17 1001
age Number(2) => -99 to 99 23 1002
18 1003
m1 Number(3) => -999 to 999
f1 number(38) =>
-999….99 [38digits] to 99999…99 [38 digits]
Number(p,s):
• used to hold floating point type data.
• p => precision => Total Number of Digits
• s => scale => Number of decimal places
• p => 1 to 38
• s => -84 to 127
Oracle7AM Page 12
avrg sal
Example: ---------- ----------
67.89 15000.00
avrg Number(5,2) => -999.99 to 999.99 54.23 12000.00
sal Number(8,2) => -999999.99 to 999999.99 89.61 100000.00
100.00
100000.00
char(n)
varchar2(n)
long
clob
nchar(n)
nvarchar2(n)
nclob
char(n):
• n => max number of characters
• used to hold a set of characters [strings].
• Fixed length data type
varchar2(n):
• n => max number of characters
• used to hold a set of characters [strings]
• Variable length data type
ename
---------
sai
arun
10 chardemo 3
10 4
10 f1 char(10) f2 varchar2(10) 6
sai7spaces sai
Ravi6spaces Ravi
Charan4spaces Charan
char(n):
• n => max number of characters
• used to hold a set of characters [strings].
• Fixed length data type
• default size: 1
• max memory: 2000 Bytes
Ex:
state_code char(2)
coutry_Code char(3)
section char
Oracle7AM Page 13
section char
varchar2(n):
• n => max number of characters
• used to hold a set of characters [strings]
• Variable length data type
• default size => no default size. we must specify
the size
• max memory => 4000 Bytes
char varchar2(n)
• max size => 2000 Bytes • max size => 4000 Bytes
''
E.F.Codd => RDBMS
null
12 Rules
0 => value
null => unknown => empty / blank
Note:
There should be difference between null and
' ' [space]
varchar data type was not following this
rule.
Oracle 7 version varchar2 data type
introduced. It treats null and ' ' [space] as
different.
In later versions, they changed meaning
varchar also.
In current versions, varchar and varchar2
Oracle7AM Page 14
In current versions, varchar and varchar2
both acts as same.
Oracle is suggesting that don't use "varchar"
data type. in future versions they may
change the meaning of varchar or they may
remove varchar type. It means, it is
deprecated data type.
long:
• it is used to hold a set of characters [string].
• max size: 2 GB
• It is outdated. Its better to avoid of using
long.
• We can take one field as a long type for a
table. we cannot take more than one field as
long type.
• We can use string functions on long data
type.
CLOB:
• Character Large Object.
• It is used to hold a set of chars [string].
• max size: 4GB
Ex: 2012-15
experience_summary 2015-17
Feedback
Complaints
Date:
• It is used to hold date values.
• It is fixed length data type. DOB
• default date format: dd-mon-rr. -----------
• It can hold date, month, year, hours, 23-dec-04
Oracle7AM Page 15
• It is used to hold date values.
• It is fixed length data type. DOB
• default date format: dd-mon-rr. -----------
• It can hold date, month, year, hours, 23-dec-04
minutes and seconds.
• default time values is 12.00.00 AM
[mid night]. hiredate
• It cannot hold milli seconds. -------------
• size: 7 Bytes
Ex:
DOB date
DOJ date
DOR date
Transaction_date date
RR
Timestamp:
• introduced in Oracle 9i version.
• It is an extension of date data type.
• date, month, year, hours, minutes, seconds &
milli seconds.
• size: 11 Bytes
Oracle7AM Page 16
Date Timestamp
7 Bytes 11 Bytes
BFILE
BLOB
BFILE:
• External Large Object.
• it maintains path only.
• Object will be stored out of the database.
• It is not secured.
D:
Oracle Database
emp_photos folder
1001.jpg file
emp
ephoto => BFILE
----------
Oracle DB
Oracle7AM Page 17
Oracle DB
emp
ephoto => BLOB
----------
12AB676C35556DA
Log in as DBA:
username: system
password: nareshit [password given at the time
of installation of oracle]
Ex-1:
Student
sid sname Marks Max marks: 1000
1001 Ravi 678
1002 Vijay 789
1003 Sravan 567
Creating Table:
Inserting Records:
1 row created
SQL> /
Enter value for sid:1004
Enter value for sname:sai
Enter value for marks:867
Ex-2:
Create table with following structure:
Employee
empid ename job sal doj
5001 Ramu clerk 7000 23-oct-20
5002 Srinu manager 12000 18-aug-18
Oracle7AM Page 19
job Varchar2(10),
sal Number(8,2),
doj Date
);
Note:
To insert date value, we use to_Date() function.
to_Date function converts string to date value.
It is called "Explicit Conversion".
If we don't use to_Date() function implicit
conversion will be done.
Constraint:
• Constraint is a rule applied on a column.
• It restricts the user from entering invalid data.
sid sname M1
1234 Ravi
Gender
--------------
M
F
Z => invalid
Constraint:
Online Bus Ticket Reservation
• Constraint is a rule applied on a column.
system
• It restricts the user from entering invalid data.
• Constraint is used to maintain data integrity.
seatnum
• Data Integrity means, maintaining accurate
----------------
& quality data.
51 => invalid
Constraints in SQL:
Oracle7AM Page 20
Constraints in SQL:
• Primary Key
• Unique
• Not Null
• Check
• Default
• References [Foreign key]
Primary Key:
• should not accept duplicate values.
• should not accept null values.
student
Unique:
• it should not accept duplicate values.
• it accepts the null values.
Customer
cid cname mail_id mobile_num aadhar_nu
m
1001 Ramu 90123 45678
1002 Srinu [email protected] 90123 45678
1003 Vijay [email protected] ……
Not Null:
• should not accept null values.
• accepts duplicate values.
emp
PK
empno ename
1001 Ravi
1002
1003 Ravi
Oracle7AM Page 21
Constraint Duplicate Null
Primary Key NO NO
Unique NO YES
Not Null YES NO
Check:
• It is used to apply our own rules on a
column.
Default:
• it is used to give default value to a column.
• When we don't give the value, this default
value will be taken.
• When all column values are same, it's better
to give default value.
emp
empno ename company_name company_Address nationality
1001 A nareshit ameerpet India
1002 B nareshit ameerpet India
student
sid sname group
EEE
EEE
EEE
Oracle7AM Page 22
Course
cid cname
10 Java
20 Python Student
30 HTML sid sname cid
40 C#.net 4001 A 30
4002 B 20
4003 C 40
4004 D 80
DEPT
deptno dname
10 SALES
20 ACCOUNTS
30 RESEARCH Emp
empno ename deptno
3001 A 20
3002 B 30
3003 C 30
3004 D 70
Examples on Constraints:
Std
sid sname M1
Null:
• Null is a value.
• It means empty or blank.
• When the value is unknown, then insert null
value.
• It is not equals to zero or space
Oracle7AM Page 23
• Implicit [insert limited column values]
Example on constraints:
emp1
empno ename sal aadhar cname ccity
6001 Ravi 7000 1234 nareshit hyd
6002 nareshit hyd
6003 nareshit hyd
empno => PK
ename => not null
sal => min 5000 max 100000.00
aadhar => unique
cname => default nareshit
ccity => default hyd
Oracle7AM Page 24
Error: check constraint violated
Course
cid cname Std
10 Python sid sname cid
20 Java 1001 Ravi 20
30 Oracle 1002 Srinu 30
1003 Charan 90 Invalid
SQL> /
Enter value for cid: 20
Enter value for cname: Java
SQL> /
Enter value for cid: 30
Enter value for cname: Oracle
CID CNAME
---------- ----------
10 Python
20 Java
30 Oracle
Oracle7AM Page 25
SQL> Insert into std values(2003,'C',90);
Error: Integrity constraint violated
dept emp2
deptno dname empno ename deptno
10 Sales 1234 A 10
20 Accounts 1235 B 30
30 Research 1236 C 80 invalid
Naming Constraints:
• Giving names to the constraints is called "Named
Constraints".
• If we don't give name to the constraint by default
oracle gives constraint name by prefixing a random
number with 'sys_c'.
• If we give constraint names oracle will not give
constraint names.
Ex:
Create table t1(f1 number(4) primary key);
User_Constraints:
All constraints information of user stored in
"User_Constraints".
Oracle7AM Page 26
Example on Naming Constraints:
student1
sid sname m1
DDL Commands:
Create
Alter
Drop
Truncate
Rename
Flashback
Purge
Alter:
• Alter => Change
• It is used to change structure of the table.
sid sname
Alter
sid sname m1
Oracle7AM Page 27
Alter:
• Alter => Change
• It is used to change structure of the table.
• Using "Alter" Command we can
○ Add the columns
○ Rename The Columns
○ Drop the Columns
○ modify the data types
○ modify the field sizes
○ add the constraints
○ rename the constraints
○ disable the constraints
○ enable the constraints
○ drop the constraints
add:
is used to add the columns.
Ex:
emp
empno ename sal
Syntax:
Alter tabe <name> add(field_Definitions);
Examples:
Adding one column:
Alter table emp add job varchar2(10);
rename column:
used to change name of existing column.
emp
empno ename Date_of_Joining
Syntax:
Alter Table emp rename column <old_name> to <new_name>;
Ex:
Alter Table emp rename column date_of_joining to doj;
Oracle7AM Page 28
drop column:
is used to drop (Delete) one column from existing table.
Syntax:
Alter Table <name> drop column <column_name>;
emp
empno ename job sal gender city
drop:
is used to drop one or multiple columns
Syntax:
Alter table <name> drop(<column_list>);
emp
empno ename job sal gender
emp
empno ename job
modify:
it can be used to change field size or data type.
empno [ Number(4) ]
--------------
hyd_1234
del_1235
mum_1236
Syntax:
Alter table <name> modify(<field_definitions>);
ename
-----------
ename
-------------
sai
raju
naresh
ravi
Oracle7AM Page 29
Add Constraint:
used to add the constraint to existing field.
emp
empno ename
Syntax:
Alter table <name> add constraint <con_name> <con_type>(<field_name>);
Rename Constraint:
used to change name of the constraint
Syntax:
Alter table <name> rename constraint <old_name> to
<new_name>;
Ex:
Alter table emp rename constraint con1 to emp_pk;
Disable Constraint:
used to disable the constraint. It means, temporarily
constraint will not work.
Syntax:
Alter table <name> disable constraint <con_name>;
Ex:
Alter table emp disable constraint emp_pk;
Enable Constraint:
used to enable the disabled constraints. It means,
again constraint will work. To enable it, data must
follow the properties of that constraint type.
Syntax:
Alter table <name> enable constraint <con_name>;
Ex:
Alter table emp enable constraint emp_pk;
Drop Constraint:
To drop [delete] the constraint permanently use it.
Syntax:
Alter table <name> drop constraint <con_name>;
Oracle7AM Page 30
Alter table <name> drop constraint <con_name>;
Ex:
Alter table emp drop constraint emp_pk;
Primary Key
Unique
Check
References [Foreign Key]
Default
Not Null
Ex:
create table customer
(
cid number(4) constraint cc1 Primary Key,
cname Varchar2(10) constraint cc2 not null
);
Ex:
std11
sid sname
sid => PK
Oracle7AM Page 31
Course12
Std12
cid cname
sid sname cid
10 Java
2001 A 20
20 Python
2002 B 30
30 C#
2003 C 50
Ex on Alter:
std13
sid sname
Desc std13;
o/p:
sid
sname
m1
Renaming a Column:
Oracle7AM Page 32
Dropping a Column:
Adding Constraint:
Note:
Using "add constraint", we can add table level
constraints [PK, U, C, R].
"modify" is used to add not null and default constraints
Disabling Constraint:
Enabling Constraint:
Dropping Constraint:
Create
Alter
Truncate
Oracle7AM Page 33
Truncate
Drop
Rename
Flashback
Purge
Truncate:
• is used to delete all records from table.
• It releases the memory.
Oracle DB
Tablespaces [DB File]
Segments
Extents => Extent = 8 Blocks [64KB]
Blocks [Pages] => 8KB
Data
Syntax:
Example:
Truncate table employee;
Drop
Flashback
Purge
Drop:
• used to drop [delete] the tables.
• When we delete the table it will be stored in
"recyclebin".
• "Recyclebin" concept introduced in Oracle 10g
version.
Syntax:
Oracle7AM Page 34
version.
Syntax:
Ex:
Drop Table employee;
Flashback:
• used to recollect the dropped tables from recycle bin.
Syntax:
Ex:
Flashback Table employee to before drop;
Example:
employee
drop table employee;
show recyclebin
Purge:
• is used to delete the table from recyclebin.
Syntax:
Ex:
Drop Table employee_old;
Purge Table employee_old;
[or]
Oracle7AM Page 35
Now, dropped object will not be
stored in recyclebin. It will be
dropped permanently.
Purge recyclebin;
Create
Alter
Truncate
Drop
Flashback
Purge
Rename
Rename:
is used to rename the database objects like
tables, vies ..etc
Syntax:
DDL
DRL => SELECT => Operators
DML
DCL
TCL
SQL
DDL
DRL / DQL
DML
DCL / ACL
Oracle7AM Page 36
DCL / ACL
TCL
English SQL
Sentences Queries
Words Clauses
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
DISTINCT
emp
empno ename job sal doj
1001 A .. 15000 ..
102 B 8000
1010 C 12000
SELECT empno,ename,sal
FROM emp
WHERE sal>10000;
SELECT:
this clause is used to specify column list
FROM:
this clause is used to specify table list
Oracle7AM Page 37
WHERE:
this clause is used to write the conditions on rows
SELECT empno,ename,sal
FROM emp
WHERE sal>10000;
FROM emp:
emp
empno ename job sal doj
1001 A .. 15000 ..
1002 B 8000
1003 C 12000
WHERE sal>10000:
SELECT empno,ename,sal:
Examples on SELECT:
SELECT *
FROM emp; -- * => All Columns
SELECT empno,ename,sal
FROM emp;
SELECT *
FROM emp
WHERE sal=3000;
SELECT empno,ename,sal
FROM emp
WHERE sal<1300;
Oracle7AM Page 38
WHERE sal<1300;
Operators in SQL:
• Operator is a symbol that is used to perform arithmetic or
logical operations.
Arithmetic + - * /
Relational / < > <= >= = != / <> / ^=
Comparison
Logical And Or Not
Special IN NOT IN
BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL
ANY
ALL
EXISTS
PIVOT
UNPIVOT
SET UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||
DUAL:
• is a dummy table created in the oracle database.
• it is used to work with non-database values.
Calculating 2+3:
2+3
-------
5
total value
--------------------
5
TOTAL VALUE
---------------------
5
Oracle7AM Page 39
to use multiple words as alias
student
sid sname M1 M2 M3
1 A 50 80 60
2 B 45 78 62
emp
empno ename job sal comm mgr hiredate deptno
7369 SMITH CLERK 800
Oracle7AM Page 40
7369 SMITH CLERK 800
Select empno,ename,
sal*0.1 as TA,
sal*0.2 as HRA,
sal*0.15 as DA,
sal*0.05 as ITAX,
sal+sal*0.1+sal*0.2+sal*0.15-sal*0.05 as GROSS
from emp;
Fee
sid sname total_fee paid_fee
101 A 15000 5000
Arithmetic: + - * /
no rows selected
Oracle7AM Page 41
string comparison is case sensitive
Logical Operators:
are used to perform logical operations like logical and,
logical or and logical not operations.
Oracle7AM Page 42
Not
Student
sid sname M1 M2 M3
1234 Ravi 60 90 70
1235 Kiran 70 30 50
gender
check(gender='M' OR gender='F')
-----------
M
F
Display all managers records who is earning more than 2800 and
who joined after apr 1981:
Oracle7AM Page 43
who joined after apr 1981:
Display the emp records who are working in deptno 10 and 20:
Display the emp records whose empnos are 7499, 7521, 7788:
Condn Not
T F
F T
Special Operators:
IN:
• used to compare column value with a list of values
• If column value existed in list of values then record
will be retrieved.
• it avoids of writing multiple equality conditions
using or.
Syntax:
column_name IN(value_list);
Ex:
Deptno IN(10,30);
Oracle7AM Page 44
Display the emp records who are working in
10,20,50,60,80 depts:
Between And:
• It is used to compare column value with a range of values
• If column value falls under the range then record will be
retrieved.
Syntax:
column_name Between min_value And max_value
Ex:
sal BETWEEN 1000 and 2000
Display the emp records who are not joined from 1982 to
1984:
Select * from emp
where hiredate not between '1-JAN-1982' and '31-DEC-1984';
Oracle7AM Page 45
where hiredate not between '1-JAN-1982' and '31-DEC-1984';
Arithmet + - * /
ic
Relation > >= < <= = <>
al
Logical And Or Not
Special IN NOT IN
Between And
IS NULL IS NOT NULL
IS NULL:
• is used to compare column value with null value
• For Null comparison we cannot use comparison
operator ( = ).
= comparison operator
Syntax:
column_name IS NULL
Like:
• is used to compare column value with text pattern.
d: wildcard characters:
all jpg images
* 0 or any number of chars
*.jpg
? replaces 1 char
*.*
Oracle7AM Page 46
all jpg images
* 0 or any number of chars
*.jpg
? replaces 1 char
*.*
s*.jpg
?a*.jpg
Syntax:
column_name like text_pattern
JAMES
ALLEN
Oracle7AM Page 47
Display the emp records whose names are having 4 chars:
mailid
------------
[email protected]
[email protected]
Oracle7AM Page 48
Display the emp records whose names are
having _:
Select * from emp
where ename like '%\_%' ESCAPE '\';
"steve" \\ \
\" "
Concatenation Operator :
Symbol => ||
Ex:
Raj Kumar
Customer
Cid Fname Lname
1234 Sai Kumar
1235 Ravi Teja
1236 Sravan Kumar
name
……
Sai Kumar
Ravi Teja
Oracle7AM Page 49
DML Commands
Wednesday, January 19, 2022 7:23 AM
SQL:
5 sub languages:
DDL => C A D T R F P
DRL => SELECT
DML
DCL
TCL
TCL Commands:
• Transaction Control Language
• COMMIT
• ROLLBACK
• SAVEPOINT
COMMIT [SAVE]:
• used to save the transaction.
insert
insert
rollback => used to cancel the previous actions
Note:
DDL commands are auto-committed
DML commands are not auto-committed
Oracle7AM Page 50
DML Commands:
• Data Manipulation Language
• Manipulation = Insert or Delete or Update
• Ex:
• emp joined => INSERT
• emp left => DELETE
• emp got promotion => UPDATE [modify]
• DML commands deal with data.
• DML commands are used to manipulate the data.
• DML commands are not auto-committed.
• After using DML command
○ to save the transaction we use "COMMIT"
○ to cancel the transaction we use "ROLLBACK"
COMMIT [SAVE]:
• is used to save the transactions.
• when commit is executed, the changes of oracle
instance [RAM] will be applied to Oracle Database
[Hard Disk].
• After commit, we cannot use rollback.
• Rollback is applied on Oracle Instance. Not on
Database.
• INSERT
• DELETE
• UPDATE
• INSERT ALL
• MERGE
INSERT:
• used to insert the records
• using this command we can
○ insert single record
○ insert records using parameters
○ insert limited column values
○ insert column values by changing the order
○ insert records from existing table
Syntax:
Example:
Customer
cid cname ccity
101 Ravi Hyd
102 Kiran Chennai
Oracle7AM Page 51
);
/
Enter value for cid:
Enter value for cname:
Enter value for ccity:
Syntax:
Insert into table_name(column_list)
select query;
DELETE:
• is used to delete the records.
• Using this command we can
○ delete single record
○ delete a set of records
○ delete all records
○ delete records using parameters
Syntax:
Oracle7AM Page 52
Syntax:
Delete from <table_name>
[WHERE <condition>];
EMP
empno ename job sal
7900 … .. …
/
Enter value for empno:7521
Delete emp records who are working in 10th dept & 3oth
dept:
UPDATE:
Oracle7AM Page 53
UPDATE:
• is used to modify [update] the data.
• Using this command we can
○ update single column value of single record
○ update multiple column values of single record
○ update a set of records
○ update all records
○ update the records using parameters
Syntax:
Update <table_name>
Set <column_name>=<value>[,<col>=<value>,…….]
[Where <condition>];
Update emp
Set sal=sal+2000
where empno=7698;
Update emp
set job='MANAGER', sal=sal+sal*0.2
where empno=7876;
Update emp
set sal=sal+sal*0.2, comm=comm+comm*0.15
where comm is not null;
Oracle7AM Page 54
Updating records using parameters:
/
Enter value for amt:3000
Enter value for empno:7902
student
sid sname M1 M2 M3 Total Avrg
5001 A 60 50 80
5002 B 75 40 39
…
Emp1
empno ename job sal TA HRA DA TAX GROSS
1001 A clerk 5000
1002 B manager 10000
Oracle7AM Page 55
Create table emp1
(
empno number(4),
ename varchar2(10),
job varchar2(10),
sal number(8,2),
ta number(8,2),
hra number(8,2),
da number(8,2),
tax number(8,2),
gross number(10,2)
);
DML DDL
----- -----------
INSERT Create
DELETE Alter
UPDATE Drop
Truncate
INSERT ALL Rename
MERGE Flashback
Purge
Oracle7AM Page 56
DELETE TRUNCATE
std
sid sname scity
1001 A Hyd
1002 B Chennai
SQL
DDL C A D T R F P
DRL SELECT
DML I D U IA M
TCL Rollback Commit Savepoint
DCL Grant Revoke
TCL Commands:
• Transaction Control Language
• It deals with transactions.
• Transaction => is a series of commands
• Ex: withdraw deposit placing order
withdraw :
• read card info
• pin valid or not
• display the menu
• selecting withdraw
• entering amount
• checks sufficient balance is there
updaes ur account balance
Oracle7AM Page 57
• updaes ur account balance
Commit [Save]:
• used to apply the changes to oracle database.
• to make changes permanent, use it.
SavePoint:
• is used to set margin for the rollback.
Syntax:
Savepoint <savepoint_name>;
EMP
SQL
DDL
DRL
DML
TCL rollback commit savepoint
DCL:
• Data Control Language
• It deals with data accessibility.
GRANT
select => displays
REVOKE
Oracle7AM Page 58
SQL provides 2 DCL commands. They are:
• GRANT
• REVOKE
• GRANT:
• is used to give [grant] permission to other users on
DB objects like tables, views …etc.
Syntax:
Grant <priviliges_list> ON <table_name>
to <users_list>;
Ex:
privileges GRANT select, insert, update
SELECT ON emp
INSERT TO c##ravi;
DELETE
UPDATE
ALL
Revoke:
• is used to cancel the permissions from other users
Syntax:
Revoke <privileges_list> ON <table_name>
FROM <user_list>;
Creating user:
there are 2 types of users:
• common user => can access any DB data
• to create common user, user name must be prefixed
with 'c##' [c => common user]
• Ex: c##raju
Creating user:
"system" tablespace
Log in as DBA:
username: system
Every table space is a file
password: nareshit
file extension is ".DBF"
Create user c##usera
identified by nareshit
default tablespace users
quota unlimited on users;
Oracle7AM Page 59
Grant connect,resource to c##usera;
c##usera c##userb
std
Select * from c##usera.std;
sid sname
1 A ERROR: Insufficient privileges
2 B
displays records
displays records
SELECT
INSERT
DELETE
UPDATE
Oracle7AM Page 60
USERA USERB
Batch7AM
Create std
c##usera:
Grant all on std
to c##userb
with grant option;
Insert All
Merge => Oracle 9i
Insert All:
• used to insert multiple records in multiple
tables or in single table using one query.
• it avoids of writing multiple insert commands.
Oracle7AM Page 61
• unconditional insert all:
• Syntax:
insert all
into <table_name>[(<column_list>)] values(<value_list>)
into <table_name>[(<column_list>)] values(<value_list>)
..
..
<Select query>;
Insert All
into emp(empno,ename) values(1,'A')
into emp(empno,ename) values(2,'B')
into emp(empno,ename) values(3,'C')
Select * from dual;
emp empdemo
empno ename job sal empno ename job sal
1001
1002
1010
Insert into empdemo
select empno,ename,job,sal from emp;
emp emp1
empno ename job sal empno ename job sal
1001
1002
emp2
1010 empno ename job sal
emp3
empno ename job sal
Insert All
into emp1(empno,ename,job,sal) values(empno,ename,job,sal)
into emp2(empno,ename,job,sal) values(empno,ename,job,sal)
into emp3(empno,ename,job,sal) values(empno,ename,job,sal)
Select empno,ename,job,sal from emp;
Syntax:
Create table <table_name>
As
<Select query>;
Oracle7AM Page 62
emp => is existed table with 10 records
create "empdemo" table with records =>
Case-2:
Creating table from existing table without records:
Ex on Insert All:
Insert All
into emp1 values(empno,ename,job,sal)
into emp2 values(empno,ename,job,sal)
into emp3 values(empno,ename,job,sal)
Select empno,ename,job,sal from emp;
Replication:
Oracle7AM Page 63
Replication:
is the process of making multiple copies of db
objects like tables.
Replica:
Duplicate copy is called "Replica".
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>;
Emp emp_Clerk
empno ename job sal empno ename job sal
clerk
manager
clerk emp_mgr
manager
analyst
emp_others
empno ename job sal
Insert All
When job='CLERK' Then
into emp_clerk values(empno,ename,job,sal)
When job='MANAGER' Then
into emp_mgr values(empno,ename,job,sal)
Else
into emp_others values(empno,ename,job,sal)
Select empno,ename,job,sal from emp;
Oracle7AM Page 64
Assignment:
Assignment:
Copy the emps who joined in 1981 to emp1981 table
Copy the emps who joined in 1982 to emp1982 table
Copy other than 1981,1982 to emp_other table
Merge:
Merge => Combine
• is a combination of Update & Insert
Commands.
• It can be also called as "UPSERT"
command.
• is used to apply the changes of a
table to its replica [duplicate copy]
OLTP OLAP
Customer1 Customer2
cid cname ccity cid cname ccity
1 A Bangalore [Update] 1 A Hyd
2 B Mumbai 2 B Mumbai
3 C Delhi 3 C Delhi
4 D Kolkata [Insert]
Syntax:
Merge into <target_table_name> <alias>
Using <source_table_name> <alias>
On(<condition>)
When MATCHED Then
UPDATE query
When NOT MATCHED Then
INSERT query ;
Ex on "MERGE":
Customer1
Customer2
cid cname ccity
cid cname ccity
1 A Hyd
1 A Hyd
2 B Mumbai
2 B Mumbai
3 C Delhi
3 C Delhi
Oracle7AM Page 65
cname varchar2(10),
ccity varchar2(10)
);
SQL:
DDL Create
Alter
Truncate
Drop
Rename
Flashback [10g]
Purge [10g]
DRL Select
DML INSERT
UPDATE
DELETE
Oracle7AM Page 66
Built-in Functions
Tuesday, January 25, 2022 8:01 AM
Built-In Functions:
• Function is a set of statements that gets
executed on calling.
• Oracle developers already defined some functions
and placed them in oracle database. These are
called "Built-In Functions / Predefined Functions".
• A function can take arguments & return the value.
• Every function is defined to perform particular
task.
• String Functions
• Aggregate [Group] Functions
• Conversion Functions
• Math Functions
• Date Functions
• Miscellaneous Functions
• String Functions:
lower()
upper()
initcap()
length()
concat()
substr()
raj kumar
instr()
ltrim()
rtrim()
trim()
lpad()
rpad()
replace()
translate()
reverse()
soundex()
Oracle7AM Page 67
soundex()
ascii()
chr()
Lower():
returns string in lower case [small letters]
Syntax:
Lower(<string>)
Ex:
Lower('RAMU') => ramu
Upper():
reruns string in upper case[all capital letters]
Syntax:
Upper(<string>)
Ex:
Upper('ramu') => RAMU
Initcap():
Syntax:
Initcap(<string>) Intial letter capital
Ex:
Initcap('RAMU') => Ramu
Initcap('RAVI TEJA') => Ravi Teja
Oracle7AM Page 68
length():
returns length (no of chars) of the
string.
Syntax:
length(<string>)
Ex:
length('ramu') => 4
length('sai') => 3
length('ravi teja') => 9
Concat():
used to concatenate [combine] 2 strings.
Syntax:
Concat(<string1>,<string2>)
Ex:
Concat('ravi','teja') => raviteja
Concat(Concat('ravi',' '),'teja') => ravi teja
Oracle7AM Page 69
Ex:
Concat('ravi','teja') => raviteja
Concat(Concat('ravi',' '),'teja') => ravi teja
ename
-----------
WARD
ALLEN
BLAKE
Ex:
Player
pid fname lname PName
5001 sachin tendulkar Sachin Tendulkar
5002 rahul dravid
5003 virat kohli
5004 rohit sharma
Oracle7AM Page 70
Alter table player add pname varchar2(20);
display the player records whose names are having more than 12
chars:
substr():
is used to get substring from the string.
Syntax:
substr(<string>,<position>[,no_of_chars])
Examples:
1 2 3 4 5 6 7 8 9
r a v i t e j a
-9 -8 -7 -6 -5 -4 -3 -2 -1
aadhar card:
Oracle7AM Page 71
in name first 4 chars, in dob year 4 chars
aadhar
name dob password
--------------------- ------------ ----------------
ravi teja 23-oct-1998 ravi1998
generate email ids for all players with their name's first 5
chars & their id's last 3 chars:
Oracle7AM Page 72
Instr():
used to search for sub string in the string.
Default position value : 1
Default occurrence value : 1
If substring existed in the string it returns position.
If substring not existed in the string it returns 0.
Syntax:
Instr(<string>,<substring>[,<position>,<occurrence>])
Ex:
Instr('Ravi Teja','Teja') =>
t h i s i s h i s w i s h
Oracle7AM Page 73
Display the employee records which are
having 'AM' characters:
Lpad():
pad => fill
is used to fill specified characters from left side.
default char [3rd argument] is: space
Syntax:
Lpad(<string>,<size>[,<char_set>]);
Ex:
Lpad('Ravi',10) => 6spacesRavi
Rpad():
is used to fill specified chars from right side.
default char is: space
Oracle7AM Page 74
default char is: space
Syntax:
Rpad(<string>,<size>[,<char_set>])
Acno
--------
1234567890
XXXXX7890
Oracle7AM Page 75
Ltrim(), Rtrim() & Trim():
Syntax:
Ltrim(<string>[,<char_set>])
Rtrim():
used to remove unwanted chars from right side.
default char is: space
Syntax:
Rtrim(<string>[,<char_set>])
trim():
used to remove unwanted chars from left side or right
side or both sides.
Syntax:
trim(leading / trailing / both <char_set> from <string>
Examples:
Ltrim(' NARESH ') => NARESH5spaces
Ltrim('@@@NARESH@@@','@') => NARESH@@@
Reverse():
used to reverse a string.
Oracle7AM Page 76
used to reverse a string.
Syntax:
Reverse(<string>)
Ex:
Reverse("ramu") => umar
Replace():
is used to replace search string with replace string.
Syntax:
Replace(<string>,<search_String>,<replace_string>)
Ex:
Replace('Ravi teja','Ravi','Sai') -> Sai teja
Replace('Ravi teja','teja','kumar') -> Ravi kumar
Translate():
is used to translate each occurrence of char with
corresponding char.
Syntax:
Translate(<string>,<from_String>,<to_string>)
Ex:
Translate('hello have a nice day','helo','abcd')
Replace('abcdxyzabcdaabbccxxyyzz','abc','PQR')
Translate('abcdxyzabcdaabbccxxyyzz','abc','PQR')
Oracle7AM Page 77
ASCII():
used to know ASCII value of particular char.
Syntax:
ASCII(<char>)
Ex:
ASCII('A') => 65 ASCII('a') => 97
ASCII('B') => 66 ASCII('b') => 98
ASCII('Z') => 90 ASCII('z') => 122
Chr():
is used to get character of specified ascii value
Syntax:
Chr(<number>)
Ex:
Chr(65) => A
Chr(97) => a
Soundex():
This function is used to get records based on
pronunciation.
Syntax:
Soundex(column_name)
Ex:
Display the emp record whose name is smith:
Oracle7AM Page 78
Aggregate [group] functions:
multi-row function:
it is applied on multiple rows [set of values]
Sum()
Avg()
Min()
Max()
Count()
Sum():
is used to find sum of column values.
Syntax:
Sum(<column_name>)
Ex:
Sum(Sal) => 23000
Sal
5000
10000
8000
Avg():
is used to find average value of a
21000/3 = 7000
column.
Oracle7AM Page 79
Syntax:
avg(<column_name>)
Sal
Ex:
---------
avg(Sal) => 7000
10000
5000
6000
Min():
used to minimum value in a
column.
Syntax:
Min(<column_name>)
Sal
Ex:
---------
Min(Sal) => 5000
10000
5000
6000
Max():
is used to find max value in a column
Syntax:
Max(<column_name>)
Ex:
Max(Sal) => 10000 Sal
---------
10000
5000
6000
Count():
is used to count number of column
values or number of records
Syntax:
Count(<column_name> / *)
Ex:
Sal
Count(sal) => 3 [counts not nulls]
---------
10000
Oracle7AM Page 80
Ex:
Sal
Count(sal) => 3 [counts not nulls]
---------
10000
Count(*) => 4 [counts no of records]
5000
null
6000
count(*) VS count(1):
job
--------
CLERK CLERK
CLERK MANAGER
MANAGER SALESMAN
SALAESMAN ANALYST
MANAGER
ANALYST
MANAGER
Oracle7AM Page 83
• The result of inner query becomes input for the outer
query
• Inner query must be written in parenthesis.
• Inner query is always SELECT query. It cannot be
INSERT / UPDATE / DELETE.
• Outer query can be INSERT / UPDATE / DELETE /
SELECT.
• upto 255 levels we can write the nested queries.
power():
used to find power values.
Syntax:
power(<number>,<power>)
Ex:
power(2,3) => 8
power(5,2) => 25
sqrt():
is used to find square root values
Syntax:
sqrt(<number>)
Ex:
sqrt(100) => 10
sqrt(81) => 9
sin():
is used to find sine values
Oracle7AM Page 86
is used to find sine values
Syntax:
sin(<angle>)
cos():
is used to find cosine values
Syntax:
cos(<angle>)
tan():
is used to find tangent values
Syntax:
tan(<angle>)
Note:
angle in the form of radians
Ex:
sin(90*3.14/180) degrees to radians:
cos(0*3.14/180)
tan(45*3.14/180) radians = degrees * pi/180
sign():
is used to know the sign of the number. it is
used to know whether number is +ve or -ve or
zero.
Syntax:
sign(<number>)
Ex:
sign(5) => 1
sign(-5) => -1
sign(0) => 0
mod():
IN Java:
is used to find remainder values
% => modulus
Syntax:
mod(<number>,<divisor>)
Oracle7AM Page 87
Ex:
mod(20,2) => 0
mod(20,3) => 2
log():
is used to find logarithmic values.
Syntax:
log(<number>,<base>)
log(10,10) => 1
ln():
is used to find natural logarithmic
values.
Syntax:
ln(<number>)
ln(7)
abs():
is used to get absolute value.
Syntax:
abs(<number>)
Ex:
abs(5) => 5
abs(-5) => 5
ceil():
used to get upper integer value.
Oracle7AM Page 88
used to get upper integer value.
Syntax:
ceil(<number>)
floor():
used to get lower integer value.
Syntax:
floor(<number>)
trunc():
is used to remove decimal places.
Syntax:
trunc(<number>[,<number_of_decimal_places>])
Ex:
trunc(123.45678) => 123
Round():
is used to get rounded values.
If value is .5 or greater than .5. it takes upper
value.
If value is less than .5, then it takes lower value.
Syntax:
Round(<number>[,<number>])
Ex:
Round(123.4567) => 123
Round(123.6789) => 124
Round(123.5678) => 124
Number(p,s)
Conversion Functions:
Implicit conversion:
If conversion is done implicitly by oracle then it is
called "Implicit Conversion".
Exs:
Select '100'+'200' from dual;
Oracle7AM Page 91
Select '100'+'200' from dual;
300
Explicit conversion:
The conversion which is done explicitly by using
built-in function is called "Explicit Conversion".
char
date number
Syntax:
to_char(date,format)
Oracle7AM Page 92
to_char(date,format)
Oracle7AM Page 93
AD / BC for AD or BC
Oracle7AM Page 94
Select to_Char(sysdate,'dd') from dual;
01
getting quarter:
jan-mar => 1st quarter
apr-jun => 2nd quarter
Select to_Char(sysdate,'q')
jul-sep => 3rd
from dual;
oct-dec => 4th
1
getting century:
Oracle7AM Page 95
Select ename,
to_char(hiredate,'dd/mm/yyyy') as hiredate
from emp;
Select ename,
to_char(hiredate,'mm/dd/yyyy') as doj
from emp;
Select ename,
to_char(hiredate,'mm/dd/yyyy dy') as doj
from emp;
Syntax:
to_char(number,format)
Oracle7AM Page 96
$5000.00
Log in as DBA:
to_date():
used to convert the string to date.
Syntax:
to_date(string,format)
Oracle7AM Page 97
Insert into emp(empno,ename,hiredate)
values(5678,'Ravi','25-nov-2019');
to_number():
used to convert string to number.
string must be numeric string.
'123' => numeric string
Oracle7AM Page 98
'123' => numeric string
'raju' => not numeric string
Syntax:
to_number(string,format)
Oracle7AM Page 99
Display the emp records who joined in december:
no rows selected
Date Functions:
TO_CHAR(SY
----------
02/02/2022
TO_CHAR(
--------
07:48 AM
Add_Months():
This function is used to add months to a date
or subtract months from a date.
Syntax:
Add_Months(date,number_of_months)
emp
empno ename dob doj dor
23-dec-2000
India_CMs
Last_day():
is used to get last day in the month.
Syntax:
Last_day(date)
28-feb-22
Last_day(Add_months(sysdate,-2))+1
Next_day():
it is used to find next coming weekday date.
Syntax:
Next_Day(date,weekday)
Next_day(sysdate,'sun')
Next_day(Last_day(sysdate),'sun')
Select
Next_day(Last_day(Add_months(sysdate,-1)),'sun')
from dual;
Syntax:
Months_Between(date1,date2)
Select
trunc(Months_Between(sysdate,'24-apr-1973')/12) age
from dual;
Select
Months_Between('12-dec-2020','12-jun-2020')
from dual;
Miscellaneous:
Greatest =>
is used to find greatest in specified values
Least =>
is used to get least value in a set of values
Least(40,59,89,24,101,35) => 24
NVL
NVL2
Rank
Dense_Rank
NVL():
used to replace null value with another value.
Syntax:
NVL(value1,value2)
Select ename,sal,comm,
sal+NVL(comm,0) as "tot sal" from emp;
Student
sid sname m1
1001 Ravi 45
1002 Kiran
1003 Ramu 30
1004 Sravan
Select sid,sname,NVL(to_Char(m1),'AB') m1
from student;
NVL2():
is used to replace null values and not null values
with other values.
Syntax:
NVL2(value1,value2,value3)
value1 => is not null, it returns value2
value1 => is null, it returns value3
comm
Oracle7AM Page 107
comm
500 + 250 = 750
null = 550
Rank():
used to apply ranks to column values
Ex:
750
970
950
970
950
890
950
650
Dense_Rank():
used to apply ranks to column values
Ex:
750
970
950
970
950
890
950
650
Syntax:
Rank() over(order by <column_name> asc/desc)
sal
---------
4000
5500
3000
5500
4000
4000
2500
Select ename,sal,
Rank() over(Order By sal desc) as Rank
from emp;
Select ename,sal,
Dense_Rank() over(Order By sal desc) as Rank
from emp;
Select ename,sal,hiredate,
dense_rank() over(order by sal desc,hiredate asc) as rank
from emp;
RowID:
used to get row address
trunc(sysdate)
emp
Interval Expressions:
• introduced in Oracle 9i version.
• we can add days, months, years to a date value
(or) we can subtract days, months, years from
date value.
• we can also add hours, minutes, seconds to a
time value or subtract hours, minutes, seconds
from time value.
• EX: sysdate+interval '1' day
Display the emp records who joined 1 month ago from today's
date:
Display the emp record who joined 1 year ago from today's
date:
Flashback Query:
• This feature introduced in Oracle 10g version.
• It is used to recollect the data which is existed
some time ago. To recollect the past data we use
it.
• "AS OF TIMESTAMP" clause used for FLASHBACK
QUERY.
• After commit also we can recollect the data by
using this FLASHBACK QUERY.
Log in as DBA:
Case Expressions:
• introduced in Oracle 9i version.
• are used to implement "if-then-else'.
• It avoids of writing a procedure in which we write 'if-
then-else' code.
Simple Case:
Syntax:
Case <column_name>
WHEN <value-1> THEN <return_expression>
WHEN <value-2> THEN <return_expression>
.
.
Else
<return_expression>
End
Searched Case:
Syntax:
Case
WHEN <condition-1> THEN <return_expression>
WHEN <condition-2> THEN <return_expression>
.
.
Else
<return_expression>
End
Select ename,sal,deptno,
Case deptno
When 10 Then sal+sal*0.1
When 20 Then sal+sal*0.2
When 30 Then sal+sal*0.15
Else sal+Sal*0.05
End As "Incr salary"
from emp;
Searched Case:
Syntax:
Case
WHEN <condition-1> THEN <return_expression>
WHEN <condition-2> THEN <return_expression>
..
..
Else <return_expression>
End
Select ename,sal,
Case
WHEN sal>3000 THEN 'HiSal'
WHEN sal<3000 THEN 'LoSal'
Oracle7AM Page 119
WHEN sal<3000 THEN 'LoSal'
WHEN sal=3000 THEN 'AvrgSal'
End as "salary"
From emp;
Student
max marks: 100
sid sname M1 M2 M3
min marks: 40 in each sub
1001 A 50 70 60
1002 B 65 35 81
Select sid,sname,
Case
WHEN m1>=40 And m2>=40 And m3>=40 Then 'PASS'
Else 'FAIL'
End as Result
From Student;
m1<40 Or m2<40 Or m3<40
In Oracle SQL,
we can implement if-then-else using 2 ways:
• Case Expression [from oracle 9i onwards]
• Decode() Function [till oracle 8i we were using]
Syntax:
Decode(<column>,
<column_value1>,<return_value1>,
<column_value2>,<return_value2>,
..
.. ,
<else_return_value>)
Select ename,
Case Job
When 'MANAGER' Then 'BOSS'
When 'PRESIDENT' Then 'BIG BOSS'
When 'CLERK' Then 'WORKER'
Else 'EMPLOYEE'
End as Job
from emp;
Decode() Function:
Select ename,
Decode(Job,
'MANAGER','BOSS',
'CLERK','WORKER',
'PRESIDENT','BIG BOSS',
'EMPLOYEE') as Job
from emp;
Select ename,deptno,sal,
Decode(Deptno,
10,sal+sal*0.1,
20,sal+sal*0.2,
30,sal+sal*0.15,
sal+sal*0.05) as "Incr_Sal"
from emp;
My SQL
Assignment:
Case to_char(hiradate,'yyyy')
when 1980 then
when 1981 then
English SQL
Sentences Queries
Words Clauses
Clauses:
• Clause means, it is part of SQL query.
• SELECT
• FROM
• WHERE
• DISTINCT
• GROUP BY
• HAVING
• ORDER BY
SELECT empno,ename,sal
FROM emp
WHERE sal>5000;
SELECT clause:
is used to specify column list.
FROM clause:
is used to specify table list.
WHERE clause:
is used to write the condition on rows.
EXECUTION ORDER:
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
emp
empno ename job sal
1 A clerk 7000
2 B manager 10000
3 C clerk 4500
4 D salesman 4000
5 E manager 9000
FROM emp:
SELECT empno,ename,sal:
DISTINCT:
• is used to avoid duplicate rows.
COURSE
display the course list which are
Cname
offered by the institute:
------------
Java
Select DISTINCT cname
Python
from course;
Python
Java
Java
HTML
Python
HTML
HTML
Java
Python
ORDER BY:
it is used to arrange the records in ascending or
descending order according to specific column /
columns.
Select empno,ename,sal
from emp
Order By ename; --default => Asc
(or)
Select empno,ename,sal
from emp
Order By ename Asc;
Select empno,ename,sal
from emp
order by sal desc;
Select empno,ename,sal
from emp
order by sal desc nulls last;
Select empno,ename,sal
from emp
order by sal nulls first;
emp
empno ename hiredate sal
1001 A 23-AUG-2020 8000
1002 B 17-NOV-2019 10000
1003 C 18-OCT-2021 8000
1004 D 25-DEC-2018 10000
EX:
emp
empno ename hiredate sal
1001 A 23-AUG-2020 8000
1002 B 17-NOV-2019 10000
1003 C 18-OCT-2021 8000
1004 D 25-DEC-2018 10000
1005 E 17-NOV-2019 10000
Select empno,ename,hiredate,sal
from emp
order by sal desc, hiredate asc,empno asc;
Assignment:
Select empno,ename,sal
from emp
order by 2; --2 => ename
Select empno,ename,sal
from emp
order by 3 desc;
Group By Deptno
Group By:
• is used to group the records according to
specific column / columns. emp
• If column values are same, it will be empno ename sal deptno
treated as one group.
1001 A 5000 20 deptno sum(Sal)
• It converts detailed data to summarized
1002 B 8000 20 20 13000
data.
• We can apply aggregate functions on 1003 C 10000 30 30 22000
group of records. 1004 D 12000 30 10 30000
• It is used for data analysis. 1005 E 20000 10
1006 F 10000 10
emp
empno ename sal deptno
1001 A 5000 20 deptno sum_of_Salaries
1002 B 8000 20 20 13000
1003 C 10000 30 30 22000
1004 D 12000 30 10 30000
1005 E 20000 10
1006 F 10000 10
Order of Execution:
FROM
SELECT Deptno,Sum(Sal) as sum_of_Sal
WHERE
FROM emp
GROUP BY
WHERE deptno IN(10,20)
HAVING
GROUP BY deptno
SELECT
Order By 1;
ORDER BY
FROM emp:
selects entire table
emp
empno ename sal deptno
1001 A 5000 20
1002 B 8000 20
1003 C 10000 30
1004 D 12000 30
1005 E 20000 10
1006 F 10000 10
1001 A 5000 20
GROUP BY deptno:
it groups the records according to deptno
1001 A 5000 20
1002 B 8000 20
1005 E 20000 10
1006 F 10000 10
deptno sum_of_sal
20 13000
10 30000
ORDER BY 1 [deptno]:
arranges records in ascending order according to
1st column deptno
deptno sum_of_sal
10 30000
20 13000
Output:
Year No_of_emps
1980 2 SELECT to_char(hiredate,'yyyy') Year,
1981 5 count(*)no_of_emps
FROM emp
1982 3
GROUP BY Year
1983 4
Order By Year;
Note:
We can use Alias name in "Order By".
We cannot use Alias name in "Group By"
Because,
GROUP BY gets executed before SELECT.
In SELECT we are giving the alias name. So,
GROUP BY will not identify this alias name.
quarter no_of_emps
SELECT to_char(hiredate,'q') quarter,
1 4
count(*) no_of_emps
2 8 FROM emp
3 2 GROUP BY to_char(hiredate,'q')
4 5 ORDER BY 1;
sal_range no_of_emps
hisal 3
losal 5
avgsal 2
Select
Case
When sal>3000 Then 'HiSal'
When sal<3000 Then 'LoSal' sal
When sal=3000 Then 'AvgSal' -----
End as sal_range, 5000
count(*) 2500
from emp 3000
Group By 4500
Case 2800
When sal>3000 Then 'HiSal' 6000
When sal<3000 Then 'LoSal'
When sal=3000 Then 'AvgSal'
End;
Job sum_of_Salaries
Clerk 10000
Manager 25000
Analyst 18000
emp
empno ename job sal
1001 CLERK 4000
1002 CLERK 6000
1003 ANALYST 7000
1004 ANALYST 5000
1005 MANAGER 8000
1006 MANAGER 9000
Job No_of_emps
CLERK 2
MANAGER 3
ANALYST 5
SALAESMAN 4
HAVING clause:
• It is used to the write the conditions on
group of records.
• Using this, on result of GROUP BY we can
apply the conditions.
• It Cannot be used without GROUP BY.
SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno
HAVING sum(Sal)>30000;
deptno sum_of_Sal
10 30000
20 25000
30 40000
Emp
Empno Ename Deptno Job Sal
10 CLERK
1001 10 CLERK
10 MANAGER
10 CLERK
20 MANAGER
20 CLERK
20 CLERK
20 CLERK
10 MANAGER
10 MANAGER
20 MANAGER
20 MANAGER
break on deptno
Rollup():
It calculates sub totals & grand totals according to
first column
Syntax:
Rollup(Grouping_Column_List)
Cube():
It calculates sub totals & grand totals according to
every column specified in the list.
Syntax:
Cube(Grouping_Column_List)
10 CLERK 3
MANAGER 2
10th dept sub total 5
20 CLERK 5
MANAGER 3
20th dept sub total 8
GRAND TOTAL 13
10 CLERK 2
MANAGER 3
10th dept sub total 5
20 CLERK 5
MANAGER 3
2oth sub total 8
CLERK 7
MANAGER 6
GRAND TOTAL 13
1980 1 4
2 3
3 5
4 3
1980 sub total
1981 1 4
2 8
3 7
4 3
1981 sub total
GRAND TOTAL
SALES
dateid amount
1-JAN-2017 25000
2-JAN-2017 40000
…
1-JAN-2018 50000
2-JAN-2018 35000
TELANGANA M ….
F ….
TELANGANA sub TOTAL
GUJARAT M
F
Gujarat sub total
GRAND TOTAL
TELANGANA scitizen M
scitizen F
minors M
minors F
midage M
midage F
SELECT state,
CASE
WHEN age>=60 THEN 'scitizen'
WHEN age<18 THEN 'minor'
WHEN age>=18 and age<60 THEN 'midage'
END as "age range",
Gender, count(*) as "no of people"
FROM person
GROUP BY state,
CASE
WHEN age>=60 THEN 'scitizen'
WHEN age<18 THEN 'minor'
WHEN age>=18 and age<60 THEN 'midage'
END,
gender
ORDER BY state;
CLAUSES :
GROUP BY
Execution Order:
HAVING
FROM
JOINS
WHERE
GROUP BY
FROM
JOINS
WHERE
GROUP BY
SET OPERATORS
HAVING
SELECT
SUB QUERIES
ORDER BY
VIEWS
INDEXES
M VIEW
SEQUENCES
SYNONYMS
A = {1,2,3,4,5}
B = {6,7,2,3,8,9}
A U B = {1,2,3,4,5,6,7,8,9}
A I B = {2,3}
CUST1 CUST2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
1001
1002
1003
5001
5003
SET OPERATORS:
• are used to combine the records
from multiple tables.
<SELECT STATEMENT>
set operator
<SELECT STATEMENT>;
CUST1 CUST2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
UNION:
• is used to get all records from multiple tables
uniquely [without duplicate records]
• It always gives result in the order.
1001
1002
1003
Oracle7AM Page 137
1003
5001
5003
Rules:
• Number of columns in Both SELECT
statements must be matched.
○ Ex:
Oracle7AM Page 138
• Number of columns in Both SELECT
statements must be matched.
○ Ex:
SELECT cid FROM cust1
UNION
SELECT cid,cname FROM cust2;
ERROR:
ERROR at line 1:
ORA-01789: query block has incorrect
number of result columns
ERROR:
ERROR at line 1:
ORA-01790: expression must have same
datatype as corresponding expression
RESULT
cust_id cname => column headings in result tables
UNION ALL:
• is used get all records from multiple tables
including duplicate records.
• It does not give result in the order.
CUST1 CUST2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
1001
1002
1003
5001
1002
5003
INTERSECT:
used to get common records from multiple tables
CUST1 CUST2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
1002 B
MINUS:
Oracle7AM Page 141
MINUS:
• is used to get specific records from first table.
• It means, it gives all records from first table
except common records.
CUST1 CUST2
cid cname cid cname
1001 A 5001 D
1002 B 1002 B
1003 C 5003 E
1001 A
1003 C
5001 D
5003 E
JOB JOB
--------- ---------
MANAGER CLERK
PRESIDENT MANAGER
CLERK ANALYST
CLERK
ANALYST
JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
JOB
---------
CLERK
MANAGER
JOB
---------
PRESIDENT
JOB
---------
ANALYST
Oracle7AM Page 144
ANALYST
COLLEGE DB
student
marks
fee
library
employee
student
sid sname scity mobile
marks
sid maths physics chemistry
Products
pid pname qty
Orders
oid cid pid ord_date del_date order_qty amount
Customers
cid cname cstreet ccity cstate mobile
Joins:
• Join => Combine / Connect / Link
• Join is an operation that combines one
table records with another based on join
condition.
student marks
sid sname scity mobile sid maths physics chemistry
1001 A .. .. 1001 70 60 80
1002 B .. .. 1002 77 44 55
1003 C .. .. 1003 63 49 81
Joins:
• Join => Combine / Connect / Link
• Join is an operation that combines one
table records with another based on join
condition.
• Join Condition decides, the record in one
table should be joined with which record
in another table.
• used to retrieve the data from multiple
tables.
• Normally, to perform join operation one
common column is required.
• This common column name in both
tables need not to be same.
• Ex: student.stdid = marks.sid
Types of Joins:
emp.deptno=dept.deptno
EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30
SELECT ename,sal,dname,loc
FROM emp,dept
WHERE emp.deptno = dept.deptno;
Table Alias:
• It makes table name short
• It improves the performance
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e, dept d
WHERE e.deptno=d.deptno;
SQL SERVER
ORACLE
Join Query
Join Query
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 INNER JOIN dept d
ON e.deptno=d.deptno;
Note:
• To separate two table names use "keyword" in
ANSI style. Whereas in oracle style we use ,
• Write Join Condition in ON clause (or) USING clause
for ANSI style. Whereas in oracle style we write in
"WHERE" clause.
SELECT e.ename,e.sal,d.dname,d.loc
FROM emp e INNER JOIN dept d
USING(deptno);
Note:
for USING clause, common column name must be
same
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
WHERE e.deptno=d.deptno and e.ename='BLAKE';
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';
Note:
To retrieve data from 3 tables, write 2 Join Conditions
To retrieve data from 5 tables, write 4 Join Conditions
To retrieve data from 10 tables, write 9 Join Conditions
IN ORACLE Style:
SELECT e.ename,d.dname,l.lname,c.cname
FROM emp1 e,dept1 d,location1 l,country1 c
WHERE e.deptno=d.deptno and
d.locid=l.locid and
l.cid=c.cid;
ANSI style:
SELECT e.ename,d.dname,l.lname,c.cname
FROM emp1 e INNER JOIN dept1 d
ON e.deptno=d.deptno
INNER JOIN Location1 l
ON d.locid=l.locid
INNER JOIN country1 c
ON l.cid=c.cid;
JOINS:
OUTER JOIN:
• INNER JOIN can display matching records only. It
cannot display unmatching records.
• OUTER JOIN can display matching & unmatching records
also.
• OUTER JOIN = matching records + unmatching records
emp.deptno=dept.deptno(+)
EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30 40 OPERATIONS BOSTON
1006 30
1007 Ramu .. ..
1008 Kiran .. ..
ORACLE style:
SELECT e.ename,d.dname
FROM emp e,dept d
WHERE e.deptno=d.deptno(+);
ANSI style:
emp.deptno=dept.deptno(+)
EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30 40 OPERATIONS BOSTON
1006 30
1007 Ramu .. ..
1008 Kiran .. ..
ORACLE Style:
SELECT e.ename,d.dname
FROM emp e,dept d
WHERE e.deptno(+)=d.deptno;
ANSI style:
SELECT e.ename,d.dname
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno=d.deptno;
ORACLE style:
SELECT e.ename,d.dname
SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno=d.deptno(+)
UNION
SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno;
ANSI Style:
emp.deptno=dept.deptno(+)
EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30 40 OPERATIONS BOSTON
1006 30
1007 Ramu .. ..
1008 Kiran .. ..
ORACLE style:
ANSI style:
ORACLE style:
ANSI style:
ORACLE style:
SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno=d.deptno(+) and d.dname is null
UNION
SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno(+)=d.deptno and e.ename is null;
ANSI style:
SELECT e.ename,d.dname
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"
e.deptno!=d.deptno
EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30
1006 30
ORACLE style:
SELECT e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno!=d.deptno
ORDER BY 1;
ANSI style:
SELECT e.ename,d.dname
FROM emp e JOIN dept d
ON e.deptno!=d.deptno
ORDER BY 1;
emp salgrade
empno ename job sal grade losal hisal
1001 A 3000 1 500 1000
1002 B 5000 2 1001 2000
1003 C 2500 3 2001 3000
1004 D 800 4 3001 4000
5 4001 5000
ORACLE style:
SELECT e.ename,e.sal,s.grade
FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;
ANSI style:
SELECT e.ename,e.sal,s.grade
FROM emp e JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal;
Types of Joins:
emp emp
empno ename job sal MGR empno ename job sal MGR
1001 A CLERK 5000 1003 1001 A CLERK 5000 1003
1002 B SALESMAN 4000 1003 1002 B SALESMAN 4000 1003
1003 C MANGER 9000 1007 1003 C MANGER 9000 1007
1004 D CLERK 6000 1006 1004 D CLERK 6000 1006
1005 E ANALYST 5000 1006 1005 E ANALYST 5000 1006
1006 F MANAGER 10000 1007 1006 F MANAGER 10000 1007
1007 G CEO 15000 1007 G CEO 15000
ORACLE style:
ANSI style:
ORACLE style:
ANSI style:
ORACLE style:
ANSI style:
A = {1,2,3}
B = {4,5}
AXB = {
Cross Join:
• Each record in one table will be joined with
each record another table.
• No of records in cross join result = no of
records in first table * no of records in second
table
GROUPA GROUPB
cid cname cid cname
10 IND 40 PAK
20 AUS 50 NZ
30 WI 60 ENG
SELECT a.cname,b.cname
FROM groupa a, groupb b;
ANSI style:
SELECT a.cname,b.cname
FROM groupa a CROSS JOIN groupb b;
Natural Join:
• Equi Join without duplicate columns
• We will not write join condn. Implicitly Equi Join
condition will be taken.
ANSI style:
SELECT * FROM emp NATURAL JOIN dept;
(or)
dname sum_of_Sal
ACCOUNTING …
SALES …
RESEARCH …
emp.deptno=dept.deptno
EMP
empno ename job sal deptno DEPT
1001 10 deptno dname loc
1002 10 10 ACCOUNTS CHICAGO
1003 20 20 RESEARCH DALLAS
1004 20 30 SALES NEW YORK
1005 30
1006 30
SELECT d.loc,
Location Year no_of_emps to_char(e.hiredate,'yyyy') year,
Oracle7AM Page 158
SELECT d.loc,
Location Year no_of_emps to_char(e.hiredate,'yyyy') year,
CHICAGO 1980 2 count(*) no_of_emps
1981 4 FROM emp e,dept d
1982 6 WHERE e.deptno=d.deptno
NEW YORK 1980 3 GROUP BY d.loc, to_char(e.hiredate,'yyyy')
ORDER BY 1;
1982 2
Assignment:
Student Course
sid sname cid cid cname
1001 A 20 10 Java
1002 B 30 20 Python
1003 C 20 30 Oracle
1004 D 30 40 HTML
1005 E
1006 F
Syntax:
SELECT <column_list>
FROM <table_list>
WHERE <column_name> <operator> (SELECT_Query);
Note:
SELECT ename FROM emp
WHERE sal = second max salary
Note:
Find salary values less than 2nd max salary.
In that list we are finding max value.
Update emp
SET sal=(SELECT max(Sal) FROM emp where deptno=30)
WHERE ename='ALLEN';
ASSIGNMENT
Assignment:
• Inner query gets executed first • Outer query gets executed first
• Inner gets executed only once • Inner query gets executed for
multiple times
emp Find
empno ename job sal how many sal values>emp sal
6000
8000 0 > emp sal max salary
Dept
emp deptno dname loc
empno ename deptno 10 accounting
1001 10 20 research
1003 20 30 sales
1004 30 40 operations
Inline View:
• If sub query is written in FROM clause then it is
called "Inline View".
• Sub query acts like table.
• We can change the execution order
execution order
FROM
WHERE => does not know alias name. alias name specified in SELECT
SELECT
rownum:
pseudo => FALSE
• Rownum is a pseudo column.
• It applies row number on the
result of SELECT query
2)8(4 2)7(3
8 6
------------ ----------
0 1
emp dept
---------- ------------
14 4
Tables
Views
Sequences
SQL-Introduction
Oracle7AM Page 174
Tables
Views
Sequences
SQL-Introduction
Synonyms
5 sub languages
Indexes
DDL, DRL, DML, DCL, TCL
Materialized Views
Operators in SQL
Built-In Functions
Clauses in SQL
Joins
SET operators
Sub Queries
View:
• View is a DB Object.
• View is a Virtual Table.
• Virtual Table means, It does not contain
physical data & It does not occupy the
memory.
• A view holds SELECT query.
• When we retrieve data through view,
implicitly oracle runs SELECT query which
is associated with that view.
• Some can be updated. These are called
"Updatable Views". Some views cannot be
updated. These are called "Read-Only
Views".
CREATE VIEW v1
AS
SELECT empno,ename,job
FROM emp;
USERA:
SELECT * FROM v1;
SELECT ename,sal,dname,loc
FROM emp e,dept d
Create view v2
As
Complex Join Query;
JAVA developer
Log in As DBA:
username: system
password: nareshit
Create View v1
As
SELECT empno,ename,Job FROM emp;
v1
emp
Create View V1
As
SELECT * FROM emp;
Advantages:
• provides security [Data Level Security]
• reduces the complexity & simplifies the queries
Types of Views:
2 Types:
• Simple View
• Complex View
Simple View:
• If view is created based on one table then it is called
"Simple View".
• It can be also called as "Updatable View".
• We can perform DML operations through Simple View.
Creating View:
CREATE VIEW v1
AS
SELECT empno,ename,job FROM emp;
v1 -> VIEW
Log in as DBA:
username: system
password: nareshit
Log in as c##batch7am:
Log in as c##naresh:
emp
empno ename job sal deptno
Batch7AM:
CREATE VIEW v2
AS
SELECT * FROM emp
WHERE deptno=20;
GRANT All ON v2
TO c##naresh;
c##naresh:
CREATE VIEW v2
AS
SELECT * FROM emp WHERE deptno=20
WITH CHECK OPTION;
Insert into
c##batch7am.v2(empno,ename,deptno)
values(22,'AB',10);
ERROR: WHERE condition violated
View created.
M1+M2+M3 =>
sal*12 =>
COMPLEX VIEW:
expression
Oracle7AM Page 181
M1+M2+M3 =>
sal*12 =>
COMPLEX VIEW:
expression
• If a view is created based on multiple tables
[Joins] or SET operators or Sub Queries or
Aggregate Functions or expressions or
GROUP BY or HAVING then it is called "
Complex View".
• It can be also called as read-only view.
• We cannot perform DML operations using
COMPLEX VIEW.
Ex on Complex View:
Create view v3
AS
SELECT e.ename, e.sal, d.dname, d.loc
FROM emp e,dept d
WHERE e.deptno=d.deptno;
Views:
• Virtual Table
• no physical data
• not occupies memory
security
2 Types: reduces complexity
• Simple View =>
• based on one table
• DML operations
• Updatable View
FORCE VIEW:
If a view is created forcibly with some errors
then it is called "FORCE VIEW".
Example:
Without existing table we can create the view
forcibly with some errors. This view will not
Oracle7AM Page 183
forcibly with some errors. This view will not
work till we create the table. This view is
called "FORCE VIEW".
Table View
View Table
Example:
emp
empno ename job sal mgr comm deptno hiredate
v1 => view
empno ename job
CREATE view v6
AS
SELECT * FROM v1;
Example:
emp
empno ename job sal mgr comm deptno hiredate
CREATE VIEW v7
AS
SELECT empno,ename,deptno
FROM emp;
CREATE VIEW v8
AS
SELECT *
FROM emp;
* empno,ename,job,sal,comm,hiredate,deptno,gender,mgr
USER_TABLES
USER_VIEWS
USER_CONSTRAINTS
USER_SEQLENCES
CREATE VIEW v9
AS
SELECT empno,ename FROM emp;
CREATE OR REPLACE v9
AS
SELECT empno,ename,job FROM emp;
USER_VIEWS:
• It maintains all views information
Syntax:
SEQUENCES:
• is a DB Object.
• It is independent of table.
• It is used to generate sequential
integer values.
Ex:
CREATE SEQUENCE s1;
clause default
START WITH 1
MINVALUE 1
MAXVALUE 10 power 28
INCREMENT BY 1
cycle nocycle
cache 20
Syntax:
Sequence_name.pseudo_Column
Ex:
s1.nextval
s1.currval
MINVALUE clause:
used to specify minimum value
Ex:
MINVALUE 1
MINVALUE 300
MAXVALUE clause:
used to specify maximum value in the sequence
Ex:
MAXVALUE 10
MAXVALUE 500
INCREMENT BY clause:
used to specify step value. How many values should be
increased or decreased after a value will be specified
here.
cid cname
Insert into customer11
1 A
values(s2.nextval,'&cname');
2 B Enter value for cname: A
3 C
4 D /
5 E Enter value for cname: B
/
Enter value for cname: C
/
Enter value for cname: D
/
Enter value for cname: E
/
ERROR: reached MAXVALUE
ASSIGNMENT:
CREATE a sequence with minimum
cid cname value 10 & max value 40
CREATE SEQUENCE s3
START WITH 10
INCREMENT BY 10
MINVALUE 10
MAXVALUE 40;
course5
cid cname
/
Enter value for cname: PYTHON
/
Enter value for cname: ORACLE
/
Enter value for cname: HTML
cycle / nocycle:
cycle:
If we create a sequence with cycle,
SEQUENCE starts from START WITH value.
It generates next value up to MAXVALUE.
After reaching maximum value it will be reset to MINVALUE.
Again it generates up to MAXVALUE.
After reaching maximum value again it will be reset to
MINVALUE.
CREATE SEQUENCE s4
START WITH 300
INCREMENT BY 1
Oracle7AM Page 191
INCREMENT BY 1
MINVALUE 100
MAXVALUE 350
cycle;
START WITH
300
CREATE SEQUENCE s5
INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
cycle;
--ERROR : CACHE size must be less than one cycle
default cache value is 20
In above example one cycle value is 10
cache size must be < 10
CREATE SEQUENCE s5
INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
cycle
cache 10; --ERROR => cache size must be < one cycle
CREATE SEQUENCE s5
INCREMENT BY 1
START WITH 5
MINVALUE 1
MAXVALUE 10
Oracle7AM Page 192
MAXVALUE 10
cycle
cache 9;
sequence created
nocycle:
• it is default one.
• If we create sequence with nocycle,
SEQUENCE starts from START WITH
value, it generates next value up to
MAXVALUE. After reaching MAXVALUE
it stops.
Ex:
CREATE SEQUENCE s6
INCREMENT BY 1
START WITH 200
MINVALUE 1
MAXVALUE 500
nocycle;
nocache:
CREATE SEQUENCE s7
INCREMENT BY 1
START WITH 101
MINVALUE 101
MAXVALUE 500
nocache;
cache <size>:
CREATE SEQUENCE s8
INCREMENT BY 1
START WITH 101
MINVALUE 101
MAXVALUE 500
cache 100;
s8.nextval =>
emp
empno ename Update empnos in the order with
7369 Sequential integers from 1001:
7454
7521 CREATE SEQUENCE s8
START WITH 1001
7900
INCREMENT BY 1
7902
MINVALUE 1001
7932 MAXVALUE 9999;
UPDATE emp
SET empno=s8.nextval;
CREATE SEQUENCE s9
START WITH 5001
INCREMENT BY 1
MINVALUE 5001
MAXVALUE 9999;
Dropping sequence:
user_sequences:
It maintains information about the
user_tables
sequence.
user_views
user_constraints
user_sequences
SELECT sequence_name,
MIN_VALUE, MAX_VALUE,
INCREMENT_BY
FROM user_sequences;
PERSON
pid pname state aadhar
Disadvantage of VIEW:
Less Performance
Materialized View:
• is a DB Object.
• It is not Virtual Table.
• It contains physical data. It occupies the memory.
• It is mainly used in DataWare Housing [DWH/OLAP] to
maintain summarized data physically.
• It holds precomputed result.
• Materialized view holds result of select query
physically. WHEREAS view holds SELECT query.
• Materialized view must be refreshed frequently to get
recent data.
LOG in AS DBA:
emp emp
empno ename sal deptno empno ename sal deptno
Oracle7AM Page 199
emp emp
empno ename sal deptno empno ename sal deptno
1001 2000 10 1001 2000 10
1002 3000 10 1002 3000 10
1003 5000 20 1003 5000 20
1004 4000 20 1004 4000 20
deptno sum_of_Sal
10 5000
20 9000
5 times calculation
1 time calculation will be done
will be done
emp
emp
empno ename sal deptno
empno ename sal deptno
1001 2000 10
1001 2000 10
1002 3000 10
1002 3000 10
1003 5000 20
1003 5000 20
1004 4000 20
1004 4000 20
1005 6000 10
1005 6000 10
1006 8000 20
1006 8000 20
Advantages:
• improves the performance
• we can maintain local physical copy of remote
database.
• On demand [Default]:
• In this way, we call a procedure "refresh" which
is defined in "dbms_mview" package.
COMMIT;
exec dbms_mview.refresh('mv2');
On Commit:
• When commit command is executed materialized
view will be refreshed.
INSERT
COMMIT;
materialized view will be refreshed
deptno sum_of_Sal
10 5000
20 9000
1005 8000 10
1006 5000 20
Log in as DBA:
username: system
password: nareshit
Materialized view:
• Not a virtual table
• contains physical data
• occupy the memory
Refresh ways:
on demand => refresh procedure
on commit => after commit command
on reg int => for regular interval of time
Refresh Types:
Complete
Fast
Force
Java Developer
---------------------
frequently he wants to work with
dept wise sum of salaries
SELECT deptno,sum(sal)
sum_of_sal
FROM emp
GROUP BY deptno;
User_Mviews:
It maintains information about all
materialized views
INDEX
DDL Commands 10
DML 20
FUNCTIONS 30
CLAUSES 40
JOINS 60
.. ..
..
Indexes:
• Index is a DB Object.
• Index is used to improve the performance of
Data Retrieval.
• In a BOOK, to refer particular chapter we use
INDEX for faster reference. Similarly, if index
is created on table data retrieval becomes
faster.
• BOOK INDEX
CHAPER_NAME PAGE_NUM
• ORACLE INDEX
DATA Row_ID
• Index is created on column / columns.
• We create the index on the columns which
we frequently use in WHERE clause or in
JOIN condition
Syntax:
CREATE INDEX <index_name>
ON <table_name>(<column>/<columns>);
Oracle7AM Page 206
Syntax:
CREATE INDEX <index_name>
ON <table_name>(<column>/<columns>);
Ex:
CREATE INDEX i1
ON emp(sal);
Note:
Index Scan will be performed faster than
Table Scan.
Table Scan:
If 100 records are there, 100 comparisons will
be performed.
Index Scan:
If 100 records are there, maximum half of the
comparisons will be done. So, INDEX improves
the performance of data retrieval.
2 Types:
• B-Tree Index
○ Simple Index
○ Composite Index
○ Unique Index
○ Function-Based Index
• Bitmap Index
B-Tree Index:
• B-Tree => Balanced Tree
• In B-TREE Index, when index is created implicitly
one structure will be created. It is called
"Balanced Tree".
• Sub Types:
○ Simple Index
○ Composite Index
○ Unique Index
○ Function-Based Index
Types of Indexes:
Simple Index:
If index is created on one column then it is called "Simple
Index".
Ex:
SELECT * FROM emp WHERE sal>2800; --Table Scan
Composite Index:
If index is created on multiple columns then it is called "
Composite Index".
deptno job
10 manager
10 clerk
10 clerk
10 manager
20 clerk
20 manager
30 manager
30 clerk
Note:
If we apply primary key to a column, by default
index will be created for this column. This index
name is PK constraint's name.
Ex:
CREATE TABLE inddemo
(f1 number(4) primary key,
f2 varchar2(10) );
Function-Based Index:
If index is created based on function or expression then it is
called "Function-Based Index".
EX:
Bitmap Index:
• It stores bits i.e. 0s and 1s.
• Every bit will be associated with one ROW ID.
• This bit will be converted to ROW ID & picks the
record.
• Bitmap index is created on low cardinality
columns.
gender
--------------
M
M
F
M
F
F
empno
----------- distinct values
1001
1002 empno
1003 ---------
. 1001
. 1002
1010 .
.
1010
bi1
std
M F
sid sname gender
0 1
F
1 0
M
1 0
M
0 1
F
1 0
M
0 1
F
• contains data & row ids • contains bits [0s & 1s]. bit will
be converted to row id
USER_INDEXES:
It maintains information about all
indexes.
Dropping Index:
Synonym:
• is a DB Object.
• It is used to give alias name [alternative name] for
DB Object.
• Synonym is permanent whereas table alias and
column alias are temporary.
emp employee_salary_details
dept dept_location_details
Ramu:
SELECT * FROM c##batch7am.employee_salary_details;
SELECT ename,
sal salary,
sal*12 an_sal
FROM emp;
Synonym is permanent.
Advantages:
• It makes table name [db object name] short.
• It avoids of writing schema.
• It provides security.
Syntax:
Log in as DBA:
username: system
password: nareshit
Log in as c##batch7am:
Log in as Ramu:
username: c##ramu
password: nareshit
SELECT * FROM z;
Types of Synonyms:
There are 2 types of Synonyms. They are:
• Private Synonym
• Public Synonym
Private Synonym:
• It is created by the user.
• can be used by specific user [owner of synonym] only.
Public Synonym:
• It is created by the DBA.
• Any user can use this name if permission granted by
the DBA.
Oracle7AM Page 219
the DBA.
Ex:
Owner => c##batch7am
emp
GRANT permission to
c##oracle7am/c##oracle11am/c##oracle6pm
c##oracle7am:
SELECT * FROM c##batch7am.emp;
CREATE SYNONYM s1 for c##batch7am.emp;
c##oracle11am:
SELECT * FROM c##batch7am.emp;
CREATE SYNONYM s2 for c##batch7am.emp;
c##oracle6pm:
SELECT * FROM c##batch7am.emp;
CREATE SYNONYM s3 for c##batch7am.emp;
Log in as DBA:
username: system
password: nareshit
GRANT all ON ps
TO c##oracle7am,c##ramu,c##oracle6pm;
DROP SYNONYM e;
USER_SYNONYMS:
It maintains information about all
synonyms
ORACLE
• SQL
• PL/SQL
VIEWS
SEQUENCES
INDEXES
MATERIALIZED VIEW
SYNONYM