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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.