Combining Data from Multiple Tables in SQL 🔗📊

Combining Data from Multiple Tables in SQL 🔗📊
SQL allows combining data from multiple tables using JOINs, UNIONs, and Subqueries.
1️⃣ Using JOINs (Combining Related Data)
JOINs combine records based on a common foreign key.
✅ Example: Students & Courses
SELECT students.name, courses.course_name
FROM students
INNER JOIN enrollments ON students.student_id = enrollments.student_id
INNER JOIN courses ON enrollments.course_id = courses.course_id;
🔹 Why use JOINs?
Useful when data is spread across multiple tables (e.g., student details in one table, course details in another).
Retrieves related data efficiently.
2️⃣ Using UNION (Stacking Data from Similar Tables)
UNION combines the results of two queries with the same structure.
✅ Example: Merging Two Student Tables
SELECT name, age FROM students_2024
UNION
SELECT name, age FROM students_2023;
🔹 Why use UNION?
Combines results from different tables.
Removes duplicates by default.
Use UNION ALL to keep duplicates.
3️⃣ Using Subqueries (Nested Queries for Lookups)
A Subquery (inner query) is used inside another SQL statement.
✅ Example: Find Students Enrolled in a Course
SELECT name
FROM students
WHERE student_id IN (
SELECT student_id FROM enrollments WHERE course_id = 101
);
🔹 Why use Subqueries?
Used when filtering based on another table.
Can replace some JOIN operations.
🎯 Summary
Method Use Case
JOINs Combine related data (matching rows) from multiple tables.
UNION Merge results from similar tables.
Subqueries Filter or retrieve data based on another query.
Date: 2025-03-29 00:00:00.000000