Define the basic table
The basic format of the SQL statement is as follows
CREATE TABLE 表名(
列名 数据类型 列级完整性约束条件,
列名 数据类型 列级完整性约束条件,
...
表级完整性约束
);
[Example 1]
Create a student table STUDENT
CREATE TABLE STUDENT (
Sno CHAR(9) PRIMARY KEY, /*列级完整性约束条件,Sno时主码*/
Sname char(20) UNIQUE, /*列级完整性约束条件,Sname取唯一值*/
Ssex char(2),
Sage SMALLINT,
Sdept CHAR(20)
);
[Example 2]
Added a course schedule Course
CREATE TABLE Course(
Cno CHAR(4)PRIMARY KEY, /*列级完整性约束条件,Cno时主码*/
Cname CHAR(40) NOT NULL, /*列级完整性约束条件,Cname不能取空值*/
Cpno CHAR(4),
Ccredit SMALLINT,
FOREIGN KEY (Cpno) REFERENCES COURSE(Cno)
/*表级完整性约束条件,Cpno是外码,被参照表是Course,被参照列是Cno*/
);
Modify the basic table
SQL language uses the ALTER TABLE statement to modify the basic table, the format is
ALTER TABLE 表名 ADD COLUMN 列名 数据类型 完整性约束
ALTER TABLE 表名 ADD 表级完整性约束
ALTER TABLE 表名 DROP COLUMN 列名 CASCADE|RESTRICT
ALTER TABLE 表名 DROP CONSTRAINT 完整性约束名
ALTER TABLE 表名 ALTER COLUMN 列名 数据类型
[Example 3]
Add "Enrollment Time" column to the table STUDENT, the data type is date type
ALTER TABLE STUDENT ADD S_entrance DATE;
[Example 4]
Change the data type of age from character type (assuming the original data type is character type) to integer.
ALTER TABLE STUDENT MODIFY Sage INT;
[Example 5]
Add the constraint condition that the course name (Cname) must take a unique value.
ALTER TABLE Course ADD UNIQUE(Cname);
[Example 6]
Add a foreign key, Cpno is the foreign code, the referenced table is Course, and the referenced column is Cno.
ALTER TABLE Course ADD FOREIGN KEY (Cpno) REFERENCES Course(Cno);
Delete basic table
SQL language can use DROP TABLE to delete an unnecessary basic table, the format is:
DROP TABLE 表名 RESTRICT|CASCADE
[Example 7]
Delete the STUDENT table
DROP TABLE STUDENT CASCADE