Friday, May 2, 2014

IMPORTANT QUERIES - PART 2


1.     Get duplicate rows from the table:
Select empno, count (*) from EMP group by empno having count (*)>1;
2.     Remove duplicates in the table:
Delete from EMP where rowid not in (select max (rowid) from EMP group by empno);
3.     Below query transpose columns into rows.
Name
No
Add1
Add2
abc
100
Hyd
bang
xyz
200
Mysore
pune

Select name, no, add1 from A
UNION
Select name, no, add2 from A;
4.     Below query transpose rows into columns.
select
emp_id,
max(decode(row_id,0,address))as address1,
max(decode(row_id,1,address)) as address2,
max(decode(row_id,2,address)) as address3
from (select emp_id,address,mod(rownum,3) row_id from temp order by emp_id )
group by emp_id
Other query:
select
emp_id,
max(decode(rank_id,1,address)) as add1,
max(decode(rank_id,2,address)) as add2,
max(decode(rank_id,3,address))as add3
from
(select emp_id,address,rank() over (partition by emp_id order by emp_id,address )rank_id from temp )
group by
emp_id
5.     Rank query:
Select empno, ename, sal, r from (select empno, ename, sal, rank () over (order by sal desc) r from EMP);
6.     Dense rank query:
The DENSE_RANK function works acts like the RANK function except that it assigns consecutive ranks:
Select empno, ename, Sal, from (select empno, ename, sal, dense_rank () over (order by sal desc) r from emp);
7.     Top 5 salaries by using rank:
Select empno, ename, sal,r from (select empno,ename,sal,dense_rank() over (order by sal desc) r from emp) where r<=5;
Or
Select * from (select * from EMP order by sal desc) where rownum<=5;
8.     2 nd highest Sal:
Select empno, ename, sal, r from (select empno, ename, sal, dense_rank () over (order by sal desc) r from EMP) where r=2;
9.     Top sal:
Select * from EMP where sal= (select max (sal) from EMP);
10.                        How to display alternative rows in a table?
          SQL> select *from emp where (rowid, 0) in (select rowid,mod(rownum,2) from emp);

11.                        Hierarchical queries
Starting at the root, walk from the top down, and eliminate employee Higgins in the result, but
process the child rows.
SELECT department_id, employee_id, last_name, job_id, salary
FROM employees
WHERE last_name! = ’Higgins’
START WITH manager_id  IS NULL
CONNECT BY PRIOR employee_id = menagerie;

What is Hints and Why hints Require?


It is a perfect valid question to ask why hints should be used. Oracle comes with an optimizer that promises to optimize a query's execution plan. When this optimizer is really doing a good job, no hints should be required at all.
Sometimes, however, the characteristics of the data in the database are changing rapidly, so that the optimizer (or more accuratly, its statistics) are out of date. In this case, a hint could help.
You should first get the explain plan of your SQL and determine what changes can be done to make the code operate without using hints if possible. However, hints such as ORDERED, LEADING, INDEX, FULL, and the various AJ and SJ hints can take a wild optimizer and give you optimal performance
Tables analyze and update Analyze Statement
The ANALYZE statement can be used to gather statistics for a specific table, index or cluster. The statistics can be computed exactly, or estimated based on a specific number of rows, or a percentage of rows:
ANALYZE TABLE employees COMPUTE STATISTICS;
ANALYZE TABLE employees ESTIMATE STATISTICS SAMPLE 15 PERCENT;
EXEC DBMS_STATS.gather_table_stats('SCOTT', 'EMPLOYEES');

Automatic Optimizer Statistics Collection
By default Oracle 10g automatically gathers optimizer statistics using a scheduled job called GATHER_STATS_JOB. By default this job runs within maintenance windows between 10 P.M. to 6 A.M. week nights and all day on weekends. The job calls the DBMS_STATS.GATHER_DATABASE_STATS_JOB_PROC internal procedure which gathers statistics for tables with either empty or stale statistics, similar to the DBMS_STATS.GATHER_DATABASE_STATS procedure using the GATHER AUTO option. The main difference is that the internal job prioritizes the work such that tables most urgently requiring statistics updates are processed first.
Hint categories:
Hints can be categorized as follows:
  • 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 */) 
  • Hints for Join Orders,
  • Hints for Join Operations,
  • Hints for Parallel Execution, (/*+ parallel(a,4) */)  specify degree either 2 or 4 or 16
  • Additional Hints
  • 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 */
Use Hint to force using index

SELECT /*+INDEX (TABLE_NAME INDEX_NAME) */ COL1,COL2 FROM TABLE_NAME
 Select  ( /*+ hash  */ ) empno from
ORDERED-à This hint forces tables to be joined in the order specified. If you know table X has fewer rows, then ordering it first may speed execution in a join.
PARALLEL (table, instances)àThis specifies the operation is to be done in parallel.

If index is not able to create then will go for  /*+ parallel(table, 8)*/-----For select and update example---in where clase like st,not in ,>,< ,<> then we will use.

Explain plan

Explain plan will tell us whether the query properly using indexes or not.whatis the cost of the table whether it is doing full table scan or not, based on these statistics we can tune the query.
The explain plan process stores data in the PLAN_TABLE. This table can be located in the current schema or a shared schema and is created using in SQL*Plus as follows:
SQL> CONN sys/password AS SYSDBA
Connected
SQL> @$ORACLE_HOME/rdbms/admin/utlxplan.sql
SQL> GRANT ALL ON sys.plan_table TO public;
 

SQL> CREATE PUBLIC SYNONYM plan_table FOR sys.plan_table;

What is your tuning approach if SQL query taking long time? Or how do u tune SQL query?


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 on statistics 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.

What is the difference between sub-query & co-related sub query?

A sub query is executed once for the parent statement
whereas the correlated sub query is executed once for each
row of the parent query.
Sub Query:
Example:
 Select deptno, ename, sal from emp a  where sal  in (select sal from Grade  where sal_grade=’A’ or  sal_grade=’B’)
Co-Related Sun query:
Example:
Find all employees who earn more than the average salary in their department.
SELECT last-named, salary, department_id  FROM employees A
WHERE salary > (SELECT AVG (salary)
FROM employees B WHERE B.department_id =A.department_id
Group by B.department_id)


Sub-query
Co-related sub-query
A sub-query is executed once for the parent Query
Where as co-related sub-query is executed once for each row of the parent query.
Example:
Select * from emp where deptno in (select deptno from dept);
Example:
Select a.* from emp e where sal >= (select avg(sal) from emp a where a.deptno=e.deptno group by  a.deptno);

View & Materialized View & Inline View

View:

Why Use Views?
• To restrict data access
• To make complex queries easy
• To provide data independence
  A simple view is one that:
– Derives data from only one table
– Contains no functions or groups of data
– Can perform DML operations through the view.

 A complex view is one that:
– Derives data from many tables
– Contains functions or groups of data
– Does not always allow DML operations through the view
 
 
A view has a logical existence but a materialized view has 
a physical existence.Moreover a materialized view can be 
Indexed, analysed and so on....that is all the things that 
we can do with a table can also be done with a materialized 
view.
 
We can keep aggregated data into materialized view. we can schedule the MV to refresh but table can’t.MV can be created based on multiple tables.
 

Materialized View:

 
In DWH materialized views are very essential because in reporting side if we do aggregate calculations as per the business requirement report performance would be de graded. So to improve report performance rather than doing report calculations and joins at reporting side if we put same logic in the MV then we can directly select the data from MV without any joins and aggregations. We can also schedule MV (Materialize View).

Inline view:

If we write a select statement in from clause that is nothing but inline view.
 
Ex:
Get dept wise max sal along with empname and emp no.
 
Select a.empname, a.empno, b.sal, b.deptno 
From EMP a, (Select max (sal) sal, deptno from EMP group by deptno) b
Where
a.sal=b.sal and

a.deptno=b.deptno

Differences between where clause and having clause


Where clause
Having clause
Both where and having clause can be used to filter the data.
Where as in where clause it is not mandatory.
But having clause we need to use it with the group by.
Where clause applies to the individual rows.
Where as having clause is used to test some condition on the group rather than on individual rows.
Where clause is used to restrict rows.
But having clause is used to restrict groups.
Restrict normal query by where
Restrict group by function by having
In where clause every record is filtered based on where.
In having clause it is with aggregate records (group by functions).



Order of where and having:
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

The WHERE clause cannot be used to restrict groups. you use the
HAVING clause to restrict groups.

Difference between Rowid and Rownum?

ROWID
A globally unique identifier for a row in a database. It is created at the time the row is inserted into a table, and destroyed when it is removed from a table.'BBBBBBBB.RRRR.FFFF' where BBBBBBBB is the block number, RRRR is the slot(row) number, and FFFF is a file number.


ROWNUM

For each row returned by a query, the ROWNUM pseudo column returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.

You can use ROWNUM to limit the number of rows returned by a query, as in this example:

SELECT * FROM employees WHERE ROWNUM < 10;

Rowid
Row-num
Rowid is an oracle internal id that is allocated every time a new record is inserted in a table. This ID is unique and cannot be changed by the user.
Row-num is a row number returned by a select statement.
Rowid is permanent.
Row-num is temporary.
Rowid is a globally unique identifier for a row in a database. It is created at the time the row is inserted into the table, and destroyed when it is removed from a table.
The row-num pseudocoloumn returns a number indicating the order in which oracle selects the row from a table or set of joined rows.

What is the Difference between Delete, Truncate and Drop?

DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. The operation cannot be rolled back.

What is the difference between view and materialized view?

View
Materialized view
A view has a logical existence. It does not contain data.
A materialized view has a physical existence.
Its not a database object.
It is a database object.
We cannot perform DML operation on view.
We can perform DML operation on materialized view.
When we do select * from view it will fetch the data from base table.
When we do select * from materialized view it will fetch the data from materialized view.
In view we cannot schedule to refresh.
In materialized view we can schedule to refresh.

We can keep aggregated data into materialized view. Materialized view can be created based on multiple tables.

IMPORTANT QUERIES - PART 1


1)   To find the nth row of a table
SQL> Select *from emp where rowid = (select max(rowid) from emp where rownum <= 4);
Or
   SQL> Select *from emp where rownum <= 4 minus select *from emp where rownum <= 3;

2)   To find duplicate rows
SQL> Select *from emp where rowid in (select max(rowid) from emp group by empno,          
         ename, mgr, job, hiredate, comm, deptno, sal);
Or
 SQL> Select empno,ename,sal,job,hiredate,comm , count(*) from emp group by
         empno,ename,sal,job,hiredate,comm  having count(*) >=1;

3)   To delete duplicate rows
      SQL> Delete emp where rowid in (select max(rowid) from emp group by
              empno,ename,mgr,job,hiredate,sal,comm,deptno);

4)   To find the count of duplicate rows
      SQL> Select ename, count(*) from emp group by ename having count(*) >= 1;

5)   How to display alternative rows in a table?
          SQL> select *from emp where (rowid,0) in (select rowid,mod(rownum,2) from emp);

6)   Getting employee details of each department who is drawing maximum sal?
       SQL> select *from emp where (deptno,sal) in
               ( select deptno,max(sal)  from emp group by deptno);

7)   How to get number of employees in each department  , in which department is having more than 2500 employees?
       SQL> Select deptno,count(*) from emp group by  deptno having count(*) >2500;

           9) To reset the time to the beginning of the day

                  SQL> Select to_char(trunc(sysdate),’dd-mon-yyyy hh:mi:ss am’) from dual;

10) To find nth maximum sal
  SQL> Select *from emp where sal in (select max(sal) from (select *from emp order by sal)

          where rownum <= 5);

INDEXES - Detailed Indexes(End to End)





Index is typically a listing of keywords accompanied by the location of information on a subject. We can create indexes explicitly to speed up SQL statement execution on a table. The index points directly to the location of the rows containing the value.

Some Imp Notes:
1.     Bitmap indexes are most appropriate for columns having low distinct values—such as GENDER, MARITAL_STATUS, and RELATION. This assumption is not completely accurate, however. In reality, a bitmap index is always advisable for systems in which data is not frequently updated by many concurrent systems. In fact, as I'll demonstrate here, a bitmap index on a column with 100-percent unique values (a column candidate for primary key) is as efficient as a B-tree index.
2.     When to Create an Index
3.     You should create an index if:
4.        A column contains a wide range of values
5.       A column contains a large number of null values
6.       One or more columns are frequently used together in a WHERE clause or a join condition
7.     The table is large and most queries are expected to retrieve less than 2 to 4 percent of the rows
By default if u create index that is nothing but b-tree index.

WHY INDEXES?

Indexes are most useful on larger tables, on columns that are likely to appear in where clauses as simple equality.

TYPES

Ø  Unique index
Ø  Non-unique index
Ø  Btree index
Ø  Bitmap index
Ø  Composite index
Ø  Reverse key index
Ø  Function-based index
Ø  Descending index
Ø  Domain index
Ø  Object index
Ø  Cluster index
Ø  Text index
Ø  Index organized table
Ø  Partition index
v  Local index
ü  Local prefixed
ü  Local non-prefixed
v       Global index
ü       Global prefixed
ü       Global non-prefixed

UNIQUE INDEX

Unique indexes guarantee that no two rows of a table have duplicate values in the columns that define the index. Unique index is automatically created when primary key or unique constraint is created.

Ex:
     SQL> create unique index stud_ind on student(sno);

NON-UNIQUE INDEX

Non-Unique indexes do not impose the above restriction on the column values.

Ex:
     SQL> create index stud_ind on student(sno);

BTREE INDEX or ASCENDING INDEX

The default type of index used in an oracle database is the btree index. A btree index is designed to provide both rapid access to individual rows and quick access to groups of rows within a range. The btree index does this by performing a succession of value comparisons. Each comparison eliminates many of the rows.

Ex:
     SQL> create index stud_ind on student(sno);

BITMAP INDEX

This can be used for low cardinality columns: that is columns in which the number of distinct values is snall when compared to the number of the rows in the table.

Ex:
     SQL> create bitmap index stud_ind on student(sex);


COMPOSITE INDEX

A composite index also called a concatenated index is an index created on multiple columns of a table. Columns in a composite index can appear in any order and need not be adjacent columns of the table.

Ex:
     SQL> create bitmap index stud_ind on student(sno, sname);

REVERSE KEY INDEX

A reverse key index when compared to standard index, reverses each byte of the column being indexed while keeping the column order. When the column is indexed in reverse mode then the column values will be stored in an index in different blocks as the starting value differs. Such an arrangement can help avoid performance degradations in indexes where modifications to the index are concentrated on a small set of blocks.

Ex:
     SQL> create index stud_ind on student(sno, reverse);

We can rebuild a reverse key index into normal index using the noreverse keyword.

Ex:
     SQL> alter index stud_ind rebuild noreverse;

FUNCTION BASED INDEX

This will use result of the function as key instead of using column as the value for the key.

Ex:
     SQL> create index stud_ind on student(upper(sname));




DESCENDING INDEX

The order used by B-tree indexes has been ascending order. You can categorize data in B-tree index in descending order as well. This feature can be useful in applications where sorting operations are required.

Ex:
     SQL> create index stud_ind on student(sno desc);

TEXT INDEX

Querying text is different from querying data because words have shades of meaning, relationships to other words, and opposites. You may want to search for words that are near each other, or words that are related to thers. These queries would be extremely difficult if all you had available was the standard relational operators. By extending SQL to include text indexes, oracle text permits you to ask very complex questions about the text.

To use oracle text, you need to create a text index on the column in which the text is stored. Text index is a collection of tables and indexes that store information about the text stored in the column.

TYPES

There are several different types of indexes available in oracle 9i. The first, CONTEXT is supported in oracle 8i as well as oracle 9i. As of oracle 9i, you can use the CTXCAT text index fo further enhance your text index management and query capabilities.

Ø  CONTEXT
Ø  CTXCAT
Ø  CTXRULE

The CTXCAT index type supports the transactional synchronization of data between the base table and its text index. With CONTEXT indexes, you need to manually tell oracle to update the values in the text index after data changes in base table. CTXCAT index types do not generate score values during the text queries.


HOW TO CREATE TEXT INDEX?

You can create a text index via a special version of the create index comman. For context index, specify the ctxsys.context index type and for ctxcat index, specify the ctxsys.ctxcat index type.

Ex:
Suppose you have a table called BOOKS with the following columns
Title, Author, Info.

SQL> create index book_index on books(info) indextype is ctxsys.context;
SQL> create index book_index on books(info) indextype is ctxsys.ctxcat;

TEXT QUERIES

Once a text index is created on the info column of BOOKS table, text-searching capabilities increase dynamically.

CONTAINS & CATSEARCH

CONTAINS function takes two parameters – the column name and the search string.

Syntax:
Contains(indexed_column, search_str);

If you create a CTXCAT index, use the CATSEARCH function in place of CONTAINS. CATSEARCH takes three parameters – the column name, the search string and the index set.

Syntax:
Contains(indexed_column, search_str, index_set);

HOW A TEXT QEURY WORKS?

When a function such as CONTAINS or CATSEARCH is used in query, the text portion of the query is processed by oracle text. The remainder of the query is processed just like a regular query within the database. The result of the text query processing and the regular query processing are merged to return a single set of records to the user.
SEARCHING FOR AN EXACT MATCH OF A WORD

The following queries will search for a word called ‘prperty’ whose score is greater than zero.

SQL> select * from books where contains(info, ‘property’) > 0;
SQL> select * from books where catsearch(info, ‘property’, null) > 0;

Suppose if you want to know the score of the ‘property’ in each book, if score values for individual searches range from 0 to 10 for each occurrence of the string within the text then use the score function.

SQL> select title, score(10) from books where contains(info, ‘property’, 10) > 0;

SEARCHING FOR AN EXACT MATCH OF MULTIPLE WORDS

The following queries will search for two words.

SQL> select * from books where contains(info, ‘property AND harvests’) > 0;
SQL> select * from books where catsearch(info, ‘property AND harvests’, null) > 0;

Instead of using AND you could hae used an ampersand(&). Before using this method, set define off so the & character will not be seen as part of a variable name.

SQL> set define off
SQL> select * from books where contains(info, ‘property & harvests’) > 0;
SQL> select * from books where catsearch(info, ‘property  harvests’, null) > 0;

The following queries will search for more than two words.

SQL> select * from books where contains(info, ‘property AND harvests AND workers’) > 0;
SQL> select * from books where catsearch(info, ‘property harvests workers’, null) > 0;

The following queries will search for either of the two words.

SQL> select * from books where contains(info, ‘property OR harvests’) > 0;

Instead of OR you can use a vertical line (|).
SQL> select * from books where contains(info, ‘property | harvests’) > 0;
SQL> select * from books where catsearch(info, ‘property | harvests’, null) > 0;

In the following queries the ACCUM(accumulate) operator adds together the scores of the individual searches and compares the accumulated score to the threshold value.

SQL> select * from books where contains(info, ‘property ACCUM harvests’) > 0;
SQL> select * from books where catsearch(info, ‘property ACCUM harvests’, null) > 0;

Instead of OR you can use a comma(,).

SQL> select * from books where contains(info, ‘property , harvests’) > 0;
SQL> select * from books where catsearch(info, ‘property , harvests’, null) > 0;

In the following queries the MINUS operator subtracts the score of the second term’s search from the score of the first term’s search.

SQL> select * from books where contains(info, ‘property MINUS harvests’) > 0;
SQL> select * from books where catsearch(info, ‘property NOT harvests’, null) > 0;

Instead of MINUS you can use – and instead of NOT you can use ~.

SQL> select * from books where contains(info, ‘property - harvests’) > 0;
SQL> select * from books where catsearch(info, ‘property ~ harvests’, null) > 0;

SEARCHING FOR AN EXACT MATCH OF A PHRASE

The following queries will search for the phrase. If the search phrase includes a reserved word within oracle text, the you must use curly braces ({}) to enclose text.

SQL> select * from books where contains(info, ‘transactions {and} finances’) > 0;
SQL> select * from books where catsearch(info, ‘transactions {and} finances’, null) > 0;

You can enclose the entire phrase within curly braces, in which case any reserved words within the phrase will be treated as part of the search criteria.

SQL> select * from books where contains(info, ‘{transactions and finances}’) > 0;
SQL> select * from books where catsearch(info, ‘{transactions and finances}’, null) > 0;

SEARCHING FOR WORDS THAT ARE NEAR EACH OTHER

The following queries will search for the words that are in between the search terms.

SQL> select * from books where contains(info, ‘workers NEAR harvests’) > 0;

Instead of NEAR you can use ;.

SQL> select * from books where contains(info, ‘workers ; harvests’) > 0;

In CONTEXT index queries, you can specify the maximum number of words between the search terms.

SQL> select * from books where contains(info, ‘NEAR((workers, harvests),10)’ > 0;

USING WILDCARDS DURING SEARCHES

You can use wildcards to expand the list of valid search terms used during your query. Just as in regular text-string wildcard processing, two wildcards are available.

%        -           percent sign; multiple-character wildcard
_          -           underscore; single-character wildcard

SQL> select * from books where contains(info, ‘worker%’) > 0;
SQL> select * from books where contains(info, ‘work___’) > 0;

SEARCHING FOR WORDS THAT SHARE THE SAME STEM

Rather than using wildcards, you can use stem-expansion capabilities to expand the list of text strings. Given the ‘stem’ of a word, oracle will expand the list of words to search for to include all words having the same stem. Sample expansions are show here.

Play    -           plays playing played playful

SQL> select * from books where contains(info, ‘$manage’) > 0;

SEARCHING FOR FUZZY MATCHES

A fuzzy match expands the specified search term to include words that are spelled similarly but that do not necessarily have the same word stem. Fuzzy matches are most helpful when the text contains misspellings. The misspellings can be either in the searched text or in the search string specified by the user during the query.

The following queries will not return anything because its search does not contain the word ‘hardest’.

SQL> select * from books where contains(info, ‘hardest’) > 0;

It does, however, contains the word ‘harvest’. A fuzzy match will return the books containing the word ‘harvest’ even though ‘harvest’ has a different word stem thant the word used as the search term.

To use a fuzzy match, precede the search term with a question mark, with no space between the question mark and the beginning of the search term.

SQL> select * from books where contains(info, ‘?hardest’) > 0;

SEARCHING FOR WORDS THAT SOUND LIKE OTHER WORDS

SOUNDEX, expands search terms based on how the word sounds. The SOUNDEX expansion method uses the same text-matching logic available via the SOUNDEX function in SQL.

To use the SOUNDEX option, you must precede the search term with an exclamation mark(!).

SQL> select * from books where contains(info, ‘!grate’) > 0;

INDEX SYNCHRONIZATION

When using CONTEXT indexes, you need to manage the text index contents; the text indexes are not updated when the base table is updated. When the table was updated, its text index is out of sync with the base table. To sync of the index, execute the SYNC_INDEX procedure of the CTX_DDL package.

SQL> exec CTX_DDL.SYNC_INDEX(‘book_index’);

INDEX SETS

Historically, problems with queries of text indexes have occurred when other criteria are used alongside text searches as part of the where clause. To improve the mixed query capability, oracle features index sets. The indexes within the index set may be structured relational columns or on text columns.

To create an index set, use the CTX_DDL package to create the index set and add indexes to it. When you create a text index, you can then specify the index set it belongs to.

SQL> exec CTX_DDL.CREATE_INDEX_SET(‘books_index_set’);

The add non-text indexes.

SQL> exec CTX_DDL.ADD_INDEX(‘books_index_set’, ‘title_index’);

Now create a CTXCAT text index. Specify ctxsys.ctxcat as the index type, and list the index set in the parameters clause.

SQL> create index book_index on books(info) indextype is ctxsys.ctxcat parameters(‘index set books_index_set’);

INDEX-ORGANIZED TABLE

An index-organized table keeps its data sorted according to the primary key column values for the table. Index-organized tables store their data as if the entire table was stored in an index.
An index-organized table allows you to store the entire table’s data in an index.
Ex:
     SQL> create table student (sno number(2),sname varchar(10),smarks number(3) constraint
             pk primary key(sno) organization index;

PARTITION INDEX

Similar to partitioning tables, oracle allows you to partition indexes too. Like table partitions,  index partitions could be in different tablespaces.

LOCAL INDEXES

Ø  Local keyword tells oracle to create a separte index for each partition.
Ø  In the local prefixed index the partition key is specified on the left prefix. When the underlying table is partitioned baes on, say two columns then the index can be prefixed on the first column specified.
Ø  Local prefixed indexes can be unique or non unique.
Ø  Local indexes may be easier to manage than global indexes.

Ex:
     SQL> create index stud_index on student(sno) local;

GLOBAL INDEXES

Ø  A global index may contain values from multiple partitions.
Ø  An index is global prefixed if it is partitioned on the left prefix of the index columns.
Ø  The global clause allows you to create a non-partitioned index.
Ø  Global indexes may perform uniqueness checks faster than local (partitioned) indexes.
Ø  You cannot create global indexes for hash partitions or subpartitions.

Ex:
     SQL> create index stud_index on student(sno) global;

Similar to table partitions, it is possible to move them from one device to another. But unlike table partitions, movement of index partitions requires individual reconstruction of the index or each partition (only in the case of global index).

Ex:
     SQL> alter index stud_ind rebuild partition p2


Ø  Index partitions cannot be dropped manually.
Ø  They are dropped implicitly when the data they refer to is dropped from the partitioned table.

MONITORING USE OF INDEXES

Once you turned on the monitoring the use of indexes, then we can check whether the table is hitting the index or not.

To monitor the use of index use the follwing syntax.

Syntax:
alter index index_name monitoring usage;

then check for the details in V$OBJECT_USAGE view.

If you want to stop monitoring use the following.

Syntax:

alter index index_name nomonitoring usage;