Insert into a specific row of a table - sql

I am trying to select the row in a table where the id = user and once I have that row I want to insert into the docId column the value docId. To do this I have tried this:
INSERT INTO (SELECT * FROM users WHERE (id='"+user+"')); (docId) VALUES ('"+docId+"')
but this does not work

I think you want:
update users
set docId = ?
where id = ?
Do not munge the query string with parameter values. These only cause unexpected syntax errors and make the code vulnerable to SQL injection. Learn to use parameters.

Try INSERT INTO TableNmae(SELECT * FROM users WHERE (id='value') and (docId) = ('value1'))

Related

PostgreSQL subqueries as values

I am trying to use a postgreSQL INSERT query with a subquery as parameter value. This is to find the corresponding user_id from an accompanying auth_token in user_info tabel first and then create a new entry in a different table with the corresponding user_id.
My query looks something like this
INSERT INTO user_movies(user_id, date, time, movie, rating)
VALUES ((SELECT user_id FROM user_info where auth_token = $1),$2,$3,$4,$5)
RETURNING *
I know that a query such as this will work with a single value
INSERT INTO user_movies(user_id)
SELECT user_id FROM user_info where auth_token = $1
RETURNING *
but how do I allow for multiples input values. Is this even possible in postgreSQL.
I am also using nodejs to run this query -> therefore the $ as placeholders.
To expand on my comment (it is probably a solution, IIUC): Easiest in this case would be to make the inner query return all the values. So, assuming columns from the inner query have the right names, you could just
INSERT INTO user_movies(user_id, date, time, movie, rating)
SELECT user_id,$2,$3,$4,$5 FROM user_info where auth_token = $1
RETURNING *
Note this form is also without VALUES, it uses a query instead.
Edited 20220424: a_horse_with_no_name removed the useless brackets around SELECT ... that appeared in my original version; thanks!
YOu could try uising where IN clause
INSERT INTO user_movies(user_id)
SELECT user_id
FROM user_info
WHERE auth_token IN ($1,$2,$3,$4,$5)
RETURNING *

How to combine these two Postgresql queries?

I want to insert into a first table, then update a second table with the returned (DB generated) UUID of the inserted row before finally returning the result of the insert.
The insert query looks like this:
INSERT INTO public.organisations ("name")
VALUES('StackOverflow')
RETURNING *
This will return a row with name, data and id. Data is an empty JSON and can be ignored, id is the UUID used below.
The update query looks like this, with <orgId> indicating the UUID generated and returned by the above insert and <userId> indicating a value passed in from code:
UPDATE public.users
SET id_organisation = <orgID>, last_modified_by = <userID>
WHERE id = <userID>;
Both of these queries work but I do not know how to string them together and return the output of the first query.
Is it possible to do this or would I be better just running two queries?
Use CTEs:
with i as (
INSERT INTO public.organisations ("name")
VALUES('StackOverflow')
RETURNING *
)
UPDATE public.users
SET id_organisation = (SELECT i.id FROM i LIMIT 1), last_modified_by = <userID>
WHERE id=<userID>;
Note that this uses a subquery with LIMIT -- this guarantees that at most one row is returned.
Here is a db<>fiddle illustrating that the syntax works.

Sql query to find records with column value is blank

I'm trying to find records with Column value is blank. as you can see in the table I have records with following values when I fire a Distinct query on the Column MOVE_STU.
now I can find all the record with column value related to (1,2,3,4 and 6) but I'm not able to find the records with Column Value related to (5). as there are Thousands of record in the table i'm not able to figure out how should I write query in order to get these records. Kindly help. Thanks in Advance. :)
Use trim and comparison with empty string to get records that contain only whitespaces:
SELECT *
FROM your_table
WHERE LTRIM(RTRIM(MOVE_STU)) = ''
Try something like this:
SELECT * FROM YourTable WHERE LTRIM(RTRIM(YourField)) = ''
This will give you all matches that are empty, or have only whitespace.
How about this ?
SELECT * FROM YourTable WHERE MOVE_STU = ''
SELECT * FROM YourTable WHERE ISNULL(MOVE_STU,'') = ''
You can try this:
If your datatype is int then you have to change in varchar
ALTER TABLE [tbl_name] ALTER COLUMN [MOVE_STU] [VARCHAR(50)];
then run the query:
SELECT * FROM [tbl_name] WHERE MOVE_STU IS NULL;

Oracle SQL, SELECT clause using &input

I have an quite simple query
SELECT id FROM table where ID in &data
When I run this SQL I am prompted to type in some values to &data.
I would like to be able to select several id's using this. i.e. &data = "11,12,13"
but then I get an error ORA-00933.
Ive tried with:
11,12,13
'11,12,13' -> ORA-01722
'11','12','13'
Any ideas?
Try to add ():
SELECT id FROM table where ID in (&data)
the input values should be '11,12,13'
or try to add (''):
SELECT id FROM table where ID in (&data)
the input values should be 11,12,13

Using SQl Server CE; Possible to Insert Only If Not Exists?

I'm trying to verify a simple 1 field table to determine if a record exists before inserting a duplicate.
if not exists (select * from url where url = ...)
insert into url...
Can someone Help?
Your code example will run in the full version of SQL, or you could rearrange to the following:
insert into url
select 'myvalue'
where not exists (select * from url where url = 'myvalue')
Just reverse it and add the condition as a where clause predicate
Insert Into Table ....
Where Not Exists
(Select * From table where ...)
... But your basic problem sounds like it might be better solved by putting a alternate key (unique) constraint on the insert table, referencing the url column (I assume Sql CE does Referential Integrity (RI) constraints?)
You might want to read this thread. performing-insert-or-update-upsert-on-sql-server-compact-edition
In a nutshell a sqlce specific solution (using SqlCeResultSet) will provide the maximum performance.
Use an Outer Join
Insert into X(...)
select blah, blah, blah
from
table t left outer join
X on t.id=x.id
where
x.id is null
Granted, this is way past the posting date, but since I've not seen this answered elsewhere in my quick Google search, I thought I'd share how I solved this with SQL CE so others searching might find an answer.
-- Update existing record's value
UPDATE myTable SET myValue = 'Hello World' WHERE keyField = 'MyKey';
-- Insert new record if existing record doesn't exist`
INSERT INTO myTable (keyField, myValue)
SELECT I.keyField, I.myValue
FROM (
SELECT 'Hello World' AS myValue, 'MyKey' AS keyField
) I
LEFT JOIN myTable T ON I.keyField = T.keyField
WHERE T.keyField IS NULL;
You are on the right path with IF NOT EXISTS. It is better to use IF NOT EXISTS() or IF EXISTS() than a Sub Query because SQL Server will stop scanning rows in the table when it finds the first instance that matches the EXISTS() condition your looking for. With a Sub Query written in the examples above it will scan the whole table.
A Classic example is the Insert or Update aka the SAVE.
IF EXISTS(SELECT * FROM Table_A WHERE Column_1 = #Parameter)
BEGIN
--Update Statement here.
END
ELSE
BEGIN
--Insert Statement here.
END
What about something like this:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF ##ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
Source