Database Management System (DBMS) / SQL(STRUCTURED QUERY LANGUAGE)

SET operations in SQL (UNION/INTERSECT/MINUS)

Set operations combine the results of two or more SELECT queries into a single result set β€” just like in mathematics.

πŸ“Œ Rules:

  • Number of columns and their data types must match

  • Column order matters

  • By default, they remove duplicates


🀯 Base Setup for further examples:

-- 1. Create the first table
CREATE TABLE science_students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50)
);

-- 2. Create the second table
CREATE TABLE math_students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50)
);

-- 3. Insert sample data
INSERT INTO science_students (name) VALUES
('Anya'),
('Ravi'),
('Sara');

INSERT INTO math_students (name) VALUES
('Ravi'),
('Tina'),
('Meena');

πŸ”— UNION – Combine & Remove Duplicates

Returns all unique rows from both queries.

πŸ“Œ Example:

-- UNION query to get unique student names from both tables
SELECT name FROM science_students
UNION
SELECT name FROM math_students;

βœ”οΈ Combines names from both tables

βœ”οΈ Removes any duplicate names


βž• UNION ALL – Combine All (Including Duplicates)

Same as UNION but keeps duplicate rows

πŸ“Œ Example:

-- Use UNION ALL to combine names (including duplicates)
SELECT name FROM science_students
UNION ALL
SELECT name FROM math_students;

βœ”οΈ Faster than UNION

βœ”οΈ Includes repeated names


🎯 INTERSECT – Common Rows Only

Returns only the rows that exist in both queries.

πŸ“Œ Example:

-- βœ… INTERSECT equivalent using INNER JOIN
SELECT s.name
FROM science_students s
INNER JOIN math_students m ON s.name = m.name;
-- βœ… INTERSECT equivalent using IN
SELECT name
FROM science_students
WHERE name IN (SELECT name FROM math_students);

βœ”οΈ Shows students enrolled in both subjects

❗ Not supported in MySQL (can be emulated using INNER JOIN or IN)


βž– MINUS (or EXCEPT) – Rows in First, Not in Second

Returns rows from the first query that do not appear in the second.

πŸ“Œ Example:

-- βœ… MINUS Equivalent using LEFT JOIN
SELECT s.name
FROM science_students s
LEFT JOIN math_students m ON s.name = m.name
WHERE m.name IS NULL;
-- βœ… MINUS Equivalent using NOT IN
SELECT name
FROM science_students
WHERE name NOT IN (SELECT name FROM math_students);

βœ”οΈ Shows students only in science, not in math

βœ… MINUS β†’ Oracle

βœ… EXCEPT β†’ PostgreSQL & SQL Server

❌ Not supported in MySQL directly


βœ… Summary Table

Set Operation

Description

Removes Duplicates

MySQL Support

πŸ”— UNION

Combines results, removes duplicates

βœ… Yes

βœ… Yes

βž• UNION ALL

Combines results, keeps duplicates

❌ No

βœ… Yes

🎯 INTERSECT

Common rows in both queries

βœ… Yes

❌ No (use JOIN)

βž– MINUS/EXCEPT

Rows in 1st query but not in 2nd

βœ… Yes

❌ No (use LEFT JOIN)