ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Union in MySql

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='7' AND `tutorial_submenu`='55' AND `tutorial_status`=1 LIMIT 1

Union in MySql

UNION in MySQL

The UNION operator in MySQL is used to combine the results of two or more SELECT statements into a single result set. It removes duplicate rows by default.


1. Syntax

SELECT column1, column2 FROM table1UNIONSELECT column1, column2 FROM table2;

🔹 Rules for Using UNION:
✅ Both SELECT statements must have the same number of columns.
✅ The columns must have compatible data types.
✅ By default, UNION removes duplicate rows.


2. Example Tables

📌 Table: employees_us

emp_idnamecountry
1AliceUSA
2BobUSA

📌 Table: employees_uk

emp_idnamecountry
3CharlieUK
4BobUK


3. Using UNION

SELECT name, country FROM employees_usUNIONSELECT name, country FROM employees_uk;

✅ Result (Duplicates Removed):

namecountry
AliceUSA
BobUSA
CharlieUK
BobUK

🔹 Bob appears only once because UNION removes duplicates.


4. Using UNION ALL (Keeps Duplicates)

SELECT name, country FROM employees_usUNION ALLSELECT name, country FROM employees_uk;

✅ Result (Duplicates Kept):

namecountry
AliceUSA
BobUSA
CharlieUK
BobUK

🔹 Here, Bob appears twice because UNION ALL does not remove duplicates.


5. Using ORDER BY with UNION

SELECT name, country FROM employees_usUNIONSELECT name, country FROM employees_ukORDER BY name ASC;

✅ Sorted Result:

namecountry
AliceUSA
BobUSA
BobUK
CharlieUK

🔹 The ORDER BY must be at the end of the UNION query.


6. Using UNION with Different Conditions

SELECT name, country FROM employees_us WHERE country = 'USA'UNIONSELECT name, country FROM employees_uk WHERE country = 'UK';

✅ Filters employees by country before combining results.


Key Takeaways

✅ UNION combines results from multiple SELECT queries.
✅ Duplicates are removed by default (use UNION ALL to keep them).
✅ The number of columns and their data types must match.
✅ Use ORDER BY at the end of the final query.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql