Thursday, October 5, 2017

Alter table column


Sometimes, the table structures need to change due to certain reasons. SQL command allows the table structure to be change. The basic operation can be done to change the structure of a tables are:

  • Add a new column:
Adding a new column into a table can be done through the following command syntax:
The example of the command in action is shown in Figure 1 below, where a new column "data" with datatype "text" is added into the table "students_with_pk" created previously:
Figure 1: Add table column
  • Remove a column
Removing a column from a table can be done through the following command syntax:
The example of the command in action is shown in Figure 2 below, where a column "data" is removed from the table "students_with_pk":
Figure 2: Remove column "Data" from Table 
  • Changing the datatype in a column
The DBMS also allows database administrator to edit the datatype of a column using the SQL command:
The example of the command in action is shown in Figure 3 below, where the datatype for column "stdemail" is changed from "text" to "varchar(155)":
Figure 3: Modifying the datatype is a column.
  • Removing a primary key from a table
Database administrator can add or remove a primary key from a table. Although this seldom happen, but sometime it is needed due to certain circumstances. Removing a primary key can be problematic as it may jeopardize other tables which uses the primary key as foreign key. The SQL command to remove a primary key for MySQL/MariaDB is:

The example of the command in action is shown in Figure 4 below:
Figure 4: Drop primary key from table
  • Add a primary key to a table

Beside removing a primary key, we can also add primary key in the table. the SQL command for MySQL to add a primary key is:
The example of the command in action is shown in Figure 5 below:
Figure 5: Add primary key to a table.
A primary key of a table can be a combination of multiple key. Therefore an administrator can add a primary key with multiple keys using the SQL commands below:
The sample of the command in action is in Figure 6 below:

* this code is optional to demonstrate, if want to demonstrate, please perform a drop primary key action first before demo.