0

I'm using psycopg2 in a python script:

  conn = psycopg2.connect(......)
  cur = conn.cursor()
  cur.execute("select * from table1")
  rows = cur.fetchall()
  for a1 in rows: # how to shuffle them?

I want the rows to be in a different order each time I retrieve them. How can I do that?

update:

the amount of rows is around 50.000

Kurama
  • 569
  • 2
  • 6
  • 14

1 Answers1

3

If the count is not huge, you could use random.shuffle:

from random import shuffle

...

rows = list(cur.fetchall())
shuffle(rows)
# do what you need with the suffled rows

Otherwise you could select items in a random order. There're ways to do it in Postgres:

1) Best way to select random rows PostgreSQL

2) quick random row selection in Postgres

Community
  • 1
  • 1
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
  • it's around 50k rows in my case. is it huge? – Kurama Dec 19 '16 at 11:09
  • I think yes, it would consume a lot of memory. I would recommend you to select your items in a random order instead of shuffling in Python. In order to do it see http://stackoverflow.com/questions/8674718/best-way-to-select-random-rows-postgresql or http://stackoverflow.com/questions/5297396/quick-random-row-selection-in-postgres – Fomalhaut Dec 19 '16 at 11:11
  • where is shuffing in these links? they merely are selecting random elements, not all elements in a random order. – Kurama Dec 20 '16 at 09:51
  • 1
    `select * from table1 order by random()` – Fomalhaut Dec 20 '16 at 09:58