1

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
DarthOpto
  • 1,640
  • 7
  • 32
  • 59
  • possible duplicate of [How can i optimize MySQL's ORDER BY RAND() function?](http://stackoverflow.com/questions/1244555/how-can-i-optimize-mysqls-order-by-rand-function) – krokodilko Mar 01 '14 at 10:51

2 Answers2

3

Randomly generating a number based on the total, then using the offset is extremely quick.

SELECT COUNT(*) AS Total 
FROM customers 
WHERE cust_type='C';

PHP:

$rand = rand(1, $count);

SELECT * 
FROM customer 
WHERE cust_type='C' 
LIMIT $rand, 1;
Michael Benjamin
  • 2,895
  • 1
  • 16
  • 18
0

Try

SELECT * FROM customers 
WHERE id >= 
(SELECT FLOOR( MAX(id) * RAND()) FROM customers ) 
AND cust_type = 'C'
LIMIT 1;
Sam
  • 2,761
  • 3
  • 19
  • 30