Table and Table Partition Defragmentation in Oracle Database



In an Oracle database, table and table partition fragmentation can occur over time as data is inserted, updated, and deleted, causing the physical data blocks to become spread out on disk and slowing down query performance. Defragmentation is the process of reorganizing the physical data blocks to improve performance.

 Methods for defragmenting tables and partitions in Oracle

Shrinking a table:

ALTER TABLE table_name SHRINK SPACE CASCADE;

Shrinking a partition:

ALTER TABLE table_name MODIFY PARTITION partition_name SHRINK SPACE;

Moving a table or partition to a new tablespace:

ALTER TABLE table_name MOVE TABLESPACE new_tablespace;

Moving a table to a new table space will not automatically move its partitions to the new tablespace. You would need to move each partition separately using the ALTER TABLE MOVE PARTITION command


ALTER TABLE table_name MOVE PARTITION partition_name TABLESPACE new_tablespace;

Replace table_name with the name of the table, partition_name with the name of the partition you want to move, and new_tablespace with the name of the new tablespace you want to move the partition to.


Exporting and importing a table or partition:
 EXPDP and IMPDP

Rebuilding a table index:

ALTER INDEX index_name REBUILD;

Rebuilding an index involves creating a new index and copying the data from the existing index into the new one. This can help to improve performance and reduce fragmentation, but it can also be a time-consuming process, so it is recommended to schedule it during a maintenance window.

There are several ways to rebuild an index in an Oracle database, including the following:

Online Index Rebuild:

ALTER INDEX index_name REBUILD ONLINE;

Offline Index Rebuild:

ALTER INDEX index_name REBUILD;

Drop and Re-Create the Index:

DROP INDEX index_name;
CREATE INDEX index_name ON table_name (column1, column2, ...);

Note that the ONLINE option for the ALTER INDEX command allows you to rebuild the index without taking the table offline. The DROP and CREATE method is a more invasive method and should only be used if other methods are not possible.
If you like please follow and comment