By 25/02/2016 11 Comments

What Is FOREIGN KEY Constraint In SQL?

  • SQL FOREIGN KEY constraint is used to build logical/physical relationship between two or more tables.
  • SQL FOREIGN KEY in one table makes relation or point to a PRIMARY KEY in another table.
  • SQL FOREIGN KEY constraint prevents actions which destroys the relations/links between these tables.
  • SQL FOREIGN KEY constraint also prevents of invalid data insertion in FOREIGN KEY column.

Example: MySQL

CREATE TABLE city
(
id BIGINT(11) NOT NULL,
city_name VARCHAR(200) NOT NULL,
country_id BIGINT(11),
PRIMARY KEY (id),
FOREIGN KEY (country_id) REFERENCES country (country_id)
);

Example: SQL Server, Oracle, MS Access

CREATE TABLE city
(
id int NOT NULL PRIMARY KEY,
city_name VARBINARY(MAX) NOT NULL,
country_id int FOREIGN KEY REFERENCES country(country_id)
)

Note:

  • In above examples a FOREIGN KEY constraint is defined in table city on country_id column which is referencing to┬ácountry_id column in country table through REFERENCES keyword.






Posted in: Sql

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .