How to select the record from table and insert into another table? - sql

I wanted to select the last record from the table1 and insert into another table .Here is my query.
Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).
I know for adding the value into table,need to be in cotation.But where to add?

You can select literals to fill in the other columns that table1 can't provide, something like this:
insert into table2 (col_a, col_b, col_c, col_d)
select top 1 col1, col2, 'foo', 'bar'
from table1
order by id desc
Any columns you do not name in the column list will get the default value, or null if no default is defined.
The number and type of columns selected must match the number and type of columns in the insert column list.

In SQL, there are essentially basically two ways to INSERT data into a table: One is to insert it one row at a time, the other is to insert multiple rows at a time. Let's take a look at each of them individually:
INSERT INTO table_name (column1, column2, ...)
VALUES ('value1', 'value2', ...)
The second type of INSERT INTO allows us to insert multiple rows into a table. Unlike the previous example, where we insert a single row by specifying its values for all columns, we now use a SELECT statement to specify the data that we want to insert into the table. If you are thinking whether this means that you are using information from another table, you are correct. The syntax is as follows:
INSERT INTO table1 (column1, column2, ...)
SELECT t2.column3, t2.column4, ...
FROM table2 t2
So, in you case, you can do it like this:
Insert into table2
select top 1 t1.col1,t1.col2 from table1 t1 order by id desc
Or you can use your syntax like this:
declare #col1 type_of_col1, #col2 type_of_col2
select top 1 #col1 = t1.col1, #col2 = t1.col2 from table1 t1 order by id desc
Insert into table2 values(#col1, #col2)
Offcourse, this all works assuming that the column datatypes are matched.

Related

How to Update a SQL table using Union

So I have 2 tables and I want to UPDATE Table 1 so that it is the Union of Table 1 and Table 2. Any suggestions?
It looks like you just want to insert rows of table2 into table1. If so:
insert into table1 (col1, col2)
select col1, col2 from table2
You might be looking to a more subtle logic, like,: insert names that do not exist, and update values on name that exist already. If so, I would recommend on conflict. For this to work, you need a unique constraint on table2(col1), and then:
insert into table1 (col1, col2)
select col1, col2 from table2
on conflict (col1) do update set col2 = excluded.col2

SQL INSERT from select with NULL values

Good afternoon in my timezone.
i have to insert a row in a table but one of the columns are values from another table.So what i want to accomplish is something like this
INSERT TABLE_NAME(COL1,COL2,COL3,COL4) VALUES("VAL1","VAL2","VAL3",(SELECT COL_A FROM TABLE2 WHERE COL_B = 'X'))
But i think the above code is not possible so i use the following code:
INSERT INTO TABLE_NAME(COL1,COL2,COL3,COL4)
SELECT "COL1","COL2","COL3", COL_A FROM TABLE2 T2
WHERE COL_B= "X"
My question is:
I want to insert values even the select does not return values and in this case the COL4 will be NULL
How can i achieve this ?
Thanks in advance
Best regards
No, you cannot insert a row that is not in the table.
If you are expecting one row (in the case of a match), you can use aggregation:
INSERT INTO TABLE_NAME(COL1, COL2, COL3, COL4)
SELECT "COL1","COL2","COL3", MAX(COL_A)
FROM TABLE2 T2
WHERE COL_B = 'X';
This will return NULL if there is no match -- but only one row even if there are multiple matches in the table.
As i understood from your description, only one column is NULL, other 3 columns have values. You should use Select INTO as https://www.w3schools.com/sql/sql_select_into.asp
SELECT COL1,COL2,COL3,COL4 INTO TABLE2 FROM TABLE_NAME WHERE COL_B= "X"
You can create a temp table to store the primary keys of TABLE2 (for eg TABLE2 has primary key 'X', 'Y')
CREATE TABLE #TempPK (COLB int null);
insert into #TempPK(COLB) values ('X');
insert into #TempPK(COLB) values ('Y');
--then you do a FULL OUTER JOIN on your insert select from statement
INSERT INTO TABLE_NAME(COL1, COL2, COL3, COL4)
SELECT "COL1","COL2","COL3", MAX(COL_A)
FROM TABLE2 T2 FULL OUTER JOIN #TempPK TPK
ON T2.COL_B = TPK.COLB
This way you should be able to insert both rows(X and Y) and the Row X should show NULL values all across the row. Hope it makes sense.

select table to select from, dependent on column-value of already given table

for my intention I have to select a table to select columns from dependent on the column-value of an already given table.
First I thought about a CASE construct, if this is possible with sqlite.
SELECT * FROM
CASE IF myTable.column1 = "value1" THEN (SELECT * FROM table1 WHERE ...)
ELSE IF myTable.column1 = "value2" THEN (SELECT * FROM table2 WHERE ...)
END;
I am new to SQL. What construct would be the most concise (not ugly) solution and if I cannot have it in sqlite, what RDBM would be the best fit?
Thanks
Here is a proposal for associating a value from one of two tables for each entry in mytable. I.e. this is making the assumption that mytable does not only contain a single entry for choosing the secondary table.
For details on what this means, see "MCVE" at the end of this answer.
If you want to switch between two secondary tables, based on a single entry in main table, see at the very end of this answer.
Details:
a hardcoded "value1"/"value2" as column1 added on the fly to the result from secondary tables
joining by the faked colummn1 and a secondary join-key, assumption here id
a union all to make a single table from both secondary tables (including the fake column1)
select *
from mytable
left join
(select 'value1' as column1, * from table1
UNION ALL
select 'value2' as column1, * from table2)
using(id, column1);
Output (for the MCVE provided below, "a-f" from table1, "A-Z" from table2):
value1|1|a
value2|2|B
value1|3|c
value1|4|d
value2|5|E
value2|6|F
MCVE:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE mytable (column1 varchar(10), id int);
INSERT INTO mytable VALUES('value1',1);
INSERT INTO mytable VALUES('value2',2);
INSERT INTO mytable VALUES('value1',3);
INSERT INTO mytable VALUES('value1',4);
INSERT INTO mytable VALUES('value2',5);
INSERT INTO mytable VALUES('value2',6);
CREATE TABLE table2 (value varchar(2), id int);
INSERT INTO table2 VALUES('F',6);
INSERT INTO table2 VALUES('E',5);
INSERT INTO table2 VALUES('D',4);
INSERT INTO table2 VALUES('C',3);
INSERT INTO table2 VALUES('B',2);
INSERT INTO table2 VALUES('A',1);
CREATE TABLE table1 (value varchar(2), id int);
INSERT INTO table1 VALUES('a',1);
INSERT INTO table1 VALUES('b',2);
INSERT INTO table1 VALUES('c',3);
INSERT INTO table1 VALUES('d',4);
INSERT INTO table1 VALUES('e',5);
INSERT INTO table1 VALUES('f',6);
COMMIT;
For selecting between two tables based on a single entry in main table (in this case "mytable2":
select * from table1 where (select column1 from mytable2) = 'value1'
union all
select * from table2 where (select column1 from mytable2) = 'value2';
Output (with mytable2 only containing 'value1'):
a|1
b|2
c|3
d|4
e|5
f|6

Insert distinct values from one table into another table

So for each distinct value in a column of one table I want to insert that unique value into a row of another table.
list = select distinct(id) from table0
for distinct_id in list
insert into table1 (id) values (distinct_id)
end
Any ideas as to how to go about this?
Whenever you think about doing something in a loop, step back, and think again. SQL is optimized to work with sets. You can do this using a set-based query without the need to loop:
INSERT dbo.table1(id) SELECT DISTINCT id FROM dbo.table0;
There are some edge cases where looping can make more sense, but as SQL Server matures and more functionality is added, those edge cases get narrower and narrower...
insert into table1 (id)
select distinct id from table0
The following statement works with me.
insert into table1(col1, col2) select distinct on (col1) col1 col2 from table0
The below query will also check the existing data in the Table2.
INSERT INTO Table2(Id) SELECT DISTINCT Id FROM Table1 WHERE Id NOT IN(SELECT Id FROM Table2);
Other Simple way to copy distinct data with multiple columns from one table to other
Insert into TBL2
Select * from (Select COL1, ROW_NUMBER() over(PARTITION BY COL1 Order By COL1) AS COL2 From TBL1)T
where T.COL2 = 1

Copy data into another table

How to copy/append data from one table into another table with same schema in SQL Server?
Edit:
let's say there is a query
select *
into table1
from table2
where 1=1
which creates table1 with the same schema as well as data as in table2.
Is there any short query like this to only copy entire data only into an already existing table?
If both tables are truly the same schema:
INSERT INTO newTable
SELECT * FROM oldTable
Otherwise, you'll have to specify the column names (the column list for newTable is optional if you are specifying a value for all columns and selecting columns in the same order as newTable's schema):
INSERT INTO newTable (col1, col2, col3)
SELECT column1, column2, column3
FROM oldTable
Simple way if new table does not exist and you want to make a copy of old table with everything then following works in SQL Server.
SELECT * INTO NewTable FROM OldTable
This is the proper way to do it:
INSERT INTO destinationTable
SELECT * FROM sourceTable
INSERT INTO table1 (col1, col2, col3)
SELECT column1, column2, column3
FROM table2
Try this:
INSERT INTO MyTable1 (Col1, Col2, Col4)
SELECT Col1, Col2, Col3 FROM MyTable2
Try this:
Insert Into table2
Select * from table1
Insert Selected column with condition
INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;
Copy all data from one table to another with the same column name.
INSERT INTO where_to_insert
SELECT * FROM from_table WHERE condition;
INSERT INTO DestinationTable(SupplierName, Country)
SELECT SupplierName, Country FROM SourceTable;
It is not mandatory column names to be same.
CREATE TABLE `table2` LIKE `table1`;
INSERT INTO `table2` SELECT * FROM `table1`;
the first query will create the structure from table1 to table2 and second query will put the data from table1 to table2
Copy all columns from one table to another table:
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
You can duplicate or "clone" a table's contents by executing:
CREATE TABLE new_table AS SELECT * FROM original_table;
-- for Sql Server users.
if you don't have the new table then you can create the new table with same structure as old table, and also copy data over from old table to the new table. For example:
select * into new_table
from old_table;
also you can copy the column / table structure, and just some of data. For example:
select * into new_table
from old_table
where country = 'DE';