SQL FOREIGN KEY instance tutorial

Source: Internet
Author: User

SQL FOREIGN KEY instance tutorial

Key constraints of foreign SQL statements
The foreign key is located at one table point, and the primary key is seated at another table point.

Let's explain the foreign key and an example. Take a look at the two tables below:

In the "persons" table:

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


Order table.

O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1


Note that the "order" table in the "P_Id" column indicates that "persons" are seated in the "P_Id" column.

The "person" table in the "P_Id" column is the primary key to taking a seat at "person.

The Order table of the foreign key of the Order table in the "P_Id" column.

The foreign key constraint is used to prevent actions from damaging the contact table between them.

Foreign key constraints can also prevent invalid data from being inserted into foreign key columns because it is a value table.


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

Foreign SQL key constraints: Table Creation
When the following SQL statement creates the "P_Id" column on the foreign key, the "order" table is created:

MySQL:

Create table Orders
(
O_Id int not null,
OrderNo int not null,
P_Id int,
Primary key (O_Id ),
Foreign key (P_Id) REFERENCES Persons (P_Id)
)
Web SQL Server/Oracle/MS Access
Create table Orders
(
O_Id int not null primary key,
OrderNo int not null,
P_Id int foreign key references Persons (P_Id)
) To get the naming foreign key constraints and determine the foreign key constraints for multiple columns, use the following SQL Syntax: MySQL/SQL Server/Oracle/MS Access: to reduce foreign key constraints, use the following SQL: MySQL: ALTER TABLE Orders
Drop foreign key fk_PerOrdersSQL Server/Oracle/MS Access: alter table Orders
Drop constraint fk_PerOrders

Related Article

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.