ALTER TABLE ADD COLUMN – MySQL Shell Python style

We all know as SQL professionals that a common use of the ALTER TABLE command is that we can change a tables’ structure in a myriad number of ways. And, that’s a good thing too because chances are, you won’t always nail down the initial structure. Due to changing business or application requirements, you may even have to add additional columns that were not considered during the schema design phase. Suppose you have many tables that are structured similarly and they all need a specific column added to their already-existing design. Under certain circumstances, using the MySQL Shell in Python mode (\py), can reduce the number of manual ALTER TABLE statements you have to type. Continue reading to see examples in the MySQL Shell…

multiple sets of identical colored concrete columns
Photo by elCarito on Unsplash

OS, Software, and DB used:

  • OpenSuse Leap 15.1
  • MySQL 8.0.21


Self-Promotion:

If you enjoy the content written here, by all means, share this blog and your favorite post(s) with others who may benefit from or like it as well. Since coffee is my favorite drink, you can even buy me one if you would like!


If you have read the post, MySQL Shell Python mode for multiple ALTER TABLE statements – easily, then you might recall I used these 3 tables, all of which have similar columns and structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 MySQL  localhost:33060+ ssl  practice  SQL > DESC ages_1;
+--------+------+------+-----+---------+-------+
| Field  | Type | Null | Key | Default | Extra |
+--------+------+------+-----+---------+-------+
| an_age | int  | YES  |     | NULL    |       |
+--------+------+------+-----+---------+-------+
1 row in set (0.0027 sec)

 MySQL  localhost:33060+ ssl  practice  SQL > DESC ages_2;
+--------+------+------+-----+---------+-------+
| Field  | Type | Null | Key | Default | Extra |
+--------+------+------+-----+---------+-------+
| an_age | int  | YES  |     | NULL    |       |
+--------+------+------+-----+---------+-------+
1 row in set (0.0027 sec)

 MySQL  localhost:33060+ ssl  practice  SQL > DESC ages_3;
+--------+------+------+-----+---------+-------+
| Field  | Type | Null | Key | Default | Extra |
+--------+------+------+-----+---------+-------+
| an_age | int  | YES  |     | NULL    |       |
+--------+------+------+-----+---------+-------+
1 row in set (0.0027 sec)

(If you have not read, MySQL Shell Python mode for multiple ALTER TABLE statements – easily, then I highly recommend doing so. It covers how you can use the powerful MySQL shell in Python (\py) mode and a few lines of Python to execute multiple ALTER TABLE commands with the end goal of renaming and changing the datatype/length of an identical column across all tables.)

For demonstration purposes, suppose I want to add an additional column to each of the 3 demo tables. Granted there are only 3 of them, and re-typing the below ALTER TABLE statement manually for each table is feasible and not too cumbersome:

1
 MySQL  localhost:33060+ ssl  practice  SQL > ALTER TABLE [appropriate_table] ADD COLUMN a_val VARCHAR(10) AFTER an_age;

However, what if you have 10 tables and all of them require an additional identical column? Or, you need to include multiple new columns in all of the tables due to changing requirements? Now all of those similar ALTER TABLE statements become more of an issue than previously thought.

Again your worries are for naught. The powerful MySQL Shell in Python mode (\py) makes these types of tasks all too easy.

First, I need to establish a list of all the tables present in the ‘practice’ database. The get_tables() method does just that:

1
2
3
4
5
6
7
 MySQL  localhost:33060+ ssl  practice  Py > tables = db.get_tables()
 MySQL  localhost:33060+ ssl  practice  Py > tables
[
    <table:ages_1>,
    <table:ages_2>,
    <table:ages_3>
]

In order to execute an ALTER TABLE type of MySQL statement in MySQL Shell, I need to use the .sql() method, as there is not a direct ALTER TABLE method to my knowledge at the time of writing. Therefore, a session object must be used on the .sql() method call. We can use the get_session() method for that:

1
2
3
 MySQL  localhost:33060+ ssl  practice  Py > session = db.get_session()
 MySQL  localhost:33060+ ssl  practice  Py > session
<Session:j2112o@localhost:33060>

Then, I simply use a for loop and iterate through the ‘tables’ list, applying the ALTER TABLE statement to each table. The get_name() method includes the actual string table name – instead of the Shell object name (see the mentioned post for the specific error returned in this case) – in the ALTER TABLE statement using the format() method:

1
2
 MySQL  localhost:33060+ ssl  practice  Py > for table in tables:
                                          ->     session.sql('ALTER TABLE {} ADD COLUMN a_val VARCHAR(10) AFTER an_age'.format(table.get_name())).execute()

As shown in the below DESC commands, all 3 tables now have an ‘a_val’ column of datatype VARCHAR(10) after the ‘an_age’ column:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 MySQL  localhost:33060+ ssl  practice  SQL > DESC ages_1;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| an_age | int         | YES  |     | NULL    |       |
| a_val  | varchar(10) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
2 rows in set (0.0034 sec)

 MySQL  localhost:33060+ ssl  practice  SQL > DESC ages_2;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| an_age | int         | YES  |     | NULL    |       |
| a_val  | varchar(10) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
2 rows in set (0.0029 sec)

 MySQL  localhost:33060+ ssl  practice  SQL > DESC ages_3;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| an_age | int         | YES  |     | NULL    |       |
| a_val  | varchar(10) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
2 rows in set (0.0029 sec)

Again, all too easy using the MySQL Shell in Python mode.

What are your favorite MySQL Shell tricks? Have any special Python ones you like in particular? Tell me all about them in the comments below and thanks for reading!

Like what you have read? See anything incorrect? Please comment below and thanks for reading!!!

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, is performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

2 thoughts on “ALTER TABLE ADD COLUMN – MySQL Shell Python style

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.