Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

MySQL Alter Table Statement Exercises: Change the name of the column state_province to state, keeping the data type and size same

MySQL Alter Table Statement: Exercise-7 with Solution

Write a SQL statement to change the name of the column state_province to state, keeping the data type and size same.

Here is the structure of the table locations.

mysql> SHOW COLUMNS FROM locations;
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| LOCATION_ID    | decimal(4,0) | YES  |     | NULL    |       |
| STREET_ADDRESS | varchar(40)  | YES  |     | NULL    |       |
| POSTAL_CODE    | varchar(12)  | YES  |     | NULL    |       |
| CITY           | varchar(30)  | YES  |     | NULL    |       |
| STATE_PROVINCE | varchar(25)  | YES  |     | NULL    |       |
| COUNTRY_ID     | varchar(2)   | YES  |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+

Code:

ALTER TABLE locations
DROP state_province,
ADD state varchar(25)
AFTER city;

Let execute the above code in MySQL 5.6 command prompt

In that case, if there are no data in the table, the old column will be removed and new column will be create, no problem at all, but if data in the table you can use the following statement :

ALTER TABLE locations
CHANGE state_province state varchar(25);

Now see the structure of the table locations after alteration.

mysql> SHOW COLUMNS FROM locations;
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| LOCATION_ID    | decimal(4,0) | YES  |     | NULL    |       |
| STREET_ADDRESS | varchar(40)  | YES  |     | NULL    |       |
| POSTAL_CODE    | varchar(12)  | YES  |     | NULL    |       |
| CITY           | varchar(30)  | YES  |     | NULL    |       |
| state          | varchar(25)  | YES  |     | NULL    |       |
| COUNTRY_ID     | varchar(2)   | YES  |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a SQL statement to drop the column city from the table locations.
Next: Write a SQL statement to add a primary key for the columns location_id in the locations table.

What is the difficulty level of this exercise?