Rasmus Puls
Rasmus Puls

Reputation: 3229

postgresSQL insert multiple rows, of id returned from select queries

I have a complex query that join multiple tables and return many member ids (line 5)

For each memberId I want to insert a memberSegment record, consisting of the memberId (new for each insert) and a segmentId (always the same/not list)

INSERT INTO db."memberSegment"(
    "memberId",
    "segmentId")
VALUES (
    (select table."memberId" complex query returns many ids ),
    (SELECT id FROM db.segment where "idName" = 'due-for-360')
);

From reading on SO this is how I interpret it should look, but I am getting following error message, making me think that my query is not expecting a list in either values.

ERROR: more than one row returned by a subquery used as an expression SQL state: 21000

Each query on its' own returns following:

enter image description here

Upvotes: 1

Views: 2086

Answers (2)

Zendem
Zendem

Reputation: 528

For example:

CREATE OR REPLACE FUNCTION f_get(ikey text)
  returns integer
  AS
$func$
DECLARE 
  l_id integer;
BEGIN
  LOCK TABLE foo IN SHARE ROW EXCLUSIVE MODE;
  INSERT INTO foo (type)
  SELECT ikey
   WHERE NOT EXISTS (
     SELECT * FROM foo WHERE type=ikey
   )
   returning id into l_id; --< store the returned ID in local variable
   return l_id; --< return this variable
END
$func$ LANGUAGE plpgsql;

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522712

You might be able to phrase this as an INSERT INTO ... SELECT:

INSERT INTO db."memberSegment" (memberId, segmentId)
SELECT
    memberId,
    (SELECT id FROM db.segment WHERE idName = 'due-for-360')
FROM table -- (complex query returns many ids );

This would at the very least get around your current error, which is stemming from the query returning more than one id. The only possible issue would be if the subquery on db.segment also returns more than a single value. If it does not, then the above should work. If it does return more than one value, then your logic needs to be reconsidered.

Upvotes: 2

Related Questions