0

I'm trying to write sql statement in oracle 11g that will randomly select 5000 records from union of two different tables with same columns:

select * 
  from (
       select ename, job
       from emp1
       union all
       select ename, job
       from emp2
       order by dbms_random.value()
        )
where rownum <= 5000

And when run it, I get error ORA-01785: ORDER BY item must be the number of a SELECT-list expression. When I remove second table it works just fine. But, now I need to select randomly from two tables, first union all them, order them randomly and then select 5000 of them.

Or maybe there is some other approach with same result?

Tnx for help.

2
  • Hi Johnny, how important is the number 5000? Would it be ok if it is about 5000 records?
    – wolφi
    Commented Jun 6, 2013 at 18:43
  • It is not imortant...do you mean to use sample function?
    – Johnny CRO
    Commented Jun 7, 2013 at 11:55

1 Answer 1

3

Your ORDER BY applies only to the second part of the UNION ALL - you'll have to perform the UNION ALL first and then apply the ORDER BY:

select * 
  from (
    select * from (
       select ename, job
       from emp1
       union all
       select ename, job
       from emp2
    )
    order by dbms_random.value()
)
where rownum <= 5000
1
  • In pl-sql we have to give table name alias if you wanted to remove outer select clasue for same code, it would be select * from ( select ename, job from emp1 union all select ename, job from emp2 ) a order by dbms_random.value(), also upvoted. Commented May 21, 2020 at 6:04

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.