oracle Delete Table Fields and oracle Add Table Fields

  • 2021-10-27 09:40:52
  • OfStack

Syntax for adding fields: alter table tablename add (column datatype [default value] [null/not null],...);

Modify the syntax of the field: alter table tablename modify (column datatype [default value] [null/not null], …);

Syntax for deleting fields: alter table tablename drop (column);

If you add, modify or delete multiple columns, separate them with commas.

Example of adding, deleting, and modifying 1 column using alter table.

Create a table structure:
create table test1
(id varchar2(20) not null);

Add 1 field:


alter table test1
add (name varchar2(30) default  'Anonymous ' not null);

Use one SQL statement to add three fields at the same time:


alter table test1
add (name varchar2(30) default  'Anonymous ' not null,
age integer default 22 not null,
has_money number(9,2)
);

Modify 1 field


alter table test1
modify (name varchar2(16) default  ' unknown');


Another: The more formal writing is:

-- Add/modify columns 
alter table TABLE_NAME rename column FIELD_NAME to NEW_FIELD_NAME;


Delete 1 field

alter table test1
drop column name;


It should be noted that if there are values in a 1 column, if you want to modify the column width to be smaller than these values, there will be an error.

For example, if we insert 1 value earlier,


insert into test1
values ('1 ' ,' We love you very much ');

The column was then modified: alter table test1
modify (name varchar2(8));
You will get the following error:
ERROR is on line 2:
ORA-01441: Column length cannot be reduced because 1 value is too large

Advanced usage:

Rename table
ALTER TABLE table_name RENAME TO new_table_name;

Modify the name of the column

Syntax:
ALTER TABLE table_name RENAME COLUMN supplier_name to sname;

Example:
alter table s_dept rename column age to age1;


Attachment: Creating a table with a primary key > >


create table student (
studentid int primary key not null,
studentname varchar(8),
age int);

1. Create primary key constraints while creating tables
(1) No naming


create table student (
studentid int primary key not null,
studentname varchar(8),
age int);

(2) There are names


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) No naming
Available SELECT * from user_cons_columns;
The primary key name in the student table for the primary key name in the lookup table is SYS_C002715
alter table student drop constraint SYS_C002715;
(2) There are names
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);


Related articles: