Guide to Changing Columns in MySQL Tables
This lesson walks through how to change a column in a MySQL table. Specifically, we'll examine how to ensure that a foreign key is required for every new record.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In the last guide, we build out our addresses table and in addresses table we integrated a foreign key. I did something that was wrong in the last guide depending on your knowledge of databases. I allowed the users_id to be null by not checking the “not null” box.

Typically we wouldn't want that, but that gives us a good opportunity for seeing how can we edit a table after it's been created. Doing this in the MySQL workbench is insanely easy. All you have to do is open up the addresses table. So the way that you can do this is if you go to “addresses” and hover over it you'll see this little wrench icon.

medium

if I click that, it will open up the addresses table in a new tab. So inside of this tab, this is where you can make changes. In order to make the change, we want to come down to our foreign key right here which is addresses_users_id and click on the box ‘not null’. From here we can click on apply.

large

This is going to alter the table and the code will be slightly different. It's going to drop the foreign key. This is very important if you are altering a table after you’ve created one. Let's imagine we're in a table and we have a million addresses in here. This is probably not the way that you want to do it.

There are other ways of doing it but if you are working on an application that large then you're probably beyond the introductory course to it. What we're going to do here is pretty basic. This is going to drop it and then it's going to alter it by changing the column. The only change that's going to be made is that it's going to be not null where before allowed it to be null. if I hit apply this is going to execute everything. Now hit close. We are back to this being set up properly.

The reason why I think a much better way of doing it is, I don't have an issue if the secondary street is null. There's going to be many times where that's going to be the case. We want to make sure that it’s allowed. Now the “users_id” on the other hand I don't think it would make much sense for us to have an address that's not connected to a user.

We’re going to be running queries at some point or where we're going to want to see what user they belong to. That's kind of just a practical way of viewing this type of data and first structuring a database schema. So that is how you can edit a column inside of MySQL.