Home » SQL

How to use Foreign Key in SQL?

In this article, we will learn how A FOREIGN KEY in one table points to a PRIMARY KEY in another table?
Submitted by Bharti Parmar, on January 09, 2019

Basically, Foreign Key represents relationship between tables.

Syntax:

    column-name data_type (size) CONSTRAINT constraint-name  
    References  Table-name (Column-name)

Example:

Table 1:

Foreign-table-1

Table 2:

Foreign-table-2

First create a primary key in first table which is also called unique key.

Like this:

create table student 
(enroll number(6) primary key, s_name varchar(25), address varchar2(20), 
contact number(10) );

Second create foreign key by using second table.

Like this:

create table student_fees
(enroll number(6) constraint en_fk References Student (enroll) , course_fee number(8), 
status varchar2(6), amount number(10) );

Query to find student name, address, contact from the database.

Foreign result

Conclusion:

In this article, we have learnt how to use foreign key and how it works and useful for us to retrieve data from the relational database? I hope you understand the concept; if you have any query, feel free to ask in the comment section.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.