Day 37: UNION and UNION ALL in MySQL - Merging Query Results!

Today, let us explore UNION and UNION ALL in MySQL, which allow us to combine results from multiple queries into a single result set!


1. UNION - Merging Results Without Duplicates

? Combines results from multiple SELECT queries

? Removes duplicate records

? All SELECT queries must have the same number of columns and compatible data types

Example: Merging Customers from Two Different Regions

SELECT customer_id, name, region FROM customers_north
UNION
SELECT customer_id, name, region FROM customers_south;        

Example: Fetching Unique Employee Names from Two Departments

SELECT name FROM sales_team
UNION 
SELECT name FROM support_team;        

2. UNION ALL - Merging Results With Duplicates

? Works like UNION but keeps duplicate records

? Faster than UNION since it does not check for duplicates

Example: Listing All Customers from Two Databases

SELECT customer_id, name FROM customers_2023
UNION ALL
SELECT customer_id, name FROM customers_2024;        

Example: Fetching All Employee Names from Two Departments

SELECT name FROM sales_team
UNION ALL
SELECT name FROM support_team;        

#100DaysOfCode #MySQL #SQL #Database #DataAnalysis #Learning #Python #BackendDevelopment

要查看或添加评论,请登录

Sarasa Jyothsna Kamireddi的更多文章

社区洞察