0

I want to delete multiple records from table at the same time.

Sample input:

{"INPUT":{"ID":"2200038,2200039,2200073,2200019"}}

Input will be provided from the application i.e.,

ID can be random - it gets changed based on requirements.

delete from mytable
where id = ....?

I want to delete multiple ID's coming from the input at the same time.

2
  • delete from yourtable where id IN (1,2,3) Commented Dec 20, 2018 at 9:09
  • Where will you be creating this query ? Commented Dec 20, 2018 at 9:21

3 Answers 3

3

To delete multiple rows at once with different IDs, one approach is to use IN:

DELETE FROM mytable 
WHERE ID IN (2200038,2200039,2200073,2200019)

Here's some documentation and further examples: http://www.postgresqltutorial.com/postgresql-in/

Sign up to request clarification or add additional context in comments.

2 Comments

i cannot hard code any id... it will get changed randomly
@adams I'm just demonstrating the principle in SQL - since you seemed to be talking about = , I thought maybe you didn't know about IN. How are you constructing your DELETE query? You've shown us some sample input data - where is that coming from? Is it in an application which must build a query? Or as an input parameter to some stored procedure? It appears to be some (poorly structured) JSON but apart from that I've got no context about it. If you want a more precise answer you'll have to give more precise details about your situation. I suggest you edit the question to provide more clarity.
1

You may extract the ids from your json string as an array and delete those using ANY operator

WITH t AS 
( 
  SELECT '{"INPUT":{"ID":"2200038,2200039,2200073,2200019"}}' AS input 
) 
DELETE FROM   mytable 
   WHERE  id = ANY ( SELECT unnest(
                          String_to_array(input::json->'INPUT'->>'ID',',')::int[]) 
                  FROM   t );

Demo

Here's a demo using a Bind variable for input in psql. Note that UNNEST was not needed here.

\set input '{"INPUT":{"ID":"2200038,2200039,2200073,2200019"}}'
knayak=# DELETE FROM  mytable WHERE
          id = ANY( String_to_array(:'input'::json->'INPUT'->>'ID',',')::int[] )
DELETE 2

Comments

0

Maybe some dynamic sql will help

EXEC SQL BEGIN DECLARE SECTION;
const char *stmt = "DELETE FROM tablename WHERE ID IN(?);";

EXEC SQL END DECLARE SECTION;

EXEC SQL PREPARE mystmt FROM :stmt;
inputdata varchar; -- remove unwanted parts of the string

EXEC SQL EXECUTE mystmt USING inputdata;

2 Comments

Nice, but unfortunately your code is for the wrong DBMS...check the tags on the question
Yikes, sorry dude! I updated my suggestion sans the string replacement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.