Multiple INSERT queries turned into one single query [duplicate] - sql

This question already has answers here:
Inserting multiple rows in a single SQL query? [duplicate]
(4 answers)
Closed 9 years ago.
I've searched through Stackoverflow and nothing answers my question properly.
My question is how do you turn multiple INSERT queries into 1 single insert query.
More specific; https://gist.github.com/gregariousjb/e73fdf1489acbbb63651 this one. That's the query I need to understand how to make into a single one.
Sample;
INSERT INTO `creature` (`guid`, `id`, ...)
VALUES (1, 2843, ...);
INSERT INTO `creature` (`guid`, `id`, ...)
VALUES (2, 7853, ...);
There's 1000 of these, that needs to be turned into a single one. I sincerely appreciate any help I can get on this.

If you are using Sql Server try the following
Insert into table (columns..)
Values(values1,value2,...),
(values1,value2,...),
(values1,value2,...),
(values1,value2,...)

In Mysql, do this (most popular databases have a similar syntax):
INSERT INTO mytable (col1, col2, col3, ...) VALUES
(1, 2843, 0, ...),
(2, 7853, 0, ...);
In most databases, you can do this:
INSERT INTO mytable (col1, col2, col3, ...)
SELECT 1, 2843, 0, ...
UNION ALL
SELECT 2, 7853, 0, ...;
In backward, behind-the-times databases, like Oracle, you must code this second option using the artificial single-rowed table DUAL:
INSERT INTO mytable (col1, col2, col3, ...)
SELECT 1, 2843, 0, ...
FRIM DUAL
UNION ALL
SELECT 2, 7853, 0, ...
FROM DUAL;

The closest is the shorthand version that requires the field list only once:
INSERT INTO `creature` ( <field list> ) VALUES
( <value list> ),
( <value list> ),
( <value list> )

Related

Update statement gives wrong result with subquery [duplicate]

This question already has answers here:
sql server 2008 management studio not checking the syntax of my query
(2 answers)
Closed 4 years ago.
I have the following query which gives no error when I used a non-existent column reference in the subquery. The column which I referred in the subquery is actually a column in the table being updated.
create table tbl1 (f1 bigint, f2 char(10), f3 integer);
insert into tbl1 values (1, 'aa', 0);
insert into tbl1 values (2, 'bb', 0);
insert into tbl1 values (3, 'cc', 0);
insert into tbl1 values (4, 'dd', 0);
create table temp_tbl (ref_num bigint);
insert into temp_tbl values (1);
insert into temp_tbl values (3);
update tbl1 set f2='ok' where f1 in (select f1 from temp_tbl);
-- 4 records updated
can anyone tell me why it is not giving any error? and records are updated irrespective of the condition.
I tried this in both Oracle and SQLserver. results are same
The sub-query's column reference goes to the outer table!
update tbl1 set f2='ok' where f1 in (select f1 from temp_tbl);
Is read as
update tbl1 set f2='ok' where f1 in (select tbl1.f1 from temp_tbl);
Qualify your columns:
update tbl1 set f2='ok' where f1 in (select temp_tbl.ref_num from temp_tbl);
This is happening because the values in a SELECT don't just have to be columns from the table you're selecting from, the sub-query is returning the value for f1 from the outer query, instead of a value from temp_tbl.
Consider if you re-wrote the UPDATE query to:
SELECT *
FROM tbl1
WHERE f1 IN (select f1 from temp_tbl);
The results returned would actually be:
When you're trying to reason about something like this (and as a generally good way of working to get queries right!), it's useful to write your UPDATE query in the form:
UPDATE T
SET F2 = 'ok'
FROM TBL1 T
WHERE T.f1 IN
(
SELECT F1
FROM temp_tbl
)
By writing it this way you can readily comment out the UPDATE and SET components of the query, replace them with a SELECT and see what the set of data the query will operate on is.

Insert Multiple Rows SQL Teradata

I am creating a volatile table and trying to insert rows to the table. I can upload one row like below...
create volatile table Example
(
ProductID VARCHAR(15),
Price DECIMAL (15,2)
)
on commit preserve rows;
et;
INSERT INTO Example
Values
('Steve',4);
However, when I try to upload multiple I get the error:
"Syntax error: expected something between ')' and ','."
INSERT INTO Example
Values
('Steve',4),
('James',8);
As Gordon said, Teradata doesn't support VALUES with multiple rows (and the UNION ALL will fail because of the missing FROM.
You can utilize a Multi Statement Request (MSR) instead:
INSERT INTO Example Values('Steve',4)
;INSERT INTO Example Values('James',8)
;
If it's a BTEQ job the Inserts are submitted as one block after the final semicolon (when there's a new command starting on the same line it's part of the MSR). In SQL Assistant or Studio you must submit it using F9 instead of F5.
I don't think Teradata supports the multiple row values syntax. Just use select:
INSERT INTO Example(ProductId, Price)
WITH dual as (SELECT 1 as x)
SELECT 'Steve' as ProductId, 4 as Price FROM dual UNION ALL
SELECT 'James' as ProductId, 8 as Price FROM dual;
CTE syntax (working):
insert into target_table1 (col1, col2)
with cte as (select 1 col1)
select 'value1', 'value2' from cte
union all
select 'value1a', 'value2a' from cte
;
CTE Syntax not working in Teradata
(error: expected something between ")" and the "insert" keyword)
with cte as (select 1 col1)
insert into target_table1 (col1, col2)
select 'value1', 'value2' from cte
union all
select 'value1a', 'value2a' from cte
;
I found a solution for this via RECURSIVE. It goes like this:-
INSERT INTO table (col1, col2)
with recursive table (col1, col2) as
(select 'val1','val2' from table) -- 1
select 'val1','val2' from table -- 2
union all select 'val3','val4' from table
union all select 'val5','val6' from table;
Data of line 1 does not get inserted (but you need this line). Starting from line 2, the data you enter for val1, val2 etc. gets inserted into the respective columns. Use as many UNION ALLs' as many rows you want to insert. Hope this helps :)
At least in our version of Teradata, we are not able to use an insert statement with a CTE. Instead, find a real table (preferably small in size) and do a top 1.
Insert Into OtherRealTable(x, y)
Select top 1
'x' as x,
'y' as y
FROM RealTable
create table dummy as (select '1' col1) with data;
INSERT INTO Student
(Name, Maths, Science, English)
SELECT 'Tilak', 90, 40, 60 from dummy union
SELECT 'Raj', 30, 20, 10 from dummy
;
yes you can try this.
INSERT INTO Student
SELECT (Name, Maths, Science, English) FROM JSON_Table
(ON (SELECT 1 id,cast('{"DataSet" : [
{"s":"m", "Name":"Tilak", "Maths":"90","Science":"40", "English":"60" },
{"s":"m", "Name":"Raj", "Maths":"30","Science":"20", "English":"10" }
]
}' AS json ) jsonCol)
USING rowexpr('$.DataSet[*]')
colexpr('[{"jsonpath":"$.s","type":"CHAR(1)"},{"jsonpath":"$.Name","type":"VARCHAR(30)"}, {"jsonpath":"$.Maths","type":"INTEGER"}, {"jsonpath":"$.Science","type":"INTEGER"}, {"jsonpath":"$.English","type":"INTEGER"}]')
) AS JT(id,State,Name, Maths, Science, English)

SQL: How to insert data into a table with column names

When inserting data into a SQL Server table, is it possible to specify which column you want to insert data to?
For a table with
I know you can have syntax like this:
INSERT INTO MyTable (Name, col4_on, col8_on, col9_on)
VALUES ('myName', 0, 1, 0)
But the above syntax becomes unwieldy when you have lots of columns, especially if they have binary data. It becomes hard to match up which 1 and 0 go with which column. I'm hoping there's a named-parameter like syntax (similar to what C# has) which looks like the following:
INSERT INTO MyTable
VALUES (Name: 'myName', col4_on: 0, col8_on: 1, col9_on: 0)
Thanks
You must specify the column names. However, there is one exception. If you INSERTing exactly the same number of columns as the target table has in the same order as they are in the table, use this syntax:
INSERT INTO MyTable
VALUES ('val1A', 'val4A', 'val8A')
Note that this is a fragile way of performing an INSERT, because if that table changes, or if the columns are ordered differently on a different system, the INSERT may fail, or worse-- it may put the wrong data in each column.
I've found that when I INSERT a lot of columns, I find the queries easier to read if I can group them somehow. If column names are long, I may put them on separate lines like so:
INSERT INTO MyTable
(
MyTable_VeryLongName_Col1,
MyTable_VeryLongName_Col4,
MyTable_VeryLongName_Col8,
-- etc.
)
SELECT
Very_Long_Value_1,
Very_Long_Value_4,
Very_Long_Value_8,
-- etc.
Or you can group 2 columns on a line, or put spaces on every 5, or comment every 10th line, etc. Whatever makes it easier to read.
If you find including column names onerous when INSERTing a lot of rows, then try chaining the data together:
INSERT INTO MyTable (col1, col4, col8)
VALUES ('val1A', 'val4A', 'val8A'),
('val1B', 'val4B', 'val8B'),
-- etc.
Or UNION them together:
INSERT INTO MyTable (col1, col4, col8)
SELECT 'val1A', 'val4A', 'val8A'
UNION ALL 'val1B', 'val4B', 'val8B'
UNION ALL ... -- etc.
Or, SELECT them from another table:
INSERT INTO MyTable (col1, col4, col8)
SELECT val1, va4, val8
FROM MyOtherTable
WHERE -- some condition is met
INSERT INTO MyTable (col1, col4, col8)
VALUES ('val1', 'val4', 'val8')
This statement will add values to the columns mentioned in your INSERT INTO statement, you can write the above query in the following formats it will not make any difference .
INSERT INTO MyTable (col8, col1, col4)
VALUES ('val8', 'val1', 'val4')
OR
INSERT INTO MyTable (col4, col8, col1)
VALUES ('val4', 'val8', 'val1')
to Add multiple rows at a time you can pass multiple rows at a time in you values clause something like this
INSERT INTO MyTable (col4, col8, col1)
VALUES ('val4', 'val8', 'val1'),
('val4', 'val8', 'val1'),
('val4', 'val8', 'val1'),
('val4', 'val8', 'val1')
The order of the values should match the order of the columns
mentioned in your INSERT INTO statement.
All above statement will have the same result.
keeping one thing in mind once you have mentioned a column you must provide a value for it
like this
INSERT INTO MyTable (col1, col4, col8)
VALUES ('val1', null, 'val8')
but you cannot do something like this
INSERT INTO MyTable (col1, col4, col8)
VALUES ('val1', 'val8')
I figured out a way around this but it's rather hacky and only works for tables which has columns with unique values:
INSERT INTO MyTable (Name)
VALUES ('myName')
UPDATE MyTable
SET col4_on=0, col8_on=1, col9_on=0
WHERE Name = 'myName'
This could be expanded into a multiple row insert as follows:
INSERT INTO MyTable (Name)
VALUES ('row1'), ('row2'), ('row3')
UPDATE MyTable SET col4_on=0, col8_on=1, col9_on=0 WHERE Name = 'row1'
UPDATE MyTable SET col4_on=1, col8_on=0, col9_on=0 WHERE Name = 'row2'
UPDATE MyTable SET col4_on=1, col8_on=1, col9_on=1 WHERE Name = 'row3'
No, there is no way to do specifically what you want. The closest thing you can do is to use the column creation order to avoid use the columns names on the insert command. As this:
If you have a table like
tableA ( id, name, phone )
You can insert values on it using
insert into tableA values ( 1, 'Name', '555-9999' );
But be carefull, you have to follow the exact order on the fields of your table, otherwise you can have an error and worst, put wrong data in wrong fields.
Nope you cannot do it, the only other alternative for you would be insert from select
insert into MyTable
select 'val1' as col1, 'val4' as col4, 'val8' as col8 --if any extra columns then just do "null as col10"
assuming the order is same in table

MySQL INSERT with multiple nested SELECTs

Is a query like this possible? MySQL gives me an Syntax error. Multiple insert-values with nested selects...
INSERT INTO pv_indices_fields (index_id, veld_id)
VALUES
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val1'),
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val2')
I've just tested the following (which works):
insert into test (id1, id2) values (1, (select max(id) from test2)), (2, (select max(id) from test2));
I imagine the problem is that you haven't got ()s around your selects as this query would not work without it.
When you have a subquery like that, it has to return one column and one row only. If your subqueries do return one row only, then you need parenthesis around them, as #Thor84no noticed.
If they return (or could return) more than row, try this instead:
INSERT INTO pv_indices_fields (index_id, veld_id)
SELECT '1', id
FROM pv_fields
WHERE col1='76'
AND col2 IN ('val1', 'val2')
or if your conditions are very different:
INSERT INTO pv_indices_fields (index_id, veld_id)
( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val1' )
UNION ALL
( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val2' )

sql query multiple record insertion

how can i insert multiple records using single sql statement
For SQL Server 2005 you could do the following:
INSERT INTO your_table (id, field_1, field_2)
SELECT 1, 'some-data-a', 'some-data-1'
UNION ALL
SELECT 2, 'some-data-b', 'some-data-2'
UNION ALL
SELECT 3, 'some-data-c', 'some-data-3'
UNION ALL
SELECT 4, 'some-data-d', 'some-data-4';
In most modern DBMSes, including SQL Server 2008 and MySQL 5, you could use a much neater syntax:
INSERT INTO your_table (id, field_1, field_2) VALUES
(1, 'some-data-a', 'some-data-1'),
(2, 'some-data-b', 'some-data-2'),
(3, 'some-data-c', 'some-data-3'),
(4, 'some-data-d', 'some-data-4');
Using MySQL:
INSERT INTO TABLE (col1, col2) VALUES
(val1a, val1b),
(val2a, val2b),
(valNa, valNb);
You should use table types and use bulk insert.
EDIT:
http://msdn.microsoft.com/en-us/library/bb510489.aspx
This can explain further on using either one. This works for SQL server, I am not so sure about other databases. Both are very useful for a lot of records to be inserted at one go.
You can insert multiple records from a subquery as well.
INSERT INTO TABLE (col1, col2) (select a,b from SUB)