SQLite : insert multiple value (select from) with insert specified value - sql

i'm trying to make sqlite query that can insert multiple values , here's my query that i try :
insert into table1(idy_table1,idx_table1)
values ('1', //specified value insert to idy_table1
(select id_table2 from table2)) //insert value from select id_table2
i'm having some trouble, it just only insert one value,
and my question is how to make a proper query? so i can make it work.

The VALUES clause always adds one row.
(Except when you're using multiple tuples, but this does not work with queries.)
The easiest way to add multiple rows from a query is to use the SELECT form of the INSERT statement:
INSERT INTO Table1(idy_table1, idx_table1)
SELECT '1', id_table2 FROM table2;

Related

Trying to insert values into a table where some values will be select statements whereas others will be hardcoded

My select into query would start like this:
insert into camrule (HCHARGECODE, htenant, dtfrom, dtto, IESTIMATETYPE, destimated, imaxpermo)
My hchargecode would be a hardcoded value of 174, my htenant would be based on a select statment (ex. select htenant from tableX), and so on. How can I hardcode the columns and have the other values from the select statments added to my camrule table?
Also, this is for multiple rows, not just a single row to be inserted.
I've tried creating a temp table with the hardcoded values, but am getting an error. I was hoping I could insert the columns from this temp table into my camrule table.
error message
Use the Values keyword to get this done...
insert into camrule (HCHARGECODE, htenant, dtfrom, dtto, IESTIMATETYPE, destimated, imaxpermo)
values(174,(select htenant from tableX), and so on...
This way allows you to select values from different tables, as opposed to just adding hard-coded columns to a Select statement from a single source table.
You can do as simple as:
insert into camrule (
HCHARGECODE, htenant, dtfrom, dtto,
IESTIMATETYPE, destimated, imaxpermo
)
select
174, htenant, dtfrom, dtto,
IESTIMATETYPE, destimated, imaxpermo
from tableX

need to combine 3 sql-statement into 1

I have 3 SQL-Statements that I would like to combine into just one so I dont have to make multiple requests to my database from my programm (java).
My DB is PostgreSQL 9.4
First one creates a new user in umgmt_users
INSERT INTO umgmt_users ("user") VALUES ('test1')
Second one gets the id of that user (db is postgres and id data type is serial, so it get assigned automatically with me/the programm not knowing what id the user will get
SELECT umgmt_users.id
FROM umgmt_users
WHERE umgmt_users.user = 'test1'
Thrird is to add the just created user with his id (which I need the second statement for) and some other values into a different table
INSERT INTO
umgmt_user_oe_fac_role ("user_id", "oe_id", "fac_id", "role_id")
VALUES ('ID OF USER test1 created in first statement', '1', '2', '1');
Is there a way to get all three Statements into one?
create user
look up the ID he got assigned
insert his ID + other values into a different table
I'm not that good at SQL, I tried to put brackets around the select and put it into the insert & also looked at UNION and WITH but can not get it to work...
EDIT: Ended up using this solution from a_horse_with_no_name
with new_user as (
INSERT INTO umgmt_users ("user") VALUES ('test1')
returning id
)
INSERT INTO umgmt_user_oe_fac_role (user_id, oe_id, fac_id, role_id)
SELECT id, 1, 2, 1
FROM new_user;
All you need is two inserts:
INSERT INTO umgmt_users ("user") VALUES ('test1');
INSERT INTO umgmt_user_oe_fac_role (user_id, oe_id, fac_id, role_id)
VALUES (lastval(), 1, 2, 1);
In order for lastval() to work correctly there must be no other statement between the two inserts and the have to be run in a single transaction (so autocommit needs to be turned off)
Alternatively you can use a data modifying CTE which is then executed as a single statement:
with new_user as (
INSERT INTO umgmt_users ("user") VALUES ('test1')
returning id
)
INSERT INTO umgmt_user_oe_fac_role (user_id, oe_id, fac_id, role_id)
SELECT id, 1, 2, 1
FROM new_user;
Please don't put numbers in single quotes.
The answer to this is : It's impossible to combine these into a single plain vanilla ANSI SQL statement.
The first and third ones talk about two different tables altogether.
The second one is a Select Statement which is a different type of statement from the other two.

SELECT * FROM NEW TABLE equivalent in Postgres

In DB2 I can do a command that looks like this to retrieve information from the inserted row:
SELECT *
FROM NEW TABLE (
INSERT INTO phone_book
VALUES ( 'Peter Doe','555-2323' )
) AS t
How do I do that in Postgres?
There are way to retrieve a sequence, but I need to retrieve arbitrary columns.
My desire to merge a select with the insert is for performance reasons. This way I only need to execute one statement to insert values and select values from the insert. The values that are inserted come from a subselect rather than a values clause. I only need to insert 1 row.
That sample code was lifted from Wikipedia Insert Article
A plain INSERT ... RETURNING ... does the job and delivers best performance.
A CTE is not necessary.
INSERT INTO phone_book (name, number)
VALUES ( 'Peter Doe','555-2323' )
RETURNING * -- or just phonebook_id, if that's all you need
Aside: In most cases it's advisable to add a target list.
The Wikipedia page you quoted already has the same advice:
Using an INSERT statement with RETURNING clause for PostgreSQL (since
8.2). The returned list is identical to the result of a SELECT.
PostgreSQL supports this kind of behavior through a returning clause in a common table expression. You generally shouldn't assume that something like this will improve performance simply because you're executing one statement instead of two. Use EXPLAIN to measure performance.
create table test (
test_id serial primary key,
col1 integer
);
with inserted_rows as (
insert into test (c1) values (3)
returning *
)
select * from inserted_rows;
test_id col1
--
1 3
Docs

Insert multiple rows into single column

I'm new to SQL, (using SQL 2008 R2) and I am having trouble inserting multiple rows into a single column.
I have a table named Data and this is what I am trying
INSERT INTO Data ( Col1 ) VALUES
('Hello', 'World')
That code was taken from this question, but it, like many other examples I have found on the web uses 2 columns, I just want to use 1. What am I doing wrong?
Thanks
To insert into only one column, use only one piece of data:
INSERT INTO Data ( Col1 ) VALUES
('Hello World');
Alternatively, to insert multiple records, separate the inserts:
INSERT INTO Data ( Col1 ) VALUES
('Hello'),
('World');
to insert values for a particular column with other columns remain same:-
INSERT INTO `table_name`(col1,col2,col3)
VALUES (1,'val1',0),(1,'val2',0),(1,'val3',0)
I believe this should work for inserting multiple rows:
INSERT INTO Data ( Col1 ) VALUES
('Hello'), ('World'),...
Another way to do this is with union:
INSERT INTO Data ( Col1 )
select 'hello'
union
select 'world'
If your DBMS supports the notation, you need a separate set of parentheses for each row:
INSERT INTO Data(Col1) VALUES ('Hello'), ('World');
The cross-referenced question shows examples for inserting into two columns.
Alternatively, every SQL DBMS supports the notation using separate statements, one for each row to be inserted:
INSERT INTO Data (Col1) VALUES ('Hello');
INSERT INTO Data (Col1) VALUES ('World');
INSERT INTO Data ( Col1 ) VALUES ('Hello'), ('World')
In that code you are inserting two column value.
You can try this
INSERT INTO Data ( Col1 ) VALUES ('Hello'),
INSERT INTO Data ( Col1 ) VALUES ('World')
Kindly ensure, the other columns are not constrained to accept Not null values, hence while creating columns in table just ignore "Not Null" syntax. eg
Create Table Table_Name(
col1 DataType,
col2 DataType);
You can then insert multiple row values in any of the columns you want to.
For instance:
Insert Into TableName(columnname)
values
(x),
(y),
(z);
and so on…
Hope this helps.
INSERT INTO hr.employees (location_id) VALUE (1000) WHERE first_name LIKE '%D%';
let me know if there is any problem in this statement.

Does DB2 have an "insert or update" statement?

From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.
My code now does a select and if no result is returned it does an insert. I really don't like this code since it exposes me to concurrency issues when running in a multi-threaded environment.
What I would like to do is to put this logic in DB2 instead of in my Java code.
Does DB2 have an insert-or-update statement? Or anything like it that I can use?
For example:
insertupdate into mytable values ('myid')
Another way of doing it would probably be to always do the insert and catch "SQL-code -803 primary key already exists", but I would like to avoid that if possible.
Yes, DB2 has the MERGE statement, which will do an UPSERT (update or insert).
MERGE INTO target_table USING source_table ON match-condition
{WHEN [NOT] MATCHED
THEN [UPDATE SET ...|DELETE|INSERT VALUES ....|SIGNAL ...]}
[ELSE IGNORE]
See:
http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0010873.htm
https://www.ibm.com/support/knowledgecenter/en/SS6NHC/com.ibm.swg.im.dashdb.sql.ref.doc/doc/r0010873.html
https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/merge?lang=en
I found this thread because I really needed a one-liner for DB2 INSERT OR UPDATE.
The following syntax seems to work, without requiring a separate temp table.
It works by using VALUES() to create a table structure . The SELECT * seems surplus IMHO but without it I get syntax errors.
MERGE INTO mytable AS mt USING (
SELECT * FROM TABLE (
VALUES
(123, 'text')
)
) AS vt(id, val) ON (mt.id = vt.id)
WHEN MATCHED THEN
UPDATE SET val = vt.val
WHEN NOT MATCHED THEN
INSERT (id, val) VALUES (vt.id, vt.val)
;
if you have to insert more than one row, the VALUES part can be repeated without having to duplicate the rest.
VALUES
(123, 'text'),
(456, 'more')
The result is a single statement that can INSERT OR UPDATE one or many rows presumably as an atomic operation.
This response is to hopefully fully answer the query MrSimpleMind had in use-update-and-insert-in-same-query and to provide a working simple example of the DB2 MERGE statement with a scenario of inserting AND updating in one go (record with ID 2 is updated and record ID 3 inserted).
CREATE TABLE STAGE.TEST_TAB ( ID INTEGER, DATE DATE, STATUS VARCHAR(10) );
COMMIT;
INSERT INTO TEST_TAB VALUES (1, '2013-04-14', NULL), (2, '2013-04-15', NULL); COMMIT;
MERGE INTO TEST_TAB T USING (
SELECT
3 NEW_ID,
CURRENT_DATE NEW_DATE,
'NEW' NEW_STATUS
FROM
SYSIBM.DUAL
UNION ALL
SELECT
2 NEW_ID,
NULL NEW_DATE,
'OLD' NEW_STATUS
FROM
SYSIBM.DUAL
) AS S
ON
S.NEW_ID = T.ID
WHEN MATCHED THEN
UPDATE SET
(T.STATUS) = (S.NEW_STATUS)
WHEN NOT MATCHED THEN
INSERT
(T.ID, T.DATE, T.STATUS) VALUES (S.NEW_ID, S.NEW_DATE, S.NEW_STATUS);
COMMIT;
Another way is to execute this 2 queries. It's simpler than create a MERGE statement:
update TABLE_NAME set FIELD_NAME=xxxxx where MyID=XXX;
INSERT INTO TABLE_NAME (MyField1,MyField2) values (xxx,xxxxx)
WHERE NOT EXISTS(select 1 from TABLE_NAME where MyId=xxxx);
The first query just updateS the field you need, if the MyId exists.
The second insertS the row into db if MyId does not exist.
The result is that only one of the queries is executed in your db.
I started with hibernate project where hibernate allows you to saveOrUpdate().
I converted that project into JDBC project the problem was with save and update.
I wanted to save and update at the same time using JDBC.
So, I did some research and I came accross ON DUPLICATE KEY UPDATE :
String sql="Insert into tblstudent (firstName,lastName,gender) values (?,?,?)
ON DUPLICATE KEY UPDATE
firstName= VALUES(firstName),
lastName= VALUES(lastName),
gender= VALUES(gender)";
The issue with the above code was that it updated primary key twice which is true as
per mysql documentation:
The affected rows is just a return code. 1 row means you inserted, 2 means you updated, 0 means nothing happend.
I introduced id and increment it to 1. Now I was incrementing the value of id and not mysql.
String sql="Insert into tblstudent (id,firstName,lastName,gender) values (?,?,?)
ON DUPLICATE KEY UPDATE
id=id+1,
firstName= VALUES(firstName),
lastName= VALUES(lastName),
gender= VALUES(gender)";
The above code worked for me for both insert and update.
Hope it works for you as well.