You are on page 1of 21

ORACLE SESSION 3

So,Today session number 3 right!

so... In last two sessions we only see about the basics of sql Okay...

In session 3 we will cover some topics under Advance queries okay.. like Sub
queries ,joins, Flashback queries ,constraints like that...

----------------------------------------------------------------
**************vi sess3.txt***********
Lets us see about what is Sub Query.

So guys!..anybody know what is subquery??

SQL Sub query


---------------
Sub query is a query inside a query.
(((Most of the time� a sub query is used ..when you know ..how to search for a
value ..using a SELECT statement.., but u do not know.. the exact value.. in the
database.

Sub queries are an alternate way ..of returning data.. from multiple tables. )))

Okay..did you know what are the types in Sub queries...

Sub queries has following types namely


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

>> Single row sub query�(Returns zero or one row to the outer query.)

So, in last session we do only single query..like select * from some table like
that... so SQ means query inside the query... So...as a result if i get one row
called Single row SQ

>> Multiple row SQ�(if i get 2 or more rows from the table)

>> Multiple column SQ�(it retns 2 or more columns from the tab)

>> Correlated SQ�(it interpedent of 2 tables)

So, correlated SQ nothing but a query which is going to use the values of another
query is correlated subquery...

>> Nested SQ�(it has sub query is placed another query which means multiple
subqueries...)

Clear...

So,Let me show some examples for subquery...

First is .....

(i)Single row subquery:


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

It returns only one row from the table�.

I already have a table called emp_details�


Syntax: Select column_name from table_name where column_name operator (Select
column_name from table_name);

SQL>select * from emp_details;

EMPNO ENAME SALARY DEPTNO


---------- ---------- ---------- ----------
7 dineel 50000 20
1 rohit 30000 10
2 ricardo 40000 20
3 peri 13000 10
4 san 23000 20
5 raj 5000 30
6 john 20000 30
8 santhosh 6000 30

8 rows selected.

In this, I want to select max salary okay... what normally we do

SQL> select max(salary) from emp_details;

So this is normal query ..okay..this is not a subquery...

So in subquery what i going to do nahh.. I select all the columns from the table
emp_details... so i want to select a max salary right...based on column
salary..so,here see i select the table where salary = we wrote the query right to
get a max salary ...i will wrote that query into the inner query okay...

SQL>select * from emp_details where salary=(select max(salary) from emp_details);

EMPNO ENAME SALARY DEPTNO


---------- ---------- ---------- ----------
7 dineel 50000 20

Here you can see

Here the inner query returns only single row to the outer query. Hence this is said
to be single row subquery.
________________________________________________________________

(ii)MULTI ROW SUBQUERIES/ insert statement


--------------------------------------
It returns two or more rows to the outer query right

Syntax: select column_name from table_name where column_name operator (IN,ANY, ALL,
NOT IN) (select column_name from table_name);

SQL>select * from emp_details;

EMPNO ENAME SALARY DEPTNO


---------- ---------- ---------- ----------
7 dineel 50000 20
1 rohit 30000 10
2 ricardo 40000 20
3 peri 13000 10
4 san 23000 20
5 raj 5000 30
6 john 20000 30
8 santhosh 5000 30

8 rows selected.

So,

SQL>select empno,ename from emp_details where empno in (select empno from


emp_details where ename like 'r%');

(( So, what i trying to do nahh.. in this i just want to print the name starting
with r and i don't want to display all ename))

EMPNO ENAME
---------- ----------
1 rohit
2 ricardo
5 raj
_______________________________________________________________

(iii)MULTI COLUMN SUBQUERIES


------------------------
Returns more than one columns to the outer query.

Syntax:select column_name1,column_name2 from table_name where


(column_name1,column_name2) operator (select column_name1, group
function(column_name2) from table_name group by column_name);

if we wish to retrieve the employees with lower salary grouping according to


deptno

##getting emp details who is getting lowest salary,if im getting one row nah it
look like single rw SQ,so here im getting lowest salary on each dept,we have 3
dept,from 3 dept i want to get lowest salary.

##so i want to get lowest salary by grouping them each dept.

##salary and dept are 2 columns im taking here for conditions.i don't want to
display all deptno with salary i just want to select only min salary in each dept.

##if i want to get info only particular block of row im using groupby clause. .

SQL>select * from emp_details where (deptno,salary) in (select deptno ,min(salary)


from emp_details group by deptno);

EMPNO DEPTNO ENAME SALARY


---------- ---------- ---------- ----------
5 30 raj 5000
4 20 san 23000
3 10 peri 13000
________________________________________________________________

(iv)Correlated Sub query


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

A query which uses values from the outer query is called as a correlated sub query.

Syntax: select column_name1, column_name2 from table_name outer where operator


(select column_name1 from table_name inner where inner.table_name
=outer.table_name);

SQL> select * from ref;

EMP_ID FIRST_NAME
---------- --------------------
1 James
2 Ron
3 Fred
4 Susan

0SQL>select * from ref1;

EMP_ID FIRST_NAME
---------- --------------------
1 James
2 Ron
3 Fred
4 Susan

SQL> update ref1 set first_name=null;

4 rows updated.

SQL> select * from ref1;

EMP_ID FIRST_NAME
---------- --------------------
1
2
3
4

4 rows selected.

SQL> update ref1 set first_name=(select first_name from ref where


ref.emp_id=ref1.emp_id);

4 rows updated.

SQL> select * from ref1;

EMP_ID FIRST_NAME
---------- --------------------
1 James
2 Ron
3 Fred
4 Susan

8 rows selected.

##In ref1 if i want to update first_name.now im select f_n from ref table not all
values only when it is matches emp_id on both the tables.
________________________________________________________________

NESTED SUBQUERIES:
------------------
Sub queries placed with in another queries

((
Outer query can have more than one sub query.
Syntax: Select column_name from table_name where column_name operator (Select
column_name from table_name where column_name operator (Select column_name from
table_name));
))

SQL>select * from emp_details;

EMPNO ENAME SALARY DEPTNO


---------- ---------- ---------- ----------
7 dineel 50000 20
1 rohit 30000 10
2 ricardo 40000 20
3 peri 13000 10
4 san 23000 20
5 raj 5000 30
6 john 20000 30
8 santhosh 6000 30

8 rows selected.

SQL> select * from dept_details;

DEPTNO DNAME LOCATION


---------- ---------- ----------
10 accounting new york
20 sales chicago
30 research boston

SQL>select dname from dept_details where deptno=(select deptno from emp_details


where salary=(select max(salary) from emp_details));

DNAME
----------
sales

Let us consider that we have to find the name of the department which giving
highest salary to employees in an organizaion.so we relate table by common table.

##how i get values,,by common col in each table(deptno).now im select dept no which
is having max salary not all salary.
##50000 is max salary,so tat deptno is 20 it return name of deptno 20 in 2 table.

________________________________________________________________

And then the next topic is Joints

JOINS:
------
Okay!..Basically what is joins....

Joins can be used to connect any number of tables so that you can retrieve
information from more than one table using the join operator.

There are
* Inner Join
* Outer Join( Left Outer join, Right Outer Join,Full Outer Join)
* self Join

SQL> select * from employe1;

EMPID ENAME SAL DEPTID


---------- ---------- ---------- ----------
1 saksa 9000 11
2 rias 8000 12
3 john 5000 17
4 sameer 7000 13
5 kani 6000 14
6 sena 5000 15
7 raj 7000 16

7 rows selected.

SQL> select * from dept1;

DEPTID DEPTNAME
---------- ----------
20
11 admin
12 marketing
13 account
14 finance
17 hr
18 design
19 production

8 rows selected.

Inner Join:
-----------
It returns all rows from multiple tables only when the condition is match..

This means if a row has a null value in one of the columns in the join condition
that row will not be returned.

syntax
-------
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

Example:
--------

SQL> select a.*,b.* from employe1 a inner join dept1 b on (a.deptid=b.deptid);

EMPID ENAME SAL DEPTID DEPTID DEPTNAME


------- ---------- ---------- ---------- ---------- --------
1 saksa 9000 11 11 admin
2 rias 8000 12 12 marketing
4 sameer 7000 13 13 account
5 kani 6000 14 14 finance
3 john 5000 17 17 hr
----------------------------------------------------------------
Next is Outer Join:

So the outer join has two types..


One is Left Outer Join and another one is Right Outer Join...

Left Outer Join:


-------------------
It returns All the rows from left side table and only matched records from right
side table.

Syntax
------
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;

Example:
-----------
SQL> select a.*,b.* from employe1 a left outer join dept1 b on(a.deptid=b.deptid);

EMPID ENAME SAL DEPTID DEPTID DEPTNAME


----- ---------- ---------- ---------- ---------- ----------
1 saksa 9000 11 11 admin
2 rias 8000 12 12 market
4 sameer 7000 13 13 account
5 kani 6000 14 14 finance
3 john 5000 17 17 hr
6 sena 5000 15
7 raj 7000 16

7 rows selected.
________________________________________________________________
RIGHT OUTER JOIN:
------------------

All the rows from right side table and only matched records from left side table.

SQL> select a.*,b.* from employe1 a right outer join dept1 b on(a.deptid=b.deptid);

EMPID ENAME SAL DEPTID DEPTID DEPTNAME


----- ---------- ---------- ---------- ---------- ----------
1 saksa 9000 11 11 admin
2 rias 8000 12 12 marketing
3 john 5000 17 17 hr
4 sameer 7000 13 13 account
5 kani 6000 14 14 finance
20
19 production
18 design

8 rows selected.
________________________________________________________________
FULL OUTER JOIN:
-----------------
combination of left outer and right outer joins..If any row does not have match we
have a null space there.
SQL> select a.*,b.* from employe1 a full outer join dept1 b on(a.deptid=b.deptid);

EMPID ENAME SAL DEPTID DEPTID DEPTNAME


------ ---------- ---------- ---------- ---------- ----------
1 saksa 9000 11 11 admin
2 rias 8000 12 12 marketing
4 sameer 7000 13 13 account
5 kani 6000 14 14 finance
3 john 5000 17 17 hr
6 sena 5000 15
7 raj 7000 16
20
19 production
18 design

10 rows selected.
________________________________________________________________
SELF JOIN:
--------------
A self join is a join made on the same table.

Normally for join we have 2 tables.

To perform a self join must use a different alias to identify each reference of the
table used in your query.

##to perform self join we have to give 2 diff alias name for same table.

SQL> select * from org;

MAN_ID EMP_ID NAME


---------- ---------- --------------------
100 101 goldberg
101 102 undertaker
102 110 kane
110 111 lesner
111 112 batista
112 113 austin
113 117 jeff hardy
117 118 matt hardy

8 rows selected.

SQL> select m.name||' is trainer for '||e.name from org m,org e where
m.man_id=e.emp_id;

M.NAME||'ISTRAINERFOR'||E.NAME
------------------------------------
undertaker is trainer for goldberg
kane is trainer for undertaker
lesner is trainer for kane
batista is trainer for lesner
austin is trainer for batista
jeff hardy is trainer for austin
matt hardy is trainer for jefef hardy

7 rows selected.
##it returns only when the man_id and emp_id get matched,here 100 have no match so
leave this,man_id 101 having name called undertaker,so it print undertaker is
trainer for then it will go and search 101 in emp_id golberg having 101,
______________________________________________________________

SET OPERATORS
----------------

- allows us to combine the rows of two or more tables-


v UNION ALL-all the rows(including duplicates)
v UNION-only unique rows
v INTERSECT-Only common rows
v MINUS-subtracts 1st table by 2nd table

UNION ALL:
----------
It includes all the duplicate values

SQL>select * from product_list1;

ID NAME
---------- --------
1 book
2 pencil
3 note
4 pen
5 scale
And I have the another table called product list 2

SQL>select * from product_list2;

ID NAME
---------- --------
1 book
2 bag
3 note
6 box
7 paper

SQL>select * from product_list1 union all select * from product_list2;

ID NAME
---------- --------
1 book
2 pencil
3 note
4 pen
5 scale
1 book
2 bag
3 note
6 box
7 paper

10 rows selected.

UNION :
------
SQL>select * from product_list1 union select * from product_list2;

ID NAME
---------- --------
1 book
2 bag
2 pencil
3 note
4 pen
5 scale
6 box
7 paper

8 rows selected.
In this Union operator, only unique values are selected��

INTERSECT:
----------

SQL>select * from product_list1 intersect select * from product_list2;

ID NAME
---------- --------
1 book
3 note
Here, only common rows are selected�

MINUS:
-----

SQL>select * from product_list1 minus select * from product_list2;

ID NAME
---------- --------
2 pencil
4 pen
5 scale
SQL>select * from product_list2 minus select * from product_list1;

ID NAME
---------- --------
2 bag
6 box
7 paper

Here , the frst table is subracted by secnd table�.

________________________________________________________________
ORACLE DATABASE OBJECTS
=========================

VIEW:
-----
A VIEW is a virtual table.So view is a storage of original table.
Views do not contain data of their own.
It is a logical representation of tables.
View also perform same way as table,u can update,insert,delete etx.,
It has Two types
Simple View
Complex view

Simple View:
-------------

Simple views are created by using a single base table.

we can perform dml operations on only simple views and not on complex views.
EXAMPLES:

SQL>select * from std;


ID NAME
---------- --------------------
1 sam
2 charanda
3 kiki
4 anu

SQL> create view vstd as select * from std;

View created.

SQL> select * from vstd;

ID NAME
---------- --------------------
1 sam
2 charanda
3 kiki
4 anu

And I just delete the one row from the view table�.

SQL> delete from vstd where id=2;

1 row deleted.

SQL> select * from vstd;

ID NAME
---------- --------------------
1 sam
3 kiki
4 anu

SQL> select * from std;

ID NAME
---------- --------------------
1 sam
3 kiki
4 anu

DML operations on a view like INSERT, UPDATE, DELETE affects the data in the
original table upon which the view is based
SQL> rollback;
Rollback complete.

And now I drop the view�

SQL> drop view vstd;

View dropped.
________________________________________________________________

Complex View:
-------------

In complex view we use 2 or more tables�


In complex view we can't do dml operartions.

SQL> select * from kd;

ID SALARY
---------- ----------
1 3459
2 7634
3 50000
4 899930
5 25000

SQL> select * from kd1;

ID NAME
---------- ----------
1 harsh
2 sri
3 surya
4 vini
5 josh

SQL> create view vkd1 as select kd.id,kd1.name,kd.salary from kd,kd1 where


kd.id=kd1.id;

View created.

And I show the view table.

SQL> select * from vkd1;

ID NAME SALARY
---------- ---------- ----------
1 harsh 3459
2 sri 7634
3 surya 50000
4 vini 899930
5 josh 25000

And I try to insert some values in the view�..

SQL> insert into vkd1 values(3,'fff',232);


insert into vkd1 values(3,'fff',232)
*
ERROR at line 1:
But it can�t�.. becoz�..it doesn't know which original table it should go and
affect.

We can�t perform DML operation on Complex View.


________________________________________________________________

Constraints:
------------
What is general meaning of constraint ??..

constraint is rules and regulations

these are some conditions which place some restrictrctions on column of table.

The conditions or some restrictions placing on a column of a table

SQL constraints are used to specify rules for the data in a table.

Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement..z

The following constraints are commonly used in SQL:


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

>> NOT NULL�- Ensures that a column cannot have a NULL value
>> UNIQUE�- Ensures that all values in a column are different
>> PRIMARY KEY�- A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
>> FOREIGN KEY�- Uniquely identifies a row/record in another table
>> CHECK�- Ensures that all values in a column satisfies a specific condition
>> DEFAULT�- Sets a default value for a column when no value is specified
>> INDEX�- Used to create and retrieve data from the database very quickly

NOT NULL:
---------
SQL> create table hb(id number not null);
SQL> insert into hb values(null);

In this, we can�t insert a null value in it�.it show error.

So we have to add a value

insert into hb values(1);

1 row created.

Unique:
-------
Specifies a column should be unique.Here it allows null values but restrict
duplicate values.

Only unique values in the all the row and columns�it doesn�t allows common data�s�

SQL>create table hb(id number unique);

Table created.
SQL>insert into hb values(null);

1 row created.

SQL>insert into hb values(1);

1 row created.

##I trying to insert the same value in the table team�.

SQL>insert into hb values(1);


insert into riz values(1)
*
ERROR at line 1:
ORA-00001: unique constraint (TEST.SYS_C0066822) violated

But! It can�t insert a same id number� this is unique constraint�

SQL>drop table team;

Table dropped.

PRIMARY KEY:
------------

It is a combination of not null and unique constrainti.e,the table having not null
values and also only unique values�

I create a table called sports team with primary key�.

SQL> create table hb(id number primary key);

Table created.

SQL> insert into hb values(&id);


Enter value for id: 1
old 1: insert into hb values(&id)
new 1: insert into hb values(1)

1 row created.

SQL> /
Enter value for id: 1
old 1: insert into hb values(&id)
new 1: insert into hb values(1)
insert into hb values(1)
*
ERROR at line 1:
ORA-00001: unique constraint (VINS.SYS_C007533) violated

SQL> /
Enter value for id: null
old 1: insert into hb values(&id)
new 1: insert into hb values(null)
insert into hb values(null)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("VINS"."HB"."ID")

DEFAULT:
--------

The default constaint used to assign default values to the column.


SQL>create table team(id number default 0,name varchar2(10) default 'nil');

Table created.
SQL>insert into team(id) values(1);

1 row created.

SQL>select * from team;

ID NAME
---------- ----------
1 nil
I insert a value for id and I haven�t give any values to the name but by the
default constraint it defaultly takes a value nil

SQL>insert into team(name) values('dv');

1 row created.
I insert a value for name and I haven�t give any values to the id similarly the
default constraint it default ly takes a value 0

SQL>select * from team;

ID NAME
---------- ----------
1 nil
0 dv

SQL>drop table team;

Table dropped.

CHECK
------
It is used to place certain conditions for the values to be inserted.

Again I create a table called team id is greater than 18�.

SQL>create table team(id number check(id>18));

Table created.

I trying to insert some value 15 which is lesser than 18�.

SQL>insert into team values(15);


insert into team values(15)
*
ERROR at line 1:
ORA-02290: check constraint (TEST.SYS_C0066825) violated
SQL>insert into team values(19);

1 row created.

SQL>drop table team;

Table dropped.

.
Read only:
----------
Read only is a constraint we can�t insert any values in it..but we can only read a
table

Syntax: create view view_name as select * from table_name with read only;

SQL> create view vw as select * from student_details with read only;


View created.
SQL> select * from vw;

ID NAME AGE SUBJECT GAMES


---------- --------------- ---------- ---------- ----------
1 Ragav 15 CS Chess
2 Joe 14 Science Cricket
3 Tamil 18 Maths Carrom
4 Mohan 19 Economics Cricket
5 Surya 14 Maths Football
SQL> delete from vw;
delete from vw
*
ERROR at line 1:
ORA-01752: cannot delete from view without exactly one key-preserved table

We cannot delete from view because read only constraint is used in it�.

REMOVE A CONSTRAINT.
--------------------
syntax: alter table table_name disable constraint_type;
syntax: alter table table_name drop constraint constraint_name;
syntax: alter table table_name drop constraint_type;

ADD A CONSTRAINT.
----------------
syntax: alter table table_name add constraint_type(column_name);
syntax: alter table table_name add constraint constraint_name constraint_type
(column_name);
syntax: alter table table_name add constraint constraint_name constraint_type
(column_name)references table_name(column_name);

________________________________________________________________

Flashback Query
---------------
Two process:

1) recovering the dropped tables


2) review the database

1) Recovering the Dropped Tables:


---------------------------------
SQL>select * from emp;

ID NAME SALARY
---------- ------------------------------ ----------
1 san 58874
2 mathan 87685
3 nimalan 75343
4 peri 8765
5 jamesh 87867
6 parker 8746

6 rows selected.

SQL>drop table emp;

Table dropped.

SQL>select * from emp;


select * from emp
*
ERROR at line 1:
ORA-00942: table or view does not exist

once u drop table it move to the recycle bin of db.. To see the table, use the
following command,

SQL>show recyclebin

##after that if u want to recover the table back use this command.

<< Our table space is exceed the max level so we can't retrive back the table,but
this is the exact syntax >>

SQL>flashback table emp to before drop;

Flashback complete.

SQL>select * from emp;

ID NAME SALARY
------------ ----------
1 san 58874
2 mathan 87685
3 nimalan 75343
4 peri 8765
5 jamesh 87867
6 parker 8746

6 rows selected.

To Clean the recyclebin, then give the following command,

SQL>purge recyclebin;

with help of flashback we recover table from recyclebin,for eg,if iam deleting some
records in the table like name=peri.If i make any modifcation or delete any
recoreds in my table,after 2 days,if u want to see the deleted records,for that we
have this process called review the database.
________________________________________________________________
2) Review the Database
-----------------------

Using Flashback Query:


-----------------------
Flashback Query is enabled and disabled using the DBMS_FLASHBACK package. The point
in time of the flashback can be specified using the SCN or the actual time.

(i)SCN (SYSTEM CHANGE NUMBER):

SQL> select * from emp;

ID NAME SALARY
---------- ---------- ----------
1 thiya 3499
2 chin 3400
3 mano 7900
4 sam 9800

4 rows selected.

SQL>commit;

Commit complete.

SQL> select dbms_flashback.get_system_change_number from dual;

GET_SYSTEM_CHANGE_NUMBER
------------------------
1174254160
##package always start with dbms_..

SQL> delete from emp;

4 rows deleted.

SQL> commit;

Commit complete.

SQL> select * from emp;

no rows selected

After its like 2 or 3 days again i want to view the data inside table,here you
can't recover the past but u able to see wat data tat table had inside by this scn
num.

SQL> execute dbms_flashback.enable_at_system_change_number(1174254160);

PL/SQL procedure successfully completed.

SQL> select * from emp;

ID NAME SALARY
---------- ---------- ----------
1 thiya 3499
2 chin 3400
3 mano 7900
4 sam 9800

SQL>execute dbms_flashback.disable();

PL/SQL procedure successfully completed.

----------------------------------------------------------------
Global Temporary tables (GTT):
-------------------------------
created with 2 clause.

ON COMMIT PRESERVE ROWS clause:


-------------------------------
The data will be deleted when we exit the session.

The ON COMMIT PRESERVE ROWS clause indicates that the data should be deleted at the
end of the session.

SQL>create global temporary table gtt(id number)on commit preserve rows;


Table created.

SQL>insert into gtt values(1);

1 row created.

SQL>/

1 row created.

SQL>/

1 row created.

SQL>select * from gtt;

ID
----------
1
1
1

SQL>commit;

Commit complete.

SQL>select * from gtt;

ID
----------
1
1
1

SQL>exit
##after exit again if i connect to database and open table tat values will be there
right,..

Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 -


Production
With the Partitioning, OLAP and Data Mining options
[test@localhost ~]$ sqlplus

SQL*Plus: Release 10.2.0.1.0 - Production on Fri Mar 28 10:13:14 2014

Copyright (c) 1982, 2005, Oracle. All rights reserved.

Enter user-name: test


Enter password:

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options

SQL>select * from gtt;

no rows selected

Here the table is empty,bcos its a temporary table.

so ur data should be deleted at the end of the session.

It will preserve the values untill u are connect to the db.

ON COMMIT DELETE ROWS clause:


----------------------------
The transaction-specific rows in a global temporary table can be preserved untill
commit or rollback the transaction.

The ON COMMIT DELETE ROWS clause indicates that the data should be deleted when we
commit or rollback the transaction.

SQL>create global temporary table gtt(id number) on commit delete rows;

Table created.

SQL>insert into gtt values(1);

1 row created.

SQL>/

1 row created.

SQL>/

1 row created.

SQL>select * from gtt;

ID
----------
1
1
1

SQL>commit;

Commit complete.

SQL>select * from gtt;

no rows selected

-------------that's all----------------------
after 4th session you have take an interview.

You might also like