Your cart is currently empty!
Category: sql
-
Khóa học miễn phí SQL – Foreign Key nhận dự án làm có lương
SQL – Foreign Key
Table of content
The SQL Foreign Key
In SQL, a Foreign Key is a column in one table that matches a Primary Key in another table, allowing the two tables to be connected together.
A foreign key also maintains referential integrity between two tables, making it impossible to drop the table containing the primary key (preserving the connection between the tables).
The foreign key can reference the unique fields of any table in the database. The table that has the primary key is known as the parent table and the key with the foreign key is known as the child table.
Let”s consider an example scenario, assume we have two tables namely CUSTOMERS (ID, NAME, AGE, ADDRES, SALARY) and ORDERS (ID, DATE, CUSTOMER_ID, AMOUNT). Here the id of the customer is primary key (ID) in the CUSTOMERS table and foreign key in the ORDERS (CUSTOMER_ID) table observe the following diagram −
Features of Foreign Key
Following is the of features of Foreign Key −
-
A Foreign Key is used to reduce the redundancy (or duplicates) in the table.
-
It helps to normalize (or organize the data in a database) the data in multiple tables.
Syntax
Following is the basic syntax to add Foreign Key constraints on a column of a table in MySQL database −
CREATE TABLE table_name ( column1 datatype, column2 datatype, ... CONSTRAINT fk_name FOREIGN KEY (column_name) REFERENCES referenced_table(referenced_column) );
Example
Let us create two tables with the names CUSTOMERS and ORDERS. The following query creates a table with the name CUSTOMERS −
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
Output
Following is the output of the above SQL statement −
Query OK, 0 rows affected (0.02 sec)
Now, let us create the ORDERS table. While doing so, we add the foreign key constraint on column CUSTOMER_ID reference on column ID of the CUSTOMERS table as shown in the statement below −
CREATE TABLE ORDERS ( ID INT NOT NULL, DATE DATETIME, CUSTOMER_ID INT, CONSTRAINT FK_CUSTOMER FOREIGN KEY(CUSTOMER_ID) REFERENCES CUSTOMERS(ID), AMOUNT DECIMAL, PRIMARY KEY (ID) );
Output
The above statement produces the following output −
Query OK, 0 rows affected (0.04 sec)
Verification
We have created a Foreign Key Constraint on a column named CUSTOMER_ID in the ORDERS table that references the column named ID of the CUSTOMERS table; so you can”t drop table1 (CUSTOMERS) before dropping the table2 (ORDERS).
First of all, let”s drop the CUSTOMERS table without dropping the ORDERS table using the DROP TABLE statement −
DROP TABLE CUSTOMERS;
If you verify the error message below, you will observe that it says that the table can not be dropped because it is referenced by a FOREIGN KEY constraint −
ERROR 3730 (HY000): Cannot drop table ''customers'' referenced by a foreign key constraint ''FK_CUSTOMER'' on table ''orders''.
Foreign Key Constraint on an Existing Column
We can also create a Foreign key constraint on a column of an existing table. This is useful when you forget to add a Foreign Key constraint on a column while creating a table, or when you want to add this constraint on another column even if one Foreign Key column exists in a table.
Syntax
Using the ALTER TABLE statement we can add a Foreign Key constraint on an existing column in a table in MySQL database as shown below −
ALTER TABLE TABLE2 ADD CONSTRAINT[symbol] FOREIGN KEY(column_name) REFERENCES TABLE1(column_name);
Here, FK_ORDERS is the name of the foreign key constraint. It is optional to specify the name of a constraint but it comes in handy while dropping the constraint.
Example
Assume the CUSTOMERS and ORDERS tables have already been created in the SQL database. Now, we will add a Foreign Key Constraint on the ID column of the ORDERS table.
Following is the SQL query to add the foreign key constraint on an the column of an existing table −
ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS FOREIGN KEY(ID) REFERENCES CUSTOMERS(ID);
Output
Following is the output of the above program −
Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0
Verification
We have created a Foreign Key Constraint on a column named CUSTOMER_ID in the ORDERS table that references the column name ID of the CUSTOMERS table. So, you can”t drop table1 (CUSTOMERS) before dropping the table2 (ORDERS).
First of all, let us drop the CUSTOMERS table without dropping the ORDERS table by executing the following statement −
DROP TABLE CUSTOMERS;
This generates an error message saying that the table can not be dropped because it is referenced by a FOREIGN KEY constraint −
ERROR 3730 (HY000): Cannot drop table ''customers'' referenced by a foreign key constraint ''FK_CUSTOMER'' on table ''orders''.
Dropping a FOREIGN KEY
You can drop the foreign key from a table, without dropping that entire table, using the ALTER TABLE statement.
Syntax
Following is the syntax to drop the FOREIGN key constraint from the column of the table using the ALTER TABLE statement−
ALTER TABLE table_name DROP FOREIGN KEY (constraint symbol);
Where, FK_NAME is the name of the foreign key constraint you need to drop.
Example
The SQL query to drop the foreign key constraint from the column of a table is as follows −
ALTER TABLE ORDERS DROP FOREIGN KEY FK_ORDERS;
Output
Following is the output of the above SQL query −
Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0
Verification
Since we have dropped the Foreign key constraint from the ORDERS table, you can now directly drop the CUSTOMERS table without dropping the ORDERS table, as shown below −
DROP TABLE CUSTOMERS;
If you verify the below status code thrown by the above SQL command, you observe that the CUSTOMERS table has dropped.
Query OK, 0 rows affected (0.02 sec)
Primary Key vs Foreign Key
Even though both the primary key and foreign key refer to the same column, there are many differences to be observed in the way they work. They are listed below −
Primary Key Foreign Key The primary key is always unique. The foreign key can be duplicated. The primary key can not be NULL. The Foreign can be NULL. A table can contain only one Primary Key. We can have more than one Foreign Key per table.
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
-
Khóa học miễn phí SQL – Primary Key nhận dự án làm có lương
SQL – Primary Key
The SQL Primary Key
The SQL Primary Key is a column (or combination of columns) that uniquely identifies each record in a database table. The Primary Key also speeds up data access and is used to establish a relationship between tables.
Even though a table can only have one Primary Key, it can be defined on one or more fields. When a primary key is created on multiple fields of a table, it is called a .
Let us say, you are developing an application called “Customer Management System” to handle all the customer data of a member-only resort. This data can include their personal details, assigned member IDs, other details of the membership they opted, etc. And in all the tables created within this database, the member ID is used to distinguish the customers from each other. So, this field will be the Primary Key.
Following is the diagram of a CUSTOMERS table that holds the personal details of the customers. And as we can observe, the primary key is defined on the CUST_ID column. Using this primary key, we can retrieve a unique record of any customer.

Points to Remember
Here are some key points of the PRIMARY KEY −
-
It contains only a unique value.
-
It can not be null.
-
One table can have only one Primary Key.
-
A primary key length cannot be more than 900 bytes.
Creating an SQL Primary Key
While creating a table using the CREATE TABLE statement, you can add the primary key constraint on a particular column of the table just by to specifying the name of the column along with the keyword “PRIMARY KEY”.
Syntax
Following is the syntax to define a column of a table as a primary key −
CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY(column_name) );
Example
In the following example, we are trying to create a table with the name CUSTOMERS with various fields in an SQL database. While creating the table, we will add the constraint “PRIMARY KEY” on the column named ID.
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
Output
Following is the output of the above SQL statement −
Query OK, 0 rows affected (0.03 sec)
Verification
As we know primary key value must be unique, so you can not insert the record with the same ID. Here, we will verify the constraint created on the ID column, by inserting records with duplicate ID values.
First of all, let”s insert a record into the CUSTOMERS table −
INSERT INTO CUSTOMERS VALUES (3, ''Kaushik'', 23, ''Kota'', 2000.00);
Now, let”s insert one more record with same ID −
INSERT INTO CUSTOMERS VALUES (3, ''Chaitali'', 25, ''Mumbai'', 6500.00);
As we have mentioned above, if any field/column is defined as Primary Key in a database table, two records can not have the same value in that column/field. Therefore, the second insert statement generates the following error −
ERROR 1062 (23000): Duplicate entry ''3'' for key ''customers.PRIMARY''
Similarly, a primary key column cannot contain null values. Here, using the INSERT statement we are passing a NULL value to the primary key column (ID).
INSERT INTO CUSTOMERS VALUES (NULL, ''Komal'', 22, ''Hyderabad'', 4500.00);
This statement generates the following error −
ERROR 1048 (23000): Column ''ID'' cannot be null
Creating Primary Key on an Existing Column
We can also add the PRIMARY KEY constraint on an existing column of a table using the ALTER TABLE statement.
Syntax
Following is the syntax to create a primary constraint on existing columns of a table −
ALTER TABLE table_name ADD CONSTRAINT PRIMARY KEY (column_name);
Example
In this example, we are adding the PRIMARY KEY constraint on the NAME column of the existing CUSTOMERS table −
ALTER TABLE CUSTOMERS ADD CONSTRAINT PRIMARY KEY(NAME);
Output
Following is the output of the above statement −
Query OK, 0 rows affected (0.05 sec) Records: 0 Duplicates: 0 Warnings: 0
Dropping an SQL Primary Key
If you can add a Primary Key Constraint to a column in the table, you can drop it as well. This is done by using the ALTER TABLE… DROP statement.
Syntax
Following is the syntax of the ALTER TABLE statement to can drop the Primary key constraints from the column of a table −
ALTER TABLE table_name DROP PRIMARY KEY;
Example
Let us consider the CUSTOMERS table where we have created a primary key constraint on a column named ID. You can drop this constraint from the column ID by executing the following statement −
ALTER TABLE CUSTOMERS DROP PRIMARY KEY;
Output
The above SQL query produces the following output −
Query OK, 1 row affected (0.03 sec) Records: 1 Duplicates: 0 Warnings: 0
Verification
As we have dropped the Primary key from the column named ID, we can insert multiple records with the same ID. Following statement inserts four records with the same ID −
INSERT INTO CUSTOMERS VALUES (3, ''Chaitali'', 25, ''Mumbai'', 6500.00 ), (3, ''Hardik'', 27, ''Bhopal'', 8500.00 ), (3, ''Komal'', 22, ''Hyderabad'', 4500.00 ), (3, ''Muffy'', 24, ''Indore'', 10000.00 );
If you verify the content of this table, you can find multiple records with same ID −
SELECT * FROM CUSTOMERS;
The table will be displayed as −
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
3 | Kaushik | 23 | Kota | 2000.00 |
3 | Chaitali | 25 | Mumbai | 6500.00 |
3 | Hardik | 27 | Bhopal | 8500.00 |
3 | Komal | 22 | Hyderabad | 4500.00 |
3 | Muffy | 24 | Indore | 10000.00 |
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc