Search

Monday, December 7, 2015

Difference between Primary and Foreign key in table - SQL

The database is a collection of tables and a table is the collection of rows or records. A primary key is the data to uniquely identify a row in the table. For example, if an Employee table has millions of rows and emp_id is a primary key then it can uniquely identify that row. You can use this primary key to retrieve (SELECT) the row, update the row and delete the row. In SQL, a table can have only one primary key but it can contain more than one columns. There are two types of primary key, a simple primary key, and a composite primary key. A simple primary key is made of just one column while a composite primary key is made of more than one columns. Primary key also enforces some constraint e.g. UNIQUE and NOT NULL, which means if you try to enter another record with the primary key already existing in the database than DBMS will reject it. Similarly, a primary key cannot be NULL, it must have some value. On the other hand, the foreign key is just the primary key of another table. In a relational database, two tables can be related to each other e.g. Employee and Department, those cases, the primary key of one table becomes the foreign key of another table. In this article, you will learn some key difference between the Primary and foreign key in a table. This is also one of the most common SQL Interview questions for 1 to 2 years experience programmers.
Read more »

No comments:

Post a Comment