Saturday, February 8, 2014

12. INDEX


          An index helps speed up retrieval.
          Improves the performance of some queries
          A column that is frequently referred to in the WHERE clause is a potential candidate for indexing.
Why use indexing?
          It's easy and provides immediate value
          It can be used to speed up existing applications without changing any of their logic or queries
Index Creation Guidelines
Create an index when:
-A column contains a wide range of values
-A column contains a large number of null values
-One or more columns are frequently used together in a WHERE clause or a join condition
-The table is large and most queries are expected to retrieve less than 2% to 4% of the rows in the table
-Do not create an index when:
-The columns are not often used as a condition in the query
-The table is small or most queries are expected to retrieve more than 2% to 4% of the rows in the table
-The table is updated frequently
Types of Indexes
IMPLICIT INDEXES
   B-Tree Intex
      Implicit indexes on a table are created whenever a primary key, unique constraint is created on the table. 
    create table products
    (
      product_id       number,
  product_name   varchar2(30)
    );
                      
Alter table products add constraint products_pk primary key(product_id);
Bitmap indexes
          Bitmap indexes - Each bit in the bitmap corresponds to a possible rowid, and if the bit is set, it means that the row with the corresponding rowid contains the key value
          In a bitmap index, the database stores a bitmap for each index key. In a conventional B-tree index, one index entry points to a single row. In a bitmap index, each index key stores pointers to multiple rows.
CREATE BITMAP INDEX Typeid_i
   ON Books (SYS_TYPEID (Author));
CREATE BITMAP INDEX sales_cust_gender_bjix ON sales(customers.cust_gender) FROM sales, customers WHERE sales.cust_id = customers.cust_id LOCAL;
SELECT sales.time_id, customers.cust_gender, sales.amount FROM sales, customers WHERE sales.cust_id = customers.cust_id;

Partitioned indexes
          Partitioned indexes - Contain an entry for each value that appears in the indexed column(s) of the table
CREATE TABLE costs_demo (
   prod_id     NUMBER(6),    time_id     DATE,
   unit_cost   NUMBER(10,2), unit_price  NUMBER(10,2))
  
PARTITION BY RANGE (time_id)
   (PARTITION costs_old
       VALUES LESS THAN (TO_DATE('01-JAN-2003', 'DD-MON-YYYY')) COMPRESS,
    PARTITION costs_q1_2003
       VALUES LESS THAN (TO_DATE('01-APR-2003', 'DD-MON-YYYY')),
    PARTITION costs_q2_2003
       VALUES LESS THAN (TO_DATE('01-JUN-2003', 'DD-MON-YYYY')),
    PARTITION costs_recent VALUES LESS THAN (MAXVALUE));
CREATE INDEX i_cost1 ON costs_demo (prod_id) COMPRESS LOCAL (PARTITION costs_old, PARTITION costs_q1_2003, PARTITION costs_q2_2003, PARTITION costs_recent NOCOMPRESS);
Function-based indexes
          Function-based indexes - Based on expressions. They enable user to construct queries that evaluate the value returned by an expression (can use built-in or custom functions)
CREATE INDEX Income_ix  ON Employees (Salary +
     (Salary*Commission_pct));

Domain indexes
          Domain indexes -application-specific index (ie. XML)
CREATE TABLE Employees (name VARCHAR2(64), id INTEGER, resume VARCHAR2(2000));
CREATE INDEX ResumeIndex ON Employees(resume) INDEXTYPE IS TextIndexType;
SELECT * FROM Employees WHERE Contains(resume, 'Oracle') =1;
Removing an Index
          Remove an index from the data dictionary by using the DROP INDEX command:
          DROP INDEX index;
          Remove the UPPER_LAST_NAME_IDX index from the data dictionary:
          DROP INDEX emp_last_name_idx;
          Index dropped.
          To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.

11.INDEX


1.Bitmap Index
Database stores a bitmap for each index key. Indexes are  designed for data warehousing.   Indexed columns have low cardinality.The indexed table is either read-only or not subject to significant modification by DML statements.For a data warehouse example, the customer table has a cust_gender column with only two possible values: M and F. 
Bitmap index on a single table
}  SQL> SELECT cust_id, cust_last_name, cust_marital_status, cust_gender  FROM customers  WHERE ROWNUM < 8 ORDER BY cust_id;
 CUST_ID   CUST_LAST_    CUST_MAR     CUST_GEND
---------- ---------- -------- ------------------- -----------------
    1               Kessel                                                      M
    2               Koch                                                        F
    3               Emmerson                                               M
    4               Hardy                                                      M
    5               Gowen                                                     M
 6               Charlessingle      single                            F
  7               Ingram                single                            F

Sample Bitmap Index

       A mapping function converts each bit in the bitmap to a rowid of customer table.
       Each bit value depends on the values of the corresponding row in the table. 

2.Function Based Index
A function-based index computes the value of a function  or expression involving one or more columns and stores it in the index.
For Eg:SELECT           employee_id, last_name, first_name,    12*salary*commission_pct AS "ANNUAL SAL" FROM            employees    WHERE  (12 * salary * commission_pct) < 30000    ORDER BY "ANNUAL SAL" DESC;
}  A function-based index can be either a B-tree or a bitmap index.
}  The function used for building the index can be an arithmetic expression or an expression that contains a SQL function, user-defined PL/SQL function.

Uses of function based index
Evaluating statements that contain functions in their WHERE clauses.The database only uses the function-based index when the function is included in a query.
For Eg: SELECT    employee_id, last_name, first_name,
            12*salary*commission_pct AS "ANNUAL SAL" FROM        employees       WHERE           (12 * salary * commission_pct) < 30000       ORDER BY "ANNUAL SAL" DESC;
Eg: for function base index
CREATE INDEX emp_total_sal_idx ON employees (12 * salary * commission_pct, salary, commission_pct);
 Optimization with function based index

}  The optimizer can use an index range scan on a function-based index for queries with expressions in  WHERE clause.
}  The range scan access path is especially beneficial when the predicate (WHERE clause) has low selectivity.
}  virtual column is useful for speeding access to data derived from expressions.
}  column_name [datatype] [GENERATED ALWAYS] AS (expression) [VIRTUAL]
Eg:salary2 NUMBER GENERATED ALWAYS AS (ROUND(salary*(1+comm2/100),2)) VIRTUAL
create table empsal
(
emp number(2),
sal1 number(3),
sal2 number(4),
sal3 NUMBER GENERATED ALWAYS AS (ROUND(sal1*(1+sal2/100),2)) VIRTUAL
);



3.Application Domain Index
Application Domain Index are also called extensible indexing.They allow you to create your own index structures that work just like indexes supplied by Oracle. (just like primary key index)
}  A good example of an application domain index is the way Oracle Database itself implements text indexes, which are commonly used to facilitate searching on large text items.
SQL> create index test_idx2 on test_tab(desc)
2*         indextype is ctxsys.context;



10.Oracle Data types


Ø  Columns has Data types
Ø  It Has Specific Storage format, Constraints And Valid Range

Several Data types
Some Commonly used data types are:
Ø  Character Data types
Ø  Numeric Data Types
Ø  Datetime Data Types
Ø  Rowid Data Types
Ø  LOBs(large objects)

Character Data Types
It Stores Character(Alphanumeric) Data In string.
      i.e...Letters, Numbers, Spaces, Symbols, and Punctuation are stored using      Character Data types
v  Commonly Used character Data types  is VARCHAR2
v  VARCHAR2 reduces space consumption
            create table EMP(  EMPNO NUMBER(3),
                                                 NAME  VARCHAR2(20),
                                                 DTE   DATE,
                                                 IMG   BLOB,
                                                    RID   RAW(10))

Numeric Data types
Ø  Stores Fixed and Floating Point Numbers, zero and infinity.
Ø  Commonly Used Number Data types
Ø  Does Not Store Leading  zeros
Ø  Format for a number data type is a number (p,s) where p is precision and s is the scale
Ø  Floating-point Numbers ,binary _float and Binary double are also Numeric datatypes

Datetime Data Types
Ø  It stores Date and Time
Ø  Stores Internally as Numbers
Ø  Stores fixed length Fields of 7 bytes each
Ø  Displays According to specified Format
Ø  Common  date Format is DD-MON-YY

TIMESTAMP DATA TYPES
Ø  Extension of the date data types
Ø  Stores Fractional seconds
Ø  Useful for Track Event Order

ROWID DATA TYPES
Ø  Stores Address of every row in the database
Ø  Physical rowid store address of row in heap organized tables
Ø  logical rowid  stores address of rows in index organized  tables
Ø  foreign rowid are identifiers in foreign tables

LOBs(Large objects)
Ø  Used to store Large objects
Ø  Mainly Used for Storing Images
Ø  It store and manipulate large blocks of unstructured data (such as text, graphic images, video clips, and sound waveforms) in binary or character format.
Ø  Commonly used LOB  datatypes are  BLOB  and CLOB
Ø  Blob Means  BINARY LARGE OBJECT where as CLOB as Character Large Objects
Ø  For storing image, voice, graphical we using Blob

9.Columns And Rows


Columns :
       column is a set of data values of a particular simple type
       When you create a table  its each columns have a column name, a valid data type, and a width
       A table has a specified number of columns  specified by the user.
       Different Constraints are applied to the columns while the creation of the tables
       Eg: not null,unique,primary key , foreign key constraint …
       We can use any one of these Constraints in the columns
ROWS
Ø  A Table have any number of rows defined as a tuple or a record.
Ø  A database record is a row of data in a database table
Ø  Each Rows have unique Row id
Every rows in the table has the same structure

8.Oracle Date Base Table


Ø  Tables are the basic unit of data storage in a Database.
Ø  Data is stored in rows and columns .
Ø  We define a table with a table name ,each column with a column name,  And each  row has a unique row id.   
Ø  A table has a specified number of columns, but can have any number of rows
Ø  If data that are not physically stored in the database  it can be called as Views
Types Of Tables:
àRelational Tables: It have simple columns and are the   most common table type
                      Eg: emp
                                CREATE TABLE emp (empno   NUMBER(3),
                                name    VARCHAR2(20),
                                 address ADDRESS_OBJ);
Ø  Object Tables:  An object table is a special kind of table in which each row represents an object
Ø  Before Creating Object Table we have to create an Object Type
Ø  To create Object  type .
Ø                       CREATE OR REPLACE TYPE address_obj as OBJECT(
                 street VARCHAR2(20),
                 city VARCHAR2(20),
                 state CHAR(2),
                 zip CHAR(5));
Ø  Then We can create  its object Tables
Ø                      E.g: CREATE TABLE address_table OF ADDRESS_OBJ;
Ø                              CREATE TABLE address_table _new OF ADDRESS_OBJ;
Ø  à Heap  Organized table
Ø             àIt Does not Store Rows In any Particular Order
Ø  à Index Organised Table
Ø            àIt Orders rows According to the primary key Value.

Thursday, February 6, 2014

7.Introduction to Schema Objects


Introduction to Schema Objects
v  Each DB user owns a single schema,  which has the same  name as the user.
v   The schema contains the data for the user owning the schema. It is a logical container for data structures. E.g. mana0809
v  Within a schema, each schema object of a particular type has a unique name. E.g. mana0809. Employee_master
Schema objects are created and manipulated with SQL

Schema Object Types
Ø  Tables
Ø  Indexes
Ø  Partitions
Ø  Views
Ø  Sequences
Ø  Synonyms
Ø  PL/SQL subprograms

Tables
The most important schema objects in a relational database
  It is a collection of rows and columns
  We can store data into the table and retrieve the data from the table
  We can update the data and delete the data from a table
Eg: Branch_master

Indexes
  Optional Structure associated with a table
  Fast Retrieval of data by specifying indexed column in the where condition of sql querry
           E.g.Transaction_history :FIRM_ID, ACCOUNT_NO, TRADT
  Create  index for most frequently used columns.
  An index can be dropped or created without physically affecting the table for the index.(If you drop an index, then applications still work. However, access of previously indexed data can be slower.)
  The presence of many indexes on a table degrades  performance

Partitioning
Ø  Partitions are pieces of large tables and indexes.
Ø   Each partition has its own name and may optionally have its own storage characteristics
  When to Partition a Table
  Tables greater than 2 GB should always be considered as candidates for partitioning.
  Tables containing historical data, in which new data is added into the newest partition. A typical example is a historical table where only the current month's data is updatable and the other 11 months are read only.
  When the contents of a table need to be distributed across different types of storage devices.
Views
Ø  Views are customized presentations of data in one or more tables or other views.
Ø  You can think of them as stored queries.
Ø   Views do not actually contain data.
Ø  Restict the view of a table i.e. can hide some of columns in the tables.
Ø   Join two or more tables and show it as one object to user.
Ø  Restict the access of a table so that nobody can insert the rows into the table.
Ø  Views have two types
        1.  Simple View  (emp_master)
        2.  Complex View(branch_detail)

Sequences
Ø  A sequence is a user-created object that can be shared by multiple users to generate integers.
Ø  Typically, sequences are used to generate primary key values.
Ø  create sequence  emp_id_SEQ
minvalue 1
maxvalue 9999999999
start with 41
increment by 1
cache 20;
Ø   emp_id   := emp_id_SEQ.nextval;

Synonyms
Ø  A synonym is an alias for another schema object. Because a synonym is simply an alias, it requires no storage other than its definition in the data dictionary.
Ø  CREATE SYNONYM
   CREATE SYNONYM branch for mana0809.branch_master;

PL/SQL subprograms
Ø  Subprograms
Ø   Subprograms are named PL/SQL blocks that can take parameters and be invoked.
Ø  2 types
Ø   procedure and functions
Ø  procedure to perform an action
Ø  function to compute a value. (Ex, Transno)

Schema Object Dependencies
  Some schema objects reference other objects, creating schema object dependencies.
  For example, a view contains a query that references tables or other views, while a PL/SQL subprogram invokes other subprograms.
If the definition of object A references object B, then A is a dependent object with respect to B and B is a referenced object with respect to A.
Ex,
CREATE TABLE test_table ( col1 INTEGER, col2 INTEGER );

CREATE OR REPLACE PROCEDURE test_proc
AS BEGIN
FOR x IN ( SELECT col1, col2 FROM test_table ) LOOP
-- process data
NULL; END LOOP; END;
/
  After adding the col3 column to test_table, the procedure is still valid because the procedure has no dependencies on this column:
  SQL> ALTER TABLE test_table ADD col3 NUMBER; Table altered.
  However, changing the data type of the col1 column, which the test_proc procedure depends on in, invalidates the procedure:
  SQL> ALTER TABLE test_table MODIFY col1 VARCHAR2(20); Table altered.
  Running or recompiling the procedure makes it valid again, as shown in the following example:
  SQL> EXECUTE test_proc
  PL/SQL procedure successfully completed.

SYS and SYSTEM Schemas
Ø  All Oracle databases include default administrative accounts. Administrative accounts are highly privileged and are intended only for DBAs authorized to perform tasks
Ø  such as starting and stopping the database, managing memory and storage, creating and managing database users, and so on.

SYS & SYSTEM
Ø  The administrative account SYS is automatically created when a database is created.
Ø  This account can perform all database administrative functions.
Ø   The SYS schema stores the base tables and views for the data dictionary.
Ø  These base tables and views are critical for the operation of Oracle Database.
Ø   Tables in the SYS schema are manipulated only by the database and must never be modified by any user.