Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a primary-foreign key relation required when we can join without it?

Tags:

sql

database

If we can get data from two tables without having primary and foreign key relation, then why we need this rule? Can you please explain me clearly, with suitable example? It's a test database, don't mind the bad structure.

Tables' structure:

**

table - 'test1' columns - id,lname,fname,dob no primary and foreign key and also not unique(without any constraints) 

**

**table - 'test2' columns- id,native_city again, no relations and no constraints**  

I can still join these tables with same columns 'id', so if there's no primary-foreign key, then what is the use of that?

like image 492
kawade Avatar asked Apr 24 '11 14:04

kawade


People also ask

Why do we need a foreign key when we have a primary key?

A primary key ensures unique row identification. This results in faster sorting, searching, and querying operations. A foreign key creates a link between two tables. It maintains referential integrity between the referencing column(s) and the referenced column(s).

Can we join tables without primary key?

Yes, you can! The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can be handy for merging tables in SQL. In this article, I'll guide you through the different solutions with examples.

Why is the primary key foreign key relationship important in a relational database?

Foreign keys help you to migrate entities using a primary key from the parent table. A foreign key enables you to link two or more tables together. It makes your database data consistent. A foreign key can be used to match a column or combination of columns with primary key in a parent table.


2 Answers

The main reason for primary and foreign keys is to enforce data consistency.

A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.

A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.

like image 56
Daniel Renshaw Avatar answered Oct 04 '22 03:10

Daniel Renshaw


You need two columns of the same type, one on each table, to JOIN on. Whether they're primary and foreign keys or not doesn't matter.

like image 33
duffymo Avatar answered Oct 04 '22 03:10

duffymo