MySQL Server is availed as a separate program and handles all the database instructions, commands, and statements including the processing algorithms leveraged by MySQL to process views and operations like drop, update, and show/list. This blog talks about the various salient features of MySQL Keys like the MySQL Primary Key, MySQL Unique Key, MySQL Candidate Key, MySQL Foreign Key, and MySQL Super Key and the various ways to define them.
What is a MySQL Primary Key?
According to the rules of a Relational Database, each table should have only one primary key. Apart from this, Primary Keys aren’t allowed to entertain duplicates (ND), null (NN), or no change (NC) values.
If you try to update or insert NULL values to the Primary Key, it will throw an error. Apart from this, if the Primary Key contains multiple columns, the combination of values within these columns should be unique for it to be valid.
Since MySQL works swiftly with integers, the data type of the Primary MySQL Key column should be an integer.
For instance, INT or BIGINT. It is suggested that you make sure that the value ranges for the Primary Key are enough for storing all the possible rows a table can have.
In MySQL, this column generally has the AUTO_INCREMENT attribute that automatically generates a sequential integer whenever you supply a new row into the table.
Here are a couple of salient aspects of understanding MySQL Primary Key:
Looking for a solution to replicate your MySQL data? A fully managed, No-code Data Pipeline platform like Hevo Data, helps you export log data from MySQL (among 150+ Sources) to your desired destination in real-time & in an effortless manner. It allows the users to seamlessly export log data in a fully automated and convenient manner rather than requiring them to write the code repeatedly to access BinLogs.
Why Hevo?
- Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
- Live Support: Our team is available round the clock to extend exceptional support to our customers through Chat, Email, and Support Calls.
- Automapping: Hevo provides you with an automapping feature to automatically map your schema.
Explore Hevo’s features and discover why it is rated 4.3 on G2 and 4.7 on Software Advice for its seamless data integration. Try out the 14-day free trial today to experience hassle-free data integration.
Get Started with Hevo for Free
1. Using Create Table to Define a Primary MySQL Key
- Step 1: You can define the Primary MySQL Key for a table through the CREATE TABLE statement. In case the Primary MySQL Key has only one column, you can use the PRIMARY KEY constraint as a column constraint as follows:
CREATE TABLE table_name(
primary_key_column datatype PRIMARY KEY,
...
);
CREATE TABLE table_name
: This command initializes the creation of a new table named table_name
.
primary_key_column datatype
: Defines a column in the table, specifying the column name (primary_key_column
) and its data type (datatype
), which could be types like INT
, VARCHAR
, etc.
PRIMARY KEY
: This constraint enforces uniqueness in the primary_key_column
, ensuring that each row in the table has a unique identifier.
...
: This indicates where additional columns can be defined, with each column specified by its name, datatype, and optional constraints.
- Step 2: If the Primary MySQL Key has more than one column, you would have to use the PRIMARY KEY constraint as a table constraint:
CREATE TABLE table_name(
primary_key_column1 datatype,
primary_key_column2 datatype,
...,
PRIMARY KEY(column_list)
);
CREATE TABLE table_name
: Starts the creation of a new table with the specified name, table_name
.
primary_key_column1 datatype, primary_key_column2 datatype
: Defines columns in the table, specifying each column’s name (e.g., primary_key_column1
, primary_key_column2
) and its data type, like INT
, VARCHAR
, etc.
PRIMARY KEY(column_list)
: Declares a composite primary key, using multiple columns listed in column_list
. This means that the combination of values in these columns must be unique across all rows in the table.
...
: Placeholder for additional column definitions, each with a name, datatype, and optional constraints.
- Step 3: You can use the PRIMARY KEY table constraint if the Primary MySQL Key has only one column as follows:
CREATE TABLE table_name (
primary_key_column datatype,
...,
PRIMARY KEY(primary_key_column)
);
CREATE TABLE table_name
: Initiates the creation of a new table named table_name
.
primary_key_column datatype
: Defines a column named primary_key_column
and specifies its data type (e.g., INT
, VARCHAR
).
PRIMARY KEY(primary_key_column)
: Sets primary_key_column
as the table’s primary key, enforcing uniqueness and ensuring that no two rows have the same value in this column.
...
: Indicates where additional columns can be defined with their respective names, datatypes, and constraints.
- Step 4: In this example, you will be creating a table called users whose Primary MySQL Key is the user_id column:
CREATE TABLE users(
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40),
password VARCHAR(255),
email VARCHAR(255)
);
CREATE TABLE users
: Creates a new table named users
.user_id INT AUTO_INCREMENT PRIMARY KEY
: Defines user_id
as an integer column, with automatic incrementing for each new row. It also serves as the primary key, making each user_id
unique.
username VARCHAR(40)
: Creates a username
column that can store up to 40 characters.
password VARCHAR(255)
: Defines a password
column with a maximum length of 255 characters, often used for storing hashed passwords.
email VARCHAR(255)
: Defines an email
column with a maximum length of 255 characters to store email addresses for each user.
- Step 5: You can use the following statement to create a roles table that has the PRIMARY KEY constraint as the table constraint:
CREATE TABLE roles(
role_id INT AUTO_INCREMENT,
role_name VARCHAR(50),
PRIMARY KEY(role_id)
);
CREATE TABLE roles
: Creates a new table named roles
.
role_id INT AUTO_INCREMENT
: Defines role_id
as an integer column, with automatic incrementing for each new row, ensuring unique values.
role_name VARCHAR(50)
: Creates a role_name
column that can store up to 50 characters, typically used to hold the name of the role.
PRIMARY KEY(role_id)
: Sets role_id
as the primary key, enforcing uniqueness and ensuring it serves as the unique identifier for each row in the roles
table.
- Step 6: If the Primary MySQL Key contains various columns, you need to specify what they are at the end of the CREATE TABLE statement. You need to put a comma-separated list of Primary Key columns within parentheses after the PRIMARY KEY keywords. In this example, you create a user_roles table whose Primary MySQL Key contains two columns: role_id and user_id. This table defines the PRIMARY KEY constraint as the table constraint:
CREATE TABLE user_roles(
user_id INT,
role_id INT,
PRIMARY KEY(user_id,role_id),
FOREIGN KEY(user_id)
REFERENCES users(user_id),
FOREIGN KEY(role_id)
REFERENCES roles(role_id)
);
CREATE TABLE user_roles
: Initiates the creation of a new table named user_roles
, which will likely manage the association between users and their roles.
user_id INT
: Defines a column user_id
of type integer, intended to store the IDs of users from the users
table.
role_id INT
: Defines a column role_id
of type integer, intended to store the IDs of roles from the roles
table.
PRIMARY KEY(user_id, role_id)
: Establishes a composite primary key using both user_id
and role_id
, ensuring that each combination of user and role is unique in the table.
FOREIGN KEY(user_id) REFERENCES users(user_id)
: Defines a foreign key constraint on user_id
, linking it to the user_id
column in the users
table. This ensures that any user_id
in user_roles
must exist in the users
table.
FOREIGN KEY(role_id) REFERENCES roles(role_id)
: Defines a foreign key constraint on role_id
, linking it to the role_id
column in the roles
table. This ensures that any role_id
in user_roles
must exist in the roles
table.
- Step 7: You can note here that this statement also ends up creating two Foreign Key constraints.
2. Using Alter Table to Define a Primary MySQL Key
- Step 1: If due to some reason, a table does not have a Primary Key, you can leverage the ALTER TABLE statement to supply a Primary Key to the table as mentioned in the code snippet below:
ALTER TABLE table_name
ADD PRIMARY KEY(column_list);
ALTER TABLE table_name
: Initiates a command to modify an existing table named table_name
.
ADD PRIMARY KEY(column_list)
: Specifies the action of adding a primary key constraint to the table. The column_list
indicates which columns will make up the primary key.
- Primary Key Functionality: The primary key constraint ensures that the values in the specified columns are unique across all rows in the table and cannot contain
NULL
values.
- Composite Key Option: If
column_list
includes multiple columns, it creates a composite primary key, which enforces uniqueness across the combination of values in those columns.
- Step 2: The example mentioned below supplies the id column to the Primary Key. But first, you need to create the pkdemos table without a Primary Key:
CREATE TABLE pkdemos(
id INT,
title VARCHAR(255) NOT NULL
);
CREATE TABLE pkdemos
: Starts the creation of a new table named pkdemos
.
id INT
: Defines a column named id
of type integer. This column will typically hold numeric identifiers for the rows.
title VARCHAR(255) NOT NULL
: Creates a column named title
that can store up to 255 characters. The NOT NULL
constraint ensures that this column must have a value (cannot be empty) for each row.
- Step 3: Next, you need to add the Primary Key to the table by leveraging the ALTER TABLE statement as follows:
ALTER TABLE pkdemos
ADD PRIMARY KEY(id);
ALTER TABLE pkdemos
: Initiates a command to modify the existing table named pkdemos
.
ADD PRIMARY KEY(id)
: Adds a primary key constraint on the id
column.
- Primary Key Functionality: This enforces that the values in the
id
column must be unique for each row and cannot contain NULL
values, ensuring that each record in the table can be uniquely identified by its id
.
- Step 4: If you want to add a Primary Key to a table that already has data, then, the data in the column(s) which will be encapsulated within the PRIMARY KEY must be unique and NOT NULL.
Dropping a PRIMARY KEY Constraint
Use the following SQL command to drop a PRIMARY KEY Constraint
ALTER TABLE Persons
DROP PRIMARY KEY;
ALTER TABLE Persons
: Initiates a command to modify the existing table named Persons
.
DROP PRIMARY KEY
: Removes the primary key constraint from the table.
- Effect of Dropping the Primary Key: This action allows the
id
(or other previously designated primary key column(s)) to accept duplicate values and NULL
entries, meaning rows in the table will no longer be uniquely identifiable by that column.
What is a MySQL Unique Key?
A group of one or more table fields/columns that uniquely identify a record in a database table is known as a unique key in MySQL Keys.
It’s similar to a primary key in that it can only accept one null value and cannot have duplicate values.
Both the unique key and the primary key ensure that a column or set of columns is unique.
Here are a couple of salient aspects of understanding Unique Key MySQL:
1. Using Create Table to Define a Unique MySQL Key
- Step 1: You can use the following syntax if you want to define the Unique Key for a solitary column:
CREATE TABLE <table_name>
(
Column_name1 datatype() UNIQUE,
Column_name2 datatype(),
);
CREATE TABLE <table_name>
: Initiates the creation of a new table, where <table_name>
should be replaced with the desired name for the table.
Column_name1 datatype() UNIQUE
: Defines the first column named Column_name1
with a specified data type. The UNIQUE
constraint ensures that all values in this column must be distinct, preventing duplicate entries.
Column_name2 datatype()
: Defines a second column named Column_name2
, specifying its data type. This column does not have any constraints applied, allowing for duplicate values and NULL
entries if the data type allows it.
(),
: Indicates the end of the column definitions. The parentheses contain the definitions for each column in the table.
- Step 2: If you wish to define more than one Unique Key within a table you can use the following syntax:
CREATE TABLE <table_name>
(
Column_name1 datatype(),
Column_name2 datatype(),…
Column_namen datatype(),
UNIQUE (column_name1, column_name2)
);
CREATE TABLE <table_name>
: Begins the creation of a new table, where <table_name>
should be replaced with the desired name for the table.
Column_name1 datatype(), Column_name2 datatype(), …, Column_namen datatype()
: Defines multiple columns in the table, each with a specified name (e.g., Column_name1
, Column_name2
, …, Column_namen
) and a corresponding data type. The ellipsis (…
) indicates that additional columns can be defined.
UNIQUE (column_name1, column_name2)
: Applies a unique constraint on the combination of column_name1
and column_name2
. This means that the combination of values in these two columns must be unique across all rows in the table, preventing duplicate entries for that combination.
- Step 3: You will be checking this with the help of an example now. Create a table as follows:
CREATE TABLE VATSA(
ID INT AUTO_INCREMENT PRIMARY KEY,
Company_name varchar(100) UNIQUE,
Address varchar(250) UNIQUE
);
CREATE TABLE VATSA
: Initiates the creation of a new table named VATSA
.
ID INT AUTO_INCREMENT PRIMARY KEY
: Defines the ID
column as an integer that automatically increments for each new row. This column serves as the primary key, ensuring each row has a unique identifier.
Company_name varchar(100) UNIQUE
: Creates a column named Company_name
that can store up to 100 characters. The UNIQUE
constraint ensures that all values in this column must be distinct, preventing duplicate company names.
Address varchar(250) UNIQUE
: Creates a column named Address
that can store up to 250 characters. The UNIQUE
constraint ensures that all values in this column must also be distinct, preventing duplicate addresses.
- Step 4: Next, you need to insert some rows in this table as follows:
INSERT INTO VATSA VALUES (1, 'Vatsa_Empire', '132, ABC, Near Royal Club, BSR');
INSERT INTO VATSA VALUES (2, 'Vatsa_Hotel', '138, ABC, Near Royal Club, BSR');
INSERT INTO VATSA VALUES (1, 'Vatsa_Empire', '132, ABC, Near Royal Club, BSR');
:
- This command inserts a new row into the
VATSA
table.
1
: The value for the ID
column, explicitly set to 1.
'Vatsa_Empire'
: The value for the Company_name
column.
'132, ABC, Near Royal Club, BSR'
: The value for the Address
column.
INSERT INTO VATSA VALUES (2, 'Vatsa_Hotel', '138, ABC, Near Royal Club, BSR');
:
- This command inserts another new row into the
VATSA
table.
2
: The value for the ID
column, explicitly set to 2.
'Vatsa_Hotel'
: The value for the Company_name
column.
'138, ABC, Near Royal Club, BSR'
: The value for the Address
column.
- Step 5: Now, if you try to fetch the values from this table, here’s the output you can expect:
- Step 6: Now, if you try to insert a new record with existing data, MySQL will throw an error for the following code snippet:
INSERT INTO VATSA VALUES (10, 'Vatsa_Empire', '204, ABC, Near Royal Club, BSR');
INSERT INTO VATSA VALUES (10, 'Vatsa_Empire', '204, ABC, Near Royal Club, BSR');
:
- This command attempts to insert a new row into the
VATSA
table.
10
: The value for the ID
column, explicitly set to 10.
'Vatsa_Empire'
: The value for the Company_name
column.
'204, ABC, Near Royal Club, BSR'
: The value for the Address
column.
2. Using Alter Table to Define a Unique MySQL Key
- Step 1: MySQL allows you to add a Primary Key on the column of the existing table based on the syntax mentioned below:
ALTER TABLE <table_name>
ADD UNIQUE (column_name);
ALTER TABLE <table_name>
: Initiates a command to modify an existing table, where <table_name>
should be replaced with the actual name of the table you want to alter.
ADD UNIQUE (column_name)
: Adds a unique constraint to the specified column (column_name
) in the table.
- Functionality of the Unique Constraint: This constraint ensures that all values in the
column_name
must be distinct across all rows in the table, preventing duplicate entries. Any attempt to insert or update a row that would result in duplicate values for this column will result in an error.
- Step 2: If you wish to apply the Unique Key constraint on a table called friend, you can use the following code snippet:
ALTER TABLE friend
ADD CONSTRAINT uq_col
UNIQUE (friend_name);
ALTER TABLE friend
: Initiates a command to modify the existing table named friend
.
ADD CONSTRAINT uq_col
: Adds a new constraint named uq_col
to the table. This name can be used to refer to the constraint later if needed (e.g., for dropping it).
UNIQUE (friend_name)
: Specifies that the unique constraint applies to the friend_name
column.
- Functionality of the Unique Constraint: This ensures that all values in the
friend_name
column must be distinct across all rows in the friend
table, preventing any duplicate entries. If an attempt is made to insert or update a row with a duplicate friend_name
, it will result in an error.
- Step 3: Finally, check the result with the help of the following code snippet:
DESCRIBE friend
What is a MySQL Candidate Key?
A characteristic or group of attributes that can uniquely identify a tuple is known as a candidate key in MySQL Keys.
The remaining properties, with the exception of the primary key, are considered candidate keys. Candidates have the same strength as the primary key.
Take a look at the “Employee” table as an example. Emp_Id, Emp_Number, and Emp_Name are the three attributes in this table. Emp_Id and Emp_Number will have unique values, however, Emp_Name may contain duplicate values because multiple employees may have the same name.
The candidate keys here are {Emp Id} and {Emp Number}.
What is a MySQL Foreign Key?
The Foreign Key in MySQL Keys allows MySQL to ensure referential integrity by placing constraints on data in the related tables.
In MySQL, you can have more than one Foreign Key for a table where each Foreign Key references a Primary Key of various parent tables.
However, once a Foreign Key constraint is in place, the Foreign Key columns from the child table need to have the corresponding row in the parent Key columns of the parent table.
Or, the values in these Foreign Keys columns must be NULL for them to be valid.
Here are a couple of salient aspects of understanding MySQL Foreign Key:
1. Prerequisites/Conditions to use a Foreign MySQL Key
Here are a few conditions that a MySQL Foreign Key must conform to:
- The fields that need to be used in the Foreign Key relationship need to be indexed.
- Both the tables that are going to be linked need to be of the same database types.
- The Foreign Key field relationship needs to be similar in datatype as well for it to be valid.
2. How to add a Foreign MySQL Key?
You can add a Foreign Key to an existing table by using the ALTER TABLE command along with an ADD FOREIGN KEY clause to describe the appropriate field as the Foreign Key as follows:
ALTER TABLE zoo
ADD FOREIGN KEY
(FK_species) REFERENCES species (id);
ALTER TABLE zoo
: Initiates a command to modify the existing table named zoo
.
ADD FOREIGN KEY
: Indicates that a new foreign key constraint will be added to the table.
(FK_species)
: Specifies the column in the zoo
table that will act as the foreign key, named FK_species
.
REFERENCES species (id)
: Establishes a relationship between the FK_species
column in the zoo
table and the id
column in the species
table. This means that any value entered into the FK_species
column must correspond to an existing value in the id
column of the species
table.
- Functionality of the Foreign Key: This constraint enforces referential integrity, ensuring that rows in the
zoo
table can only reference valid entries in the species
table. If an attempt is made to insert or update a row in the zoo
table with a FK_species
value that does not exist in the species
table, it will result in an error.
3. How to Delete/Drop a Foreign MySQL Key?
- Step 1: If you wish to drop a Foreign Key constraint, you can leverage the ALTER TABLE statement as follows:
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
ALTER TABLE table_name
: Initiates a command to modify an existing table, where table_name
should be replaced with the actual name of the table from which you want to remove the foreign key constraint.
DROP FOREIGN KEY constraint_name
: Specifies the action of removing a foreign key constraint from the table. The constraint_name
should be replaced with the actual name of the foreign key constraint that you want to drop.
- Effect of Dropping the Foreign Key: This action removes the referential integrity enforced by the foreign key constraint. After this command is executed, the
table_name
can contain values in the specified column(s) that no longer need to correspond to existing values in the referenced table, allowing for potential orphaned records.
In the aforementioned syntax, you need to mention the name of the table from which you wish to drop the Foreign Key following the ALTER TABLE keywords. You also need to specify the constraint name after the DROP FOREIGN KEY keywords.
- Step 2: From the output, it is evident that the products table contains only one Foreign Key constraint, fk_category. You can use the following command to drop it from the table:
ALTER TABLE products
DROP FOREIGN KEY fk_category;
ALTER TABLE products
: Initiates a command to modify the existing table named products
.
DROP FOREIGN KEY fk_category
: Specifies the action of removing the foreign key constraint named fk_category
from the products
table.
- Effect of Dropping the Foreign Key: This action removes the referential integrity enforced by the
fk_category
constraint. After executing this command, the products
table will no longer enforce a relationship between the column(s) associated with fk_category
and the referenced table, allowing for potential orphaned records (i.e., products that reference categories that no longer exist).
- Step 3: To make sure that the Foreign Key constraint has been dropped, you can look at the structure of the products table as follows:
SHOW CREATE TABLE products;
4. How to Disable Foreign MySQL Key Checks?
- Step 1: Quite often, you might find it advantageous to disable Foreign Key Checks. For instance, when you import data from a CSV File within a table. If you don’t disable Foreign Key checks, you would have to load data into proper order. This means that you would have to load data into the parent tables first followed by the child tables, which can be quite cumbersome.
- Step 2: Disabling Foreign Key checks allows you to load data into the tables in any given order. You can use the following statement for the same:
SET foreign_key_checks = 0;
- Step 3: You can enable it again by using the following code snippet:
SET foreign_key_checks = 1;
What is MySQL Super Key?
In a Relational Database, a Super Key is defined as a set of attributes that can identify every tuple of a relation. Since Super Key values are unique, tuples that have the same Super Key value should also have the same non-key attribute values.
For example, (EMPLOYEE ID, EMPLOYEE NAME) in the following EMPLOYEE database, two employees’ names can be the same, but their EMPLYEE ID cannot. As a result, this combination could be a crucial.
Integrate your data in minutes!
Conclusion
You learned how to create a table to define and also how to alter the table for primary and unique keys. You also learned how to add and delete a foreign key in MySQL. It also gives a brief introduction to Relational Database Keys, how they are used to fetch rows and columns from a database when and as required and the features of MySQL before diving into the nitty-gritty of the topic.
Extracting complex data from MySQL to carry out an insightful analysis can be challenging, and this is where Hevo saves the day! Hevo is the only real-time ELT No-code Data Pipeline platform that cost-effectively automates data pipelines that are flexible to your needs to a Data Warehouse and visualize the transformed data in a BI tool. Try a 14-day free trial and experience the feature-rich Hevo suite firsthand. Also, check out our unbeatable pricing to choose the best plan for your organization.
Frequently Asked Questions (FAQs)
1. What is a MySQL Key in a table?
A key, or index, as the title implies, allows you to access the tables. You can identify specific records and the links between tables if you know the key. Each key is made up of one or more fields, often known as field prefixes.
2. How to find Primary MySQL Keys?
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ‘Your Database’
AND TABLE_NAME = ‘Your Table name’
AND COLUMN_KEY = ‘PRI’;
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ‘Your Database’
AND TABLE_NAME = ‘Your Table name’
AND COLUMN_KEY = ‘UNI’;
3. Can a Unique Key be NULL?
The primary key will not accept NULL values. A table can have only one primary key, but it can also contain numerous unique MySQL keys.
4. Can a Primary Key be NULL?
The set of columns that uniquely identify rows in a table is known as a primary key. When you create a primary key constraint, none of the columns that make up the primary key can have NULL constraints, which means they can’t contain NULL values.
Amit is a Content Marketing Manager at Hevo Data. He is passionate about writing for SaaS products and modern data platforms. His portfolio of more than 200 articles shows his extraordinary talent for crafting engaging content that clearly conveys the advantages and complexity of cutting-edge data technologies. Amit’s extensive knowledge of the SaaS market and modern data solutions enables him to write insightful and informative pieces that engage and educate audiences, making him a thought leader in the sector.