SQL UNION and SQL UNION ALL | How to Combine the result sets of 2 or more SELECT statements in SQL
HTML-код
- Опубликовано: 31 янв 2022
- The SQL UNION Operator- The UNION operator is used to combine the result-
set of two or more SELECT statements.
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
You can follow us on the below social media handles:-
Blog: - thedatamillennials.blogspot.com/
Facebook:- / the-data-millennials-5...
Instagram: - / the_data_millennials
LinkedIn: - / data-millennials-6b5a0...
Twitter: - / datamillennials
how to save union data into a new table?
To save the results of a UNION query into a new table in SQL, you can use a combination of the `CREATE TABLE` and `INSERT INTO` statements. Here’s a step-by-step guide for this process:
1. Create the New Table:
First, you need to create the structure of the new table that will store the results of the UNION. The structure should match the structure of the result set of your UNION query.
2. Insert Data Using UNION:
Use the `INSERT INTO` statement combined with your UNION query to populate the new table.
Here is an example to illustrate the process:
Suppose you have two tables, `table1` and `table2`, and you want to save the union of these tables into a new table called `new_table`.
Step 1: Create the New Table
### Step 2: Insert Data Using UNION
Next, use the `INSERT INTO` statement with your UNION query to insert data into the new table:
sql
INSERT INTO new_table (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
UNION
SELECT column1, column2, column3, ...
FROM table2;
### Example
Let’s say you have two tables with the following structure:
table1:
- id (INT)
- name (VARCHAR)
- age (INT)
table2:
id (INT)
name (VARCHAR)
age (INT)
You want to union these tables and save the results into a new table called `new_table`.
sql
Step 1: Create the new table
CREATE TABLE new_table (
id INT,
name VARCHAR(255),
age INT
);
Step 2: Insert data using UNION
INSERT INTO new_table (id, name, age)
SELECT id, name, age FROM table1
UNION
SELECT id, name, age FROM table2;
By following these steps, you will create a new table and save the results of the UNION query into it.