Tuesday, March 2, 2010

What is Join and its types in SQL Server

Join:

Joins in SQL Server allows the retrieval of data records from one or more tables having some relation between them. Logical operators can also be used to drill down the number of records to get the desired output from sql join queries.

Types:

1. Inner Join
2. Outer Join
o Left Outer Join
o Right Outer Join
o Full Outer Join
3. Cross Join

I) Inner Join: Inner Join is a default type join of SQL Server. It uses logical operators such as =, <, > to match the records in two tables. Inner Join includes equi join and natural joins.
Natural join query example:
SELECT C.*, P.PRODUCTID, P.PRODUCTNAME FROM CATEGORIES C
INNER JOIN
PRODUCTS P ON P.CATEGORYID = C.CATEGORYID
This natural join query will return all the columns of categories table and prodcutId and productName from products table.
Equi Join: Equi Join returns all the columns from both tables and filters the records satisfying the matching condition specified in Join “ON” statement of sql inner join query.

SQL Inner Equi Join Example:

USE NORTHWIND
SELECT * FROM CATEGORIES C INNER JOIN
PRODUCTS P ON P.CATEGORYID = C.CATEGORYID


Result will display the following columns:
CategoryID, CategoryName, Description, Picture, ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued

Above equi join sql query will display the categoryId two times in a row because both the tables have categoryId column. You can convert the result into natural join by elimination the identical columns and unnecessary columns.
Diffrence between natural join and equi join
natural join is basically a form of equi join where one of the join fields is projected out. i.e. it avoids repeatition of the join column.

II) Outer Join: Outer Join has further 3 sub categories as left, right and full. Outer Join uses these category names as keywords that can be specified in the FROM clause.
o Left Outer Join: Left Outer Join returns all the rows from the table specified first in the Left Outer Join Clause. If in the left table any row has no matching record in the right side table then that row returns null column values for that particular tuple.


o Right Outer Join: Right Outer Join is exactly the reverse method of Left Outer Join. It returns all the rows from right table and returns null values for the rows having no match in the left joined table.



o Full Outer Join: Full outer join returns all the rows from both left and right joined tables. If there is any match missing from the left table then it returns null column values for left side table and if there is any match missing from right table then it returns null value columns for the right side table.


III) Cross Join: Cross join works as a Cartesian product of rows for both left and right table. It combined each row of left table with all the rows of right table.

1 comment:

 
Locations of visitors to this page