How does SQL UNION work?

SQL UNION combines the results of two or more SELECT queries into a single result set. It’s important to note that UNION only returns distinct rows in the final result, automatically eliminating any duplicate entries. To use UNION, the SELECT statements being combined must have the same number of columns, and the columns must have compatible data types.

The syntax for a basic SQL UNION operation is as follows:

SELECT column_name(s)
FROM table1
UNION
SELECT column_name(s)
FROM table2;

In this example, we are combining the results of two SELECT queries, one from table1 and one from table2. The column_name(s) keywords specify the columns that we want to include in the final result set.

Practical Examples of SQL UNION

  • Merging Customer Data:

Suppose you have two tables: customers_usa and customers_europe, containing customer information for different regions. You can use UNION to create a unified customer list:

SELECT customer_id, first_name, last_name, email
FROM customers_usa
UNION
SELECT customer_id, first_name, last_name, email
FROM customers_europe;
  • Consolidating Inventory Data:

Let’s say you manage inventory data in separate tables based on product categories. To consolidate this data for efficient analysis, you can use UNION:

SELECT product_id, product_name, stock_quantity
FROM electronics_inventory
UNION
SELECT product_id, product_name, stock_quantity
FROM clothing_inventory;
  • Combining Sales Reports:

Imagine you have quarterly sales reports stored in various tables. To create an annual sales overview, you can use UNION to merge the quarterly reports:

SELECT year, quarter, total_sales
FROM Q1_sales
UNION
SELECT year, quarter, total_sales
FROM Q2_sales
UNION
SELECT year, quarter, total_sales
FROM Q3_sales
UNION
SELECT year, quarter, total_sales
FROM Q4_sales;

Enroll now in the SQL certification course to learn SQL from industry-recognised experts.

Use Cases for SQL UNION

  • Merging Similar Data: Imagine you have a customer database split into two tables, one containing basic customer information and the other containing contact details. By using UNION, you can effortlessly merge these tables to create a comprehensive customer profile.
  • Consolidating Time-Series Data: If your organization stores time-series data in different tables, you can utilize UNION to consolidate historical records into a single table. This is particularly useful for generating trend analyses and forecasts.
  • Combining Reports: Let’s say you’re dealing with multiple sales reports from different regions. With SQL UNION, you can unify these reports into a single result set for centralized reporting and analysis.
  • Categorizing Data: Suppose you have separate tables for different product categories. SQL UNION can help you create a master catalog by combining data from these tables, simplifying inventory management.

Best Practices for Using SQL UNION

  • Column Ordering and Data Types: Ensure that the columns you’re combining in the SELECT statements have the same ordering and compatible data types. Mismatched data types can lead to errors or unexpected results.
  • Use UNION ALL When Appropriate: While UNION eliminates duplicate rows, UNION ALL preserves all rows, including duplicates. If you’re confident that your data doesn’t contain duplicates, using UNION ALL can be more efficient.
  • Optimize Query Performance: Just like any other SQL operation, UNION queries can benefit from proper indexing, query optimization, and database design practices.
  • Avoid Excessive UNIONs: While UNION is a powerful tool, excessive use of UNION operations might indicate a need for better database design or normalization.

Conclusion

SQL UNION opens up a world of possibilities for combining and analyzing data from various sources. Whether you’re working with customer data, time-series records, or different types of reports, UNION allows you to create a cohesive dataset for enhanced insights. By understanding the syntax, use cases, and best practices of SQL UNION, you’ll be equipped to harness its potential and take your data analysis skills to the next level.

Intellipaat provides SQL course in Bangalore. Enroll now!

Course Schedule

Name Date Details
SQL Training 23 Mar 2024(Sat-Sun) Weekend Batch
View Details
SQL Training 30 Mar 2024(Sat-Sun) Weekend Batch
View Details
SQL Training 06 Apr 2024(Sat-Sun) Weekend Batch
View Details