Introduction
In this project, you will learn how to add a unique constraint to the city names in the country table of a MySQL database. This is a common task in database management, where you need to ensure that each city name is unique within the database to maintain data integrity.
🎯 Tasks
In this project, you will learn:
- How to start the MySQL server and log into the MySQL terminal
- How to import a SQL script to create a database
- How to add a unique constraint to a field in a MySQL table
🏆 Achievements
After completing this project, you will be able to:
- Understand the importance of unique constraints in database management
- Confidently add unique constraints to fields in MySQL tables
- Apply your knowledge to maintain data integrity in your own database projects
Start MySQL and Import the Database
In this step, you will learn how to start the MySQL server and import the world.sql database into MySQL.
Open a terminal on the server.
Start the MySQL server:
sudo /etc/init.d/mysql startLog into the MySQL terminal:
mysql -urootImport the
world.sqldatabase:SOURCE ~/project/world.sql
After completing these steps, you will have the world database imported into your MySQL server, and you can proceed to the next step.
Add a Unique Constraint to the City Names
In this step, you will learn how to add a unique constraint to the LocalName field in the country table.
Create a new file named
changeUni.sqlin the~/projectdirectory.Add the following SQL statement to the file:
ALTER TABLE country ADD CONSTRAINT UC_LocalName UNIQUE (LocalName);This statement adds a unique constraint named
UC_LocalNameto theLocalNamefield in thecountrytable.Save the
changeUni.sqlfile.Run the
changeUni.sqlscript in the MySQL terminal:SOURCE ~/project/changeUni.sqlThis will execute the script and add the unique constraint to the
countrytable.
After completing these steps, the unique constraint will be added to the LocalName field in the country table.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



