SQL FOREIGN key Foreign Key instance tutorial

Source: Internet
Author: User
Tags one table

SQL FOREIGN key Foreign Key instance tutorial

The key constraints of foreign SQL
The foreign key is at one table point and the primary key is seated in another.

Let us illustrate the foreign key with an example. Take a look at the following two tables:

In the People table:

LastName FirstName Address City
1 Hansen Ola Timoteivn Sandnes
2 Svendson Tove Borgvn Sandnes
3 Pettersen Kari Storgt Stavanger


Order table.

O_ID OrderNo p_id
1 77895 3
2 44678 3
3 22456 2
4 24562 1


Please note that the "Orders" table in the "p_id" column indicates that the "person" in the "p_id" column is seated.

The "p_id" column "People" table is the primary key in the "people" seating.

The Orders table for the foreign key in the Orders table in the p_id column.

FOREIGN KEY constraints are used to prevent actions from destroying the Contact table.

A FOREIGN key constraint can also prevent invalid data from being inserted into a foreign key column because it is the point in a value table.


-------------------------------------------------- ------------------------------

Foreign SQL Key constraints create a table
The Orders table is created when the following SQL creates the "p_id" column on a foreign key:

MySQL's:

CREATE TABLE Orders
(
o_id int not NULL,
OrderNo int not NULL,
p_id int,
PRIMARY KEY (o_id),
FO Reign KEY (p_id) REFERENCES Persons (p_id)
)
SQL server/oracle/ms Access
CREATE TABLE Orders
(
O_i d int not null PRIMARY key,
OrderNo int is not NULL,
p_id int FOREIGN key REFERENCES Persons (p_id)
) in order to have a named FOREIGN KEY constraint and determine Foreign keys constrain multiple columns, use the following SQL syntax: Mysql/sql server/oracle/ms Access: In order to reduce the key constraints on foreign keys, use the following sql:mysql: ALTER TABLE Orders
DRO P FOREIGN KEY fk_perorderssql server/oracle/ms access:alter TABLE Orders
DROP CONSTRAINT fk_perorders

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.