3
Table A
-------
id married salaried
1  true    true
2  false   true

Table B
-------
user-id id_a 
45      1
50      2
55      1

Suppose I want to update user with id 55 as not married and not salaried ​into Table B

Steps:

  • Check if there is an entry in Table A having married false and salaried false
  • If yes will return that id from Table A and add a row in Table B with the returned id
  • If no will add a new row in Table A and add a row in Table B using that inserted row id

I need to achieve this using Common Table Expression What I have tried is shown below:

WITH cte as
(select id from A
where
married = false and
salaried = false )
INSERT INTO A(married, salaried)
SELECT  false, false
WHERE NOT EXISTS (select id from cte)

This much part works, I tried to add the entries into Table B as shown below, but it is not working

WITH cte1 as
(select id from A
where
married = false and
salaried = false ),
cte2 as
(INSERT INTO A(married, salaried)
SELECT  false, false
WHERE NOT EXISTS (select id from cte1)
RETURNING id)
UPDATE A set id_a = coalesce(select id from cte1, select id from cte2)
where id = 55

Expected output is as shown below

Table A
-------
id married salaried
1  true    true
2  false   true
3  false   false

Table B
-------
user-id id_a 
45      1
50      2
55      3

Any help is appreciated Thanks in advance

1 Answer 1

3

This elaborates on your approach:

WITH cte1 as (
      select id
      from A
      where not married and not salaried
     ),
     cte2 as (
      INSERT INTO A (married, salaried)
          SELECT false, false
          WHERE NOT EXISTS (select id from cte1)
          RETURNING id
     )
update B
    set id_a = coalesce((select id from cte1), (select id from cte2))
    where id = 55;

I might suggest, though, that you put a unique constraint on table A and then use on conflict for the insertion.

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

1 Comment

it's really nice answer and I learn a lot from this. Thanks a lot.

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.