0
update testdata.test
   set abcd = (select abc 
                 from DATA1
                order by random()
                limit 1
              ) 

Doing this only makes one random entry from table DATA1 is getting populated in all the rows of TEST table.

What I need is - > to generate each row with random entry from DATA 1 table to TEST table

5
  • So could a given random value abc appear more than once in the result set? Commented Aug 4, 2017 at 1:59
  • DATA1 always has more rows then test?.. Commented Aug 4, 2017 at 6:02
  • @Tim Biegelesian yes it can appear Commented Aug 4, 2017 at 6:10
  • @Vao Tsun DATA1 has less rows than test data..but it doesn't matter I just want populate random data from DATA1 to test ..so even if there are 4 rows in DATA1 these must appear randomly in TEST table with how much ever the test columns is filled Commented Aug 4, 2017 at 6:13
  • Possible duplicate of Populate random data from another table Commented Aug 7, 2017 at 1:27

1 Answer 1

2

Reference the outer table from the subquery so that it becomes a correlated subquery. Then it has to be executed for every row:

UPDATE testdata.test
SET abcd = (SELECT CASE WHEN test.abcd IS NOT DISTINCT FROM test.abcd
                        THEN abc 
                   END
            FROM data1
            ORDER BY random()
            LIMIT 1
           );
Sign up to request clarification or add additional context in comments.

4 Comments

I get an error at distinct (select case when ipreal is not distinct) in postgresql. and I tried using condition instead of distinct WHEN test.abcd <> test.abcd THEN abc -> Query executes but NO Updation
sorry about that .. ERROR - >Invalid operation: syntax error at or near "DISTINCT" Position: 70; SET ipreal = (SELECT CASE WHEN ipreal IS NOT DISTINCT FROM ipreal
You must be using something else than plain PostgreSQL then, because I ran the statement above and did not get such an error.
You are kidding, right? 8.0.2? But even this ancient version (install at least the latest point release!) had the IS DISTINCT FROM operator.

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.