Do You Want to Learn SQL?

Take our free eight day course, where I'll teach you in simple to understand English all you need to get started learning SQL.

-
DAYS
-
HOURS
-
MINUTES
-
SECONDS

Free Beginners SQL Course!

SQL Joins: Exploring the Power of Table Combining

In this lesson you will learn about SQL joins. When you hear developer say “SQL JOIN BY” most likely they are talk about the SQL INNER JOIN and the way you’re combining tables.

Let’s start off with an example using the PizzaDB CustomerOrder table and it’s related Customers.

Joins and Matching Values

Here is a ERD (Entity Relationship Diagram) show how the two tables are related:

Using ERD diagrams to help find ways to join tables.

We use ERD’s to show us ways we can join our data. In this case we can join from the primary key of Customer, which is CustomerID, to it’s like value in CustomerOrder.

In this case CustomerOrder.CustomerID is said a foreign key. This is because its a column that represents a set of primary key values from another table.

Identifying primary and foreign keys in a ERD diagram

Many joins you’ll do involve Primary and Foreign Keys. It is a natural way to “link” data together.

SQL JOIN Example

Here is an example joining Customer Orders to their Customers by CustomerID.

select LastName, PhoneNumber, Email, OrderDate from CustomerOrder inner join Customer on CustomerOrder.CustomerID = Customer.CustomerID
/* Answer */
select LastName, PhoneNumber, Email, OrderDate
from CustomerOrder
   inner join Customer on CustomerOrder.CustomerID = Customer.CustomerID

There are several things to notice here:

  • First, notice we use the INNER JOIN clause to indicate how we join from the main table in the FROM clause to another table.
  • Also, the condition after the ON describes which rows to include. In many cases this will be an equality, as we are aiming to match like values between the tables.

The INNER JOIN is used to match CustomerID in both CustomerOrder and Customer. Only rows that have matching Customers are included.

Example showing how a SQL Join combines rows between two tables.

What is Next?

So far we have learned how to use an INNER JOIN to combine two tables together. In the next lesson we’ll see dig deeper at join syntax, learn how to join two or more tables, and then talk about how to use OUTER JOINS.

Note: If you are serious about learning more about joins, why not checkout my highly rated course Join Together Now? It is very affordable and can be taken online.