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 solved it with Python using the `psycopg2` package:

```
    cur.execute("SELECT ROUND(COUNT(id)*0.01,0)
                 FROM mytbl")
    nrows = str([int(d[0]) for d in cur.fetchall()][0])
    cur.execute("SELECT * 
                 FROM mytbl
                 WHERE var='value'
                 ORDER BY id, random() LIMIT (%s)",nrows)

```

Perhaps there is a more elegant solution using just SQL, or a more efficient one, but this does exactly what I'm looking for.