16-SQL (Joins)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

16- SQL

(JOINS)
Inner Join is used to get the common records between two tables.
Inner Join selects the records where the data between 2 columns of different
tables match.

Note that in the City table there is a city “Noida” that has an id of “4” which
doesn’t seem to exist in the City column of the Student table. So when we will
match these two columns using ON clause with Inner Join, there won’t be any
Student record in the result-set with Noida city in it.

 We can swipe the positions of matching columns in the “ON” Matching


Clause. It wouldn’t affect the result-set and as well as the order of the
records in the result-set.
We have inserted following records in the table mahnoor_family_parents:

Table1: “Mahnoor_Family_Kids” Table2: “Mahnoor_Family_Parents”

To view the Kids records along with their parents’ names, we will use INNER JOIN clause.

Instead of using table names, we can use “Alias”. Alias names are temporary names of tables.
Their advantage is that they can be used as short names of tables. Using Alias helps to shorten
our SQL commands (especially if table names are long) and thus increase their readability,
which is very useful with large and complex SQL commands. We can define and use them in the
following way:
You can see from above results that there are two useless columns being shown, namely,
“parents” and “id”. To remove these columns from the result, we will omit asterisk (*) and will
specify the column names with the SELECT command/statement.

This is how we can use INNER JOIN to view data of two tables together.
We can also use WHERE clause with this SELECT command in the following way:

We can also use ORDER BY with this SQL command.

We can write INNER JOIN as simply JOIN in our SQL command.

It should be clear by now that using Inner Join between two tables gives us records that are
common between the two tables.
Left Join will show all matching records between the two tables and as well as all of the non-
matching records from table1. In other words, Left Join will show all records from table1
including the matching records from table2.

If there are no common records between table1 and table2, then no record will be shown from
table2. Only table1 records will be shown (all of them).

However, if Inner Join was used, it would have shown only the records that are common
between the two tables. In case of no common record between the two tables, no record
would have been shown in the results.

 Left table is placed with FROM clause and Right table is placed with LEFT JOIN clause.
 Make sure you place the correct table name at the correct place in the SQL Query.
 We can swipe the positions of matching columns in the “ON” Matching Clause. It
wouldn’t affect the result-set and as well as the order of the results (records).

The rows having no matching in the result table will have NULL values.

Left Join will show all matching records between the two tables and as well as all of the non-
matching records from table2. In other words, Left Join will show all records from table2
including the matching records from table1.

If there are no common records between table1 and table2, then no record will be shown from
table1. Only table2 records will be shown (all of them).

However, if Inner Join was used, it would have shown only the records that are common
between the two tables. In case of no common record between the two tables, no record
would have been shown in the results.
 Left table is placed with FROM keyword and Right table is placed with LEFT JOIN
keyword.
 Make sure you place the correct table name at the correct place in the SQL Query.
 We can swipe the positions of matching columns in the “ON” Matching Clause. It
wouldn’t affect the result-set and as well as the sequence of the results (records).

The rows having no matching in the result table will have NULL values.

There are quite a number of MySQL software options shown in the LEFT JOIN – RIGHT JOIN
lecture video.

The FULL JOIN keyword returns all records where there is a match between left (table1) and
right (table2) table records and as well as all of the non-matching records from table1 and
table2. In other words, FULL JOIN returns all records from table1 and table2 including the
matching records from the two tables.
The difference with FULL JOIN is that it returns all records from both tables whether the other
table matches or not. So, if there are rows in table1 that do not have matches in table2, or if
there are rows in table2 that do not have matches in table1, those rows will be listed as well.
FULL JOIN can potentially return very large result-set.

MySQL doesn't offer syntax for a FULL JOIN, but you can implement one using the UNION of a
Left Join and a Right Join.

Syntax of FULL JOIN not supported in MySQL:

The above query can also be written using a combination of LEFT JOIN, RIGHT JOIN, and UNION
as shown below. The above query and the below query will provide the same output with the
same sequence of results/records.

The UNION operator is used to combine the result-sets of two or more SELECT statements. The
UNION operator selects only distinct values by default, so the matching records from the above
two SELECT statements will not be duplicated in the result-set.

Important Notes regarding UNION:


 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 according to
their data types.
 The column names in the result-set are usually equal to the column names in the first
SELECT statement.

Links:
Google Search: SQL Union
https://www.w3schools.com/sql/sql_union.asp
Google Search: Union in SQL with left and right join
https://www.geeksforgeeks.org/sql-full-outer-join-using-left-and-right-outer-join-and-union-
clause/
The following link found from the above google search shows an interesting way of combining
two or more result-sets (or tables) using UNION and then using the combined result-set as a
table in the query:
https://stackoverflow.com/questions/1440808/mysql-union-of-a-left-join-with-a-right-join

Note:

 Left Join, Right Join, and Full Join are called Outer Joins.
 The keyword LEFT JOIN can be written as LEFT OUTER JOIN.
 The keyword RIGHT JOIN can be written as RIGHT OUTER JOIN.
 MySQL doesn’t support FULL JOIN syntax. But for other SQL database
softwares, the keyword FULL JOIN can be written as FULL OUTER JOIN.
 Queries with inner or outer joins give the correct sequence of records in
the result-set only if the matching columns are foreign key and primary key
or both are primary keys.
A cross join is a type of join that returns the Cartesian product of rows from the
tables in the join. In other words, it combines each row from the first table with
each row from the second table. So basically, the CROSS JOIN query in SQL is used
to generate all possible combinations of records in two tables.
 Make sure you place the correct table name at the correct place in the SQL Query in
order to get the desired/required result-set.

For example, you have two columns: color and size, and you need a result set to
display all the possible paired combinations of those—that's where the CROSS
JOIN will come in handy.

Another CROSS JOIN example with some important code options:


https://www.sqlshack.com/sql-cross-join-with-examples/
Another CROSS JOIN example, CROSS JOIN of three tables, Using CROSS JOIN with
the same table (i.e. Self-Join) to generate a useful report:
https://www.devart.com/dbforge/sql/sqlcomplete/sql-cross-
join.html#:~:text=When%20to%20use%20the%20CROSS,JOIN%20will%20come
%20in%20handy.

Another CROSS JOIN example:

Another CROSS JOIN example (CROSS JOIN of three tables):


An SQL Query Similar to CROSS JOIN:

We can implement CROSS JOIN using comma separation between two or more
tables as shown above. The above two queries display the same result-set with
the same sequence of records in the result set.
“SELF JOIN” is not a keyword in SQL, instead it is a theoretical concept in SQL in
which you join a table with itself to generate useful reports. While most JOINs link
two or more tables with each other to present their data together, a SELF JOIN
links a table to itself. This is usually done by joining a table to itself just once
within a SQL query, but it is possible to do so multiple times within the same
query.
The SQL SELF JOIN is a concept in which you join a table to itself as if the table
were two tables or more than two (temporarily renaming the tables in the SQL
statement using SQL Alias) using where clause, inner join, left join, right join, full
join, cross join, etc. However, to perform a SELF JOIN in SQL, WHERE Clause, LEFT
JOIN and INNER JOIN are usually used (and in some cases CROSS JOIN as well).
Self-Join is mainly used to query hierarchical data within a table (hierarchical data
is a data structure where items are linked to each other in parent-child
relationships) or compare rows within the same table in order to generate useful
result-sets.
Important Links to Study Self-Join with examples:
The following are links from the Google Search: Self Join in SQL
https://www.devart.com/dbforge/sql/sqlcomplete/self-join-in-sql-server.html
https://www.w3schools.com/sql/sql_join_self.asp
https://learnsql.com/blog/what-is-self-join-sql/
https://www.tutorialspoint.com/sql/sql-self-joins.htm
https://www.sqlservertutorial.net/sql-server-basics/sql-server-self-join/
Note: Hierarchical data is a structure in which the data is stored as records which
are connected to one another through links (i.e. Foreign key – Primary key Links).
Hierarchical data is stored in a parent-child relationship, with each record linked
to one or more other records (i.e. a parent record being linked to one or more
child records).
JOINING MULTIPLE TABLES
1. INNER JOIN
Example Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name
INNER JOIN table3
ON table1.column_name = table3.column_name;
Explanation: The above query shows inner join between three tables. The inner
join first occurs between table1-table2. Let’s call the resulting result-set from the
inner join of table1-table2  tableX. So the next inner join occurs between
tableX-table3. We can expand this query to even more tables.
Example (joining three tables):

Another Example Syntax:


SELECT columns
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name
INNER JOIN table3
ON table2.column_name = table3.column_name
INNER JOIN table4
ON table3.column_name = table4.column_name;
Explanation: The above query shows inner join between four tables. The inner
join first occurs between table1-table2. Let’s call the resulting result-set from the
inner join of table1-table2  tableX. The next inner join occurs between tableX-
table3. Let’s call the resulting result-set from the inner join of table1-tableX 
tableZ. The final inner join occurs between tableZ-table4. We can expand this
query to even more tables.

2. LEFT JOIN
Example Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name
LEFT JOIN table3
ON table1.column_name = table3.column_name;
Explanation: The above query shows left join between three tables. The left join
first occurs between table1-table2 with the resulting result-set being tableX. So
the next left join occurs between tableX-table3. We can expand this query to even
more tables.
Another Example Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name
LEFT JOIN table3
ON table2.column_name = table3.column_name
LEFT JOIN table4
ON table3.column_name = table4.column_name;
Explanation: The above query shows left join between four tables. The left join
first occurs between table1-table2 with the resulting result-set being tableX. The
next left join occurs between tableX-table3 with the resulting result-set being
tableZ. The final left join occurs between tableZ-table4. We can expand this query
to even more tables.

3. RIGHT JOIN
Example Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name
RIGHT JOIN table3
ON table1.column_name = table3.column_name;
Explanation: The above query shows right join between three tables. The right
join first occurs between table1-table2 with the resulting result-set being tableX.
So the next right join occurs between tableX-table3. We can expand this query to
even more tables.
Important Note: If the number of columns of
Another Example Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name
RIGHT JOIN table3
ON table2.column_name = table3.column_name
RIGHT JOIN table4
ON table3.column_name = table4.column_name;
Explanation: The above query shows right join between four tables. The right join
first occurs between table1-table2 with the resulting result-set being tableX. The
next right join occurs between tableX-table3 with the resulting result-set being
tableZ. The final right join occurs between tableZ-table4. We can expand this
query to even more tables.
4. FULL JOIN
Example Syntax:
SELECT columns
FROM table1
FULL JOIN table2
ON table1.column_name = table2.column_name
FULL JOIN table3
ON table1.column_name = table3.column_name;
Explanation: The above query shows full join between three tables. The full join
first occurs between table1-table2 with the resulting result-set being tableX. So
the next full join occurs between tableX-table3. We can expand this query to even
more tables. But this syntax is not supported in MySQL.
Implementing the above FULL JOIN query using the UNION of LEFT and RIGHT
JOINs:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name
LEFT JOIN table3
ON table1.column_name = table3.column_name
UNION
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name
RIGHT JOIN table3
ON table1.column_name = table3.column_name;
Another Example Syntax:
SELECT columns
FROM table1
FULL JOIN table2
ON table1.column_name = table2.column_name
FULL JOIN table3
ON table2.column_name = table3.column_name
FULL JOIN table4
ON table3.column_name = table4.column_name;
Explanation: The above query shows full join between four tables. The full join
first occurs between table1-table2 with the resulting result-set being tableX. The
next full join occurs between tableX-table3 with the resulting result-set being
tableZ. The final full join occurs between tableZ-table4. We can expand this query
to even more tables. But this syntax is not supported in MySQL.
Using UNION, LEFT and RIGHT JOIN to implement the above FULL JOIN query:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name
LEFT JOIN table3
ON table2.column_name = table3.column_name
LEFT JOIN table4
ON table3.column_name = table4.column_name
UNION
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name
RIGHT JOIN table3
ON table2.column_name = table3.column_name
RIGHT JOIN table4
ON table3.column_name = table4.column_name;
5. CROSS JOIN
The CROSS JOIN query in SQL is used to generate all combinations of records in
two tables. In SQL, CROSS JOINs are used to combine each row of one table with
each row of another table, and return the Cartesian product of the sets of rows
from the tables that are joined.
Example Syntax:
SELECT columns
FROM table1
CROSS JOIN table2
CROSS JOIN table3
CROSS JOIN table4;
Explanation: The above query shows Cross Join between four tables. The above
query generates all possible combinations of records from the given four tables in
the query. The cross join first occurs between table1-table2, then tableX-table3,
and finally between tableZ-table4. We can expand this query to even more tables.
NUBMER OF COMBINATIONS=Number of rows∈table 1 × Number of rows∈table 2 × Number of rows∈table 3
.

NOTES:
Example of a Cartesian Product: if A = {1,2}, B = {x,y,z} and C = {6,7,8,9} then the
Cartesian Product of A, B and C is:
A x B = {(1, x), (1, y), (1, z), (2, x), (2, y), (2, z)}
A x B x C = {(1, x, 6), (1, y, 6), (1, z, 6), (2, x, 6), (2, y, 6), (2, z, 6),
(1, x, 7), (1, y, 7), (1, z, 7), (2, x, 7), (2, y, 7), (2, z, 7),
(1, x, 8), (1, y, 8), (1, z, 8), (2, x, 8), (2, y, 8), (2, z, 8),
(1, x, 9), (1, y, 9), (1, z, 9), (2, x, 9), (2, y, 9), (2, z, 9)}
Where (1, 2) are tableA rows, (x, y, z) are tableB rows and (6, 7, 8, 9) are tableC
rows. Number of Combinations = 2 x 3 x 4 = 24.
6. SELF JOIN
Suppose we have a staff_manager table with columns: staff_id, staff_name, city,
manager_id, and manager_name. We want to get a result-set that shows the staff
members that come from the same city and have the same manager. For this
purpose we will apply Self Join on the table using WHERE Clause and INNER JOIN.
Example Syntax of SELF-JOIN using WHERE Clause:
SELECT A.staff_id, A.staff_name, B.staff_name, A.city, A.manager_name
FROM staff_manager A, staff_manager B
WHERE A.staff_id <> B.staff_id
AND A.city = B.city
AND A.manager_id = B.manager_id
ORDER BY A.city, A.staff_id;
The same query can be performed by joining/linking the table with itself
multiple times:
SELECT A.staff_id, A.staff_name, B.staff_name, A.city, A.manager_name
FROM staff_manager A, staff_manager B, staff_manager C
WHERE (A.staff_id <> B.staff_id) and (A.staff_id <> C.staff_id)
AND A.city = B.city
AND A.manager_id = C.manager_id
ORDER BY A.city, A.staff_id;
//OR//
SELECT A.staff_id, A.staff_name, B.staff_name, A.city, A.manager_name
FROM staff_manager A, staff_manager B, staff_manager C
WHERE (A.staff_id <> B.staff_id) and (B.staff_id <> C.staff_id)
AND A.city = B.city
AND B.manager_id = C.manager_id
ORDER BY A.city, A.staff_id;

All of the three queries above yield the same result-set with the same sequence
of records in the result-set.
Notes regarding Self-Join (linking a table with itself) using WHERE clause:
 Linking a table with itself is when we compare two instances of the table
together in the WHERE clause.
 We can link a table with itself multiple times by comparing multiple
instances of the table together in the WHERE clause.

Implementing the above queries using INNER JOIN


Example Syntax of SELF-JOIN using INNER JOIN:

The same query can be performed by joining the table with itself multiple times:

//OR//

All of the six queries above yield the same result-set with the same sequence of
records in the result-set.
The following table was created to query the above problem.
Note: With the statement “ORDER BY A.city, A.staff_id”, the first priority is to
order the records according to the city name, however, where city names are
same, the records will be ordered according to the staff id.

You might also like