views:

58

answers:

4

In mysql there are lot of slow queries, only related to update and delete statements. The tables have 2 index columns and not heavily indexed tables. Each table having 30K records on average.

Please give your suggestions on how to overcome the slow queries related to update and delete queries. These kind of queries:

DELETE FROM <table2> 
 WHERE ID IN (SELECT ID 
                FROM <table1> WHERE ID2=100); 

...or:

UPDATE <table1> 
   SET <colmunname>=0 
 WHERE id=1001; 
A: 

The fact that your problem only exists on updates and deletes tells me that you are probably indexing too much.

Indexes will vastly reduce the time that certain queries take, but will require extra work when inserting, updating, and deleting entries from your tables. Try eliminating indexes on columns that are often getting updated, especially if they don't often appear in a where clause in your SQL queries.

StriplingWarrior
Indexes are used for more than just the WHERE clause - SELECT, JOIN and ORDER BY can leverage index use if the optimizer sees fit to.
OMG Ponies
A: 

First and foremost: Use stored procedures.

Next: If your db has optimizing capabilities -> use them.

Finally: Consider using no-relational dbs like CouchDB or Cassandra instead ;-)

Stored procedures don't make SQL any faster...
OMG Ponies
Sorry am allowed to use MySQL, i will add your point in future DB selections.
Sharpeye500
+1  A: 

Being that the tables are indexed, my first suggestion is to update the statistics for the tables using ANALYZE TABLE:

ANALYZE TABLE table1, table2

But beware:

During the analysis, the table is locked with a read lock for MyISAM, BDB, and InnoDB.

OMG Ponies
What benefit Analyze will give on slow queries?
Sharpeye500
OMG Ponies
Thanks Ponies. When i ran Analze table <tablename>, all i see is thisTable->table name Op->analyze Msg_type->status Msg_text->Okso this will help and reduce the overhead of slow queries?
Sharpeye500
Also, the slow queries occur @ a particular time – How can we determine what happened at this time to make the database so slow?
Sharpeye500
@Karthick: You'll want to read about MySQL query profiling using the [MySQL Query Profiler](http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html) to see if slowdown is due to server load/etc.
OMG Ponies
@Ponies - Thanks for the link.
Sharpeye500
@Karthick: No prob, let me know if you find what the issue is.
OMG Ponies
A: 

Managing indexes and foreign key relationships both incur overhead during update and delete operations. I would restore a copy of your prod db on a dev server, drop all foreign key constraints and all expect your primary key indexes and see the performance difference. Then you can add back your indexes until you have a better performance balance for your app.

Tahbaza
Foreign keys do not impact speed of queries; they only constrain data for the designated column(s).
OMG Ponies