Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
Postgres DB Insert data to a table based on another table using Common Table Expression
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!