I have around 300 records in some table in mysql database. And I have a requirement to fetch 40 random records with one query. How to write the query? need help thanks.
                +3 
                A: 
                
                
              
            For a small table likes yours it should suffice with this:
SELECT * FROM table ORDER BY RAND() LIMIT 40;
Note that this is not suitable for large tables since MySQL will have to do a table scan and order all rows in the table due to the usage of ORDER BY RAND(). For large tables you will have to implement this mostly in application code, keeping track of which rows you've already got and generating random ids to fetch.
                  Emil Vikström
                   2010-10-23 12:01:38
                
              
                +2 
                A: 
                
                
              
            You should use rand() with order by like this:  
SELECT field1, field2
FROM tableName
ORDER BY RAND()
LIMIT 40
                  SaltLake
                   2010-10-23 12:02:19
                
              
                
                A: 
                
                
              
            Note that this is not a fast solution, but it works fine for just 300 records
SELECT [rows]
FROM [table]
ORDER BY RAND()
LIMIT 40
                  Harmen
                   2010-10-23 12:02:34
                
              
                
                A: 
                
                
              
            $row ="insert into sc(table name)";
$r =mysql_array($i) or die (mysql_error));
$i ="SELECT * FROM table ORDER BY RAND() LIMIT 40";
                  Ricky
                   2010-10-23 12:05:35
                
              
                +1 
                A: 
                
                
              
            order by rand() may cause performance issue, instead try to do in following way:
 // what NOT to do:  
 $r = mysql_query("SELECT username FROM user ORDER BY RAND() LIMIT 1");  
 // much better:  
 $r = mysql_query("SELECT count(*) FROM user");  
 $d = mysql_fetch_row($r);  
 $rand = mt_rand(0,$d[0] - 1);  
  $r = mysql_query("SELECT username FROM user LIMIT $rand, 1");    
                  gajendra.bang
                   2010-10-23 12:15:16