Merge 2 tables in SQL and save into 1 new table - sql

If we have two or more tables with the same columns
Table 1
Structure, Name, Active
1,A,1
Table 2
Structure, Name, Active
2,B,0
We would like to combine these two tables and save it into a new one
New Table
Structure, Name, Active
1,A,1
2,B,0
Here is the code
CREATE TABLE Amide_actives_decoys
(
Structure NVARCHAR(255),
Name NVARCHAR(255),
Active INT
)
GO
INSERT Amide_actives_decoys
FROM (
SELECT * FROM Amide_decoys
UNION
SELECT * FROM Amide_actives
)
The following error message will show up
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'FROM'.
The same thing if we use
SELECT * INTO Amide_actives_decoys
FROM (
SELECT * FROM Amide_decoys
UNION
SELECT * FROM Amide_actives
)
Following this answer
Joining a table onto itself in SQL and saving the result
The error message will be
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ';'.
Could any guru kindly offer some comments? Thanks!

This syntax works in different databases:
INSERT INTO Amide_actives_decoys(Structure, Name, Active)
SELECT * FROM Amide_decoys
UNION
SELECT * FROM Amide_actives;
In this form of INSERT, the output of the subquery becomes the set of
input values for the INSERT.
Note that the datatypes for the expressions in the SELECT statement
subquery must match the datatypes in the target table of the INSERT
statement.
All of the rows returned by the subquery are inserted into the
Amide_actives_decoys table.
If any one row fails the INSERT due to a constraint violation or
datatype conflict, the entire INSERT fails and no rows are inserted.
Any valid subquery may be used within the INSERT statement.

I think you need to UNION ALL otherwise you may not capture all the data; depends on what data is in the table (duplicates etc).
INSERT INTO Amide_actives_decoys(Structure, Name, Active)
SELECT * FROM Amide_decoys
UNION ALL
SELECT * FROM Amide_actives;

create table Amide_actives_decoys
as
select Structure, Name, Active from
(
SELECT * FROM Amide_decoys
UNION
SELECT * FROM Amide_actives
)
;

The General syntax is
INSERT INTO table2
SELECT * FROM table1;
you can SELECT INTO Statement in this Case
with cte as (select 1 col1 ,2 col2
union all
select 2,3)
select * into #tabletest from cte
select *From #tabletest

In both your answers, the issue is that you have not given an alias name for the table as a result.I think you missed an 'INTO' in the INSERT statement as well.
Query 1:
CREATE TABLE Amide_actives_decoys
(
Structure NVARCHAR(255),
Name NVARCHAR(255),
Active INT
)
GO
INSERT INTO Amide_actives_decoys
SELECT *
FROM (
SELECT * FROM Amide_decoys
UNION
SELECT * FROM Amide_actives
) LU --LU is added.
For Query 1, the below also is correct
INSERT INTO Amide_actives_decoys
SELECT * FROM Amide_decoys
UNION
SELECT * FROM Amide_actives
Query 2:
SELECT *
INTO Amide_actives_decoys
FROM (
SELECT * FROM Amide_decoys
UNION
SELECT * FROM Amide_actives
) LU -- LU added

SELECT
tab1.firstName,
tab1.lastName,
tab2.city,
tab2.state
FROM TABLE_1 tab1 LEFT JOIN TABLE_2 tab2
ON tab1.personId=tab2.personId

Related

Create new table using WITH clause

Is it possible to create a table based on a query that is using WITH clause?
The query:
with test as (
select 999 as col1
)
select * from test;
I tried :
select * into newtable from
(
with test as(
select 999 as col1
)
select * from test
) as newtable
But I get this error:
Msg 319, Level 15, State 1, Line 3 Incorrect syntax near the keyword
'with'. If this statement is a common table expression, an
xmlnamespaces clause or a change tracking context clause
NOTE: My real query is more complex so I cannot remove the WITH clause.
You can't stuff a CTE inside a subquery like you're trying to do. Rather the insert syntax should be:
with test as (
select 999 as col1
)
select *
into newtable
from test;

Create table from simple UNION statement

What is wrong with this union? first 'select' and ')' are incorrect
create table GL_ALL
(
select *from GL1
)
UNION
(
select *from GL2
)
UNION
(
select *from GL3
)
UNION
(
select *from GL4
)
UNION
(
select *from GL5
);
That's not the correct syntax for creating a table on the fly in SQL Server, or UNION for that matter.
Assuming that the schemas of each of your tables are the same
SELECT *
INTO GL_ALL FROM GL1 UNION
SELECT * FROM GL2 UNION
SELECT * FROM GL3 UNION
SELECT * FROM GL4 UNION
SELECT * FROM GL5;
As pointed out in comments, this will work for the initial creation of GL_ALL, but not for subsequent inserts after the table is created.
If you need to append to the table at a later time then the sytax changes to:
INSERT INTO GL_ALL
SELECT * FROM GL6;
It's important to realize that the new table will NOT have a primary key nor any foreign keys, indexes (clustered or non), constraints, defaults, etc. that the source tables may have. If these are needed then you will need to manually create them.
And do note the difference between UNION and UNION ALL, where UNION will exclude duplicate rows.
Also note, it's best practice to avoid SELECT * and to specifically call out the columns you want to work with - even if it actually is all columns.

Save a Select/Except Union into a Temp Table

This code does precisely what I want: finds the difference between two tables, including nulls, and returns them. Thanks to: sql query to return differences between two tables
(
SELECT * FROM table1
EXCEPT
SELECT * FROM table2
)
UNION ALL
(
SELECT * FROM table2
EXCEPT
SELECT * FROM table1
)
I am having trouble getting this to turn into a temporary table (or even a regular table) to store its results for later use. Is there a way that I can tack on INSERT INTO here or generate a temp table from this beautiful query?
Select from your existing query as a sub-query INTO the temp table of your choice.
SELECT *
INTO #temp1
FROM (
(
SELECT * FROM #table1
EXCEPT
SELECT * FROM #table2
)
UNION ALL
(
SELECT * FROM #table2
EXCEPT
SELECT * FROM #table1
)
) X

How to create table with multiple rows and columns using only SELECT clause (i.e. using SELECT without FROM clause)

I know that in SQL Server, one can use SELECT clause without FROM clause, and create a table with one row and one column
SELECT 1 AS n;
But I was just wondering, is it possible to use SELECT clause without FROM clause, to create
a table with one column and multiple rows
a table with multiple columns and one row
a table with multiple columns and multiple rows
I have tried many combinations such as
SELECT VALUES(1, 2) AS tableName(n, m);
to no success.
You can do it with CTE and using union(Use union all if you want to display duplicates)
Rextester Sample for all 3 scenarios
One Column and multiple rows
with tbl1(id) as
(select 1 union all
select 2)
select * from tbl1;
One row and multiple columns
with tbl2(id,name) as
(select 1,'A')
select * from tbl2;
Multiple columns and multiple rows
with tbl3(id,name) as
(select 1,'A' union all
select 2,'B')
select * from tbl3;
-- One column, multiple rows.
select 1 as ColumnName union all select 2; -- Without FROM;
select * from ( values ( 1 ), ( 2 ) ) as Placeholder( ColumnName ); -- With FROM.
-- Multiple columns, one row.
select 1 as TheQuestion, 42 as TheAnswer; -- Without FROM.
select * from ( values ( 1, 42 ) ) as Placeholder( TheQuestion, TheAnswer ); -- With FROM.
-- Multiple columns and multiple rows.
select 1 as TheQuestion, 42 as TheAnswer union all select 1492, 12; -- Without FROM.
select * from ( values ( 1, 2 ), ( 2, 4 ) ) as Placeholder( Column1, Column2 ); -- With FROM.
You can do all that by using UNION keyword
create table tablename as select 1 as n,3 as m union select 2 as n,3 as m
In Oracle it will be dual:
create table tablename as select 1 as n,3 as m from dual union select 2 as n,3 as m from dual
You can use UNION operator:
CREATE TABLE AS SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
The UNION operator selects only distinct values by default. To allow duplicate values you can use UNION ALL.
The column names in the result-set are usually equal to the column names in the first SELECT statement in the UNION.
try this:
--1) a table with one column and multiple rows
select * into tmptable0 from(
select 'row1col1' as v1
union all
select 'row2col1' as v1
) tmp
--2) a table with multiple columns and one row
select 'row1col1' as v1, 'row1col2' as v2 into tmptable1
--3) a table with multiple columns and multiple rows
select * into tmptable2 from(
select 'row1col1' as v1, 'row1col2' as v2
union all
select 'row2col1' as v2, 'row2col2' as v2
) tmp
One can create a view and later can query it whenever required
-- table with one column and multiple rows
create view vw1 as
(
select 'anyvalue' as col1
union all
select 'anyvalue' as col1
)
select * from vw1
-- table with multiple columns and multiple rows
create view vw2 as
(
select 'anyvalue1' as col1, 'anyvalue1' as col2
union all
select 'anyvalue2' as col1, 'anyvalue2' as col2
)
select * from vw2

Oracle create table using with clause

Can I create a table from a query formed using with clause?
Sure:
CREATE TABLE t
AS
WITH some_data AS (
SELECT 1 as some_value
FROM dual
UNION ALL
SELECT 2
FROM dual
)
SELECT *
FROM some_data
The CREATE TABLE table_name AS statement creates a table based on a select statement. The solution for a with clause will be :
CREATE TABLE t
AS
SELECT * FROM (
WITH some_data AS (
SELECT 1 as some_value
FROM dual
UNION ALL
SELECT 2
FROM dual
)
);
For multiple CTE (common table expressions; i.e. multiple WITH clause), I found the same syntax worked. i.e.
CREATE TABLE schema.table_name as
WITH table1 as (SELECT 1),
table2 as (SELECT 2)
select * from table2
will create the table_name in the schema from the select statement