1

My table tbltemp has around 9 lakhs records. The columns are: id (primary key, autoincrement), name, qty, price, status, mod_date, created_date.

My query is:

SELECT * 
 FROM tbltemp 
 WHERE qty > 3 
 ORDER By Rand() 
 LIMIT 50

It takes around 7 to 10 seconds to execute. How can I optimize my table or query?

Sirko
  • 72,589
  • 19
  • 149
  • 183
Flora Clinton
  • 1,871
  • 2
  • 11
  • 3

3 Answers3

0

You should create ad index on qty column.
Anyway ORDER By Rand() is time consuming...

Marco
  • 56,740
  • 14
  • 129
  • 152
  • That will be a optional good thing but not needed at all. I am sure if he runs the query `select * from tbltemp where qty > 3 ORDER By id Limit 50` ... will be much faster. – Rahul Jun 01 '12 at 10:07
  • I want to show the random list when each time user refresh my page..thats why i use the "ORDER BY RAND()" in query @Rahul – Flora Clinton Jun 01 '12 at 11:05
0

Here is an alternative for order by rand(). Try this once and see if it works

select @lims := floor(1+rand()*(count(*) - 1)) from tbltemp;  

PREPARE mystatement FROM "SELECT * FROM tbltemp WHERE qty > 3 LIMIT ?, 50";

EXECUTE mystatement USING @lims;
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

In your query :

SELECT * FROM tbltemp WHERE qty > 3 ORDER By Rand() LIMIT 50

For query optimization please take a look :

  1. ORDER BY clause is the main reason for taking long time.
  2. Add an Index to qty column.
  3. Also the storage engine you are using can also affect the performance optimization of query.MYISAM is the fastest storage engine.
CP Soni
  • 423
  • 4
  • 13