EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials Oracle Tutorial Oracle FOREIGN Key
Secondary Sidebar
Oracle Tutorial
  • Advanced
    • Timestamp to Date in Oracle
    • Oracle Golden Gate
    • Oracle Virtual Machine
    • Oracle Describe Table
    • Oracle Clauses
    • Oracle Having Clause
    • Oracle?Primavera
    • Oracle FOREIGN Key
    • PIVOT in Oracle
    • Oracle Alter Table
    • Oracle Queries
    • Oracle Views
    • Oracle Window Functions
    • Oracle String Functions
    • Oracle Date Functions
    • Oracle Analytic Functions
    • Oracle Aggregate Functions
    • Select in Oracle
    • INSERT in Oracle
    • DISTINCT in Oracle
    • Function in Oracle
    • Oracle GROUP_CONCAT
    • Oracle INSTR()
    • Oracle CONVERT
    • Oracle LENGTH()
    • Oracle EXISTS
    • Oracle REPLACE()
    • Oracle MERGE
    • Oracle LEAD()
    • Oracle EXTRACT()
    • Oracle LISTAGG()
    • Oracle SYS_CONTEXT()
    • Oracle COALESCE
    • Oracle NVL()
    • Oracle SYSDATE()
    • Oracle?Date Format
    • Oracle SYS_GUID()
    • Oracle WILDCARDS
    • Oracle Synonyms
    • Oracle Subquery
    • BETWEEN in Oracle
    • FETCH in Oracle
    • Oracle Index
    • Oracle Function-based Index
    • Oracle UNIQUE Index
    • Oracle Bitmap Index
    • Oracle Column
    • Oracle Triggers
    • Oracle Procedures
    • Sample Database for Oracle
    • Oracle LIKE Operator
    • ORDER BY in Oracle
    • Oracle ORDER BY DESC
    • GROUP BY in Oracle
    • Oracle GROUP BY HAVING
    • Oracle Aliases
    • Table in Oracle
    • Oracle Temporary Table
    • Oracle? Table Partition
    • Oracle rename table
    • Oracle CTE
    • Cursor in Oracle
    • Oracle LOCK TABLE
    • Oracle Tablespace
    • Oracle CARDINALITY
    • Oracle REGEXP
    • Oracle REGEXP_REPLACE
    • Oracle to_date
    • JSON in Oracle
    • Oracle COMMIT
    • Oracle GRANT
    • Oracle MD5
    • Oracle ROLLBACK
    • Oracle Users
    • Oracle TIMESTAMP
    • IF THEN ELSE in Oracle
    • Oracle While Loop
    • Oracle Clone Database
    • Oracle Backup Database
    • Oracle? XML
    • Oracle XMLAGG
    • Oracle XMLTABLE
    • Oracle Performance Tuning
    • Oracle B Tree Index
    • Oracle fusion
    • Oracle ebs
    • Oracle GRC
    • Oracle ERP
    • Oracle ASM
    • Oracle Cloud
    • Oracle HCM Cloud
    • Oracle Integration Cloud
    • Oracle Jinitiator
    • Oracle pathfinder
    • Oracle VirtualBox
    • Oracle Weblogic Server
    • Oracle decode
    • Oracle Exadata
    • Oracle ZFS
    • Oracle? utilities
    • JDBC Driver for Oracle
    • Oracle? DBA Versions
    • Oracle DBA Salary
  • Basic
    • Oracle Marketing Cloud
    • What is Oracle?
    • Career in Oracle
    • How to Install Oracle
    • Oracle Versions
    • What Is Oracle Database
    • Oracle Data Warehousing
    • Oracle Warehouse Builder
    • Career In Oracle Database Administrator
    • Career In Oracle DBA
    • What is Oracle RAC
    • Oracle DBA
    • Oracle? Vanderbilt
    • What is RMAN Oracle
    • Oracle Database Administration
    • Oracle Operators
    • Oracle Constraints
    • Oracle number
    • Oracle Data Types
    • Oracle UNIQUE Constraint
    • Oracle Check Constraint
  • Joins
    • Joins in Oracle
    • Inner Join in Oracle
    • Oracle Cross Join
    • Left Join in Oracle
    • OUTER Join in Oracle
    • Oracle Full Outer Join
    • Natural Join in Oracle
    • Oracle Self Join
    • Oracle hash join
    • Oracle? Update with Join
  • Oracle SET Operators
    • UNION in Oracle
    • Oracle UNION ALL
    • INTERSECT in Oracle
    • MINUS in Oracle
  • Interview Questions
    • Oracle Interview Questions
    • Oracle Apps Interview Questions
    • Oracle Apps Technical Interview Questions
    • Oracle Database Interview Questions
    • Oracle Forms Interview Questions
    • Oracle PL/SQL Interview Questions
    • Oracle RAC Interview Questions
    • Oracle SOA Interview Questions

Related Courses

Oracle Course Training

Oracle DBA Certification Course

MongoDB Certification Training

Oracle FOREIGN Key

By Priya PedamkarPriya Pedamkar

oracle foreign key

What is Oracle FOREIGN Key?

An Oracle FOREIGN Key is used to define an integrity constraint that restricts the values in a Database Table. The table which contains a FOREIGN key called the child table. The FOREIGN key column data reference the parent column data.

Declaration Style of FOREIGN Key

It can be declared in two ways. They are,

1. Column Level (In-Line) Style

  • It can be declared as part of the definition of an individual column or attribute.
  • Usually applied when the constraint is specific to that column only.

2. Table Level (Out of Line) Style

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

  • It can be declared as part of the table definition.
  • It can be declared on the combination of columns together.

Points of Concentration

  • An Oracle FOREIGN key called REFERENTIAL INTIGRITY CONSTRAINT.
  • A FOREIGN KEY column makes a relationship with a specified PRIMARY or UNIQUE KEY.
  • If a FOREIGN KEY is applied on multiple columns, called a composite FOREIGN KEY.
  • A Table or VIEW which contains the FOREIGN Key is known as child object and if FOREIGN Key column(s) references the TABLE or VIEW is known as PARENT object.
  • The same TABLE or VIEW can contain FOREIGN KEY and REFERENCE KEY.
  • ORDER and DATA type must match with the corresponding FOREIGN key and REFERENCE key column(s).
  • A COMPOSITE UNIQUE or PRIMARY key of the PARENT TABLE or VIEW can only be referred by a composite FOREIGN key.
  • Those Tables which contain only FOREIGN keys that relate to another table (s) PRIMARY key, called PURE Details.

Restrictions

The FOREIGN KEY cannot be applied to:

  • LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, OBJECT, BFILE, REF, TIMESTAMP WITH TIME ZONE.
  • The REFERENCED UNIQUE / PRIMARY KEY must be existed on the PARENT TABLE or VIEW before declaring the FOREIGN KEY to reference that column.
  • Maximum 32 columns can be a part of a COMPOSITE FOREIGN key combination.
  • Both Child and Parent tables that are being used for FOREIGN KEY must belong to the same Database.
  • ORACLE TRIGGERS can be used on a distributed Database across nodes to make enable REFERENTIAL integrity.
  • Within a single user or in the same schema, no two FOREIGN keys can have the same name.

References Clause

The REFERENCES clause should be used when the FOREIGN key constraint is INLINE declared. When the constraint is OUT, OF LINE, FOREIGN KEY keyword must be specified.

Syntax #1 – For INLINE FOREIGN Key

CREATE table Table_Name (col_1 Datatype (width), col_2 Data type (width)   CONSTRAINT cons_name REFERENCES Table (column name));

Syntax #2 – For OUT OF LINE FOREIGN Key

CREATE table Table_Name (col_1 Datatype (width), col_2 Datatype (width), col_2 Datatype (width), CONSTRAINT cons_name FOREIGN KEY (col_1, col_2)  REFERENCES Table (col_1, col_2);

Explanation: Col_1/2/n: The column(s) or calculation as per your requirement. Table_Name: As per your requirement. Table (col_1, col_2): Table is the table name that we use for referencing and col_1/2 are the columns from the Table for FOREIGN key reference.

Implementations of FOREIGN Key with Examples

In this section, we’ll see the implementation of Oracle FOREIGN Key and its behavior.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,294 ratings)

Example #1

Code:

CREATE TABLE emp_1 (emp_id NUMBER (2), emp_dept NUMBER (2) CONSTRAINT   DeptID REFERENCES dept (deptno));

Output:

Oracle FOREIGN Key - 1

Explanation: In the above example, FOREIGN key CONSTRAINT applies on the emp_dept column that FOREIGN key referencing the deptno column from the dept table. It means the emp_dept column of the emp_1 table can contain only record(s) which exist in the deptno column of the dept table. This kind of record is called the child record.

Example #2

Code:

INSERT INTO Emp_1 VALUES (1, 70);

Output:

Oracle FOREIGN Key - 2

Explanation: The above INSERT query inserts one record (see below image) and emp_dept value (70) exits in the dept table.

Output:

Oracle FOREIGN Key - 3

Example #3

Code:

INSERT INTO Emp_1 VALUES (1, 90);

Output:

Oracle FOREIGN Key - 4

Explanation: But we run the same insert query with a different value (90) and it returns an error. WHY? Because the value (90) does not exist in the column deptno of the dept table (see dept table data below). As per FOREIGN key rule, the column which consists of a FOREIGN key can only contain referential data, not new value.

Code:

SELECT Deptno from Dept;

Output:

Oracle FOREIGN Key - 5

Composite FOREIGN Key in Oracle

Composite FOREIGN KEY / Table Level (Out of Line) style:

Code:

CREATE TABLE Samp_PK
(
SamID NUMBER (2),
SamName VARCHAR2 (10),
SamDate DATE
) ;

Output:

create table

Explanation: The above SELECT statement creates a table Samp_PK without any CONSTRAINT. We’ll use this table in the below CREATE table statement to declare/reference the FOREIGN key.

Code:

CREATE TABLE Samp_FK
(
SamID NUMBER (2),
SamName VARCHAR2 (10),
SamDate DATE,
CONSTRAINT sampFK_01 FOREIGN KEY (SamID, SamName)
REFERENCES Samp_PK (SamID, SamName)
);

Output:

CREATE table statement

Explanation: In the above example, we tried to create a composite FOREIGN key using table Samp_PK for reference the columns but it throws an error. WHY? Because as per rule a composite FOREIGN key only can refer to a COMPOSITE UNIQUE key or a composite PRIMARY key column in the PARENT TABLE or VIEW.

1. FOREIGN Key Maintenance

  • FOREIGN key can be ADDED, DROPPED, ENABLED or DISABLED but cannot modify the physical structure of the table.
  • The FOREIGN key constraint name can be checked form the
  • USER_CONSTRAINTS
  • USER_CONS_COLUMNS data dictionary views

2. Viewing FOREIGN Key

Syntax:

SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME= ‘Table_Name’;

Code:

SELECT Constraint_Name, Constraint_type FROM USER_CONSTRAINTS WHERE  TABLE_NAME= ‘Emp_1’;

Output:

Viewing

Output showing Constraint_Name and Type. Here R denotes REFERENTIAL INTEGRITY means FOREIGN Key.

3. Adding FOREIGN Key

Syntax:

ALTER TABLE Table_Name ADD [CONSTRAINT <Constraint Name>]   Constraint_Type (Column_Name);

Code:

ALTER TABLE Samp_PK ADD CONSTRAINT samp_FK UNIQUE (SamID,    SamName);

Output:

Adding

Earlier SAMP_PK table had no CONSTRAINT.

4. Droping FOREIGN Key

Syntax:

ALTER TABLE Table_Name DROP [CONSTRAINT <Constraint Name>]   Constraint_Type (Column_Name);

Code:

ALTER TABLE Emp_1 DROP CONSTRAINT DeptID;

Output:

Droping

In the above example, the FOREIGN KEY (DeptID) from the Emp_1 table got dropped. Now, Emp_1 doesn’t have any FOREIGN Key (see image below).

Code:

SELECT Constraint_Name, Constraint_type FROM USER_CONSTRAINTS WHERE     TABLE_NAME= ‘Emp_1’;

Output:

Oracle FOREIGN Key - 11

TIP

1. FOREIGN Key constraint can be disabled or enabled as well. The syntax is given below.

Syntax:

ALTER TABLE Table_Name ENABLE / DISABLE CONSTRAINT <Constraint   Name>];

2. PARENT record can’t be deleted if child record(s) exist. If you try to delete it, it will throw an error message (given below).

Output:

TIP

Conclusion

Oracle FOREIGN KEY is CONSTRAINT which provides REFERENTIAL integrity and which restricts the value(s) that doesn’t exist in parent TABLE or VIEW.  FOREIGN KEY is the best practice to link one table with another.

Recommended Articles

This is a guide to Oracle FOREIGN Key. Here we discuss declared in two ways, References clause, with examples and Composite key. You can also go through our other related articles to learn more –

  1. Cursor in Oracle
  2. BETWEEN in Oracle
  3. ORDER BY in Oracle
  4. MINUS in Oracle
  5. Guide to Oracle Alter Table
Popular Course in this category
Oracle Training (14 Courses, 8+ Projects)
  14 Online Courses |  8 Hands-on Projects |  120+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle DBA Database Management System Training (2 Courses)4.9
All in One Financial Analyst Bundle- 250+ Courses, 40+ Projects4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more