Sunday, 17 January 2016

Oracle Data Types

PL/SQL is a Programming Language with SQL commands. Since oracle is an RDBMS, we can not define our own programs by only using it. That’s why it supports a language called PL/SQL. We can compile the sql and non sql statements for performing an action that is related to either a data in the data base or not related to data base.

Oracle Data types :

The information in a database is maintained in the form of table, each table consists of rows and columns to store the data. A particular column in a table must contain similar data, which is of a particular type.
The following are different data types supported by ORACLE
1. CHAR This data type is used to store fixed length character of the specified length. Where the maximum size is 255 bytes for columns/rows.
Syntax: char (size)
Example : Result char(4)
2. VARCHAR2 This data type is used to store variable length characters.
Maximum it can take is 2000 bytes for columns/row.
Syntax: varchar2 (size)
Example : sname varchar2(15)
3. NUMBER this data type is used to store both numbers and numbers with decimal pointes. It can take maximum precision up to 38 digits after decimal.
Syntax: Number(value, precisions)
Example : Empno number(5) -> Pure Integers
Sal number(6,2) -> Numbers With Decimals
4. DATE This data type is used to store date and time in a table. The date data types stores year (including the century) . the month, the days, hours, minutes, seconds. The maximum size is 7 bytes for each row in a table.
Syntax: Date
Example : Doj Date
5. LONG This data type is used to store variable length character containing up to 2 GB of information.
Syntax: Long
Example : Remarks Long
Restriction of Long
There are some restrictions of long data type.
1) Only one column is defined as long for table.
2) Long columns con not be indexed.
3) Long columns can’t appear in integrity constraints.
4) Long columns can’t be used in SQL expressions.
5) Long columns cannot be referenced by the SQL function

Oracle Query Tuning

If query taking long time then First will run the query in Explain Plan, The explain plan process stores data in the PLAN_TABLE.
it will give us execution plan of the query like whether the query is using the relevant indexes on the joining columns or indexes to support the query are missing.
If joining columns doesn’t have index then it will do the full table scan if it is full table scan the cost will be more then will create the indexes on the joining columns and will run the query it should give better performance and also needs to analyze the tables if analyzation happened long back. The ANALYZE statement can be used to gather statistics for a specific table, index or cluster using
ANALYZE TABLE employees COMPUTE STATISTICS;
If still have performance issue then will use HINTS, hint is nothing but a clue. We can use hints like
  • ALL_ROWS
    One of the hints that 'invokes' the Cost based optimizer
    ALL_ROWS is usually used for batch processing or data warehousing systems.
(/*+ ALL_ROWS */)
  • FIRST_ROWS
    One of the hints that 'invokes' the Cost based optimizer
    FIRST_ROWS is usually used for OLTP systems.
(/*+ FIRST_ROWS */)
  • CHOOSE One of the hints that 'invokes' the Cost based optimizer
    This hint lets the server choose (between ALL_ROWS and FIRST_ROWS, based onstatistics gathered.
  • HASH Hashes one table (full scan) and creates a hash index for that table. Then hashes other table and uses hash index to find corresponding records. Therefore not suitable for < or > join conditions.
/*+ use_hash */
Hints are most useful to optimize the query performance.

Explain Plan

Explain Plan : It is a statement that allows you to have oracle generate execution plan for any sql statement with out actually executing it.You will be able to examine the execution plan by querying the plan table.
Plan Table : A Plan table holds execution plans generated by the explain plan statements.Create Plan table by  running utlxplan.sql located in
$oracle_home/rdbms/admin.
Explain Plan Syntax :
Explain plan [set statement_id=<string in single quotes>]
[into <plan table name>]
for
<sql statements>;
Example to Explain Plan:
Sql> Explain plan set statement_id=’demo’ for
select a.customer_name,a.customer_number,b.invoice_number,
b.invoice_type,b.invoice_data,b.total_amount,
c.line_number,c.part_number,c.quantity,c.unit_cost
from customers a, invoices b, invoice_items c
where c.invoice_id=:b1
and c.line_number=:b2
and b.invoice_id=c.invoice_id
and a.customer_id=b.customer_id

Sql> @ explain.sql
Enter statement_id : Demo

Frequently Used Data Dictionary Queries

1.Index Table :
Select INDEX_NAME ,INDEX_TYPE,TABLE_OWNER,TABLE_NAME,NUM_ROWS,
LAST_ANALYZED,PARTITIONED From All_Indexes;
2. Index Columns :
select INDEX_NAME,TABLE_OWNER,TABLE_NAME,COLUMN_NAME,
COLUMN_POSITION, COLUMN_LENGTH,CHAR_LENGTH from ALL_IND_COLUMNS;
3. Table Column Level Stats :
Select TABLE_NAME,COLUMN_NAME,NUM_DISTINCT,LAST_ANALYZED,AVG_COL_LEN from All_Tab_Col_Statistics;
4. Constraints on a table:
select CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME,SEARCH_CONDITION,
LAST_CHANGE,INDEX_OWNER,INDEX_NAME from All_Constraints;
5. Text of a View:
select view_name,text,owner from All_Views;
6. Text of a Trigger :
select   trigger_name,trigger_type,triggering_event,table_owner,table_name,
description,trigger_body from all_triggers;
7. Locks on Table:
select c.owner,c.object_name,c.object_type,c.object_id,b.sid,b.serial#,
b.status,b.osuser,b.machine,a.LOCKED_MODE from v$locked_object
a ,v$session b,dba_objects c where b.sid = a.session_id and  a.object_id =
c.object_id;
Locking Modes Description:
0- none
1 - null (NULL)
2 - row-S (SS)
3 - row-X (SX)
4 - share (S)
5 - S/Row-X (SSX)
6 - exclusive (X)
8. Query to Kill a Session :
alter system kill session(sid,serial no)
9.Find the Actual size of a Database
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;
10.Find the size occupied by Data in a Database or Database usage details
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;
11. Last SQL fired by the User on Database
SELECT S.USERNAME || '(' || s.sid || ')-' || s.osuser UNAME, s.program || '-' ||
s.terminal || '(' || s.machine || ')' PROG,s.sid || '/' || s.serial# sid, s.status
"Status",p.spid,sql_text sqltext FROM v$sqltext_with_newlines t,
V$SESSION s, v$process p   WHERE t.address = s.sql_address   AND
p.addr = s.paddr(+) AND t.hash_value = s.sql_hash_value  ORDER BY s.sid,
t.piece;
12. CPU usage of the USER
SELECT ss.username, se.SID, VALUE / 100 cpu_usage_seconds FROM
v$session ss, v$sesstat se, v$statname sn WHERE  se.STATISTIC# =
sn.STATISTIC#  AND NAME LIKE '%CPU used by this session%' AND se.SID
= ss.SID AND ss.status = 'ACTIVE' AND ss.username IS NOT NULL ORDER
BY VALUE DESC;
13. Long Query progress in database
SELECT a.sid,a.serial#,b.username,opname OPERATION,target
OBJECT,TRUNC (elapsed_seconds, 5) "ET (s)",TO_CHAR (start_time,
'HH24:MI:SS') start_time,ROUND ( (sofar / totalwork) * 100, 2) "COMPLETE
(%)" FROM v$session_longops a, v$session b  WHERE     a.sid = b.sid  AND
b.username NOT IN ('SYS', 'SYSTEM') AND totalwork > 0 ORDER BY
elapsed_seconds;
14.Last DDL SQL Fired from particular Schema or Table:
SELECT CREATED, TIMESTAMP, last_ddl_time  FROM all_objects  WHERE     OWNER = 'MYSCHEMA'  AND OBJECT_TYPE = 'TABLE' AND OBJECT_NAME = 'EMPLOYEE_TABLE';
15.Find Top 10 SQL by reads per execution
SELECT * FROM (  SELECT ROWNUM,SUBSTR (a.sql_text, 1, 200)
sql_text,TRUNC (a.disk_reads / DECODE (a.executions, 0, 1, a.executions))
reads_per_execution,a.buffer_gets,a.disk_reads,a.executions,a.sorts,a.address
FROM v$sqlarea a ORDER BY 3 DESC) WHERE ROWNUM < 10;
16.Oracle SQL query that show the opened connections group by the program that opens the connection.
SELECT program application, COUNT (program) Numero_Sesiones FROM
v$session GROUP BY program ORDER BY Numero_Sesiones DESC;
17.Get number of objects per owner
SELECT owner, COUNT (owner) number_of_objects FROM dba_objects
Group By Owner ORDER BY number_of_objects DESC;
18.Oracle SQL query that shows Oracle users connected and the sessions number for user
SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones
FROM v$session Group By Username ORDER BY Numero_Sesiones DESC;
19. DML Operation Audit
select username ,obj_name ,to_char(timestamp,'dd-mon-yy hh24:mi')
event_time  ,substr(ses_actions,4,1) del  ,substr(ses_actions,7,1)
ins ,substr(ses_actions,10,1) sel  ,substr(ses_actions,11,1) upd  from dba_audit_object;
20.SQL Statements with Maximum Wait
select ash.user_id, u.username, s.sql_text, sum(ash.wait_time +
ash.time_waited) ttl_wait_time from v$active_session_history ash,
v$sqlarea s, dba_users u where ash.sample_time between sysdate -
60/2880 and sysdate and ash.sql_id = s.sql_id and ash.user_id = u.user_id
group by ash.user_id,s.sql_text, u.username order by ttl_wait_time ;
21. SQL Text:
select sid, sql_text from v$session s, v$sql q where sid in (* ,*) and
(q.sql_id = s.sql_id or q.sql_id = s.prev_sql_id);
Note:
Provide the Sid for which you wish to see the SQL Text else list will be exhaustive.
22.query to find out which session is currently using the most undo
select s.sid, t.name, s.value from v$sesstat s, v$statname t where
s.statistic# = t.statistic# and t.name = 'undo change vector size' order by
s.value desc;
23. Monitoring Temporary Tablespace Usage
select * from (select a.tablespace_name,sum(a.bytes/1024/1024)
allocated_mb  from dba_temp_files a where a.tablespace_name = upper
('&&temp_tsname') group by a.tablespace_name) x, (select sum
(b.bytes_used/1024/1024) used_mb, sum(b.bytes_free/1024/1024)
free_mb  from v$temp_space_header b where b.tablespace_name=upper
('&&temp_tsname') group by b.tablespace_name);
24. query to find out which sessions are using space in the temporary tablespace.
select s.sid || ',' || s.serial# sid_serial, s.username, s.osuser,
p.spid,s.module,s.program,sum (o.blocks) * t.block_size / 1024 / 1024
mb_used, o.tablespace,count(*) sorts from v$sort_usage o, v$session s,
dba_tablespaces t, v$process p where o.session_addr = s.saddr and
s.paddr = p.addr and o.tablespace = t.tablespace_name group by s.sid,
s.serial#, s.username, s.osuser, p.spid, s.module, s.program, t.block_size,
o.tablespace order by sid_serial;

SQL Loader

SQL*Loader (sqlldr ) is the utility to use for high performance data loads. The data can be loaded from any text file and inserted into the database.
During processing, SQL*Loader writes messages to the log file, bad rows to the bad file, and discarded rows to the discard file.
The SQL*Loader control file contains information that describes how the data will be loaded. It contains the table name, column data types, field delimiters, etc. It simply provides the guts for all SQL*Loader processing.
SQL*Loader provides the following options, which can be specified either on the command line or within a parameter file:
  1.  bad – A file that is created when at least one record from the input file is rejected. The rejected data records are placed in this file. A record could be rejected for many reasons, including a non-unique key or a required column being null.
  2.  bindsize – [256000] The size of the bind array in bytes.
  3.  columnarrayrows – [5000] Specifies the number of rows to allocate for direct path column arrays.
  4.  control – The name of the control file. This file specifies the format of the data to be loaded.
  5. data – The name of the file that contains the data to load.
  6.  direct – [FALSE] Specifies whether or not to use a direct path load or conventional.
  7. discard – The name of the file that contains the discarded rows. Discarded rows are those that fail the WHEN clause condition when selectively loading records.
  8.   discardmax – [ALL] The maximum number of discards to allow.
  9. errors – [50] The number of errors to allow on the load.
  10. external_table – [NOT_USED] Determines whether or not any data will be loaded using external tables. The other valid options include GENERATE_ONLY and EXECUTE.
  11. file – Used only with parallel loads, this parameter specifies the file to allocate extents from.
  12. load – [ALL] The number of logical records to load.
  13.  log – The name of the file used by SQL*Loader to log results.
  14.  multithreading – The default is TRUE on multiple CPU systems and FALSE on single CPU systems.
  15.  parfile – [Y] The name of the file that contains the parameter options for SQL*Loader.
  16.  parallel – [FALSE] Specifies a filename that contains index creation statements.
  17.  readsize – The size of the buffer used by SQL*Loader when reading data from the input file. This value should match that of bindsize.
  18.  resumable – [N] Enables and disables resumable space allocation. When “Y”, the parameters resumable_name and resumable_timeout are utilized.
  19.  resumable_name – User defined string that helps identify a resumable statement that has been suspended. This parameter is ignored unless resumable = Y.
  20.  resumable_timeout – [7200 seconds] The time period in which an error must be fixed. This parameter is ignored unless resumable = Y.
  21.  rows – [64] The number of rows to load before a commit is issued (conventional path only). For direct path loads, rows are the number of rows to read from the data file before saving the data in the datafiles.
  22.  silent – Suppress errors during data load. A value of ALL will suppress all load messages. Other options include DISCARDS, ERRORS, FEEDBACK, HEADER, and PARTITIONS.
  23.  skip – [0] Allows the skipping of the specified number of logical records.
  24.  skip_unusable_indexes – [FALSE] Determines whether SQL*Loader skips the building of indexes that are in an unusable state.
  25.  skip_index_maintenance – [FALSE] Stops index maintenance for direct path loads only.
  26.  streamsize – [256000] Specifies the size of direct path streams in bytes.
  27.  userid – The Oracle username and password.

  1. To drive the concept of the SQL loader home.., let us assume that we have text file which is the usual emp table.
  2. Now open the cmd prompt and type sqlldr.
  3. later the things should look some thing like this.
sqlldr# userid=username/pwd@ora
load data
in file ‘C:\emp.txt’
into table emp_oracle
fields terminated by “,”optionally enclosed by’ ” ’
(empno,ename,job,mgr,sal,comm,deptno)

Materialized view

A materialized view is a database object that contains the results of a query. They are local copies of data located remotely, or are used to create summary tables based on aggregations of a table's data.Materialized view and the Query rewrite feature is added from ORACLE 8i.
A materialized view log is a schema object that records changes to a master table's data so that a materialized view defined on the master table can be refreshed incrementally.
  • If you delete any record from your Materialized view it is goanna impact your Source table once it is refreshed.
Examples to the Simple Materialized view’s is given below .
Eg 1 :Create materialized_view MV refresh as select * from emp;
Execute dbms_mview.refresh(‘MV’);

Refresh Complete : To perform a complete refresh of a materialized view, the server that manages the materialized view executes the materialized view's defining query, which essentially recreates the materialized view. To refresh the materialized view, the result set of the query replaces the existing materialized view data. Oracle can perform a complete refresh for any materialized view. Depending on the amount of data that satisfies the defining query, a complete refresh can take a substantially longer amount of time to perform than a fast refresh.
Create Materialized_view MV Refresh complete as select * from emp;
execute DBMS_mview.refresh(List=>’MV’,Method=>’c’);

Refresh Fast :To perform a fast refresh, the master that manages the materialized view first identifies the changes that occurred in the master since the most recent refresh of the materialized view and then applies these changes to the materialized view. Fast refreshes are more efficient than complete refreshes when there are few changes to the master because the participating server and network replicate a smaller amount of data.
Create Materialized_view MV Refresh fast as select * from emp;
execute DBMS_mview.refresh(list=>’MV’,Method=>’F’);

Primary Key Materialized Views :
The following statement creates the primary-key materialized view on the table emp located on a remote database.
SQL>  CREATE MATERIALIZED VIEW mv_emp_pk
    REFRESH FAST START WITH SYSDATE 
 NEXT  SYSDATE + 1/48
 WITH PRIMARY KEY 
 AS SELECT * FROM emp@remote_db;


Note: When you create a materialized view using the FAST option you will need to create a view log on the master tables(s) as shown below:
SQL> CREATE MATERIALIZED VIEW LOG ON emp;Materialized view log created.

Rowid Materialized Views :
The following statement creates the rowid materialized view on table emp located on a remote database:
SQL>CREATE MATERIALIZED VIEW mv_emp_rowid REFRESH WITH ROWID    AS SELECT * FROM emp@remote_db;

Materialized view log created.

Creating Materialized Aggregate Views :
CREATE MATERIALIZED VIEW sales_mv BUILD IMMEDIATE REFRESH FAST ON COMMIT AS SELECT t.calendar_year, p.prod_id, SUM(s.amount_sold) AS sum_sales FROM times t, products p, sales s WHERE t.time_id = s.time_id AND p.prod_id = s.prod_id GROUP BY t.calendar_year, p.prod_id;

Creating Materialized Join Views :
CREATE MATERIALIZED VIEW sales_by_month_by_state
     TABLESPACE example
     PARALLEL 4
     BUILD IMMEDIATE
     REFRESH COMPLETE
     ENABLE QUERY REWRITE
     AS SELECT t.calendar_month_desc, c.cust_state_province,
        SUM(s.amount_sold) AS sum_sales
        FROM times t, sales s, customers c
        WHERE s.time_id = t.time_id AND s.cust_id = c.cust_id
        GROUP BY t.calendar_month_desc, c.cust_state_province;

Periodic Refresh of Materialized Views:
CREATE MATERIALIZED VIEW emp_data 
   PCTFREE 5 PCTUSED 60 
   TABLESPACE example 
   STORAGE (INITIAL 50K NEXT 50K)
   REFRESH FAST NEXT sysdate + 7 
   AS SELECT * FROM employees; 

Automatic Refresh Times for Materialized Views
CREATE MATERIALIZED VIEW all_customers
   PCTFREE 5 PCTUSED 60 
   TABLESPACE example 
   STORAGE (INITIAL 50K NEXT 50K) 
   USING INDEX STORAGE (INITIAL 25K NEXT 25K)
   REFRESH START WITH ROUND(SYSDATE + 1) + 11/24 
   NEXT NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 15/24 
   AS SELECT * FROM sh.customers@remote 
         UNION
      SELECT * FROM sh.customers@local;

Control structures

Control structures
Control structures are used to control the flow of programs execution. The control structures are classified into the following categories:
  • Conditional Control
  •  Iterative Control
Conditional Control
PL/SQL supports the following types of Conditional control statements or Selection Statements
  1. Simple if statement
  2. If...else statement
  3. If ...elsif statement
1.Simple If
The simple if statement is used to check a simple condition, if it is true it will execute the statements that are present between "if "and "end if". Otherwise it will not execute those statements.
Syntax :
If ( Condition ) then
Statements ;
------------- ;
End If;
2.If...Else Statement
The if …else statement is used to define two blocks of statements, in order to execute only one block.
Syntax :
If (Condition ) then
True Block Statements ;
------------------------- ;
Else
False Block Statements ;
-------------------------- ;
End if;
if the condition is true, it will execute the True Block statements otherwise it will execute the false block statements.
3.If...ElsIf Statement
The if …elsIf statement is used to define Several blocks of statements, in order to execute only one block.
Syntax :
If (condition 1) then
statements 1 ;
--------------- ;
Elsif (condition 2) then
statements 2;
------------- ;
Elsif (condition 3) then
statements 3;
------------;
|
|
Elsif (condition n) then
statements n;
------------;
Else
statements;
------------;
End if;
if condition1 is true, it will execute statements1 otherwise it will check Condition2, if it is true it will execute statements2. if not it will go to condition3, like this the process continues until the condition matches. If no condition matches, it will execute the else block statements.
Eg 1. Write a program to check whether the given number is a positive number of a negative number using simple if statement
declare
n number:=&n;
begin
if(n>=0) then
dbms_output.put_line(n||' is a Positive Number');
end if;
if(n<0) then
dbms_output.put_line(n ||' is a Negative Number');
end if;
end;
/
Branching Statements
declare
x integer:=&x;
y integer:=&y;
p char(1):='&Operator';
r number;
begin
if p='+' then
goto Addition;
elsif p='-' then
goto Subtraction;
elsif p='*' then
goto Multiplication;
elsif p='/' then
goto Division;
else
goto Expt;
end if;
<<Addition>>
r:=x+y;
dbms_output.put_line(r);
return;
<<Subtraction>>
r:=x-y;
dbms_output.put_line(r);
return;
<<Multiplication>>
r:=x*y;
dbms_output.put_line(r);
return;
<<Division>>
r:=x/y;
dbms_output.put_line(r);
return;
<<Expt>>
dbms_output.put_line(sqlerrm);
end;
/                   
Loops
PL/SQL supports, the following types of loops
1. Simple Loop
2. While Loop
3. For Loop


 1.Simple Loop
This loop is used to execute a series of statements as long as the condition is false. If the condition becomes true, it will exit from that loop


Syntax :
Loop
Statements;
-----------
Exit When <condition>;
Increment/decrement Operations
End Loop;

Eg 2 :Write a program to print first 25 natural numbers using simple loop
Declare
N number:=1;
Begin
Loop
Exit When N>25;
Dbms_output.put_line(N);
N:=N+1;
End loop;
End;
/


2.While Loop
The while Loop is used to execute a series of statements as long as the condition is True. If the condition becomes false, it will exit from that loop
Syntax :
While <condition> Loop


Statements;
-----------
[ Exit When <condition>; ]
Increment/decrement Operations
End Loop;

Eg 3: Write a program to print first 25 natural numbers using While loop
Declare
N number:=1
Begin
While N<=25 Loop
Dbms_output.put_line(N);
N:=N+1;
End loop;
End;
/


3.For Loop
The For loop is used to execute a set of statements as long as the condition is false. If the condition becomes true, it will exit from that loop
Syntax :
For <variable> in [reverse] <start value> .. <end Value> Loop


Statements;
-----------
End Loop;

Eg 4: Write a program to print first 25 natural numbers using For loop
Declare
N number:=1;
Begin
For N in 1..25 Loop
Dbms_output.put_line(N);
End loop;
End;
/


Eg 5 :Write a program to print first 25 natural numbers using For loop in Reverse order
Declare
N number:=1;
Begin
For N in Reverse 1..25 Loop
Dbms_output.put_line(N);
End loop;
End;
/

Eg 6: Write a program to print multiplication table for the given number
Declare
i number:=1;
r number:=&number;
Begin
While i<=10 loop
dbms_output.put_line(r||'*'|| i ||'='||r*i);
i:=i+1;
End loop;
End;
/