Monday, March 2, 2026

Oracle Database 12c -- Move a Table to Another Tablespace with LOBs and Indexes Along

Problem

You need to move a table or a list of tables to another tablespace with LOBs and indexes along

Solution

Use the below script, just input target tablespace and define a subquery to return the table list

with t(owner, table_name) as (
<subquery_which_returns_a_list_of_tables>
)
select 
    replace(replace(replace(replace(replace(alter_table, 
    '<owner>',          owner),
    '<table_name>',     table_name),
    '<lob_clause>',     nvl2(lob_list, replace(lob_clause, '<lob_list>', lob_list), '')),
    '<index_clause>',   nvl2(index_list, replace(index_clause, '<index_list>', index_list), '')),
    '<tbs>',            '<TARGET_TBS>') -- <<<<<<<<<<<<<<<<<<<<<<< TARGET TABLESPACE <<<<<<<<<
from (
    select 
        'alter table <owner>.<table_name> move online tablespace <tbs> <lob_clause> <index_clause>;' alter_table,
        owner,
        table_name,
        'lob (<lob_list>) store as (tablespace <tbs>)' lob_clause,
        (select listagg(column_name, ', ') within group (order by column_name) 
            from dba_lobs where table_name=t.table_name and owner=t.owner) lob_list,
        'update indexes (<index_list>)' index_clause,
        (select listagg(owner||'.'||index_name||' tablespace <tbs>', ', ') within group (order by index_name) 
            from dba_indexes where table_name=t.table_name and table_owner=t.owner and index_type <>'LOB') index_list
    from t
);

 

No comments: