Tuesday, June 2, 2015

SQL Joins (INNER JOIN Tutorial)

SQL joins are used when you want to combine rows from more than one table in a database. A JOIN is a means of combining fields from two or more tables by using a common field.

First things first, before I show you an example, I will tell you the most common types SQL JOINs you can have:

INNER JOIN:
This will return all rows when there is at least one match in both tables.
LEFT JOIN: This will return all rows from the left table, and the matched rows from the right table.
RIGHT JOIN:
This will return all rows from the right table, and the matched rows from the left table.
FULL JOIN:
This will return all rows when there is a match in at least one of the tables.

The most common type of all the JOINS is the INNER JOIN or a simple join. This is the example I will be showing you more of today.

Table 1: Customer
IDName
1Walmurt
2Turgat
3Mojulrs
4Kroogers
Table 2: Orders
CustomerIDOrderIDDateAmount
210011-1-2015$100
410021-4-2015$400
210031-6-2015$200
310041-6-2015$100


Now, lets JOIN these two tables with a SQL Select Statement.

Select Customer.ID as CustomerID, Name, OrderID, Date, Amount from Customer
INNER JOIN
Orders on Orders.CustomerID = Customer.ID;



The results to this statement will produce the results below.
CustomerIDNameOrderIDDateAmount
2Turgat10011-1-2015$100
4Kroogers10021-4-2015$400
2Turgat10031-6-2015$200
3Mojulrs10041-6-2015$100

Please note, several operators can be used to join tables, such as =, <, >, <>, <=, >=, BETWEEN, LIKE, and NOT, just to name a few. However, the most common operator is the equal symbol.


If you like this post and want to see more, follow me on my website www.chadcompton.com
Or if you prefer...

No comments:

Post a Comment

Drop me a line.