CS SQL Joins Class XII
CS SQL Joins Class XII
CS SQL Joins Class XII
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.
Syntax
The basic syntax of the CARTESIAN JOIN or the CROSS JOIN is as follows −
SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]
Example
EQUI JOIN
An EQUI JOIN is a type of join that combines tables based on matching values in specified
columns.
Syntax
There are two ways to use equi join in SQL:
WHERE TABLENAME1.COLUMNNAME=TABLENAME2.COLUMNNAME;
OR
In the second method, the JOIN keyword is used to join the tables based on the
condition provided after the ON keyword.
Example
The following tables have been created
1. PRODUCT_LIST
ID Pname
1 Apples
2 Oranges
3 Mangoes
2. PRODUCT_DETAILS
ID Brand Origin
3. BRAND_DETAILS
Brand OfficeAddress
Another Example –
Let’s Consider the two tables given below.
Table name — Student
Select * from Student;
3 Hina 3 Delhi
4 Megha 2 Delhi
6 Gouri 2 Delhi
Table name — Record
Select * from Record;
id class city
9 3 Delhi
10 2 Delhi
12 2 Delhi
1. EQUI JOIN :
Example –
SELECT student.name, student.id, record.class, record.city FROM student, record
WHERE student.city = record.city;
Or
SELECT student.name, student.id, record.class, record.city FROM student
JOIN record ON student.city = record.city;
Output :
name id class city
Hina 3 3 Delhi
Megha 4 3 Delhi
Gouri 6 3 Delhi
Hina 3 2 Delhi
Megha 4 2 Delhi
Gouri 6 2 Delhi
Hina 3 2 Delhi
Megha 4 2 Delhi
Gouri 6 2 Delhi
Syntax:
SELECT *
FROM table_name1, table_name2
WHERE table_name1.column [> | < | >= | <= ] table_name2.column;
Example –
SELECT student.name, record.id, record.city FROM student, record
WHERE Student.id < Record.id ;
Output :
name id city
Hina 9 Delhi
Megha 9 Delhi
Gouri 9 Delhi
Hina 10 Delhi
Megha 10 Delhi
Gouri 10 Delhi
Hina 12 Delhi
Megha 12 Delhi
Gouri 12 Delhi
NATURAL JOIN
We have already learned that an EQUI JOIN performs a JOIN against equality or matching
column(s) values of the associated tables and an equal sign (=) is used as comparison
operator in the where clause to refer equality.
The NATURAL JOIN is a type of EQUI JOIN and is structured in such a way that, columns
with the same name of associated tables will appear once only.
- The associated tables have one or more pairs of identically named columns.
- The columns must be the same data type.
- Don’t use ON clause in a natural join.
Syntax:
SELECT * FROM TABLE1 NATURAL JOIN TABLE2;
Example:
Here is an example of SQL natural join between tow tables:
To get all the unique columns from foods and company tables, the following SQL statement
can be used:
SQL Code:
SELECT * FROM foods NATURAL JOIN company;
Points to remember: