Learn MySQL for Developing Web Application

Learn to build web applications with PHP and MySQL, Start your own blog, e-commerce site. In this tutorial you will learn queries of MySQL and MySQLi.

SQL JOINS


A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

Why SQL JOIN is used?

If you want to access more than one table through a select statement.

If you want to combine two or more table then SQL JOIN statement is used .it combines rows of that tables in one table and one can retrieve the information by a SELECT statement.

The joining of two or more tables is based on common field between them.

SQL INNER JOIN also known as simple join is the most common type of join.


Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

  • (INNER) JOIN: Returns records that have matching values in both tables
  • LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
  • RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
  • FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
  • CROSS JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement

INNER JOIN

The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax

SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;

LEFT JOIN

The SQL left join returns all the values from the left table and it also includes matching values from right table, if there are no matching join value it returns NULL.

LEFT JOIN Syntax

SELECT table1.column1, table2.column2....
FROM table1
LEFTJOIN table2
ON table1.column_field = table2.column_field;

RIGHT JOIN

The SQL right join returns all the values from the rows of right table. It also includes the matched values from left table but if there is no matching in both tables, it returns NULL.

RIGHT JOIN Syntax

SELECT table1.column1, table2.column2.....
FROM table1
RIGHT JOIN table2
ON table1.column_field = table2.column_field;

FULL OUTER JOIN

The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or right (table2) table records.

FULL OUTER JOIN Syntax

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

CROSS JOIN

When each row of first table is combined with each row from the second table, known as Cartesian join or cross join. In general words we can say that SQL CROSS JOIN returns the Cartesian product of the sets of rows from the joined table.

We can specify a CROSS JOIN in two ways:

  1. Using the JOIN syntax.
  2. the table in the FROM clause without using a WHERE clause.

CROSS JOIN Syntax

SELECT * FROM [TABLE1] CROSS JOIN [TABLE2]
OR
SELECT * FROM [ TABLE1] , [TABLE2]