Syntax for adding fields: alter table tablename add (column datatype [default value][null/not null],….);
The syntax for modifying a field: alter table tablename modify (column datatype [default value][null/not null],….);
The syntax for deleting a field: alter table tablename drop (column);
To add, modify, or delete multiple columns, separate them with commas.
Example of using alter table to add, delete and modify a column.
Create table structure:
create table test1
(id varchar2(20) not null);
Add a field:
alter table test1
add (name varchar2(30) default 'anonymous' not null);
Add three fields at the same time using one SQL statement:
alter table test1
add (name varchar2(30) default 'anonymous' not null,
age integer default 22 not null,
has_money number(9,2)
);
modify a field
alter table test1
modify (name varchar2(16) default ‘unknown’);
Another: The more formal way of writing is:
-- Add/modify columns
alter table TABLE_NAME rename column FIELD_NAME to NEW_FIELD_NAME;
delete a field
alter table test1
drop column name;
It should be noted that if there are already values in a column, if you want to modify the column width to be smaller than these values, an error will occur.
For example, earlier if we insert a value
insert into test1
values ('1', 'We love you');
Then I have modified the column: alter table test1
modify (name varchar2(8));
will get the following error:
ERROR at line 2:
ORA-01441: cannot reduce column length because some values are too large
---------------------------------------------------------------------------------------------------------------
Advanced usage:
重命名表
ALTER TABLE table_name RENAME TO new_table_name;
Modify column names
Syntax:
ALTER TABLE table_name RENAME COLUMN new name to old name;
Example:
alter table s_dept rename column new name to old name;
Attachment: Create table with primary key >>
create table student (
studentid int primary key not null,
studentname varchar(8),
age int);
1. Create a primary key constraint while creating a table
(1) Unnamed
create table student (
studentid int primary key not null,
studentname varchar(8),
age int);
(2) Named
create table students (
studentid int ,
studentname varchar( 8),
age int,
constraint yy primary key(studentid));
2. Delete the existing primary key constraint in the table
(1) Unnamed
available SELECT * from user_cons_columns;
look up the primary key name in the table to get the primary key in the student table named SYS_C002715
alter table student drop constraint SYS_C002715;
(2) have a named
alter table students drop constraint yy;
3. Add a primary key constraint to the
table alter table student add constraint pk_student primary key(studentid);