For working professionals
For fresh graduates
More
SQL Tutorial: Learn Structured…
1. SQL Tutorial
2. The Essential Guide To Understanding SQL In DBMS
3. SQL Commands
4. SQL Data Types
5. SQL Aliases
6. SQL INSERT INTO With Examples
7. Master SQL Update
8. SQL Delete Statement: A Complete Overview with Examples
9. SQL Delete Statement Example
10. SQL WHERE Clause
11. SQL AND Operator
12. SQL NOT Operator: A Comprehensive Guide
13. SQL Like
14. SQL Between Operator: A Complete Overview with Examples
15. Difference Between SQL and MySQL: Get to Know Your DBMS
16. MySQL Workbench
17. A Comprehensive Guide to MySQL Workbench Installation and Configuration
18. Mastering SQL: Your Comprehensive Guide to Becoming an SQL Developer
19. SQL CREATE TABLE With Examples
20. How To Add Columns In SQL: A Step-By-Step Guide
21. Drop Column in SQL: Everything You Need to Know
22. Index in SQL
23. Constraints in SQL: A Complete Guide with Examples
24. Schema in SQL
25. Entity Relationship Diagram (ERD) - A Complete Overview
26. Foreign Key in SQL with Examples
27. An Ultimate Guide to Understand all About Composite Keys in SQL
28. Normalization in SQL
29. Better Data Management: The Efficiency of TRUNCATE in SQL
30. Difference Between DELETE and TRUNCATE in SQL
31. SQL ORDER BY
32. SQL Not Equal Operator
33. SQL Intersect Operator: A Comprehensive Guide
34. SQL Union: Explained with Examples
Now Reading
35. SQL Case Statement Explained with Examples
36. Unleashing the CONCAT Function In SQL: String Manipulation Made Easy
37. Understanding and Mastering COALESCE in SQL
38. NVL in SQL
39. Understanding SQL Date Formats and Functions
40. DateDiff in SQL: A Complete Guide in 2024
41. SQL Wildcards
42. SQL DISTINCT: A Comprehensive Guide
43. LIMIT in SQL: A Comprehensive Tutorial
44. SQL Aggregate Functions
45. GROUP BY in SQL
46. SQL HAVING
47. EXISTS in SQL
48. SQL Joins
49. Inner Join in SQL
50. Left Outer Join in SQL
51. Full Outer Join in SQL
52. Cross Join in SQL
53. Self Join SQL
54. Left Join in SQL
55. Mastering SQL Substring
56. Understanding the ROW_NUMBER() Function in SQL
57. Cursor in SQL
58. Triggers In SQL
59. Stored Procedures in SQL
60. RANK Function in SQL
61. REPLACE in SQL
62. How to Delete Duplicate Rows in SQL
63. Transact-SQL
64. INSTR in SQL
65. PostgreSQL vs MySQL: Explore Key Differences
66. Mastering SQL Server Management Studio (SSMS): A Comprehensive Guide
67. Auto-Increment in SQL
68. Unveiling the Power of SQL with Python
69. SQL Vs NoSQL: Key Differences Explained
70. Advanced SQL
71. SQL Subquery
72. Second Highest Salary in SQL
73. Database Integrity Constraints: Everything You Need to Know
74. Primary Key In SQL: A Complete Guide in 2024
75. A Comprehensive Guide on View in SQL
76. Understanding PostgreSQL: A Complete Tutorial
77. SQL Injection Attack
78. MySQL database
79. What is SQLite
80. SQLite
81. ALTER Command in SQL
Wise decisions require the ability to extract insightful information from a range of sources. Accessing data from diverse tables is often a necessity if you are analyzing customer behavior, tracking sales trends, or performing any data-related tasks. This is where the SQL UNION command comes into play.
The SQL UNION operator or command serves as a bridge between different datasets. It allows you to easily aggregate the results of many SELECT operations performed on columns from different tables.
I will show you how to use the SQL UNION command in this article by providing clear explanations and valuable examples.
Through the use of SQL UNION, you can simplify your data analysis and extract insightful information from several datasets. You can do it by combining the results of two or more SELECT command searches.
This guide will not only help you have a solid understanding of SQL UNION, but it will also help you with its application within your data analysis procedures. To start with the basics, we will cover the syntax and key concepts of SQL Union.
SQL Union is a strong SQL command that combines the results of numerous SELECT queries into a single distinct result set. This operator is quite useful when you need to integrate data from many sources or tables.
The SQL union syntax is described below.
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
In this syntax:
Now let’s look at some fundamental SQL union examples
Let's say you have two tables, employees and customers, each containing information about different entities.
Employees Table
employee_id | name | department |
1 | John | Sales |
2 | Alice | Marketing |
3 | Michael | Finance |
Customers Table;
customer_id | name | |
101 | Emily | |
102 | Brian | |
103 | Sophia |
You wish to get a list of names from the two tables. Here's how you can accomplish this using SQL Union:
SELECT name FROM employees
UNION
SELECT name FROM customers;
This query will combine the names from both tables and remove any duplicates, which gives you a unified list of names across employees and customers.
Output:
name |
John |
Alice |
Michael |
Emily |
Brian |
Sophia |
In some cases, you may want to provide custom names for columns in the resulting union. This can be achieved using column aliases by the same example as before:
SELECT name AS entity_name FROM employees
UNION
SELECT name AS entity_name FROM customers;
By specifying AS entity_name, you ensure that the name columns from both of the tables are combined under a single alias, making the result set more readable and intuitive.
Output:
name |
John |
Alice |
Michael |
Emily |
Brian |
Sophia |
SQL UNION is not limited to just two tables—you can combine results from multiple tables in a single union operation. For instance, using the same example as before, suppose you have additional tables such as suppliers and partners, each containing relevant information.
Suppliers Table:
supplier_id | name | product |
201 | Smith | Electronics |
202 | Emma | Clothing |
203 | David | Appliances |
Partners Table
partner_id | name | partnership_type |
301 | Lily | Technology |
302 | James | Consulting |
303 | Grace | Marketing |
You can include them in the union like so:
SELECT name FROM employees
UNION
SELECT name FROM customers
UNION
SELECT name FROM suppliers
UNION
SELECT name FROM partners;
This query aggregates names from all four tables, which further creates a comprehensive list of entities across different categories.
Output:
name |
John |
Alice |
Michael |
Emily |
Brian |
Sophia |
Smith |
Emma |
David |
Lily |
James |
Grace |
Combining SQL Union with other subqueries opens up a world of possibilities for data manipulation and analysis. Let's explore three key scenarios where SQL UNION can be enhanced with subqueries:
When using SQL UNION with a WHERE clause, you can filter the results of each SELECT query before combining them. This allows you to focus on specific subsets of data and refine your final result set.
Consider a scenario where you have two tables: ‘sales_2021’ and ‘sales_2022’, each containing sales data for different years.
Table 1: Sales Data for 2021 (sales_2021)
product_name | sales_amount |
Product A | 150 |
Product B | 120 |
Product C | 130 |
Table 2: Sales Data for 2022 (sales_2022)
product_name | sales_amount |
Product A | 180 |
Product B | 110 |
Product D | 140 |
You want to combine the sales figures for products that cost more than $100, and you want to do it from both tables. Here's how you can achieve this using SQL UNION with a WHERE clause:
SELECT product_name, sales_amount
FROM sales_2021
WHERE price > 100
UNION
SELECT product_name, sales_amount
FROM sales_2022
WHERE price > 100;
Output table:
product_name | sales_amount |
Product A | 150 |
Product B | 120 |
Product C | 130 |
By combining SQL UNION with an ORDER BY clause, you can sort the final result set according to your preferred criteria. This allows you to arrange the combined data in a meaningful and structured way, which enhances readability and analysis.
For example, Let's say you want to merge employee records from two tables, ‘employees_1’ and ‘employees_2’,
Table 1: Employee Records (employees_1)
employee_id | employee_name |
101 | John |
102 | Alice |
103 | Bob |
Table 2: Employee Records (employees_2)
employee_id | employee_name |
104 | Emma |
105 | Mike |
In case, you want to display the results sorted by employee ID in ascending order, here's how you can accomplish this using SQL Union with an ORDER BY clause:
SELECT employee_id, employee_name
FROM employees_1
UNION
SELECT employee_id, employee_name
FROM employees_2
ORDER BY employee_id ASC;
Output table
employee_id | employee_name |
101 | John |
102 | Alice |
103 | Bob |
104 | Emma |
105 | Mike |
SQL UNION can also be combined with SQL JOIN operations to further enhance data integration and analysis. By joining tables before using Union, you can incorporate additional filtering and data enrichment, leading to more comprehensive insights.
For example;
Suppose you have two tables, ‘customers’ and ‘orders’, and you want to combine customer information with order details for last month’s buyers.
Table 1: Customer Information (customers)
customer_id | customer_name |
1 | John Smith |
2 | Alice Johnson |
3 | Bob Davis |
Table 2: Order Details (orders)
order_id | customer_id | order_date | order_amount |
101 | 1 | 2023-02-15 | 200 |
102 | 2 | 2023-02-20 | 150 |
103 | 3 | 2023-02-10 | 180 |
You can do this by first joining the tables based on customer IDs and then applying Union:
SELECT customer_name, order_date, order_amount
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
WHERE order_date >= '2023-02-01' AND order_date < '2023-03-01'
UNION
SELECT customer_name, order_date, order_amount
FROM customers_archive
JOIN orders_archive ON customers_archive.customer_id = orders_archive.customer_id
WHERE order_date >= '2023-02-01' AND order_date < '2023-03-01';
Output Table:
customer_name | order_date | order_amount |
John Smith | 2023-02-15 | 200 |
Alice Johnson | 2023-02-20 | 150 |
Bob Davis | 2023-02-10 | 180 |
Emma Wilson | 2023-02-05 | 220 |
Mike Brown | 2023-02-25 | 190 |
When working with SQL, you often encounter scenarios where you need to combine data from multiple sources to derive meaningful insights. Just like SQL UNION, SQL offers several powerful commands for this purpose, including SQL UNION and UNION ALL, INTERSECT, EXCEPT, and JOIN operations. While these operations share some similarities, they also have distinct features and use cases.
Feature | UNION | UNION ALL | JOIN | INTERSECT | EXCEPT |
Purpose | Combines two or more SELECT statements' results. | Same as UNION, but retains duplicates | Merges columns from many tables by using a common column. | Retrieves common rows between two result sets | Retrieves unique rows from the first result set but not present in the second result set |
Duplicates Handling | Automatically removes duplicates | Retains all rows, including duplicates | Depends on the type of JOIN used (INNER JOIN, LEFT JOIN, etc.) | Automatically removes duplicates | Automatically removes duplicates |
Syntax | SELECT column_name1, column_name2 FROM table1 UNION SELECT column_name1, column_name2 FROM table2; | SELECT column_name1, column_name2 FROM table1 UNION ALL SELECT column_name1, column_name2 FROM table2; | SELECT table1.column_name1, table1.column_name2, table2.column_name1, table2.column_name2 FROM table1 JOIN table2 ON table1.common_column = table2.common_column; | SELECT column_name1, column_name2 FROM table1 INTERSECT SELECT column_name1, column_name2 FROM table2; | SELECT column_name1, column_name2 FROM table1 EXCEPT SELECT column_name1, column_name2 FROM table2; |
Number of Result Rows | May return fewer rows due to duplicate removal | Returns all rows, including duplicates | Depends on the type of JOIN and the relationship between tables | Returns rows present in both result sets | Returns rows present in the first result set but not in the second result set |
Performance | Typically, slower than UNION ALL due to duplicate removal | Typically, faster than UNION due to fewer operations | Depends on the complexity of JOIN conditions and the size of tables | Performance depends on the size and distribution of data in both result sets | Performance depends on the size and distribution of data in both result sets |
Use Cases | Ideal for combining distinct sets of data | Suitable when duplicates need to be retained | Used to retrieve data from related tables based on a common column | Useful for finding common elements between two datasets | Useful for finding differences between two datasets |
In summary, the SQL UNION operator serves as an important tool in database management. It facilitates seamless integration of data from various sources. Throughout this article, you have acquired a thorough comprehension of the SQL UNION operator, its syntax, and its practical applications through illustrative examples.
We have explored how SQL UNION enables the efficient merging of data from multiple tables. Furthermore, we looked into advanced techniques such as combining UNION with other subqueries, including WHERE clauses, ORDER BY clauses, and SQL JOIN operations. This will help to further refine and augment your data analysis capabilities.
There is no doubt that by mastering SQL UNION, you are well-prepared to address a myriad of data manipulation challenges.
1. What does the UNION do in SQL?
The UNION operator in SQL combines the outcomes of two or more SELECT queries into just one outcome set. It effectively merges the rows from each query, while automatically removing duplicates.
2. What is the distinction between a JOIN and a UNION in SQL?
In SQL, a JOIN is used to combine columns from two or more tables based on a related column. It essentially creates a Cartesian product of the tables involved. On the other hand, UNION is used to combine the results of two or more SELECT queries into a single result set, removing duplicates automatically.
3. Is UNION costly in SQL?
The cost of using UNION in SQL depends on various factors such as the size of the datasets, the complexity of the queries, and the database engine that is being used. Generally, UNION operations can be less efficient compared to other operations like UNION ALL since they involve removing duplicates.
4. What is UNION and distinct in SQL?
In SQL, UNION merges the outcomes of two or more SELECT queries into a single result set while deleting duplicates. DISTINCT, on the other hand, is used within a single SELECT query to eliminate duplicate rows from the result set.
5. Is UNION faster in SQL?
The speed of a UNION operation in SQL depends on factors, such as the size of the datasets and the database engine in use. Generally, UNION ALL is faster than UNION since it does not involve removing duplicates, but this may vary based on the specific circumstances.
6. Does UNION include duplicates?
No, by default, the UNION operator in SQL removes duplicate rows from the result set. If you want to retain duplicates, you can use the UNION ALL operator instead.
7. How can I eliminate duplicate rows while keeping one copy in SQL?
To delete duplicate rows while keeping one copy in SQL, you can use the ROW_NUMBER() function along with a common table expression (CTE) or a subquery. Here's a basic example:
WITH CTE AS (
SELECT column1, column2, ..., ROW_NUMBER() OVER (PARTITION BY column1, column2, ... ORDER BY column1) AS RowNumber
FROM your_table
)
DELETE FROM CTE WHERE RowNumber > 1;
This query assigns row numbers to each row, partitioned by the columns you specify and deletes rows where the row number is greater than 1, effectively keeping only one copy of each duplicate row.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.