5

I'm using PostgreSQL 11. I want to conditionally insert values into a table while having the result of the insertion include a null for each row of the input which did not result in an insertion.

For example

CREATE TABLE all_sums (sum INTEGER);
SELECT
 CASE WHEN a_sum IS NULL THEN null
 ELSE (SELECT sum FROM (INSERT INTO sums (sum) VALUES (sum) RETURNING sum))
 END
FROM
 (SELECT a + b FROM (VALUES (1, null), (null, 2), (2, 3)) AS row (a, b))
AS a_sum;

should result in the table all_sums looking like:

all_sums: sum
 ------
 5
 (1 row)

but the output of the query should be:

 null
 null
 5
------
(3 rows)

This example fails due to a syntax error:

ERROR: syntax error at or near "INTO"

Is there any way to achieve the desired query output?


(For context: My reason for doing this is because there are further queries which rely on knowing whether the insertion occurred for a particular row.

This is part of an effort to insert some data more efficiently from a file by transposing my queries from one per row to one per column. I'm not looking for other tips in improving insert speed though and if it's not possible I'm happy to call it a day at this point.)

Colin 't Hart
9,51015 gold badges37 silver badges44 bronze badges
asked Mar 31, 2020 at 7:10
0

1 Answer 1

4

I would simply separate the query logic and the insert logic:

with vals (a,b) as (
 VALUES (1, null), (null, 2), (2, 3)
), new_rows as (
 insert into all_sums (sum)
 select a + b
 from vals
 where a + b is not null
)
select a + b
from vals;

Online example

answered Mar 31, 2020 at 7:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.