Insert multiple rows into a table with a single statement - sql

Looking to insert 500 rows into many-to-many table (sample_tag).
Aiming to have 500 new records created in sample_tag linking the first 500 rows from sample to associated tag_id in the tag table.
The following code seems to make sense, but triggers an error because the nested SELECT statement returns more than one row:
INSERT INTO sample_tag (sample_id, tag_id)
VALUES ((SELECT sample_id FROM sample WHERE sample_id <= 500), 1)
What could be the correct SQL to accomplish this insert for multiple rows?

You can have multiple inserts by not using VALUES keyword. You need to specify same number of columns on your source table.
INSERT INTO sample_tag (sample_id, tag_id)
SELECT sample_id, tag_id from sample where sample_id<=500

Related

INSERT OR REPLACE multiple rows, but there is no unique or primary keys

Hi I'm running into the following problem on SQlite3
I have a simple table
CREATE TABLE TestTable (id INT, cnt INT);
There are some rows already in the table.
I have some data I want to be inserted into the table: {(id0, cnt0), (id1, cnt1)...}
I want to insert data into the table, on id conflict, update TestTable.cnt = TestTable.cnt + value.cnt
(values.cnt is cnt0, cnt1 ... basically my data to be inserted)
*** But the problem is, there is no primary or unique constraint on id, and I am not allowed to change it!
What I currently have :
In my program I loop through all the values
UPDATE TestTABLE SET count = count + value.cnt WHERE id = value.id;
if (sqlite3_changes() == 0)
INSERT INTO MyTable (id, cnt) values (value.id, value.cnt);
But the problem is, with a very large dataset, doing 2 queries for each data entry takes too long. I'm trying to bundle multiple entries together into one call.
Please let me know if you have questions about my description, thank you for helping!
If you are able to create temporary tables, then do the following. Although I don't show it here, I suggest wrapping all this in a transaction. This technique will likely increase efficiency even if you are also able to add a temporary unique index. (In that case you could use an UPSERT with source data in the temporary table.)
CREATE TEMP TABLE data(id INT, cnt INT);
Now insert the new data into the temporary table, whether by using the host-language data libraries or crafting an insert statement similar to
INSERT INTO data (id, cnt)
VALUES (1, 100),
(2, 200),
(5, 400),
(7, 500);
Now update all existing rows using the single UPDATE statement. SQLite does not have a convenient syntax for joining tables and/or providing a source query for an UPDATE statement. However, one can use nested statement to provide similar convenience:
UPDATE TestTable AS tt
SET cnt = cnt + ifnull((SELECT cnt FROM data WHERE data.id == tt.id), 0)
WHERE tt.id IN (SELECT id FROM data);
Note that the two nested queries are independent of each other. In fact, one could eliminate the WHERE clause altogether and get the same results for this simple case. The WHERE clause is simply to make it more efficient, only attempting to update matching id's. The other subquery in the SET clause also specifies a match on id, but alone it would still allow updates of rows that don't have a match, defaulting to a null value and being converted to 0 (by isnull() function) for a no-op. By the way, without the isnull() function, the sum would result in null and would overwrite non-null values.
Finally, insert only rows with non-existing id values:
INSERT INTO TestTable (id, cnt)
SELECT data.id, data.cnt
FROM data LEFT JOIN TestTable
ON data.id == TestTable.id
WHERE TestTable.id IS NULL;

How to add more rows to an existing DB Table

I'm currently updating an existing DB table.
The Table has 14924 rows, I'm trying to insert new data which is requiring 15000 rows.
When running my Query, I'm getting this error message:
There are fewer columns in the INSERT statement than values specified
in the VALUES clause. The number of values in the VALUES clause must
match the number of columns specified in the INSERT statement.
Is there a way to add the additional 76 rows as needed?
I'm using MSSMS (Microsoft SQL Server Management Studio)
Query I'm running:
Insert INTO [survey].[dbo].[uid_table] (UID)
VALUES ('F32975648JX2','F32975681JX2',..+14998 more)
Should I clear the Column first by setting to NULL
What I'm trying to do is add all the VALUES to the UID column
My Columns are currently set as is:
UID | Email | Name | Title | Company | Address1 | Address2 | DateCreated |
All columns I have set to NULL except for UID, which already contains Values like above. Just need to replace the old values with the new ones. BUt getting error stated above
For inserting more than one value into a column you need to make the Insert statement in this format
Insert INTO [survey].[dbo].[uid_table] (UID)
VALUES ('F32975648JX2'),
('F32975681JX2'),
..+14998 more)
Also note that, The maximum number of rows that can be constructed by inserting rows directly in the VALUES list is 1000. So you have to break the INSERT statement into 1000 rows per INSERT
To insert more than 1000 rows, use one of the following methods
Create multiple INSERT statements
Use a derived table
Bulk import the data by using the bcp utility or the BULK INSERT
statement
Derived table approach
Insert INTO [survey].[dbo].[uid_table] (UID)
select 'F32975648JX2'
Union All
Select 'F32975681JX2',
Union All
..+14998 more)
your problem is in your INSERT statment
An example is
INSERT INTO table (col1, col2, col3,...)
VALUES(valCol1, valcol2, valcol3...)
Ensure that the number of columns (col1, col2, col3...) is the same number that VALUES (valCol1, valcol2, valcol3...) 3 columns and 3 values in this case

Insert row to database based on form values not currently in database

I am using Access 2013 and I am trying to insert rows to a table but I don't want any duplicates. Basically if not exists in table enter the data to table. I have tried to using 'Not Exists' and 'Not in' and currently it still does not insert to table. Here is my code if I remove the where condition then it inserts to table but If I enter same record it duplicates. Here is my code:
INSERT INTO [UB-04s] ( consumer_id, prov_id, total_charges, [non-covered_chrgs], patient_name )
VALUES ([Forms]![frmHospitalEOR]![client_ID], [Forms]![frmHospitalEOR]![ID], Forms![frmHospitalEOR].[frmItemizedStmtTotals].Form.[TOTAL BILLED], Forms![frmHospitalEOR].[frmItemizedStmtTotals].Form.[TOTAL BILLED], [Forms]![frmHospitalEOR]![patient_name])
WHERE [Forms]![frmHospitalEOR]![ID]
NOT IN (SELECT DISTINCT prov_id FROM [UB-04s]);
You cannot use WHERE in this kind of SQL:
INSERT INTO tablename (fieldname) VALUES ('value');
You can add a constraint to the database, like a unique index, then the insert will fail with an error message. It is possible to have multiple NULL values for several rows, the unique index makes sure that rows with values are unique.
To avoid these kind of error messages you can build a procedure or use code to check data first, and then perform some action - like do the insert or cancel.
This select could be used to check data:
SELECT COUNT(*) FROM [UB-04s] WHERE prov_id = [Forms]![frmHospitalEOR]![ID]
It will return number of rows with the spesific value, if it is 0 then you are redy to run the insert.

What is the fastest way to insert 1 mln+ records in DB2 table?

In C# I have 1mln+ records which are necessary to insert into DB2 table.
What is the fastest way to insert 1 mln+ records in DB2 table?
I've check several way and the fastest is by 1000 rows basing on the following request:
INSERT INTO tbl (id, rel) values (1, 2), (2,3),...
Are the any other ideas?
Try wth something like that for 1000 records:
INSERT INTO table
SELECT
cast (RAND()*50000 as numeric(6)) AS id,
cast (RAND() as varchar(30)) AS rel,
FROM qsys2/COLUMNS
fetch first 1000 rows only
change table and the field nature/length in relation with you table.
I assumed with that
cast (RAND()*50000 as numeric(6)) AS id
that id is numeric 6 byte
with the last line you limit 1000 rows insert

Is there a way i can do multiple inserts into one table using a condition?

Is there a way i can do multiple inserts into one table using a condition?
i have a list of subscribers in tbl_subscribers. i have an update on productX so i would like everyone who is subscribes to productX to get a notification. The user_notification table is id PK, user_id, notification_id. The two values i need is product_id (productX) which allows me to find a list of subscribers in tbl_subscribers and the notification_id to insert into the user_notification table.
How can i do this insert using one query? I see you can do a select statement in sqlite http://www.sqlite.org/lang_insert.html but i cannot wrap my head around how i may do this nor seen an example.
I believe you're looking from INSERT SELECT as outlined here:
http://www.1keydata.com/sql/sqlinsert.html
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 "column3", "column4", ... FROM "table2"
insert into user_notification(user_id, notification_id)
select s.user_id, #notification_id
from tbl_subscriber s
where s.product_id = #productX