🧠 Introduction
Modern applications often rely on multiple related tables
to store data efficiently. To query across them, SQL provides two powerful
tools:
This chapter explores how to use both tools to retrieve
meaningful, cross-referenced information from relational databases.
🔗 1. Joins in SQL
A join lets you combine data from two or more tables
based on a related column, typically a foreign key.
🔹 Types of Joins
|
Join Type |
Description |
|
INNER JOIN |
Returns matching rows
from both tables |
|
LEFT JOIN |
Returns all
rows from the left table + matched rows |
|
RIGHT JOIN |
Returns all rows from
the right + matched rows |
|
FULL OUTER JOIN |
Returns all
rows from both tables (matched/unmatched) |
|
SELF JOIN |
Joins a table with
itself |
✅ Example Database Structure
Customers
|
CustomerID |
Name |
Country |
|
1 |
Alice |
USA |
|
2 |
Bob |
UK |
|
3 |
Charlie |
India |
Orders
|
OrderID |
CustomerID |
Product |
Amount |
|
101 |
1 |
Laptop |
799 |
|
102 |
2 |
Smartphone |
499 |
|
103 |
1 |
Headphones |
99 |
🔍 2. INNER JOIN
Returns rows only where there is a match between
tables.
sql
SELECT
Customers.Name, Orders.Product, Orders.Amount
FROM
Customers
INNER
JOIN Orders
ON
Customers.CustomerID = Orders.CustomerID;
📋 Output
|
Name |
Product |
Amount |
|
Alice |
Laptop |
799 |
|
Bob |
Smartphone |
499 |
|
Alice |
Headphones |
99 |
⬅️ 3. LEFT JOIN (or LEFT OUTER
JOIN)
Returns all rows from the left table and matched rows
from the right. Unmatched rows get NULL.
sql
SELECT
Customers.Name, Orders.Product
FROM
Customers
LEFT
JOIN Orders
ON
Customers.CustomerID = Orders.CustomerID;
📋 Output
|
Name |
Product |
|
Alice |
Laptop |
|
Alice |
Headphones |
|
Bob |
Smartphone |
|
Charlie |
NULL |
➡️ 4. RIGHT JOIN
Like LEFT JOIN, but includes all rows from the right
table.
sql
SELECT
Orders.Product, Customers.Name
FROM
Orders
RIGHT
JOIN Customers
ON
Orders.CustomerID = Customers.CustomerID;
🔄 5. FULL OUTER JOIN
Returns all records from both tables. If no match
exists, returns NULL.
sql
SELECT
Customers.Name, Orders.Product
FROM
Customers
FULL
OUTER JOIN Orders
ON
Customers.CustomerID = Orders.CustomerID;
Note: Not supported in some DBMS like MySQL (use UNION
instead).
♻️ 6. SELF JOIN
Joins a table to itself. Useful for hierarchical or
comparative data.
✅ Example: Employees Table
|
EmpID |
Name |
ManagerID |
|
1 |
Alice |
NULL |
|
2 |
Bob |
1 |
|
3 |
Carol |
1 |
sql
SELECT
E.Name AS Employee, M.Name AS Manager
FROM
Employees E
JOIN
Employees M
ON
E.ManagerID = M.EmpID;
🔄 7. Subqueries in SQL
A subquery is a SQL query nested inside another
query.
📚 Types of Subqueries
|
Subquery Type |
Description |
|
Scalar |
Returns a single value |
|
Row |
Returns one
row |
|
Column (Single
Column) |
Returns one column |
|
Table (Multiple Columns) |
Returns a
full result set |
|
Correlated |
Depends on outer query
per row |
🧩 8. Subquery in WHERE
Clause
sql
SELECT
Name FROM Customers
WHERE
CustomerID IN (
SELECT CustomerID FROM Orders WHERE Amount
> 500
);
Returns customers who placed orders above 500.
🧮 9. Subquery in SELECT
Clause
sql
SELECT
Name,
(SELECT COUNT(*) FROM Orders WHERE
Orders.CustomerID = Customers.CustomerID) AS TotalOrders
FROM
Customers;
🔃 10. Correlated
Subqueries
These refer to outer query values for each row.
sql
SELECT
Name FROM Customers C
WHERE
EXISTS (
SELECT * FROM Orders O WHERE O.CustomerID =
C.CustomerID
);
🔀 11. Subquery vs JOIN –
When to Use
|
Feature |
JOIN |
Subquery |
|
Performance |
Generally faster |
Can be slower in
nested queries |
|
Use Case |
Combine
related data |
Filter,
calculate, or test |
|
Reusability |
Easier in reporting
queries |
Flexible for
conditional logic |
|
Readability |
More readable
with fewer joins |
Better for
scalar conditions |
🧪 Practice Exercise
sql
--
Create tables
CREATE
TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50)
);
CREATE
TABLE Employees (
EmpID INT,
Name VARCHAR(50),
Salary INT,
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES
Departments(DeptID)
);
--
Insert sample data
INSERT
INTO Departments VALUES (1, 'HR'), (2, 'Engineering');
INSERT
INTO Employees VALUES
(1,
'Alice', 60000, 2),
(2,
'Bob', 55000, 2),
(3,
'Carol', 50000, 1);
--
JOIN Example: Employees and Departments
SELECT
E.Name, D.DeptName
FROM
Employees E
JOIN
Departments D ON E.DeptID = D.DeptID;
--
Subquery: Highest salary
SELECT
Name FROM Employees
WHERE
Salary = (SELECT MAX(Salary) FROM Employees);
📚 Summary Table
|
Concept |
Key Points |
|
INNER JOIN |
Returns matched rows
only |
|
LEFT JOIN |
All rows from
left + matched from right |
|
RIGHT JOIN |
All rows from right +
matched from left |
|
FULL JOIN |
All rows from
both sides |
|
SELF JOIN |
Join a table with
itself |
|
Subqueries |
Use queries
inside queries for flexibility |
|
Correlated Subquery |
Depends on each outer
row |
A: SQL is a query language, not a general-purpose programming language. It’s used to communicate with databases.
A: SQL is a language. MySQL is a database management system (DBMS) that uses SQL.
A: Yes. Libraries like JDBC (Java) or sqlite3/sqlalchemy (Python) allow SQL integration.
A: A JOIN combines rows from two or more tables based on a related column between them.
A: The process of structuring data to reduce redundancy and improve integrity.
A: WHERE filters rows before aggregation. HAVING filters groups after aggregation.
A: SQL keywords are case-insensitive, but string comparisons may be case-sensitive, depending on the DBMS.
A: SQL can handle moderate volumes. For large-scale datasets, use SQL-based engines like Presto, Hive, or BigQuery.
A: A view is a virtual table based on the result of a query. It doesn't store data itself.
A: Use parameterized queries or prepared statements instead of dynamic SQL strings
Tutorials are for educational purposes only, with no guarantees of comprehensiveness or error-free content; TuteeHUB disclaims liability for outcomes from reliance on the materials, recommending verification with official sources for critical applications.
Kindly log in to use this feature. We’ll take you to the login page automatically.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Comments(0)