![]() |
VOOZH | about |
In this article, we are going to update the structure of the table using the sqlalchemy module.
The structure of the table includes name of columns, the datatype of columns, constraints, keys, etc which we are going to update in this post.
Let us first install the SQLAlchemy module by running the following pip command in the terminal:
pip install sqlalchemy pymysql
Note: pymysql is a dependency of sqlalchemy which we need to install for this post
database used :
👁 ImageThe first step includes importing the sqlalchemy module and connection to the database. This we can do by the following code:
Let us now define the table name we will use:
So now we will define the sql query to update the structure of the table. For performing our task we will use alter command of sql which is used to update the table.
Syntax of altering command:
ALTER TABLE table_name CLAUSE change_in_structure;
Here, clauses can be: ADD, RENAME, CHANGE, DROP, MODIFY
The use of each clause is as follows :
ALTER TABLE table_name ADD column_name DATATYPE CONSTRAINTS ;
ALTER TABLE table_name RENAME new_name_of_table ;
ALTER TABLE table_name CHANGE old_column new_column DATATYPE CONSTRAINTS ;
ALTER TABLE table_name DROP column_name;
ALTER TABLE table_name MODIFY column_name DATATYPE CONSTRAINTS ;
Let us see an example of each of the above :
Let us add a new column to our table named "gender" which can accept 2 values namely "m" for male and "f" for female.
Output:
👁 ImageLet us drop the "gender" column which we have created above in this example.
Output:
👁 ImageLet us rename the column "sno" to "id" with the help of the CHANGE clause in ALTER command of sql.
Output:
👁 ImageLet us modify our column "id" and make it a primary key.