MySQL Alter Table Statement Exercises: Add a primary key for the columns location_id in the locations table
MySQL Alter Table Statement: Exercise-8 with Solution
Write a SQL statement to add a primary key for the columns location_id in the locations table.
Here is the sample table employees.
Sample table: locations
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
ADD PRIMARY KEY(location_id);
Let execute the above code in MySQL 5.6 command prompt
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) | NO | PRI | 0 | |
| 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 | |
+----------------+--------------+------+-----+---------+-------+
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a SQL statement to change the name of the column state_province to state, keeping the data type and size same.
Next: Write a SQL statement to add a primary key for a combination of columns location_id and country_id.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework