Alter Table
Instructor: Samia arshad
Changing Tables
• Sometimes
ALTER TABLE you
canwant to change the structure
of
• an
Addexisting table
a new column
• Remove
One wayan existing
is to DROP column
it then rebuild it
• Add
This ais new constraint
dangerous, so there is the ALTER TABLE
• command
Remove aninstead
existing constraint
More SQL Data Definition
ALTERing Columns
Examples
To change existing attribute type and
renaming a column Changing attribute
type:
ALTER TABLE <table>
ALTER TABLE Student
Modify <col>
Modify
Alter TABLE <table> Degree CHAR(5)
Renaming
CHANGE <oldname> <newname> attribute:
type(size)
ALTER TABLE Student
CHANGE Degree
Degree1 varchar(25)
More SQL Data Definition
Adding Constraints
To add or remove Examples
columns use Adding constraint:
Unique Constraint
ALTER TABLE <table> ALTER TABLE STUDENT
ADD CONSTRAINT
ADD CONSTRAINT
ck UNIQUE (DEGREE)
<definition>
Not Null constraint
• alter table STUDENT
ALTER TABLE <table modify Degree varchar(25)
name> modify Not Null;
<column name>
type(size) not
null; More SQL Data Definition
Adding Constraints
Primary Key • Foreign key
ALTER TABLE ALTER TABLE
STUDENT STUDENT
ADD CONSTRAINT ADD CONSTRAINT
pk Primary key fk Foreign key
(id) (column name)
references
primary
table(column
More SQL Data Definition name)
Adding constraints
• Check
ALTER TABLE
STUDENT
ADD CONSTRAINT
chk check
(id>10)
More SQL Data Definition
Dropping Constraint
Dropping Constraint:
ALTER TABLE
ALTER TABLE STUDENT
<table>
DROP foreign key
DROP
constraintname;
CONSTRAINT
Dropping Not Null
<name>
constraint
ALTER TABLE student
CHANGE column name
column name int(25) null;
More SQL Data Definition
Dropping Constraint
• To drop primary • Alter table
key, check, STUDENT drop
unique constraint, index
the following constraintname;
syntax will be
used
More SQL Data Definition
Drop table
Drop table Examples
Drop TABLE <table name>
Drop TABLE student
More SQL Data Definition