0

I'm trying to do a query on Postgres but it's not working. I'd like to create an insert query with 2 select:

Example :

INSERT INTO table1 (id_1, id_2)
SELECT id from table_2 where code='01',
SELECT id from table_2 where code='02';

I don't find the good syntax for this.

2 Answers 2

1

I believe below query will works for your use case

INSERT INTO stats(totalProduct, totalCustomer, totalOrder)
VALUES(
    (SELECT COUNT(*) FROM products),
    (SELECT COUNT(*) FROM customers),
    (SELECT COUNT(*) FROM orders)
);

you can changes query accordingly

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

Comments

0

You can add one more SELECT to achieve this

INSERT INTO table_1 (id_1, id_2)
SELECT 
    (SELECT id FROM table_2 WHERE code = '01') AS Id_1,
    (SELECT id FROM table_2 WHERE code = '02') AS Id_2;

Or you may try with CASE expression:

INSERT INTO table1 (id_1, id_2)
SELECT MAX(CASE WHEN code = '01' THEN id ELSE 0 END) AS Id_1,
       MAX(CASE WHEN code = '02' THEN id ELSE 0 END) AS Id_2
FROM table_2

Please refer to the working fiddle on db<>fiddle

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.