Question: I would like to select the top 1% of rows; however, I cannot use subqueries to do it. I.e., this won't work:

```
SELECT * FROM mytbl
WHERE var='value'
ORDER BY id,random()
LIMIT(SELECT (COUNT(*) * 0.01)::integer FROM mytbl)

```

How would I accomplish the same output without using a subquery with limit?

Answer: 
You can utilize [`PERCENT_RANK`](http://www.postgresql.org/docs/current/static/functions-window.html):

```
WITH cte(ID, var, pc) AS
(
  SELECT ID, var, PERCENT_RANK() OVER (ORDER BY random()) AS pc
  FROM mytbl
  WHERE var = 'value'
)
SELECT *
FROM cte
WHERE pc <= 0.01
ORDER BY id;

```

`**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/1ede2/3/0)**`
I don’t have your data, of course, but I have no trouble using a sub query in the `LIMIT` clause.

However, the sub query contains only the `count(*)` part and I then multiply the result by `0.01`:

```
SELECT * FROM mytbl
WHERE var='value'
ORDER BY id,random()
LIMIT(SELECT count(*) FROM mytbl)*0.01;

```