1

Table name: myTable, where I need to update the values of A with Null from the same column

Group      Value
A            10
A            NULL
A            NULL
A            10
B            20
B            20
B            20
C            30  

Expected:

Group      Value
A            10
A            10
A            10
A            10
B            20
B            20
B            20
C            30

MY query:

Update myTable
Set myTable.Age = b.Age
FROM myTable b
WHERE A.Age is Null

I am getting relation doesn't exist.

What am I doing wrong?

1
  • I suggest to join these tables in where clause, otherwise it would result in cartesian product. Commented Oct 22, 2018 at 18:36

2 Answers 2

2

Try this query

UPDATE myTable SET Age = 
    (SELECT b.Age 
     FROM myTable b 
     WHERE b.Group = myTable.Group AND  b.Age IS NOT NULL
     LIMIT 1) 
WHERE Age IS NULL 
Sign up to request clarification or add additional context in comments.

2 Comments

my only question here is why LIMIT 1
@user2934524 Because in your table could be several rows for Group = A. For example table contains these rows (A, 10), (A, 20). So, LIMIT 1 choose only one row with Value=10.
1

I think a correlated subquery might be the way to go:

update myTable t
    set Age = (select t2.Age from mytable t2 where t2.name = t.name and t2.Age is not null)
    where t.Age is Null;

Note: This will generate an error if age is on more than one row of the original data for a given name.

If performance is an issue, you want an index on mytable(name, age).

Here is a db<>fiddle example.

3 Comments

I ran this and its been 10 mins and still running
IT completed after an hour but didnt update anything
@user2934524 . . . The code works. I provided an example.

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.