ALTER TABLE

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

In Oracle, ALTER TABLE statement specifies how to add, modify, drop or delete columns in a table. It is also used to rename a table.

How to add column in a table

Syntax:

  1. ALTER TABLE table_name  
  2.   ADD column_name column-definition;   

Example:

Consider that already existing table customers. Now, add a new column customer_age into the table customers.

  1. ALTER TABLE customers  
  2.   ADD customer_age varchar2(50);  

Now, a new column "customer_age" will be added in customers table.

How to add multiple columns in the existing table

Syntax:

  1. ALTER TABLE table_name  
  2.   ADD (column_1 column-definition,  
  3.        column_2 column-definition,  
  4.        ...  
  5.        column_n column_definition);  

Example

  1. ALTER TABLE customers  
  2.   ADD (customer_type varchar2(50),  
  3.        customer_address varchar2(50));  
Now, two columns customer_type and customer_address will be added in the table customers.

How to modify column of a table

Syntax:

  1. ALTER TABLE table_name  
  2.   MODIFY column_name column_type;   

Example:

  1. ALTER TABLE customers  
  2.   MODIFY customer_name varchar2(100) not null;  
Now the column column_name in the customers table is modified
to varchar2 (100) and forced the column to not allow null values. 

How to modify multiple columns of a table

Syntax:

  1. ALTER TABLE table_name  
  2.   MODIFY (column_1 column_type,  
  3.           column_2 column_type,  
  4.           ...  
  5.           column_n column_type);  

Example:

  1. ALTER TABLE customers  
  2.   MODIFY (customer_name varchar2(100) not null,  
  3.           city varchar2(100));  
This will modify both the customer_name and city columns in the table. 

How to drop column of a table

Syntax:

  1. ALTER TABLE table_name  
  2.   DROP COLUMN column_name;  

Example:

  1. ALTER TABLE customers  
  2.   DROP COLUMN customer_name;  
This will drop the customer_name column from the table.

How to rename column of a table

Syntax:

  1. ALTER TABLE table_name  
  2.   RENAME COLUMN old_name to new_name;  

Example:

  1. ALTER TABLE customers  
  2.  RENAME COLUMN customer_name to cname;  
This will rename the column customer_name into cname.

How to rename table

Syntax:

  1. ALTER TABLE table_name  
  2.   RENAME TO new_table_name;   

Example:

  1. ALTER TABLE customers  
  2. RENAME TO retailers;  
This will rename the customer table into "retailers" table.