sql join
sql join
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID"
column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records
from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
We will join the Products table with the Categories table, by using the CategoryID field from
both tables:
SELECT ProductID, ProductName, CategoryName
FROM Products
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID;
Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Tip: FULL OUTER JOIN and FULL JOIN are the same.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
Every SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
In the below query we will select NAME and Age from Student table and COURSE_ID from
StudentCourse table. In the output you can see that each row of the table Student is joined
with every row of the table StudentCourse. The total rows in the result-set = 4 * 4 = 16.
SELECT Student.NAME, Student.AGE, StudentCourse.COURSE_ID
FROM Student
CROSS JOIN StudentCourse;