Question

I want to create a procedure that retrieves all indexes on my table and rebuilt

i retrieves all indexes with this query:

select index_name from user_indexes where table_name='your_table_name'

and i rebuilt with this query:

alter index <index_name> rebuild;

Thx.

Was it helpful?

Solution

create or replace procedure rebuild_indexes(
    p_owner in varchar2,
    p_table_name in varchar2
) as
begin
    for indexes_to_rebuild in
    (
        select index_name
        from all_indexes
        where owner = p_owner
            and table_name = p_table_name
    ) loop
        execute immediate 'alter index '||p_owner||'.'
            ||indexes_to_rebuild.index_name||' rebuild';
    end loop;
end;
/

Although this will only work with the simplest indexes. There are many restrictions on rebuilding. For example, if the index is partitioned you need to rebuild each partition or subpartition.

And there are many options you may want to consider. For example, use ONLINE if you want others to use the index during the rebuild, add a PARALLEL option to rebuild faster (but this also changes the index's parallel setting, which can cause problems), etc.

Keep in mind that many of the top Oracle experts think rebuilding indexes is usually a waste of time. There are some rare cases where rebuilding can help an index, such as sparse deletions of monotonically increasing values. But most index rebuilding is done because of myths that can be dispelled by reading Richard Foote's presentation Index Internals - Rebuilding the Truth.

Rebuilding will make your indexes initially run faster and look smaller, but that's because of caching and the reduction of overheads like segment space allocation. A week later, your indexes will probably be right back to where they started.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top