Sql Standard Joins

When you need to get sensible data out of a well designed database, you will often need to use a JOIN condition.

JOINs will join together two (or more) tables, based on the columns that you select. The two most common types of join are the INNER JOIN and LEFT OUTER JOIN.

An inner join will return rows from the database that match on both tables referenced in the join. A left outer join will return all rows from the first referenced table (the left), and include matching data from the second table.

As a simple example, imagine we had a table containing the details of some Invoices, and a table with details of the Line Items on each invoice.

In a realistic schema we’d have further tables for Customers, Items and so on, this is kept deliberately simple for illustration purposes.


InvoiceID   InvoiceDate   Customer

1           2013-05-01    John Smith

2           2013-05-03    Mike Philpott


LineItemID   InvoiceID   Item       ItemPrice   Quantity

1            1           No6 Bolt   0.54        20

2            1           No7 Screw  0.31        10

With these two very simple tables, we can see the syntax for both types of common join, and also what records would be returned.


SELECT
    InvoiceDate, Customer, Item, ItemPrice, Quantity
FROM
    Invoices
INNER JOIN
    LineItems
ON
    Invoices.InvoiceID = LineItems.InvoiceID

This will return only the two rows for John Smith’s order, Mike Philpott’s will be excluded, as it has no line items


SELECT
    InvoiceDate, Customer, Item, ItemPrice, Quantity
FROM
    Invoices
LEFT OUTER JOIN
    LineItems
ON
    Invoices.InvoiceID = LineItems.InvoiceID

In this case, we will see three rows, two for John Smith, with full items details. The third will show Mike Philpott’s order. It will contain values for InvoiceDate and Customer, but will have NULL in Item, ItemPrice and Quantity, as there are no matching rows in the table that is used.

We can expand the joins to consider further tables, by using additional blocks of JOIN and ON. Be careful that when you do this your joins are ordered correctly, so that the appropriate tables are considered at the right time. If the order is incorrect, an INNER JOIN may be applied to the results of a LEFT OUTER JOIN, when you intended the INNER JOIN to be applied first.

In summary, we should use INNER JOIN when we only want to know about the rows that have matches in the linked table, and the LEFT OUTER JOIN when we want to retain all rows in the first table.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s