Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Saturday, 23 August 2014

Foreign Key Constraint in MySql

Foreign Key is a referential kind of constraint in any database. whenever you will try to insert a records
into a column which is foreign key, it will first check whether the value is present in a parent key (Primary Key) Without which it will not allow you to insert a records into the table.

To create a foreign key, there must be a primary key. We cannot create foreign key constraint referencing any other constraint.

Syntax of the Foreign key is:-

CREATE TABLE TABLE_NAME
(
COLUMN_NAME DATA_TYPE
COLUMN_NAME DATA_TYPE
.,
.,
(N),
FOREIGN KEY (COLUMN_NAME) REFERENCES REF_TABLE_NAME(COLUMN_NAME)
);

Below is an example:-

Creating a Primary Key :-

CREATE TABLE EMPLOYEE
(
EMP_ID INT,
EMP_NAME VARCHAR(20),
EMP_ADR VARCHAR(20),
EMP_DEPT_NO INT NOT NULL
PRIMARY KEY(EMP_DEPT_NO) 
);

Creating Foreign Key :-

CREATE TABLE DEPARTMENT
(
DEPT_NO INT NOT NULL,
DEPT_NAME VARCHAR(20)
FOREIGN KEY (DEPT_NO) REFERENCES EMPLOYEE(EMP_DEPT_NO)
);





Read Also:-  Constraint in Oracle
Please provide your feedback in the comments section above. Please don't forget to follow.