Sunday, 31 March 2013

Loops in Oracle

1 comments


The ability to repeat or skip sections of a block can be achieved with the usage of LOOP or GOTO statements
 There are three forms of the LOOP statement
      LOOP
      WHILE-LOOP
      FOR-LOOP

LOOP Statement
LOOP repeats a sequence of statements
Statements to be repeated are placed between keyword LOOP and END LOOP
With each iteration of the loop, the sequence of statements is executed, then control resumes at the top of the loop.

LOOP
statements;
END LOOP;

EXIT Statement:

 Used to complete a loop if further processing in a loop is undesirable or impossible
There are two forms of the EXIT statement
      EXIT
      EXIT-WHEN
Forces a loop to complete unconditionally
Must be placed inside a loop

LOOP
statements;
IF <condition> THEN
EXIT;   -- exit loop immediately
END IF;
END LOOP;

-- control resumes here 

Example of Loop
/*To show 1 to 10 on screen*/

Declare
    x number;
Begin
    x :=  1;
     Loop
             dbms_output.put_line(x);
              x := x + 1;
              exit when x > 10;
      End Loop;
 End;

create table five
(no number);
/*Inserting mutliples of five in table five*/

Declare
    x number;
Begin
        x := 5;
         Loop
               Insert into five
                values(x);
                x := x + 5;
                exit when x > 50;
          End Loop;
End;

FOR LOOP
  
Advantages --

  1) No need of declaring loop variable
  2) No need of giving condition
 3) No need of updation statement (increment or decrement )
 4)Code becomes small and compact
 Disadvantage --
   Updation can be done by only one.
                                
   Syntax –

FOR <counter> IN [REVERSE]
lower_bound .. higher_bound LOOP
statements;
END LOOP

Example 1 of for loop   
/*To show 1 to 10 on screen*/

begin
    for x in 1..10
    Loop
              dbms_output.put_line(x);
   End Loop;
end;
 Example 2
   /*Reverse for loop  10,9,8 … 1*/

Begin
           for  i in REVERSE 1 ..10
            Loop
                    dbms_output.put_line(i);
             End Loop;
end;

Example 3 –
 Calculating compound interest for a principal of Rs.100 @10% for each year.
  Values will be shown of the CI after each year.

create table CI_100
(year number(2),
total number(4));
----------------------------------
Declare
     p number := 100;
     tot number;
/*Calculation of compound interest.
   Rs.100 is principal.
   Rate of interest is 10%.
    Period is 5 years.
 */
Begin
 for y in 1..5
    Loop
    /* Tot variable is getting 10% more than p */
    tot := p + p * 0.10;
    Insert into CI_100
    values(y,tot);
    /*Since the next interest is based on the current interest
      so the tot will be considered as p for the next year*/
    p := tot;
    End Loop;
end;


WHILE-LOOP Statement:

 Associates a condition with a sequence of statements enclosed within LOOP-END LOOP
 Condition evaluated before each iteration
 If condition evaluates to TRUE, sequence of statements is executed and control resumes at the top of the loop
 If condition evaluates to FALSE or NULL, loop is bypassed and control passes to next statement
 Number of iterations depends on the condition and is unknown until the loop completes.

WHILE <condition>
LOOP
statements;
END LOOP;

Example 1 of while loop to show 1 to 15

declare
  x number;
Begin
   x := 1;
   while x <=15
    Loop
            dbms_output.put_line(x);
            x := x + 1;
    End Loop;
end;

Example 2  Forces a loop to complete unconditionally

declare
 z number;
/*Using break after z reaches to 8*/
Begin
   z := 1;
   while z <=15
    Loop
            dbms_output.put_line(z);
            z := z + 1;
             exit when z = 8;
    End Loop;
end;



Ur's
AmarAlam

External Tables in Oracle

1 comments

External Tables:
---------------
External tables allow Oracle to query data that is stored outside the database in flat files.
The ORACLE_LOADER driver can be used to access any data stored in any format that can be loaded by SQL*Loader.

 No DML can be performed on external tables but they can be used for query, join and sort operations.
 Views and synonyms can be created against external tables. They are useful in the ETL process of data warehouses
 since the data doesn't need to be staged and can be queried in parallel.
They should not be used for frequently queried tables.


Next we create a directory object which points to the location of the files:

create or replace directory dir_Test as 'D:\'


Next we create the metadata for the external table using the CREATE TABLE..ORGANIZATION EXTERNAL syntax:



SQl> drop table external_temp;

SQl> create  table external_temp
     (empno number(3),ename varchar2(10),deptno number,sal number(7,2))
      organization external
        (type oracle_loader
           default directory dir_test
            access parameters(
             records delimited by newline
               fields terminated by ','
               missing field values are null
     (empno,ename,deptno,sal))
        location  ('data1.txt'))
          reject limit unlimited;

SQl> select * from external_temp;


External Tables Containing LOB Data:
-----------------------------------

The foolowing is the file name having two records.

lob_test_data.txt:
----------------

1,one,01-JAN-2006,clob_test1.txt,blob_test1.doc
2,two,02-JAN-2006,clob_test2.txt,blob_test2.doc

The first two documents are plain text files, while the second two are Microsoft Word documents.
 The documents contain the CLOB and BLOB data to be read by the external table

DROP TABLE lob_tab;

CREATE TABLE lob_tab (
  number_content    NUMBER(10),
  varchar2_content  VARCHAR2(100),
  date_content      DATE,
  clob_content      CLOB,
  blob_content      BLOB
)
ORGANIZATION EXTERNAL
(
  TYPE ORACLE_LOADER
  DEFAULT DIRECTORY temp_dir
  ACCESS PARAMETERS
  (
    RECORDS DELIMITED BY NEWLINE
    BADFILE temp_dir:'lob_tab_%a_%p.bad'
    LOGFILE temp_dir:'lob_tab_%a_%p.log'
    FIELDS TERMINATED BY ','
    MISSING FIELD VALUES ARE NULL
    (
      number_content    CHAR(10),
      varchar2_content  CHAR(100),
      date_content      CHAR(11) DATE_FORMAT DATE MASK "DD-MON-YYYY",
      clob_filename     CHAR(100),
      blob_filename     CHAR(100)
    )
    COLUMN TRANSFORMS (clob_content FROM LOBFILE (clob_filename) FROM (temp_dir) CLOB,
                       blob_content FROM LOBFILE (blob_filename) FROM (temp_dir) BLOB)
  )
  LOCATION ('lob_test_data.txt')
)
PARALLEL 2
REJECT LIMIT UNLIMITED
/


There are two things to note:
------------------------------

The field names of the LOB data (clob_filename, blob_filename) do not match the column names (clob_content, blob_content).

 This emphasizes these fields in the datafile do not contain the actual data, just filenames where the data can be found.

The COLUMN TRANSFORMS clause explains how the CLOB and BLOB data should be loaded.
 In this case we are using a field from the datafile to identify the filename and a constant for the directory name.
 To load from multiple directories use an additional field in the datafile to identify directory object.


Ur's
AmarAlam

Introduction to PLSQL

1 comments

Advantages of PL/SQL:
---------------------

PL/SQL is a completely portable, high-performance transaction processing language
 that offers the following advantages:

Support for SQL
Support for object-oriented programming
Better performance
Higher productivity
Full portability
Tight integration with Oracle
Tight security


Better Performance:
------------------
Without PL/SQL, Oracle must process SQL statements one at a time.
Each SQL statement results in another call to Oracle and higher performance overhead.
 In a networked environment, the overhead can become significant. Every time a SQL statement is issued,
 it must be sent over the network, creating more traffic.

However, with PL/SQL, an entire block of statements can be sent to Oracle at one time.
This can drastically reduce communication between your application and Oracle.
PL/SQL stored procedures are compiled once and stored in executable form, so procedure calls are quick and efficient.

Higher Productivity:
-------------------
PL/SQL adds functionality to non-procedural tools such as Oracle Forms and Oracle Reports.
With PL/SQL in these tools, you can use familiar procedural constructs to build applications

Full Portability:
----------------
Applications written in PL/SQL are portable to any operating system and platform on which Oracle runs.
 In other words, PL/SQL programs can run anywhere Oracle can run;

PL/SQL features:


 PL/SQL is an extension of SQL
 It is an application development language containing procedural statements and commands along with SQL commands.
It bridges the gap between database technology and procedural programming languages
It allows you to process data using flow control statements like iterative loops and conditional branching.
Uses procedural techniques of control, looping and branching.
Supports SQL i.e. cursor operations, exceptions, functions and transactional commands
Variables and constants, robust error handling and functions.
Adds functionality to non-procedural tools such as SQL*Forms.
Developers using SQL*Forms can enter an entire PL/SQL block using a single trigger.

Structure of PL/SQL:


Standard PL/SQL code segment is called a Block
A block consists of three parts or sections
      Declaration Part
      Executable Part
      Exception Handling Part


Declaration Part
      optional part where variables  are defined
 Executable Part
      mandatory part which consists of executable statements
 Exception Handling Part
      optional part which consists of code for handling errors (run time).


Ur's
AmarAlam

Saturday, 30 March 2013

Set Operators in Oracle

0 comments



You can combine multiple queries using the set operators UNION, UNION ALL, INTERSECT, and MINUS.
 All set operators have equal precedence.


UNION:
------

The following statement combines the results of two queries with the UNION operator,
 which eliminates duplicate selected rows. This statement shows that you must match datatype
(using the TO_CHAR function) when columns do not exist in one or the other table:

SQL> SELECT location_id, department_name "Department",
   TO_CHAR(NULL) "Warehouse"  FROM departments
   UNION
   SELECT location_id, TO_CHAR(NULL) "Department", warehouse_name
   FROM warehouses;


LOCATION_ID Department            Warehouse
----------- --------------------- --------------------------
       1400 IT
       1400                       Southlake, Texas
       1500 Shipping
       1500                       San Francisco
       1600                       New Jersey
       1700 Accounting
       1700 Administration
       1700 Benefits
       1700 Construction


UNION ALL:
---------

The UNION operator returns only distinct rows that appear in either result,
 while the UNION ALL operator returns all rows.
The UNION ALL operator does not eliminate duplicate selected rows:

SQL> SELECT product_id FROM order_items
      UNION
     SELECT product_id FROM inventories;

SQL> SELECT location_id  FROM locations
     UNION ALL
     SELECT location_id  FROM departments;

A location_id value that appears multiple times in either or both queries (such as '1700')
is returned only once by the UNION operator, but multiple times by the UNION ALL operator.


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

The following statement combines the results with the INTERSECT operator,
 which returns only those rows returned by both queries:

SQL> SELECT product_id FROM inventories
      INTERSECT
     SELECT product_id FROM order_items;

MINUS :
-------

The following statement combines results with the MINUS operator,
 which returns only rows returned by the first query but not by the second:

SQL> SELECT product_id FROM inventories
     MINUS
     SELECT product_id FROM order_items;



If you want to use ORDER BY in a query involving set operations,
you must place the ORDER BY at the end of the entire statement.
The ORDER BY clause can appear only once at the end of the compound query.
The component queries can't have individual ORDER BY clauses. For example:

SQl> SELECT cust_nbr, name FROM customer WHERE region_id = 5
     UNION
     SELECT emp_id, lname FROM employee WHERE lname = 'MARTIN'
     ORDER BY cust_nbr;


Restrictions on the Set Operators:
---------------------------------
-->Columns and datatype in  the select queries should match.
   (i.e number of columns in the first query equal to number of columns in the second query)

--->The set operators are not valid on columns of type BLOB, CLOB, BFILE, VARRAY, or nested table.

--->The UNION, INTERSECT, and MINUS operators are not valid on LONG columns.

--->If the select list preceding the set operator contains an expression,
    then you must provide a column alias for the expression in order to refer to it
    in the order_by_clause.

--->we cannot also specify the for_update_clause with the set operators.

--->we cannot specify the order_by_clause in the subquery of these operators.

--->we cannot use these operators in SELECT statements containing TABLE collection expressions


Ur's
AmarAlam

Clusters in Oracle

1 comments

CLUSTERS:
------------
Oracle Index Cluster Tables

Unlike the hash cluster where the symbolic key is hashed to the data block address,
an index cluster uses an index to maintain row sequence.

A table cluster is a group of tables that share the same data blocks,
since they share common columns and are often used together. When you create cluster tables,
Oracle physically stores all rows for each table in the same data blocks

Index cluster tables can be either multi-table or single-table.
Lets take a look at each method.

SINGLE TABLE CLUSTER:
-------------------

SYNTAX
------
SQL> create  cluster clus_emp (ename  VARCHAR2(10))
size 1024 single table  hashkeys 11  ;

SQL> select * from user_clusters


SQL> create table emp
      cluster clus_emp(ENAME) as
     select * from SCOTT.emp;


Multi-Table Cluster
------------------
SYNTAX
------
SQL> create  cluster clus_emp (DEPTNO  NUMBER(2))
size 1024  hashkeys 142  ;


CREATE TABLE empcluster (
empno    NUMBER(10),
sal      NUMBER(10),
ename     VARCHAR2(10),
deptno number(2))
CLUSTER clus_emp (deptno);

CREATE TABLE deptcluster (
deptno          NUMBER(2),
dname     VARCHAR2(15),
loc          VARCHAR2(5))
CLUSTER clus_emp (deptno);


Cluster index
-------------
Create index on cluster is called cluster index.

CREATE INDEX indx_cluster ON CLUSTER clus_emp;

In above query "indx_cluster" is the index name and "clus_emp" is the cluster name.

SELECT index_name, index_type, tablespace_name FROM user_indexes;


DROP CLUSTER
------------

SQL> drop cluster clus_emp;

SQL> drop cluster clus_emp INCLUDING TABLES



Ur's
AmarAlam

Index in Oraccle

0 comments

What is an Index?
----------------

An index is a performance-tuning method of allowing faster retrieval of records.
 An index creates an entry for each value that appears in the indexed columns.
 By default, Oracle creates B-tree indexes.

SELECT index_name, index_type
FROM user_indexes;

Create an Index:
----------------
The syntax for creating a index is:

SQl> CREATE  INDEX index_name
  ON table_name (column1, column2, . column_n)
  [ COMPUTE STATISTICS ];


COMPUTE STATISTICS tells Oracle to collect statistics during the creation of the index.
The statistics are then used by the optimizer to choose a "plan of execution" when SQL statements are executed.

Example:
--------

SQl>  CREATE INDEX Contract_idx  ON Contract (Policynumber);

In this example, we've created an index on the Contract table called Contract_idx.
It consists of only one field - the Policynumber field.

We could also create an index with more than one field as in the example below:


SQl> CREATE INDEX Contract_indx ON Contract (Policynumber,product_code);

The above statement is called as composite index.

B-Tree Index:
------------

By default, the Oracle creates a b_tree index.
 In a b-tree, you walk the branches until you get to the node that has the data you want to use.

B-tree indexes are created to decrease the amount of I/O required to find and load a set of data


SQL>create index indx_product on product(productid,product_name);

SQl> select * from product where productid='P01';

above query uses the index scan  by using the above index.


SQl> select product_name from product where productid='P01';

above query uses the index scan  by using the above in.
It will not go to table scan level because we have created index on two columns productid and product_name.

SQl> select product_name from product where product_name='Product1';

above query does not use the index scan  because WHERE clause does not contain the index lead column means
"productid" is the lead column in the index.

Note:--> Never create balance tree(B-Tree) index on low cardinality column.



Bitmap Index:
------------

Oracle's two major index types are Bitmap indexes and B-Tree indexes.
 B-Tree indexes are the regular type that OLTP systems make much use of,
and bitmap indexes are a highly compressed index type that tends to be used primarily for data warehouses.

Characteristic of Bitmap Indexes:
--------------------------------

For columns with very few unique values (low cardinality) Columns that have low cardinality are good candidates

Tables that have little insert/update are good candidates (static data in warehouse)

Syntax:
------
create bitmap index person_region on person (region);

        Row     Region   North   East   West   South
        1       North        1      0      0       0
        2       East         0      1      0       0
        3       West         0      0      1       0
        4       West         0      0      1       0
        5       South        0      0      0       1
        6       North        1      0      0       0

Advantage of Bitmap Indexes :
----------------------------

The advantages of them are that they have a highly compressed structure,
 making them fast to read and their structure makes it possible for the system to combine multiple indexes
together for fast access to the underlying table.


Disadvantage of Bitmap Indexes :
------------------------------
The reason for confining bitmap indexes to data warehouses is that the overhead on maintaining them is enormous.
 A modification to a bitmap index requires a great deal more work on behalf of the
system than a modification to a b-tree index.

Unique Index :
------------
Indexes can be unique or non-unique. Unique indexes guarantee
that no two rows of a table have duplicate values in the key column.

Use the CREATE UNIQUE INDEX statement to create a unique index.

 The following example creates a unique index:

SQL> CREATE UNIQUE INDEX dept_unique_index ON dept (dname);

The database enforces UNIQUE integrity constraints by automatically defining a unique index on the unique key.


Function-Based Index:
--------------------
In Oracle, you are not restricted to creating indexes on only columns.
 You can create function-based indexes.

Example:
--------

CREATE INDEX Index_name ON Tablename (UPPER(columnname));


SQL> CREATE INDEX Index_name ON PRODUCT (UPPER(PRODUCTNAME));

However, to be sure that the Oracle optimizer uses this index when executing your SQL statements,
 be sure that UPPER(PRODUCTNAME) does not evaluate to a NULL value.
To ensure this, add UPPER(PRODUCTNAME) IS NOT NULL to your WHERE clause as follows:

The query must be guaranteed not to need any NULL values from the indexed expression,
 since NULL values are not stored in indexes.

SELECT PRODUCT_id, UPPER(PRODUCTNAME)
FROM PRODUCT
WHERE UPPER(PRODUCTNAME) IS NOT NULL
ORDER BY UPPER(PRODUCTNAME);

To illustrate a function-based index, consider
the following statement that defines a function-based index (area_index) defined on the function area(geo):

SQL> CREATE INDEX area_index ON rivers (area(geo));

In the following SQL statement, when area(geo) is referenced in the WHERE clause,
 the optimizer considers using the index area_index.

SQL> SELECT id, geo, area(geo) FROM rivers  WHERE Area(geo) >5000;


Invisible Index:
---------------
Beginning with Release 11g, you can create invisible indexes. An invisible index is an index
that is ignored by the optimizer unless you explicitly set the OPTIMIZER_USE_INVISIBLE_INDEXES
initialization parameter to TRUE at the session or system level.
Making an index invisible is an alternative to making it unusable or dropping it.

SQL> CREATE INDEX emp_ename ON emp(ename) INVISIBLE;


Reverse index:
------------
There is an option to create index entries as reversed, which is called reverse key indexes.
 Oracle stores the index entries as their bytes reversed, except rowids

SQL> CREATE INDEX test_indexi ON test_table (a,b,c) REVERSE;

SQL> ALTER INDEX test_index REBUILD NOREVERSE;


Cluster Index:
------------
A cluster is simply a method for storing more then 1 table on the same block.  Normally
-- a block contains data for exactly 1 table. In a cluster -- you have data from many
tables sharing the same block.


Collect Statistics on an Index:
------------------------------

If you forgot to collect statistics on the index when you first created it or you want to update the statistics,
you can always use the ALTER INDEX command to collect statistics at a later date.

The syntax for collecting statistics on an index is:

SQl> ALTER INDEX index_name REBUILD COMPUTE STATISTICS;

INDEX REBUILD:
-------------

By using index rebuild we can improve the performance.

SQL> alter index index_name rebuild;


Rename an Index:
---------------

The syntax for renaming an index is:

SQl> ALTER INDEX index_name RENAME TO new_index_name;


Drop an Index:
-------------

The syntax for dropping an index is:

SQl> DROP INDEX index_name;



B-tree cluster indexes  : defined specifically for cluster
Reverse key indexes     : most useful for Oracle Real Application Clusters applications


Ur's
AmarAlam

Subquery in Oracle

0 comments

ORACLE SUBQUERIES

A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements.
 These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.


Simple Oracle subquery:
----------------------
A simple subquery is evaluated once for each table.

SQL> select empno,ename,job,sal,deptno from emp where
     deptno in (select deptno from dept
where loc = 'New York');


We can use sub queries in From caluse. This type of queries is called InLine Views.

Example:
-------

SQL> Select ename, deptno from
     (select ename, deptno from emp
where job = 'CLERK' )
     where deptno > 20;


We can even replace a column name with sub queries.

Example:
-------

SQL> select ename,(select max(sal) from emp) "maxsal" ,
            sal,((select max(sal) from emp ) - sal ) difference"  from emp;

Sub-Queries with multiple columns in Oracle:
-------------------------------------------

SQL> SELECT * FROM emp WHERE (sal,mgr) = (3000,7566);


SQL>SELECT * FROM emp
    WHERE (sal,mgr) =
    (SELECT sal,mgr FROM emp
             WHERE sal = (SELECT MIN(sal) FROM EMP
                          WHERE sal > (SELECT MIN(sal) FROM emp)))

The above returns all the employees who are earning the same salary and working under
the same manager of the employee earning the second least salary.



SELECT * FROM scott.emp WHERE empno IN   (SELECT empno FROM scott.emp
                          WHERE sal =  (SELECT MAX(sal) FROM scott.EMP WHERE sal <
                                   (SELECT MAX(sal) FROM scott.emp )));

The above query gives us all the employees earning the second highest salary.


Correlated Oracle subquery:
-------------------------

A correlated Oracle subquery is evaluated once FOR EACH ROW
as opposed to a normal subquery which is evaluated only once for each table.

Example:
-------
select all employees whose salary is less than the average of all the employees' salaries in the same department.

SQL> select ename ,sal ,deptno from emp a where
     a.sal < (select avg(sal) from emp b
          where a.deptno = b.deptno)
     order by deptno;


Using a correlated subquery in an update statement:
-------------------------------------------------

SQL>  UPDATE emp a
      set sal = (select avg(sal)
                from emp b
       where
       a.deptno = b.deptno)
      where sal <
  (select avg(sal) from emp c
  where a.deptno = c.deptno);


Using a correlated subquery in an Delete statement:
-------------------------------------------------
delete the highest earning employees in each department.

SQL>  delete from emp a where
      a.sal = (select max(sal) from emp b
 where a.deptno = b.deptno);


Ur's
AmarAlam

Friday, 29 March 2013

Oracle Integrity Constraints

1 comments


Data integrity allows to define certain data quality requirements that the data in the database needs to meet.
 If a user tries to insert data that doesn't meet these requirements,
 Oracle will not allow so.
Several types of Oracle constraints can be applied to Oracle tables to enforce data integrity.

Not Null:--------
This Oracle constraint is used to specify that a column may never contain a NULL value.
This is enforced at SQL insert and update time.
create table Test_notnull (
  a number not null,
  b number     ,
  c number
);

Unique Constraint: -----------------
This Oracle constraint is used to ensure that all column values within a table never contain a duplicate entry.
The unique constraint doesn't allow duplicate values in a column.
If the unique constraint encompasses two or more columns, no two equal combinations are allowed.
create table Test_unique (
  a number unique,
  b number
);

A unique constraint can be extended over multiple columns:
create table ri_3 (
  a number,
  b number,
  c number,
  unique (a,b)
);
Explicitly we are providing name to Unique constraint.
create table ri_3 (
  a number,
  b number,
  c number,
  constraint uq_ri_3 unique (a,b)
);

Primary Key Constraint:----------------------
Primary  Constraint is used to ensure that all column values within a table never contain duplicate and null values.
Primary key is combination of Notnull and Unique.
Table having only one primary key.
We can create primary key on multiple columns that is called composite primary key.
create table Test (
  a number primary key,
  b number
);
We can create primary key on multiple columns that is called composite primary key.
create table ri_primary_key_1 (
  a number,
  b number,
  c number,
  constraint pk_name primary key (a, b)
);

Check Constraint:
----------------
A check constraint allows to state a minimum requirement for the value in a column.
 If more complicated requirements are desired, an insert trigger must be used.

The following table allows only numbers that are between 100 and 1000 in the column empno;
create table Test1 (
  empno number check (a between 100 and 1000),
  sal number
);
Check constraints can be added after a table had been created:
alter table Test1
  add constraint CK_sal check (sal > 5000);
It is also possible to state a check constraint that check the value of more than one column.
The following example makes sure that the value of comm is smaller than the value of sal.
create table Test3 (
  empno number,
  sal     number,
  comm   number,
  check (comm < sal)
);

Foreign Key:-----------
A foreign key constraint (also called referential integrity constraint) on a column ensures that
 the value in that column is found in the primary key of another table.

 If a table has a foreign key that references a table,
 that referenced table can be dropped with a drop table .. cascade constraints.

It is not possible to establish a foreign key on a global temporary table.
If tried, Oracle issues a ORA-14455:

attempt to create referential integrity constraint on temporary table.
initially deferred-->after commiting it will effect
Initially Immediate->will effect immediatly

Here is an example of a single column foreign key constraint:
alter table emp  
add constraint fk_dept_no FOREIGN KEY (deptno)
references dept (dept_no)
initially deferred deferrable;

Here is an example of a multiple column foreign key constraint:
alter table cust_table
add constraint fk_cust_name FOREIGN KEY (person_name, person_gender)
references  person_table (person_name, person_gender)
initially deferred deferrable;

Deferring Constraint Checking:-----------------------------
Sometimes it is necessary to defer the checking of certain constraints,
 most commonly in the "chicken-and-egg" problem. Suppose we want to say:

CREATE TABLE chicken (cID INT PRIMARY KEY,
                      eID INT REFERENCES egg(eID));
CREATE TABLE egg(eID INT PRIMARY KEY,
                 cID INT REFERENCES chicken(cID));
But if we simply type the above statements into Oracle, we'll get an error.
 The reason is that the CREATE TABLE statement for chicken refers to table egg,
which hasn't been created yet! Creating egg won't help either, because egg refers to chicken.
To work around this problem, we need SQL schema modification commands.
 First, create chicken and egg without foreign key declarations:
CREATE TABLE chicken(cID INT PRIMARY KEY,
                     eID INT);
CREATE TABLE egg(eID INT PRIMARY KEY,
                 cID INT);

Then, we add foreign key constraints:

ALTER TABLE chicken ADD CONSTRAINT chickenREFegg
    FOREIGN KEY (eID) REFERENCES egg(eID)
    INITIALLY DEFERRED DEFERRABLE;
ALTER TABLE egg ADD CONSTRAINT eggREFchicken
    FOREIGN KEY (cID) REFERENCES chicken(cID)
    INITIALLY DEFERRED DEFERRABLE;
INITIALLY DEFERRED DEFERRABLE tells Oracle to do deferred constraint checking.

 For example, to insert (1, 2) into chicken and (2, 1) into egg,we use:
INSERT INTO chicken VALUES(1, 2);
INSERT INTO egg VALUES(2, 1);
COMMIT;

Because we've declared the foreign key constraints as "deferred",
they are only checked at the commit point. (Without deferred constraint checking,
we cannot insert anything into chicken and egg,
 because the first INSERT would always be a constraint violation.)
Finally, to get rid of the tables, we have to drop the constraints first,
because Oracle won't allow us to drop a table that's referenced by another table.

ALTER TABLE egg DROP CONSTRAINT eggREFchicken;
ALTER TABLE chicken DROP CONSTRAINT chickenREFegg;
DROP TABLE egg;
DROP TABLE chicken;

Foreign Keys with "set null on delete":
--------------------------------------
A foreign key with a "set null on delete" means that if a record in the parent table is deleted,
then the corresponding records in the child table will have the foreign key fields set to null.
The records in the child table will not be deleted.
A foreign key with a "set null on delete" can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
For example:
CREATE TABLE supplier
( supplier_id numeric(10) not null,
 supplier_name varchar2(50) not null,
 contact_name varchar2(50), 
 CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products
( product_id numeric(10) not null,
 supplier_id numeric(10), 
 CONSTRAINT fk_supplier
   FOREIGN KEY (supplier_id)
  REFERENCES supplier(supplier_id)
  ON DELETE SET NULL
);

Using an ALTER TABLE statement-------------------------------
If we want to add a constraint to our new column we can use the following ALTER statement :
ALTER TABLE Test3 MODIFY(empno NOT NULL);
ALTER TABLE Test3
add constraint constraintname primary key (column name);

The syntax for creating a check constraint in an ALTER TABLE statement is:
ALTER TABLE table_name
add CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE];

ALTER TABLE table_name
add CONSTRAINT constraint_name
  FOREIGN KEY (column1, column2, ... column_n)
  REFERENCES parent_table (column1, column2, ... column_n)
  ON DELETE SET NULL;

How to Enable/Disable constraints:
---------------------------------
Syntax:
-------
SQl>Alter table tablename
    enable constraint constraint_name;
SQl>Alter table tablename
    Disable constraint constraint_name;

How to Check the Constraint details:
-----------------------------------
SQL> SELECT constraint_name FROM user_constraints WHERE table_name = 'TEST'
     AND constraint_type = 'PK_NAME';

How to Drop constraint:
----------------------
ALTER TABLE table_name
drop CONSTRAINT constraint_name;

Ur's
AmarAlam

Joins in Oracle

0 comments
Joins

A join is used to combine rows from multiple tables.
A join is performed whenever two or more tables is listed in the FROM clause of an SQL statement.

Inner Join (simple join)/Equi Join:
----------------------------------
It is the most common type of join. Inner joins return all rows from multiple tables
where the join condition is met.

For example, CONTRACT AND PRODUCT TWO TABLES

sql> SELECT * FROM CONTRACT C,PRODUCT P WHERE C.PRODUCT_CODE=P.PRODUCT_CODE

sql> SELECT * FROM CONTRACT C INNER JOIN PRODUCT P ON(C.PRODUCT_CODE=P.PRODUCT_CODE) WHERE SUM_ASSURED>50000;

This SQL statement would return all rows from the CONTRACT and PRODUCT tables
where there is a matching PRODUCT_CODE value in both the CONTRACT and PRODUCT tables.

Cross Join:
-----------
Join without filter conditions.
A Cross Join is the Cartesian product or the result of all possible combinations of the rows
 from each of the tables involved in the join operation.
This occurs when, no specific Join conditions (filters) are specified.

For example, CONTRACT AND PRODUCT TWO TABLES
sql> SELECT * FROM CONTRACT C,PRODUCT P ---NO CONDITION
This SQL statement would return the number of rows in product table multiply with number of rows in contract table.
contract table having 10 rows and product table 5 rows then output becomes 10*5.

Natural Join: (ANSI Joins):
--------------------------
These are ANSI Joins which are used for portability. You can use this in almost all Standard Databases
 like Oracle, Microsoft SQL Server etc.
SQL> SELECT DNAME, ENAME, MGR FROM DEPARTMENTS NATURAL JOIN EMPLOYEES;

NOte: Both tables should have primary key-referential key relationship.

Self Join:----------
  Sometimes there are scenarios where we might need to do Join operations within the same table.
 Such joins which refers to the same, single table are known as a Self Joins.
For Eg: If you need to get all employees and their managers, then you could do a self join.
          
SQl>SELECT  E1.ENAME||' reports to '||E2.ENAME FROM EMP E1,EMP E2 WHERE E1.MGR = E2.EMPNO;

Outer Join:
------------
They are of 2 types:
a) Left Outer Join
b) Right Outer Join

Left Outer Join:----------------
Returns all records from table A and only those matching with the join operation from Table B
For eg:
SQl> select * from emp left outer join dept on(emp.deptno-dept,deptno);

SQl> SELECT * FROM  EMP, DEPT WHERE EMP.DEPTNO  = DEPT.DEPTNO (+);
Returns all records from EMP and only those records from DEPT
which matches the condition EMP.DEPTNO  = DEPT.DEPTNO

SQL> select *  from contract left outer join product using (author_key)
    order by product_code;

Right Outer Join:----------------
Returns all records from table B and only those matching with the join operation from Table A
(just the reverse of left outer join)
For eg:

SQl> SELECT * FROM    EMP, DEPT WHERE EMP.DEPTNO (+)  = DEPT.DEPTNO ;
SQl> select * from emp Right outer join dept on(emp.deptno-dept,deptno);

Returns all records from DEPT and only those records from EMP
which matches the condition EMP.DEPTNO  = DEPT.DEPTNO


Ur's
AmarAlam

Oracle in-line views

0 comments
Oracle in-line views --------------------
The inline view is a construct in Oracle SQL where you can place a query in the SQL FROM clause,
 just as if the query was a table name.
A common use for in-line views in Oracle SQL is to simplify complex queries by removing join operations
 and condensing several separate queries into a single query.

SQl> SELECT * FROM ( SELECT deptno, count(*) emp_count
                         FROM emp  GROUP BY deptno ) emp,dept
 WHERE dept.deptno = emp.deptno;

The Below query display the employees who earn the highest salary in each department.

SQl> SELECT a.last_name, a.salary, a.department_id, b.maxsal FROM employees a,
       ( SELECT department_id, max(salary) maxsal
         FROM employees
         GROUP BY department_id ) b
     WHERE a.department_id = b.department_id
     AND a.salary = b.maxsal;

Display the top 5 salaries from emp table

SQL> SELECT rownum ,emp.ename,emp.sal
     FROM ( SELECT ename,sal
         FROM scott.emp
         order by sal desc ) emp
         where rownum<=5

EXAMPLE
--------
This is a great report for display the actual amount of free space,used tablespace,total space within an Oracle tablespace.

select
   fs.tablespace_name                          "Tablespace",
   (df.totalspace - fs.freespace)              "Used MB",
   fs.freespace                                "Free MB",
   df.totalspace                               "Total MB",
   round(100 * (fs.freespace / df.totalspace)) "Pct. Free"
from
   (select
      tablespace_name,
      round(sum(bytes) / 1048576) TotalSpace
   from
      dba_data_files
   group by
      tablespace_name
   ) df,
   (select
      tablespace_name,
      round(sum(bytes) / 1048576) FreeSpace
   from
      dba_free_space
   group by
      tablespace_name
   ) fs
where
   df.tablespace_name = fs.tablespace_name;


Ur's
AmarAlam

Materialized Views in Oracle

0 comments
Materialized Views:
------------------
A materialized view provides access to table data by storing the results of a query in a
separate schema object.
Unlike an ordinary view, which does not take up any storage space or contain any data,
a materialized view contains the rows resulting from a query against one or more base tables or views.
A materialized view can be stored in the same database as its base tables or in a different database.
Materialized views stored in the same database as their base tables can
improve queryperformance through query rewrites.
When you create a materialized view, Oracle Database creates one internal table and at least one index,
and may create one view, all in the schema of the materialized view.
Oracle Database uses these objects to maintain the materialized view data.
You must have the privileges necessary to create these objects.

Refresh methods:
--------------
refresh Force on demand
refresh fast on commit
refresh Complete

Syntax:
-------
CREATE MATERIALIZED VIEW <schema.name>
BUILD IMMEDIATE
REFRESH <FAST | FORCE> ON <COMMIT | DEMAND>
<USING INDEX | USING NO INDEX>
AS (<SQL statement>);

Materialized View Logs:
---------------------
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.
Each materialized view log is associated with a single master table. The materialized
view log resides in the same database and schema as its master table.

SQL> CREATE MATERIALIZED VIEW LOG ON Emp
     WITH PRIMARY KEY, ROWID;

Query Rewrite:
-------------
Query rewrite is a mechanism where Oracle or applications from the end user or database transparently
improve query responsetime, by automatically rewriting the SQL query to use the materialized view
instead of accessing the original tables.
Query rewrites are particularly useful in a data warehouse environment.

Refreshing materialized views:
-----------------------------
In Oracle, if you specify REFRESH FAST for a single-table aggregate Oracle materialized view,
you must have created a materialized view log for the underlying table, or the refresh command will fail.
To refresh the Oracle materialized view, call one of the procedures in DBMS_MVIEW.
The DBMS_MVIEW package provides three types of refresh operations:
DBMS_MVIEW.REFRESH:  Refreshes one or more Oracle materialized views
DBMS_MVIEW.REFRESH_ALL_MVIEWS:  Refreshes all Oracle materialized views
DBMS_MVIEW.REFRESH_DEPENDENT:  Refreshes all table-based Oracle materialized views

You can use the DBMS_MVIEW package to manually invoke either a fast refresh or a complete refresh,
 where "F" equals Fast Refresh and "C" equals Complete Refresh:
EXECUTE DBMS_MVIEW.REFRESH('emp_dept_sum','F');

Creating an Oracle materialized view:
------------------------------------
Step 1
------
SQl> select * from v$parameter
chack the above query if name  column  containe query_rewrite_enabled =TRUE then no change required else
Change it in the init.ora file
query_rewrite_enabled = true
query_rewrite_integrity = enforced
compatible = 8.1.5.0.0 (or greater)

Step 2------
CREATE  MATERIALIZED VIEW EMP_SUM
BUILD IMMEDIATE
REFRESH FORCE ON DEMAND
ENABLE QUERY REWRITE
AS
  SELECT deptno,job,SUM(sal) FROM emptest GROUP BY deptno,job;

Step 3------
execute dbms_mview.refresh('emp_sum');

Step 4------
CREATE MATERIALIZED VIEW LOG ON
   emp_sum
WITH ROWID;
CREATE MATERIALIZED VIEW LOG ON
   dept
WITH ROWID;

Step 5------
EXECUTE DBMS_MVIEW.REFRESH('emp_sum');

Refresh Complete----------------
CREATE MATERIALIZED VIEW mv_complete
REFRESH COMPLETE
START WITH SYSDATE
NEXT SYSDATE + 1 AS
SELECT deptno,COUNT(*)
FROM emp
GROUP BY deptno;

Note: To create a materialized view that refreshes at 3:00am in the morning:
SQL> SELECT TO_CHAR(TRUNC(SYSDATE) + 3/24, 'MM/DD/YYYY HH:MI:SS') FROM dual;

CREATE MATERIALIZED VIEW mv_complete
REFRESH COMPLETE
START WITH SYSDATE
NEXT TO_CHAR(TRUNC(SYSDATE) + 3/24, 'MM/DD/YYYY HH:MI:SS') AS
SELECT deptno,COUNT(*)
FROM emp
GROUP BY deptno;

Materialized View Partition Tracking Change
------------------------------------------
When the source or detail tables have partitions,
the refresh mechanism follows the partition change tracking (PCT) method.
Let us look at an example to show the creation of a materialized view.
 Let us assume we have a table list_sales_time created as follows.
CREATE table list_sales_time (time_id, cust_id, month, week, quantity_sold, amount_sold)
PARTITION BY LIST (week)(
partition m1 values (48, 49, 50),
partition m3 values (5, 6, 7, 8, 9, 10, 11, 12),
partition others values (default)) ;
Then, the materialized view is defined.

CREATE MATERIALIZED VIEW pct_sales_materialized view
BUILD IMMEDIATE REFRESH FAST ON DEMAND
ENABLE QUERY REWRITE
AS
SELECT ls.week, AVG(ls.quantity_sold) as avg,
COUNT(*) as cnt, COUNT(ls.quantity_sold) as cnt
FROM list_sales_time ls GROUP BY ls.week, ls.cust_id;

Creating Materialized Aggregate Views:
-------------------------------------
CREATE MATERIALIZED VIEW LOG ON times
   WITH ROWID, SEQUENCE (time_id, calendar_year)
   INCLUDING NEW VALUES;
CREATE MATERIALIZED VIEW LOG ON products
   WITH ROWID, SEQUENCE (prod_id)
   INCLUDING NEW VALUES;
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;

Periodic Refresh of Materialized Views:--------------------------------------
The following statement creates the primary key materialized view emp_data
CREATE MATERIALIZED VIEW LOG ON Emp
   WITH PRIMARY KEY
   INCLUDING NEW VALUES;
CREATE MATERIALIZED VIEW emp_data
   REFRESH FAST NEXT sysdate + 7
   AS SELECT * FROM emp;


Ur's
AmarAlam

Thursday, 28 March 2013

Views in Oracle

0 comments




1. Overview

Representing the data in various orientations is achieved by Views. We create views on top of database tables to represent the data in a logical and meaningful way.

2. Introduction

Views are the database objects which represent data in desired and required format. Note that it is a snapshot of the table data and has no physical data of its own. Only the view definition query is stored in the database by its name

Syntax
Code :
CREATE [OR REPLACE] [FORCE]/NOFORCE] VIEW [view name]
AS
[SQL QUERY]
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]].
Explanation of syntax clauses

[OR REPLACE] retains the privileges associated with the object.

[FORCE | NOFORCE]: A FORCE view is created if the table used in the definition does not exist. View is created but remains in INVALID status until the table is created and view is recompiled or recreated. NOFORCE is the default specification.

[WITH CHECK OPTION]: The clause ensures that the data once updated must satisfy the view definition. Also only the rows included in the view can be updated. Constraint name can be specified along with the check option, if not system generates as SYS_Cn format.

[WITH READ ONLY]: The clause creates a READ ONLY view, passive against DMLs.

3. Types of Views

Simple view uses only one table in its definition while Complex view uses multiple tables for creation.
Simple View definition consists of a simple SELECT query with no functions or group clause.
Complex view definition may contain SQL functions, Group by functions.

3.1. Illustrations

1. Simple View: The below simple view select employee name, department id and salary for the employees with JOB ID as DEV

Code sql:
CREATE OR REPLACE VIEW EMP_VU
AS
SELECT
      ENAME,
      DEPTNO,
      SALARY
FROM EMPLOYEE
WHERE JOB_ID = 'DEV'
2. Complex view: The below example shows the department name, average salary drawn in the department and the count of employees working in it.

Code sql:
CREATE OR REPLACE VIEW EMP_VU
AS
SELECT
       DNAME,
       AVG (SALARY) AS "AVERAGE SAL",
       COUNT (ENAME) AS "COUNT EMP"
FROM EMP E, DEPARTMENT D
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID
GROUP BY DNAME
DESCRIBE [view name] describes the view structure. Columns are listed in the same sequence as in the view definition.

3. View with CHECK option
The view EMP_VU is created WITH CHECK OPTION with constraint name EMPVU_DEV. If the rows included in the view are updated to violate the view definition, it would raise the exception ORA-01402.
Code sql:
CREATE OR REPLACE VIEW EMP_VU
AS
SELECT EMPNO,
              ENAME,
              DEPARTMENT_ID,
              SALARY,
FROM EMPLOYEE
WHERE JOB_ID = 'DEV'
WITH CHECK OPTION EMPVU_DEV;
 VIEW created.
 UPDATE EMP_VU
SET JOB_ID='HR'
WHERE EMPNO = 100;

ORA-01402: VIEW WITH CHECK OPTION where-clause violation.
4. DML on the view

Simple views easily respond to the DML operations on them. A row inserted, updated or deleted in the view is actually reflected on the actual physical table.

Complex views work fine with DML statements until they obey few purity rules.

Complex view definition must not contain
GROUP BY functions and clause
DISTINCT keyword, pseudo column (ROWNUM, SYSDATE)
No expressions in the SELECT list. (For Inserts and Updates)
Key preserved column of the tables must be in the SELECT list (For Inserts)


5. Dropping the view

View can be dropped from the database using DROP command. For example,

Code sql:
SQL> DROP VIEW EMP_VU;

Note that it has no effect on the base table. But its dependent objects are marked INVALID.

6. Advantages

1. Restores complex logical queries without storing physical data
2. It promotes data independency.






Ur's
AmarAlam