Database - Lec4 - Joins and Subqueries in SQL
Database - Lec4 - Joins and Subqueries in SQL
SQL
Module 1. Introduction to Database and Relational Models
SQL joins
SQL joins combine rows from two or more tables based on a related column.
Types of Joins:
1. INNER JOIN
2. LEFT (OUTER) JOIN
3. RIGHT (OUTER) JOIN
4. FULL (OUTER) JOIN
5. CROSS JOIN
Inner Join
The INNER JOIN selects records that have matching values in both tables.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Inner join
SELECT customers.name, orders.product
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Left join
SELECT customers.name, orders.product
FROM customers
LEFT JOIN orders
ON customers.customer_id = orders.customer_id;
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Right join
SELECT customers.name, orders.product
FROM customers
RIGHT JOIN orders
ON customers.customer_id = orders.customer_id;
SELECT column_name(s)
FROM table1
FULL JOIN table2
ON table1.column_name = table2.column_name;
Cross Join
The CROSS JOIN returns the Cartesian product of two tables, i.e., it pairs every
row from the first table with every row from the second table.
SELECT column_name(s)
FROM table1
CROSS JOIN table2;
Subqueries
A subquery (also known as an inner query or nested query) is a query embedded
inside another query.
1. In WHERE clause
SELECT name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);
2. In FROM clause
SELECT AVG(order_count)
FROM (SELECT COUNT(*) as order_count FROM orders GROUP BY
customer_id);
WITH clause
The WITH clause in SQL, also known as Common Table Expressions (CTE),
allows you to define temporary result sets that can be referred to within a SELECT,
INSERT, UPDATE, or DELETE statement.
It helps to make complex queries more readable and easier to maintain by
breaking them into smaller, manageable parts.
employee_id name manager_id
WITH clause 1 Alice NULL