Data Definition Language
This page summarizes how to:
- Create a database table.
- Modify the existing definition of the table.
Creating Database Tables
A table can be created by using CREATE TABLE statement. We need the CREATE TABLE system privilege to execute this command.
The general syntax of the CREATE TABLE statement is as follows:
Example commands are as follows
With NOT NULL column constraint
Example :
with UNIQUE Constraint
Example:
Using PRIMARY KEY Constraint
FOREIGN KEY Constraint, REFERENCES and ON DELETE CASCADE Options
Example :
Enabling and Disabling Constraints
Table Constraints
A Table constraint is the constraint that is applied to one or more columns of a table. The table constraints are defined after the last column definition. For example.
Here a foreign key has been defined as a table constraint. Like this we can define primary key and other constraints as table constraints.
Creating a table using Subquery
The table can also be created from the existing table. The general syntax for this is
To create the new department table use the following query
Modifying the Table structure
The general syntax of the ALTER TABLE statement is as follows:
Adding columns
To add a new column in the table definition, we can use ALTER TABLE command with an ADD clause.
Example: To add a column department head (dept.head) to the dept table, use the following query
Modifying Column Definitions
The ALTER TABLE command with MODIFY clause is used to modify a column definition. The syntax is
For example, to modify the size of the dept- head to 25, use the following quety
The Drop Clause
This clause is used to remove the constraints from a table. The syntax is
Using CASCADE option with DROP, we can remove all the dependent constraints.
Example
This will drop the primary key definition in the dept table and also the foreign key definition from the emp table. This is because the foreign key definition in the emp table is dependent on ( i.e. references) the primary key definition from dept table.
Enabling /Disabling Column Constraints
To enable or disable constraints we can use ENABLE or DISABLE option of the ALTER TABLE command. For example, if we use the following query
This removes all the rows from the emp table. The table definition still remains in the database.
Deleting a Table
To delete a table DROP command is used. The DROP command deletes the table definition and all its data.
Syntax:
Example: To delete the emp table we can use the following query..
The CASCADE CONSTRAINTS option in DROP command drops all referential integrity constraints that refer to primary and unique keys in the dropped table.
For example, to delete the dept table and all the dependent constraint definitions, we can use the following query
This will delete the dept table, all the constraints from dept table (primary key definition) and also the dependent constraints from the em p table (foreign key definition).