Friday, May 11, 2012

SQL LEFT JOIN

Hello Friends, Welcome To This Post, Where I would Discuss the beauty of SQL LEFT JOIN Query.

As usual I will be explaining it after an example, lets look at out Tables:

Table1: Customer

CID     Name         Designation

222     Whiskey       Moderator
444     Onty            Member
111     Gaurav         Admin
333     Kumaar       Admin
555     Rishabh       Admin
666     Rose           Admin
888     White         Member
999     Mikey        Member


Table2: Orders

OID    Product        CID
1         Perfume        666
2         Laptop         444
3         Perfume        999
4         Cell Phone    666


Syntax:

SELECT column_name(s)
FROM table_1
LEFT JOIN table_2
ON table_1.column_name = table_2.column_name
ORDER BY column_name

Again, ORDER BY is optional

So, for our Query:

SELECT Customer.Name, Orders.Product
FROM Customer
LEFT JOIN Orders
ON Customer.CID = Orders.CID
ORDER BY Customer.Name

Our Result-set will be:

Name        Products
Gaurav
Kumaar
Mikey        Perfume
Onty          Laptop
Rishabh
Rose         Perfume
Rose        Cell Phone
Whiskey
White

So Did You Notice What Happened? INNER JOIN Returns the records of only the matched cases, but LEFT JOIN returns all the records of the LEFT TABLE(Table 1) and Displays the records of matched cases from the RIGHT TABLE(Table 2).

Thats all for this post, Don't forget to check my next post.

Thank You!

0 comments:

Post a Comment