DataBolt

All Lessons

Introduction to SQL
SQL Lesson 1: Your Sample Database
SQL Lesson 2: SELECT β€” Reading data
SQL Lesson 3: WHERE β€” Filtering rows
SQL Lesson 4: AND, OR, NOT
SQL Lesson 5: BETWEEN, IN, LIKE
SQL Lesson 6: NULL β€” The Mystery Value
SQL Lesson 7: ORDER BY
SQL Lesson 8: LIMIT & OFFSET
SQL Lesson 9: Aggregate Functions
SQL Lesson 10: GROUP BY
SQL Lesson 11: HAVING
SQL Lesson 12: INNER JOINs
SQL Lesson 13: LEFT JOINs
SQL Lesson 14: RIGHT JOINs
SQL Lesson 15: SELF JOINs
SQL Lesson 16: UNION JOINs
SQL Lesson 17: Joining Multiple Tables
SQL Lesson 18: Subqueries
SQL Lesson 19: CTEs (WITH)
SQL Lesson 20: CASE Statements
SQL Lesson 21: Window Functions
SQL Lesson 22: String Functions
SQL Lesson 23: Date & Time Functions
SQL Lesson 24: INSERT, UPDATE, DELETE
SQL Lesson 25: CREATE TABLE & DDL
SQL Lesson 26: Indexes & Performance
SQL Lesson 27: Transactions & ACID
SQL Lesson 28: SQL Execution Order
SQL Lesson 29: 50 Practice Problems

CHAPTER 17

UNION SELECT

Combining results from multiple queries into a single result set.

IN THIS CHAPTER

  • UNION is used to combine results of two or more SELECT queries
  • Each SELECT must have the same number of columns
  • Column data types must be compatible
  • UNION removes duplicate rows by default
  • Use UNION ALL to include duplicates

🌟 Think of it this way: You have two lists β€” one of customers and one of employees. UNION merges them into a single list. It’s like stacking results on top of each other.

17.1 - UNION

Combine customer names and employee names into one list (duplicates removed).

SQL

SELECT name FROM customers
UNION
SELECT name FROM employees;

17.2 - UNION ALL

Combine results including duplicates.

SQL

SELECT name FROM customers
UNION ALL
SELECT name FROM employees;

βœ… Pro Tip: Use UNION when you want unique results. Use UNION ALL when performance matters and duplicates are allowed.

Exercise πŸ‘‡

Exercise:

Tasks

1.πŸ‘‰Combine customer and employee names (unique values)
2.Combine customer and employee names (include duplicates)
3.Combine cities and departments
4.Combine countries and departments
5.Combine filtered results from two tables
6.Sort combined results
7.Sort combined results including duplicates
8.Remove duplicates from same table using UNION
9.Remove duplicates from employees
10.Keep duplicates using UNION ALL
Stuck? Read this task's