SQL Joins

Joins are used to combine rows from two or more tables based on related columns between them. Joins allow you to retrieve data from multiple tables simultaneously, enabling you to create complex queries that fetch data from different sources.

There are different types of joins in SQL, including:
  1. INNER JOIN
Returns only the rows that have matching values in both tables based on the specified join condition. It discards non-matching rows from both tables.



Example:

        create table t1(x int); insert into t1 values(1); insert into t1 values(1); insert into t1 values(0); create table t2(y int); insert into t2 values(0); insert into t2 values(1); insert into t2 values(1);

        select * from t1 inner join t2 on t1.x = t2.y

Output:


2. LEFT JOIN (or) LEFT OUTER JOIN

Returns all the rows from the left (or first) table and the matching rows from the right (or second) table. If there is no match, NULL values are returned for the columns of the right table.


Example:

select * from t1 left join t2 on t1.x = t2.y



3. RIGHT JOIN (or) RIGHT OUTER JOIN

Returns all the rows from the right (or second) table and the matching rows from the left (or first) table. If there is no match, NULL values are returned for the columns of the left table.


Example:

select * from t1 left join t2 on t1.x = t2.y

Solve the output in the comment section.

4. FULL OUTER JOIN

Returns all the rows from both tables, regardless of whether there is a match or not. Non-matching rows are filled with NULL values.


Example:

select * from t1 full outer join t2 on t1.x = t2.y

Solve the output in the comment section.


5. CROSS JOIN

Returns the Cartesian product of the two tables, i.e., all possible combinations of rows from both tables. It doesn't require a join condition.

Example:

select * from t1 cross join t2



Comments

Popular posts from this blog

Machine Learning Foundations - Deep Learning Summary - Quiz

Machine Learning Foundations - Recommender System - Quiz

Machine Learning Foundation - Deep Learning - Programming Assignment