[フレーム]

SQL Tutorial

SQL HOME SQL Intro SQL Syntax SQL Select SQL Select Distinct SQL Where SQL Order By SQL And SQL Or SQL Not SQL Insert Into SQL Null Values SQL Update SQL Delete SQL Select Top SQL Aggregate Functions SQL Min() SQL Max() SQL Count() SQL Sum() SQL Avg() SQL Like SQL Wildcards SQL In SQL Between SQL Aliases SQL Joins SQL Inner Join SQL Left Join SQL Right Join SQL Full Join SQL Self Join SQL Union SQL Union All SQL Group By SQL Having SQL Exists SQL Any SQL All SQL Select Into SQL Insert Into Select SQL Case SQL Null Functions SQL Stored Procedures SQL Comments SQL Operators

SQL Database

SQL Create DB SQL Drop DB SQL Backup DB SQL Create Table SQL Drop Table SQL Alter Table SQL Constraints SQL Not Null SQL Unique SQL Primary Key SQL Foreign Key SQL Check SQL Default SQL Create Index SQL Auto Increment SQL Dates SQL Views SQL Injection SQL Parameters SQL Prepared Statements SQL Hosting

SQL Cert

SQL Certificate

SQL References

SQL Data Types SQL Keywords MySQL Functions
String Functions: ASCII CHAR_LENGTH CHARACTER_LENGTH CONCAT CONCAT_WS FIELD FIND_IN_SET FORMAT INSERT INSTR LCASE LEFT LENGTH LOCATE LOWER LPAD LTRIM MID POSITION REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPACE STRCMP SUBSTR SUBSTRING SUBSTRING_INDEX TRIM UCASE UPPER Numeric Functions: ABS ACOS ASIN ATAN ATAN2 AVG CEIL CEILING COS COT COUNT DEGREES DIV EXP FLOOR GREATEST LEAST LN LOG LOG10 LOG2 MAX MIN MOD PI POW POWER RADIANS RAND ROUND SIGN SIN SQRT SUM TAN TRUNCATE Date Functions: ADDDATE ADDTIME CURDATE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURTIME DATE DATEDIFF DATE_ADD DATE_FORMAT DATE_SUB DAY DAYNAME DAYOFMONTH DAYOFWEEK DAYOFYEAR EXTRACT FROM_DAYS HOUR LAST_DAY LOCALTIME LOCALTIMESTAMP MAKEDATE MAKETIME MICROSECOND MINUTE MONTH MONTHNAME NOW PERIOD_ADD PERIOD_DIFF QUARTER SECOND SEC_TO_TIME STR_TO_DATE SUBDATE SUBTIME SYSDATE TIME TIME_FORMAT TIME_TO_SEC TIMEDIFF TIMESTAMP TO_DAYS WEEK WEEKDAY WEEKOFYEAR YEAR YEARWEEK Advanced Functions: BIN BINARY CASE CAST COALESCE CONNECTION_ID CONV CONVERT CURRENT_USER DATABASE IF IFNULL ISNULL LAST_INSERT_ID NULLIF SESSION_USER SYSTEM_USER USER VERSION
SQL Server Functions MS Access Functions SQL Quick Ref

SQL Examples

SQL Examples SQL Editor SQL Quiz SQL Exercises SQL Server SQL Syllabus SQL Study Plan SQL Training

SQL FOREIGN KEY Constraint


SQL FOREIGN KEY Constraint

The FOREIGN KEY constraint establishes a link between two tables, and prevents action that will destroy the link between them.

A FOREIGN KEY is a column in a table that refers to the PRIMARY KEY in another table.

The table with the foreign key column is called the child table, and the table with the primary key column is called the referenced or parent table.

The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column (in the child table), because the value has to exist in the parent table.

The FOREIGN KEY constraint also prevents you from deleting a record in the parent table, if related rows still exist in the child table.

Assume we have two tables:

Persons Table

PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23

Orders Table

OrderID OrderNumber PersonID
3 22456 2
4 24562 1

Here we see that the "PersonID" column in the "Orders" table points to the "PersonID" column in the "Persons" table.

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "PersonID" column in the "Orders" table is the FOREIGN KEY in the "Orders" table.



FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY constraint on the "PersonID" column upon creation of the "Orders" table:

CREATE TABLE Orders (
OrderID int PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int,
CONSTRAINT fk_Person
FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

FOREIGN KEY on ALTER TABLE

To create a FOREIGN KEY constraint on the "PersonID" column after the "Orders" table is created, use the following SQL:

ALTER TABLE Orders
ADD CONSTRAINT fk_Person
FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID);

Drop a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Orders
DROP CONSTRAINT fk_Person;

MySQL:

ALTER TABLE Orders
DROP FOREIGN KEY fk_Person;



New

W3Schools Adventure App

Coding fundamentals as a game. Bite-sized lessons and challenges.

Ready to start your journey? Your streak is waiting.
+60 XP
W3Schools Adventure tutor
W3Schools Adventure map
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

FORUM ABOUT ACADEMY
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

AltStyle によって変換されたページ (->オリジナル) /