0

I'm having an issue while inserting a data to postgres table..

Here is my query:

INSERT INTO products (product_id, user_id) 
SELECT id, (SELECT id FROM users WHERE c_id = _c_id) FROM product_badge WHERE comp_id = _comp_id;

Issue I'm receiving is

ERROR: more than one row returned by a subquery used as an expression CONTEXT

Thanks in advance

4
  • What are _c_id and _comp_id? What are you trying to achieve? You should give more context to your question, for example by providing sample data and expected results. Commented Feb 17, 2020 at 15:32
  • 2
    What part of the error do you not understand? Sample data and desired results would help figure out what to do. Commented Feb 17, 2020 at 15:32
  • Skip the subquery. Do a LEFT JOIN instead. Commented Feb 17, 2020 at 15:33
  • 1
    Before inserting all combination be sure of the functional impact and the business implications. The technically working solution doesn't mean that it is the right thing. Commented Feb 17, 2020 at 15:37

2 Answers 2

1

You can first the problem with limit:

INSERT INTO products (product_id, user_id) 
    SELECT id, (SELECT u.id FROM users u WHERE u.c_id = _c_id LIMIT 1) 
    FROM product_badge
    WHERE comp_id = _comp_id;

However, that is a work-around. Normally in this case, you might want all combinations, and that suggests a JOIN:

INSERT INTO products (product_id, user_id) 
    SELECT pb.id, u.id
    FROM product_badge pb CROSS JOIN
         users u
    WHERE pb.comp_id = _comp_id AND
          u.c_id = _c_id;
Sign up to request clarification or add additional context in comments.

2 Comments

This would add/take same user_id for each row im inserting?
@MateuszRek . . . The first would take an arbitrary matching user id, but probably the same one. The second would insert rows for all user ids.
0

MateuszRek,

As long as

SELECT id FROM product_badge inner join users WHERE c_id = _c_i

returns more than one row you will have a problem. Using a subquery as selected field implies the engine get the result as the value of that field. having more rows poses problem as the engine can pick a value

You can us limit to pick one value. However, even if that solves the technical part of the problem,it might leave a functional/business one because maybe something is missing, for example, for to choose that id. using limit doesnt garantee its the right value

Comments

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.