How to add comment to column in MySQL using Python?

A comment is a readable explanation that describes the purpose or function of a database column. Comments help other developers understand what data a column stores and how it should be used.

In MySQL, you can add comments to table columns using the ALTER TABLE statement with the COMMENT clause. This is particularly useful for documenting complex database schemas.

Syntax

ALTER TABLE table_name
MODIFY column_name column_definition COMMENT "your_comment"

Here, table_name specifies the table name, column_name and column_definition specify the column name and datatype, and your_comment is the descriptive text you want to add.

Steps to Add Column Comments

  • Import MySQL connector

  • Establish connection using connect()

  • Create cursor object using cursor() method

  • Create ALTER query with COMMENT clause

  • Execute the query using execute() method

  • Close the connection

Example

Let's add a comment to an "Address" column in a "Students" table to clarify its purpose ?

import mysql.connector

# Establish database connection
db = mysql.connector.connect(
    host="localhost",
    user="your_username", 
    password="your_password",
    database="school_db"
)

cursor = db.cursor()

# Add comment to Address column
query = """ALTER TABLE Students 
           MODIFY Address VARCHAR(100) 
           COMMENT 'This column stores student home address'"""

cursor.execute(query)
db.commit()
print("COMMENT ADDED..")

db.close()
COMMENT ADDED..

Verifying the Comment

You can verify that the comment was added using the SHOW FULL COLUMNS command ?

import mysql.connector

db = mysql.connector.connect(
    host="localhost",
    user="your_username", 
    password="your_password",
    database="school_db"
)

cursor = db.cursor()

# Display column information with comments
cursor.execute("SHOW FULL COLUMNS FROM Students")
columns = cursor.fetchall()

for column in columns:
    print(f"Column: {column[0]}, Type: {column[1]}, Comment: {column[8]}")

db.close()

Best Practices

  • Keep comments concise but descriptive

  • Use comments for columns with unclear names or complex data

  • Update comments when column purposes change

  • Avoid redundant comments for self−explanatory columns

Conclusion

Adding comments to MySQL columns using Python helps document your database schema effectively. Use the ALTER TABLE statement with the COMMENT clause to provide meaningful descriptions for your columns.

Updated on: 2026-03-25T22:48:13+05:30

656 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements