2

I want to be able to randomly select rows that have a certain value. For example, I have a student table in sqlite that stores different characteristics (i.e Gender). I want to randomly pick a student that is male using python. I have looked at other questions (e.g Select a random row from the table using Python) but isn't relevant to value specific rows. How would I do this?

  • If you don't care about performance, you can do it all in SQL `SELECT * FROM students WHERE gender = 'male' ORDER BY RAND() LIMIT 1` (unsure if SQLite has `ORDER BY RAND()` but I believe it does) – Bailey Parker Jan 19 '18 at 10:29
  • Its for my school project which has required me to use Python to manipulate a database. – Barry Allen Jan 19 '18 at 10:32
  • 2
    Fine. `conn = sqlite3.connect(); conn.query('SELECT * FROM students WHERE gender = 'male' ORDER BY RAND() LIMIT 1')`. But you really should be try this out yourself before asking SO. You won't learn anything by asking someone else how to do it. – Bailey Parker Jan 19 '18 at 10:33

1 Answers1

5

No python specific syntax is needed: sqlite has a random() function:

select
  *
from users

where gender == 'M'

order by random()

limit 1

For performance see this: https://stackoverflow.com/a/24591688/788700

Adobe
  • 12,967
  • 10
  • 85
  • 126