Professional Documents
Culture Documents
-- CROSS JOIN
-- CROSS JOIN returns cartesian product.
-- Meaning it will match every record from the left table with every record from
the right table hence it will return records from both table.
-- No join condition is required to be specified.
SELECT e.emp_name, d.dept_name
FROM employee e
CROSS JOIN department d;
-- Write a query to fetch the employee name and their corresponding department
name.
-- Also make sure to display the company name and the company location
correspodning to each employee.
-- NATURAL JOIN - SQL will naturally choose the column on which join should happen
based on the column name.
-- Natural join will perform inner join operation if there are columns with same
name in both table. If there are more than 1 column with same name then join will
happen based on all these columns.
-- If there are no columns with same name in both table then it performs cross join
-- If you specify * in select list then it displays the join columns in the
beginning and does not repeat it.
-- No join condition is required to be specified.
SELECT *
FROM employee e
NATURAL JOIN department d;
-- Altering the dept_id column name to see how Natural Join acts when there are no
common column names in both tables.
--alter table department rename column dept_id to department_id
--alter table department rename column department_id to dept_id;
-- SELF JOIN - When you join a table to itself, this is called as SELF Join.
-- There is no keyword like SELF JOIN but we just use the regular JOIN keyword to
make the self join.
-- Write a query to fetch the child name and their age correspodning to their
parent name and parent age.
select child.name as child_name
, child.age as child_age
, parent.name as parent_name
, parent.age as parent_age
from family as child
join family as parent on parent.member_id = child.parent_id;
-- ANSI JOIN - Uses the JOIN clause and mentions join condition under the ON clause
and filter conditions in the WHERE clause.
SELECT e.emp_name, d.dept_name
FROM employee e
JOIN department d ON e.dept_id = d.dept_id
WHERE e.salary > 15000;
-- Non ANSI JOIN - Uses comma to seperate multiple tables and then use WHERE clause
to mention both the join and filter conditions.
SELECT e.emp_name, d.dept_name
FROM employee e
, department d
WHERE e.salary > 15000
AND e.dept_id = d.dept_id;