Search code examples
sqlsql-serverunioncreate-table

Create a new table in SQL based on two other tables


I have two tables against which I would like to create new table with the output.

For example;

Table 1

Column 1    Column 2    Column 3
a               b          c

Table 2

Column 4    Column5     Column6
D              E           F

I've joined above tables with an "Union". Not sure how to create a new table from the original query itself

Any help would be appreciated


Solution

  • for creating a new table, use INTO statement that provide a new table. it should be place in the first select

    SELECT column1,
           column2,
           column3
    INTO   newtable --creating new table
    FROM   table1
    UNION
    SELECT column4,
           column5,
           column6
    FROM   table2  
    

    If you have created a New Table, then use INSERT INTO Statement

    INSERT INTO newtable
                (column1,
                 column2,
                 column3)
    SELECT column1,
           column2,
           column3
    FROM   table1
    UNION
    SELECT column4,
           column5,
           column6
    FROM   table2