Basic SQL Statements: Use "alter table" to add or rename columns (still working on this article...)

Part one of the story in this zoo: Basic SQL Statements: Creating a full Table & CRUD

All animals in this zoo are our family members, and each member has his or her name. We don't call our siblings "hey, sister number one, or brother number two." That's super weird! Let's add a new column to put each member's name.

But before adding a new column, we have to rename the existing name column, for there can't be two columns with the same name in a table.

Rename a column

alter table *table_name* rename column *original_name* to *new_name*;

e.g.
alter table animal rename column name to species_name;

Create a new column in the table

alter table *table_name* add *column_name* *datatype*;

e.g.
alter table animal add name varchar(255);

This is what the table looks like after renaming and creating a new column.

Screen Shot 2022-10-19 at 9.55.37 AM.png

Add data to the newly created column

There is no data in the newly created column "name." Use update to add some data to the new column.

update *table_name* set *column_name = __data after changing__* where *column_name = value*;

e.g.
update animal set name = "Bruce" where id = 1;
update animal set name = "Anna" where id = 2;
update animal set name = "Cutipie" where id = 3;
update animal set name = "Navy" where id = 4;
update animal set name = "Leonardo" where id = 5;
update animal set name = "Valentina" where id = 6;
update animal set name = "Casper" where id = 7;
update animal set name = "Iris" where id = 8;
update animal set name = "Luna" where id = 9;
update animal set name = "Aurora" where id = 10;

Screen Shot 2022-10-19 at 10.24.50 AM.png

Change datatype of the column