I have a database table which has over 1 million rows and could get bigger. I have a python script which queries the database to grab one random record from this database table. The query I am using is:
SELECT *
FROM customers
WHERE cust_type = 'C'
ORDER BY RAND()
LIMIT 1;
I was simply wondering if there is a better, faster way to do this?
Thanks to Michael Benjamin for his excellent answer: Below is my working Python script with his suggestions
def util_get_random_customer_individual():
# Gets a random customer from the MySQL DB Customers table. Users will need to parse items from the results into
# individual results
# Connect to the DB
config = {'user': 'user', 'password': 'password', 'host': 'host name',
'port': 3306, 'database': 'database'}
conn = mysql.connector.connect(**config)
c = conn.cursor()
type_code = 'I'
# Get a random customer based on the the count
c.execute('SELECT COUNT(*) FROM customers WHERE cust_type = %s', type_code)
count = c.fetchone()[0]
random_value = random.randint(1, count)
c.execute('SELECT * FROM customers WHERE cust_type = %s LIMIT %s, 1', (type_code, random_value,))
random_customer = c.fetchone()
return random_customer