Define primary key and foreign key in MYSQL?
In MySQL and other relational database management systems (RDBMS), primary keys and foreign keys are essential concepts used to establish relationships between tables in a database. Let me define each term for you:
Primary Key:
A primary key is a unique identifier for a record in a table. It must contain unique values and cannot have NULL values. Every table in a database should have a primary key because it ensures that each record in the table is uniquely identified. In MySQL, you can define a primary key when creating a table, and the primary key column(s) will enforce the uniqueness and non-null constraints for the table.
Here's an example of creating a table with a primary key in MySQL:
employee_id
is the primary key of the employees
table.Foreign Key:
A foreign key is a field in a table that is used to establish a link between the data in two tables. It creates a relationship between two tables by referencing the primary key of another table. The table containing the foreign key is called the referencing table, and the table with the primary key being referenced is called the referenced table. Foreign keys ensure referential integrity in the database, meaning that relationships between tables are maintained correctly.
Here's an example of creating a table with a foreign key in MySQL:
customer_id
in the orders
table is a foreign key that references the customer_id
column in the customers
table. This establishes a relationship between the orders
and customers
tables, where customer_id
in the orders
table must correspond to an existing customer_id
in the customers
table.In summary, a primary key uniquely identifies records within a table, while a foreign key establishes a relationship between tables by referencing the primary key of another table.
Comments
Post a Comment