Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I am trying to optimize a query that using IN clause in WHERE to avoid file sorting. To make it easy , I created the following sample which shows the problem. Here is my query:

SELECT * 
FROM `test` 
WHERE user_id = 9898 
AND status IN (1,3,4) 
order by id 
limit 30;

Here is the result of explain, as you can see the query is filesort

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  test    range   user_id     user_id     8   NULL    3   Using where; Using index; Using filesort

Here is my table structure

CREATE TABLE IF NOT EXISTS `test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `status` int(3) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`,`status`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `test`
--

INSERT INTO `test` (`id`, `user_id`, `status`) VALUES
(5, 9797, 2),
(6, 9797, 3),
(4, 9898, 0),
(1, 9898, 2),
(2, 9898, 3),
(3, 9898, 4);

How can I optimize the query? In my real table I can see the following information in error log: # Query_time: 26.498180 Lock_time: 0.000175 Rows_sent: 100 Rows_examined: 4926

share|improve this question
    
Is order by id necessary, or might be avoided? –  HAL9000 Oct 1 '13 at 16:02
    
Yes, I have to use it. –  usef_ksa Oct 1 '13 at 16:06

1 Answer 1

Trick MySQL the problem is harder to solve

SELECT
  *

FROM `test`

WHERE
  user_id =9898
AND
  status IN (1,3,4)

ORDER BY
  user_id ASC
, status ASC
, id ASC

limit 30;

see http://sqlfiddle.com/#!2/bd081/7

Edited because off comment off ypercube

Force the index to PRIMARY to remove the need off an range scan that triggers the need for an filesort.

SELECT
  id
, user_id
, status

FROM `test`
  FORCE INDEX(PRIMARY)

WHERE
    user_id =9898
  AND
    status IN (1,3,4)
order by id

limit 1;

see http://sqlfiddle.com/#!2/4d307/47

or even this to use an covering index see http://sqlfiddle.com/#!2/900c5/11

share|improve this answer
    
This is different ORDER BY - thus different results. –  ypercube Oct 1 '13 at 17:30
    
i see the same results in the SQL friddle.. –  Raymond Nijland Oct 1 '13 at 17:31
1  
Not in this one: SQL-Fiddle-2 –  ypercube Oct 1 '13 at 17:47
    
You are right.. –  Raymond Nijland Oct 1 '13 at 18:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.