Day 24: UNION and UNION ALL
Introduction:
The
UNIONandUNION ALLoperators are used to combine the result sets of two or moreSELECTstatements. TheUNIONoperator removes duplicate records, whileUNION ALLincludes duplicates.
Key Concepts:
UNION: Combines the result sets of two or more
SELECTstatements and removes duplicates.UNION ALL: Combines the result sets of two or more
SELECTstatements and includes duplicates.Column Matching: The
SELECTstatements must have the same number of columns in the same order, with compatible data types.
SQL Commands and Examples:
Basic UNION:
Combine rows from two
SELECTstatements and remove duplicates.
-- Combine the names of students and teachers without duplicates
SELECT FirstName, LastName FROM Students
UNION
SELECT FirstName, LastName FROM Teachers;
UNION ALL:
Combine rows from two
SELECTstatements and include duplicates.
-- Combine the names of students and teachers including duplicates
SELECT FirstName, LastName FROM Students
UNION ALL
SELECT FirstName, LastName FROM Teachers;
Combining Different Columns:
Ensure the
SELECTstatements have the same number of columns in the same order.
-- Combine student names and course names as a single result set
SELECT FirstName, LastName FROM Students
UNION
SELECT CourseName, '' FROM Courses;
Practice Exercise:
Use the Students and Courses tables.
Create a table named Teachers with columns
TeacherID,FirstName,LastName,CourseID.Write a query to union the names of students and teachers without duplicates.
Write a query to union all the names of students and teachers including duplicates.
Write a query to union the first names of students and course names.
-- Create the Teachers table
CREATE TABLE Teachers (
TeacherID INT PRIMARY KEY,
FirstName VARCHAR(255),
LastName VARCHAR(255),
CourseID INT
);
-- Insert sample data into the Teachers table
INSERT INTO Teachers (TeacherID, FirstName, LastName, CourseID)
VALUES
(1, 'John', 'Doe', 101),
(2, 'Jane', 'Smith', 102);
-- Union the names of students and teachers without duplicates
SELECT FirstName, LastName FROM Students
UNION
SELECT FirstName, LastName FROM Teachers;
-- Union all the names of students and teachers including duplicates
SELECT FirstName, LastName FROM Students
UNION ALL
SELECT FirstName, LastName FROM Teachers;
-- Union the first names of students and course names
SELECT FirstName, '' AS LastName FROM Students
UNION
SELECT CourseName AS FirstName, '' AS LastName FROM Courses;
Understanding the UNION and UNION ALL operators allows you to combine result sets effectively, providing more flexible and comprehensive queries.
0 Comments