Lesson 10 of 30Article12 min
UNION & UNION ALL
UNION stacks the results of two SELECT queries. Columns must match in count and compatible types. UNION removes duplicate rows.
UNION — combine result sets (unique rows)
UNION stacks the results of two SELECT queries. Columns must match in count and compatible types. UNION removes duplicate rows.
Real-life example: UNION is merging two attendance sheets from morning and afternoon sessions into one master list without duplicate names.
Combine Delhi and Mumbai student names
SELECT full_name, city FROM students WHERE city = 'Delhi'
UNION
SELECT full_name, city FROM students WHERE city = 'Mumbai';UNION ALL — keep duplicates
UNION ALL is faster when you know duplicates are fine or impossible. It keeps every row from both queries.
Real-life example: UNION ALL is photocopying both lists and stapling them — if a name appears twice, it stays twice.
All enrollments tagged by source query
SELECT student_id, 'Math track' AS track FROM enrollments WHERE course_id = 1
UNION ALL
SELECT student_id, 'Science track' AS track FROM enrollments WHERE course_id = 2;