Is it legitimate to use a SELECT and INSERT simultaneously? Suppose we want to move old records from one table to another table with the same columns -- can I do this in a single statement? I feel like it should be possible with a stored procedure and it would be interesting to see how that could be done (from my perspective it would seem easier to manage this sort of thing in a programmatic context.) I'm actually primarily curious about whether it would legitimate to write a statement with both a SELECT from one table and use that information to INSERT into another, and hopefully an example of what that might look like.
Yes.
INSERT INTO TargetTable (<column names>)
SELECT <column names> FROM SourceTable
WHERE blah blah blah...
yes...
insert into newtable(col1, col2, ...)
select col1, col2, ... from othertable
Check out the SELECT INTO SQL statement. Sounds like that's what you're looking for.
Related
I intend to write a INSERT INTO request in Postgresql based on several SELECT but didn't succeed.
I have one table containing data I select (srctab), and another one where I insert data (dsttab).
Here is what I run :
INSERT INTO dsttab (dstfld1, dstfld2) WITH
t1 AS (
SELECT srcfld1
FROM srctab
WHERE srcfld3 ='foo'
),
t2 AS (
SELECT srcfld5
FROM srctab
WHERE srcfld6 ='bar'
) select srcfld1, srcfld5 from srctab;
Could you please help to make this work ? Thank you !
Note: I'm guessing about what you want to do here. My guess is that you want to insert a single row with the values from the CTEs (That's the WITH block.). Your query as written would insert a row into dsttab for every row in srctab, if it were valid syntax.
You don't really need a CTE here. CTEs should really only be used when you need to reference the same subquery more than once; that's what they exist for. (Occasionally, you can somewhat abuse them to control certain performance aspects in PostgreSQL, but that isn't the case in other DBs and is something to be avoided when possible anyway.)
Just put your queries in line:
INSERT INTO dsttab (dstfld1, dstfld2)
VALUES (
(SELECT srcfld1
FROM srctab
WHERE srcfld3 ='foo'),
(SELECT srcfld5
FROM srctab
WHERE srcfld6 ='bar')
);
The key point here is to surround the subqueries with parentheses.
I wanted to throw this out there for some ideas. I'm writing a program to generate insert/update statements, and I want the table that I insert/update to come from the results of a query. So something like (please forgive the syntax):
INSERT INTO (SELECT TBL_NAME FROM MYTABLES WHERE A=B) VALUES ('A', 'B', 'C');
I have to do this in Oracle, but I'm not too familiar with their declare statements or syntax. I'm guessing the best way to go about it is to declare a variable that is the result of the SELECT, but then can I use that variable as the table name for the INSERT?
I also want to keep the code in SQL.
Thanks for any ideas.
I think you may want to look into Dynamic SQL, you may find your answer (or at least a decent starting path) there.
How about something like this:
SELECT 'INSERT INTO ' || TBL_NAME || ' VALUES (''A'', ''B'', ''C'');' cmd
FROM MYTABLES WHERE A=B
;
Run this select, then run the results of the select (which is insert statements).
Don't forget to "commit".
Regards,
Roger
All views are mine ...
I need to insert into a simple table with two columns.
The first column has to contain the same value from row to row, while the second has to hold the various values from a source table. So it all should look like this:
Question is - is there a way to make a set-based insert in this case? The way I do it now is simply iterate through the rows of the source table. Or it's also possible to use cursors, only I'm not sure which is best.
But still this is iteration.
Any means to get around this?
Thanks in advance!
If you know your static value ahead of time, you could do something like this:
INSERT INTO targetTable(Col1, Col2)
SELECT 1, yourColumn
FROM sourceTable
WHERE <condition>
This is assuming that 1 is your static value. It can be replaced with the real value, or a variable, depending on the specifics of your query.
insert into dest_tab(col1, col2)
select 1, col2
from src_table
where ....
While contemplating this question about a SQL INSERT statement, it occurred to me that the distinction in syntax between the two statements is largely artificial. That is, why can't we do:
INSERT INTO MyTable SET Field1=Value1, Field2=Value2, ...
or
UPDATE MyTable ( Field1, Field2 ...) VALUES ( Value1, Value2, ... )
WHERE some-key = some-value
Perhaps I'm missing something critical. But for those of us who have had to concatenate our SQL statements in the past, having comparable syntax for an INSERT and an UPDATE statement would have saved a significant amount of coding.
They're serving different grammatical functions. In an update you are specifying a filter that chooses a set of rows to which you will apply an update. And of course that syntax is shared with a SELECT query for the same purpose.
In an INSERT you are not choosing any rows, you are generating a new row which requires specifying a set of values.
In an UPDATE, the LHS=RHS stuff is specifying an expression which yields true or false (or maybe null :) and in an INSERT, the VALUES clause is about assignment of value. So while they are superficially similar, they are semantically quite different, imho. Although I have written a SQL parser, so that may influence my views. :)
SQL Server 2008 has introduced UPSERT functionality via the MERGE command. This is the logical equivalent of
IF FOUND THEN
UPDATE
ELSE
INSERT
I believe this is so that you may make an insert statement without being explicit about the values. If you are putting a value in every single column in the table you can write:
insert into my_table values ("value1", 2);
instead of:
insert into my_table (column1, column2) values ("value1", 2);
When importing and exporting entire (large) databases, this is invaluable for cutting down file size and processing time. Nowadays, with binary snapshots and the like, it may be "less invaluable" :-)
I am trying to import a large CSV file into a MySQL database. I have loaded the entire file into one flat table. i can select the data that needs to go into separate tables using select statements, my question is how do i copy the results of those select queries to different tables. i would prefer to do it completely in SQL and not have to worry about using a scripting language.
INSERT
INTO new_table_1
SELECT *
FROM existing_table
WHERE condition_for_table_1;
INSERT
INTO new_table_2
SELECT *
FROM existing_table
WHERE condition_for_table_2;
INSERT INTO anothertable (list, of , column, names, to, give, values, for)
SELECT list, of, column, names, of, compatible, column, types
FROM bigimportedtable
WHERE possibly you want a predicate or maybe not;
The answer from Quassnoi was the one I was looking for. Please observe that if new_table_1 doesn't exist yet the "INSERT INTO" statement has to be replaced with a "CREATE TABLE" statement.