Learn From - Interactive SQL



SQL Joins


SQL Joins are used to get data from two or more tables using the common values across the tables.
Tables are usually related to each other using Primary Key and Foreign Key.

Primary Key is one or more columns that uniquely represent a record.
Foreign Key is a column that is a Primary key in other table.

Joins are usually done using this Foreign Key and Primary Key to get related data.

The data in the tables are stored using Primary Key and Foreign Key relation to avoid redundancy.
This is to avoid same data getting stored repeatedly in the tables and making it difficult to update.

Below is shown the "Customers" table:

CustomerID CustomerName EmailID Address City PostalCode Country
C001 Fredrick Johnson FJohnson@yahoo.com Berkeley Gardens 12 Brewery London WX1 6LT UK
C002 Mary Davidson Mary@gmail.com 35 King George Madrid 28023 Spain
C003 George Clooney George@hotmail.com Obere Str. 57 Berlin 12209 Germany
C004 David Louis David@mail.com 2743 Bering St. NewJersy 07019 USA
C005 Johnny Anderson Johnny@gmail.com 55 Grizzly Peak Rd. NewJersy 07019 USA
C006 Paul Henriot PaulHenriot@yahoo.com 59 rue de l'Abbaye Paris 51100 France
C007 Henry King Henry@mail.com 120 Hanover Sq. London WA1 1DP UK
C008 Robert John Robert@gmail.com 87 Polk St. Suite 5 San Francisco 94117 USA

In the Customer table "CustomerID" is the Primary Key that acts as a unique value. You can see that the "CustomerID" column value does not repeat.

Below is shown the "Orders" table:

OrderID CustomerID Date Amount
D001 C001 4/3/2007 12:00:00 AM 150.23
D002 C003 1/22/2005 12:00:00 AM 123.57
D003 C005 3/19/2003 12:00:00 AM 220.43
D004 C007 7/21/2008 12:00:00 AM 157.72
D005 C008 2/28/2009 12:00:00 AM 223.78
D006 C011 3/21/2005 12:00:00 AM 245.34

In the Orders table the "OrderID" is the Primary Key. Here you can see that the "CustomerID" column is the Foreign Key.

The Customer and the Orders table are related to each other using the Primary Key and Foreign Key relation.

Different Joins


a.
Inner Join
b.
Left Join
c.
Right Join
d.
Full Join