0

How to retrieve 50% of records in ANSI SQL. In MS SQL Server we have Top with percent. But I want to get in Oracle and PostgreSQL.

GMB
  • 195,563
  • 23
  • 62
  • 110
shoyab
  • 3
  • 5

1 Answers1

3

In Postgres, one option uses percent_rank(). Assuming that id is your ordering column:

select *
from (select t.*, percent_rank() over(order by id) prn from mytable t) t
where prn <= 0.5

This would also work in Oracle, but for that database I would prefer a fetch clause:

select *
from mytable t
order by id
fetch first 50 percent rows only
GMB
  • 195,563
  • 23
  • 62
  • 110