Anda di halaman 1dari 11

********************************************************************************

********************************
Order By : Used to display result in particular order (Ascending or Descending)
. By default Desc.
********************************************************************************
********************************
Group By : Go for a group by only when we need a group function along with singl
e column in select statement.
Does not Sort Data.In order to sort data the Order By Clause is used.
We can have nested group function along with single column in sql que
ry.
e.g:
select roll_no,sum(marks) from student group by roll_no having sum(mar
ks)=(select max(sum(marks)) from
student group by roll_no.
********************************************************************************
*********************************
Sub Query: A subquery is basically a select clause which is used instead of anot
her statement.
e.g:

select * from sal where basic < (select avg(basic) from sal);
we can use maximum 16 subquery.
Nested query executed first and returns single column.
result only contains column which referenced in outermost query.

********************************************************************************
*********************************
Multiple Row SubQuery : In this case query returns multiple values in single col
umn. To compare values returned by
multiple row subquery we can use multiple row operator l
ike IN , ANY , ALL
********************************************************************************
*********************************
Multiple Column Subquery : In this case subquery returns more than one column.We
can use only one operator i.e IN
in case of multiple column subquery.
e.g: select * from emp where(deptno , sal) in (select deptno,max(sal) from emp
group by deptno);
********************************************************************************
********************************
Co Related SubQuery : Both Outer and Inner Query are dependent on each other.
For every execution of outer query the inner query is goin
g to be executed once.
Each and every record of outer query is known as candidate
record which result is going to
be decided by o/p of inner query.
You have to give alias name to outer query by means of whi

ch inner query is going to identify


the value of outer query.
e.g:
select sal from emp e where 2=(select count(distinct(sal) from emp e whe
re sal >e.sal))
********************************************************************************
********************************
Union : Combine result of more than one single query and produced single result
set.
Does not display duplicate values.produce sorted output.selected column
need to be of same data type.
Union all : Display Duplicate values,faster than union
********************************************************************************
********************************
Truncate :
DDL , Fast , can't use Where clause , can't rollback, after tru
ncation memory got released,deallocates
whole data page and remove pointer to indexes.Trigger will not f
ire.
Delete :
DML , Comparetively Slow , Can use Where Clause , Can roll back,
memory does not released.Trigger will fire.
********************************************************************************
********************************
CONSTRAINTS:
Primary (P): Does not allow a duplicate or Null value.
Basically used in those condition where column needs to be followe
d in other table.
Oracle creates a clustered index by default for the column.
Foreign (F): Used to follow primary key column of another table.
Does not allow any value which is not present in corresponding prim
ary key column.
You can't delete a record from primary key table which correspondin
g value exists in child table.If you need to delate a record from Master table w
hose
corresponding record exists in child table in that case you need to
go for a keyword "ON DELETE CASCADE" during the formation of foreign key.
Now Going by definition Foreign key can be of two types :
========================================
1. ON DELETE SET NULL
2. ON DELETE SET CASCADE
DETAILS:
=======
On delete set null :
=======
When a foreign key is created by on delete set null definition then when you del
ete one row from the primary column (of parent table ) , then the corresponding
entry
in the foreign key table (Child table ) have the value "NULL" for that particula
r column.

ON Delete Set Cascade:


================
When the foreign key is created by this definition then when you delete the prim
ary column (any one row -unique data) , then the Child table forcefully deletes
all the rows in the child table having same value for that particular column.
Unique (U): Does not allow duplicate values but allow NULL Values. Oracle create
s a non-clustered index by default in the column.
Check (C): We can put check condition in the check constraints.
Not Null(C): This constraint does not allow a null value.
NOT NULL constraints can be modified but the rest of constraints are supposed to
be added or dropped
e.g: Alter Table emp ADD foreign key(deptno) referenes dept(deptno);
Alter table emp modify ename not null;
We can enable or disable the constraints provided the constraints does not voila
ted any of existing data.
e.g: Alter table emp disable constrains sys_c001316;
********************************************************************************
*****************************
SUBSTR: Returens a part of string starting from a position till the given length
including starting position.
e.g: select substr('NEW DELHI',3,3) from dual; o/p: W D
select substr('NEW DELHI',-2,3) from dual; o/p: HI
********************************************************************************
********************************
INSTR:

Returns the position of particular character with in string


If character not found , return value will zero and search is case sens

itive.
3rd,4th option is optional , by default oracle will assume 1,1.
select instr('NEW DELHI','E',3,1) from dual; o/p: 6
********************************************************************************
********************************
NVL : substitutes the NULL Value by means of any given value
The Datatype of both argument has to be same.
e.g: select sal,comm,sal+nvl(comm,0) from emp;
********************************************************************************
********************************
Decode : works as if..else condition
select decode(mod('&num',2),0,'EVEN','ODD') from dual;
********************************************************************************
********************************

To_Char : converts a date to character format.


select to_char(sysdate,'DD/MM/YYYY') from dual;
********************************************************************************
********************************
PSEUDO COLUMN: these are the values which are associated with each and every tab
le but they not physically
belong to the table.
ROWID:
Memory location of record in table, unique for each row and in charact
er format.
ROWNUM: AT run time oracle internally allocates row number to the records retu
rned by select statement.
********************************************************************************
********************************
INDEX:
ee Index

Index is used for Fast Data Retrival and oracle by default uses B* Tr

Concepts : Indexing creates a pointer for a column for which index is created an
d the pointer stores the memory location of the value of that particular column
of that row and
it also maps to the row id of the corresponding values. So that during retrival
oracle has to go to memory location where value is stored with the help of point
er which makes
the retrival faster.
Simple Index: It is created on only one column of the table.
SYNTAX:

create index <Name of Index> on <Table Name> <Column Name>;

Note:- 1: Primary and unique key columns are by default index.


2: A column can't be index more than once if it is a simple index.
3: Index column does not search for Null Values.
4: you must mension the name of column where index is created in searc
h criteria(i.e where clause or
in join condition) to make use of indexing.
Complex Index: It is created on more than one column of table(Maximum 16 Index c
an be created).
create index I_Complex on emp(deptno , job);
1: In case of column index the column get the serial no. 1,2,3....etc
on the basis of their serial no
during the creation of Index.
2: If you do not mention the column at serial no. 1 of the complex ind
ex in the where condition of your
query then oracle will not make use of complex index because the le
ader colum is absent in where condition.
Unique Index: Does not allow duplicate value ..same as unique constraint.
Create unique index I_Unique_email on emp(email_id);

Bitmap Index: This is created on those column having less different values i.e
low cardinality.
In bitmap index oracle assign a value 0,1,2.... to the unique val
ue of the column ..so that during the processing of the query oracle does not go
for the searching the values like M/F , it goes for 0,1.
Create bitmap index I_BITMAP on emp(deptno);
Function Based Index: This index is created on those situatiuon where you need
to access a value of any column on the
basis of any function like substr , instr...etc.
create index I_substr on emp(substr(ename,1,3)) ;
Cluster Index: Cluster is used to store the common data of multiple tables in a
common location.
It is Database Object which acts as a storage object to store th
e data physically.
This table can be linked to the cluster in a logical way so that
the value for the common
column will be logically stored in table and physically in clust
er.
1:- create cluster <Name Of Cluster>(<col name> <data type> , <col nam
e> <data type>)
create cluster c_roll (roll_no Number);
2:- Create table student_c(RNO number primary key,name varchar2(20) ) c
luster C_ROLL(ROLLNO);
Create table batch_c(bcode char(4) , batch_rno Number refrences st
udent_c) cluster c_roll(batch_rno);
3:-

Create index I_cluster on cluster c_roll;

********************************************************************************
*********************************************
VIEW : Virtual table , Used to selecting data from table or more than one table
without applying join condition,selecting the aggregate data from a table withou
t writing the
group function every time.
Simple View: This view is based on only one table.
e.g: create or replace view v_emp as select empno,empname,deptno,job fr
om emp;
1:- You can do all the DML Operation on the table through simple view. B
ut make sure the view contains all the
not null column of the table if you want to insert records into the
table through the view.
e.g: update v_emp set sal=sal+1000 where deptno=10;
2:- View is virtual DB Objects means it does not occupy any space in the
memory in the since it does not have any

data of itw own.


Complex View: View is based on select statement involving more than one table
.
Based on Join Condition so its also called as Join View.
You can't do any DML Operation except select in Join View.
You have to write "Instead Of Triggers" to do the DML Operation
on Join View.
e.g:
Create or replace view V_Join as select empno,ename,e.deptno,dna
me,loc from emp e,dept d
where e.deptno=d.deptno;
Read Only View: Does not allow any DML Operation except select.
e.g:

Create or replace view v_read as select * from wmp with Read Onl

y;
Check View: This View allows DML Operations only on those records which satisf
y the where condition of the check condition.
e.g: create or replace view v_check as select * from emp where deptno=
30 with check option constraint c_check;
Force View: This View is based on DB Object which does not exist. Force view b
ecomes useful once the DB Object is created.
e.g:

create or replace force view v as select * from emp1;

Status of the Force View is INVALID in USER_OBJECTS because emp1


has no existence in database.
select * from user_object where objects_name='V'.
Inline View: Any subquery select in the form clause of a select statement is c
alled as an inline view.
e.g: select e.* from emp e,(select deptno,avg(sal) avg_sal from emp gr
oup by dept no) Q where e.deptno=q.deptno and e.sal>Q.avgsal
-------------------------------------------------------------------------------------------------------------------------------------------------Group Function : A group function operates on multiple rows and return one res
ult set. like avg , max,min
Single Row Function : A single function result for one row. Like Upper , lower,
translate
-------------------------------------------------------------------------------------------------------------------------------------------------Decode : Decode is value by value replacement. eg: SELECT DECODE('ABC','A',1,'B'
,2,'ABC',3) from dual. o/p : 3
Translate : Translate is character by character replacement. eg: SELECT TRANSLAT
E('ABCGH', 'ABCDEFGHIJ', 1234567899) FROM DUAL. O/P:12378

Case : Decode performs eqality check while case can work with all logical compar
isions.
case
when sal < 1000
Decode is shorter than case.
CASE expects datatype consistency, DECODE does not.
SQL> select decode(2,1,1,
2
'2','2',
3
'3') t
4 from dual;
T
---------2
SQL> select case
2
3
4
end
5 from dual;
when

2 when 1 then '1'


when '2' then '2'
else '3'
'2' then '2'
*

ERROR at line 2:
ORA-00932: inconsistent datatypes: expected NUMBER got CHAR

------------------------------------------------------------------------------------------------------------------------------------------------What is difference between Rename and Alias ??


Rename is a permanent name given to a table or column whereas Alias is a tempora
ry
name given to a table or column which do not exist once the SQL statement is
executed.
--------------------------------------------------------------------------------------------------------------------------------------------------Join :
Cartesian Join
e records from
join where all
d every record

: if you do not provide join condition at the time of selecting t


more than one table then this is called cartesian
the records from first table will be displayed along with each an
of next table.

---------------------------------------------------------------------------------------------------------------------------------------------------Adding a foreign key to any table later on:


Alter table emp add foreign key(Dept no) references dept(dept no) .
COnstraints can be enabled or disabled provided constraint does not voilate any
of existing data.
--------------------------------------------------------------------------------

--------------------------------------------------------------------Sequence : Used to generate a series of a number seperated by a common differen


ce.
create sequence seq_name start with any_value increment by any_value max value a
ny_value cycle cache <size>.
--------------------------------------------------------------------------------------------------------------------------------------------The CUBE clause return rows containing a subtotal for all combinations of column
s along with a total at the end.
SELECT city, description, SUM(salary)
2 FROM employee
3 GROUP BY CUBE(city, description);
CITY
DESCRIPTION
SUM(SALARY)
---------- --------------- ----------32574.02
Tester
21096.9
Manager
10242.56
Programmer
1234.56
Toronto
1234.56
Toronto
Programmer
1234.56
New York
12220.56
New York Tester
4322.78
New York Manager
7897.78
Vancouver
19118.9
Vancouver Tester
16774.12
Vancouver Manager
2344.78
********************************************************************************
The ROLLUP clause extends GROUP BY to return a row containing a subtotal for eac
h group along with a total for all groups.
SELECT city, description, SUM(salary)
2 FROM employee
3 GROUP BY ROLLUP(city, description);
CITY
---------Toronto
Toronto
New York
New York
New York
Vancouver
Vancouver
Vancouver

DESCRIPTION
SUM(SALARY)
--------------- ----------Programmer
1234.56
1234.56
Tester
4322.78
Manager
7897.78
12220.56
Tester
16774.12
Manager
2344.78
19118.9
32574.02

*********Dropping a column from a compressed table in Oracle********************


**
CREATE TABLE TEST COMPRESS for all operations AS SELECT * FROM INVOICE_HDR;
ALTER TABLE TEST ADD (DOCK_ZONE VARCHAR2 (100));

ALTER TABLE TEST DROP COLUMN DOCK_ZONE;


ALTER TABLE TEST SET UNUSED (DOCK_ZONE);
ALTER TABLE TEST DROP unused columns;
********************************************************************************
*************************************
1) The sql query becomes faster if you use the actual columns names in SELECT st
atement instead of than '*'.
2) HAVING clause is used to filter the rows after all the rows are selected. It
is just like a filter. Do not use HAVING clause for any other purposes.
Write the query as
SELECT subject, count(subject) FROM student_details WHERE subject != 'Sc
ience' AND subject != 'Maths' GROUP BY subject;
Instead of:
SELECT subject, count(subject) FROM student_details GROUP BY subject HAV
ING subject!= 'Vancouver' AND subject!= 'Toronto';
3) Sometimes you may have more than one subqueries in your main query. Try to mi
nimize the number of subquery block in your query.
For Example: Write the query as
SELECT name FROM employee WHERE (salary, age ) = (SELECT MAX (salary), M
AX (age) FROM employee_details) AND dept = 'Electronics';
Instead of:
SELECT name FROM employee WHERE salary = (SELECT MAX(salary) FROM employ
ee_details) AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';
4) Use JOIN instead of subqueries. As a programmer, subqueries are something tha
t you can be tempted to use and abuse. Subqueries, as show below, can be very us
eful:
SELECT a.id,(SELECT MAX(created) FROM posts WHERE author_id = a.id) AS l
atest_post FROM authors a
Although subqueries are useful, they often can be replaced by a join, which is d
efinitely faster to execute.
SELECT a.id, MAX(p.created) AS latest_post FROM authors a INNER JOIN pos
ts p ON (a.id = p.author_id) GROUP BY a.id
5) SQL Performance Tuning recommends to use COUNT(1) instead COUNT(*) for perfor
mance optimization.
6) If you are using more than one table use table aliases.
7) EXSISTS versus IN for subqueries
Note: If the selective predicate is in the subquery, then use IN. If the
selective predicate is in the parent query, then use EXISTS.

8) SQL Performance Tuning recommends to use CASE statements


It is more efficient to run single statement if possible than two separate state
ments for the same result.
Example:
Do not
SELECT
FROM
WHERE

use:
COUNT (1)
emp
salary < 1000;

SELECT COUNT (1)


FROM emp
WHERE salary BETWEEN 1000 AND 2000;
Use:
SELECT COUNT (CASE WHEN
THEN
COUNT (CASE WHEN
THEN
FROM emp;

salary
1 ELSE
salary
1 ELSE

< 1000
null END) count_1,
BETWEEN 1001 AND 2000
null END) count_2

9) WHERE statement compare string with string or number with number.


Example:
Note: Column id is NUMBER Data Type.
Do not use:
SELECT id, apn, charging_class FROM master WHERE id = '4343';
Use:
SELECT id, apn, charging_class FROM master WHERE id = 4343;
10) COUNT only counts non-null values (except for count(*)).
------------------------------------------------------------------------------------------------------------------------------------------------PL / SQL
%TYPE - This is used to follow the data type and size of any column of any table
. EX : v_ename emp.enmae%type;
%ROWTYPE - used to declare a variable having same data type and size of all the
fields of record of any table. EX : v_dept dept%rowtype
Structure:
Declare
x number;
begin
x:=&num1;
DBMS_OUTPUT.PUT_LINE(X);
EXCEPTION
END;

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

Anda mungkin juga menyukai