Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL indexing and Using filesort

Tags:

mysql

This related to my last problem. I made a new two columns in the listings table, one for composed views views_point (increment every 100 view) and one for publish on date publishedon_hourly (by year-month-day hour only) to make some unique values.

This is my new table:

CREATE TABLE IF NOT EXISTS `listings` (   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,   `type` tinyint(1) NOT NULL DEFAULT '1',   `hash` char(32) NOT NULL,   `source_id` int(10) unsigned NOT NULL,   `link` varchar(255) NOT NULL,   `short_link` varchar(255) NOT NULL,   `cat_id` mediumint(5) NOT NULL,   `title` mediumtext NOT NULL,   `description` mediumtext,   `content` mediumtext,   `images` mediumtext,   `videos` mediumtext,   `views` int(10) unsigned NOT NULL DEFAULT '0',   `views_point` int(10) unsigned NOT NULL DEFAULT '0',   `comments` int(11) DEFAULT '0',   `comments_update` int(11) NOT NULL DEFAULT '0',   `editor_id` int(11) NOT NULL DEFAULT '0',   `auther_name` varchar(255) DEFAULT NULL,   `createdby_id` int(10) NOT NULL,   `createdon` int(20) NOT NULL,   `editedby_id` int(10) NOT NULL,   `editedon` int(20) NOT NULL,   `deleted` tinyint(1) NOT NULL,   `deletedon` int(20) NOT NULL,   `deletedby_id` int(10) NOT NULL,   `deletedfor` varchar(255) NOT NULL,   `published` tinyint(1) NOT NULL DEFAULT '1',   `publishedon` int(11) unsigned NOT NULL,   `publishedon_hourly` int(10) unsigned NOT NULL DEFAULT '0',   `publishedby_id` int(10) NOT NULL,   PRIMARY KEY (`id`),   KEY `hash` (`hash`),   KEY `views_point` (`views_point`),   KEY `listings` (`publishedon_hourly`,`published`,`cat_id`,`source_id`) ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ROW_FORMAT=FIXED AUTO_INCREMENT=365513 ; 

When I run a query like this:

SELECT * FROM listings WHERE (`publishedon_hourly` BETWEEN        UNIX_TIMESTAMP( '2015-09-5 00:00:00' )        AND UNIX_TIMESTAMP( '2015-10-5 12:00:00' ))   AND (published =1)   AND cat_id IN ( 1, 2, 3, 4, 5 ) ORDER BY by `views_point` DESC LIMIT 10  

It is working great and this the explanation: enter image description here

But when I change the date range from month to day like this:

SELECT * FROM listings WHERE (`publishedon_hourly` BETWEEN        UNIX_TIMESTAMP( '2015-09-5 00:00:00' )        AND UNIX_TIMESTAMP( '2015-09-5 12:00:00' ))   AND (published =1)   AND cat_id IN ( 1, 2, 3, 4, 5 )   ORDER BY `views_point` DESC   LIMIT 10  

Then the query becomes slow and the filesort appears. Any one know the reason and how can I fix it?

the data sample (from the slow query)

INSERT INTO `listings` (`id`, `type`, `hash`, `source_id`, `link`, `short_link`, `cat_id`, `title`, `description`, `content`, `images`, `videos`, `views`, `views_point`, `comments`, `comments_update`, `editor_id`, `auther_name`, `createdby_id`, `createdon`, `editedby_id`, `editedon`, `deleted`, `deletedon`, `deletedby_id`, `deletedfor`, `published`, `publishedon`, `publishedon_hourly`, `publishedby_id`) VALUES (94189, 1, '44a46d128ce730c72927b19c445ab26e', 8, 'http://Larkin.com/sapiente-laboriosam-omnis-tempore-aliquam-qui-nobis', '', 5, 'And Alice was more and.', 'So they got settled down again very sadly and quietly, and.', 'Dormouse. ''Fourteenth of March, I think it so quickly that the Gryphon only answered ''Come on!'' and ran the faster, while more and more sounds of broken glass, from which she concluded that it was looking down at them, and then a voice sometimes choked with sobs, to sing this:-- ''Beautiful Soup, so rich and green, Waiting in a natural way. ''I thought you did,'' said the Dormouse, without considering at all what had become of it; and as it.', NULL, '', 200, 19700, 0, 0, 0, 'Max', 0, 1441442729, 0, 0, 0, 0, 0, '', 1, 1441442729, 1441440000, 0), (19030, 1, '3438f6a555f2ce7fdfe03cee7a52882a', 3, 'http://Romaguera.com/voluptatem-rerum-quia-sed', '', 2, 'Dodo said, ''EVERYBODY.', 'I wish I hadn''t to bring but one; Bill''s got the.', 'I wonder what they''ll do well enough; don''t be particular--Here, Bill! catch hold of this remark, and thought to herself. (Alice had no idea what Latitude or Longitude I''ve got to the confused clamour of the other queer noises, would change to dull reality--the grass would be offended again. ''Mine is a long way. So she went on. ''I do,'' Alice said nothing; she had succeeded in curving it down ''important,'' and some were birds,) ''I suppose so,''.', NULL, '', 800, 19400, 0, 0, 0, 'Antonio', 0, 1441447567, 0, 0, 0, 0, 0, '', 1, 1441447567, 1441447200, 0), (129247, 4, '87d2029a300d8b4314508786eb620a24', 10, 'http://Ledner.com/', '', 4, 'I ever saw one that.', 'The Cat seemed to be a person of authority among them,.', 'I BEG your pardon!'' she exclaimed in a natural way again. ''I wonder what was the same height as herself; and when she looked down at her feet as the question was evidently meant for her. ''I can tell you my history, and you''ll understand why it is I hate cats and dogs.'' It was all dark overhead; before her was another long passage, and the blades of grass, but she had sat down a very little! Besides, SHE''S she, and I''m sure I have dropped them, I wonder?'' As she said to herself; ''his eyes are so VERY tired of being all alone here!'' As she said to itself ''Then I''ll go round a deal.', NULL, '', 1000, 19100, 0, 0, 0, 'Drake', 0, 1441409756, 0, 0, 0, 0, 0, '', 1, 1441409756, 1441407600, 0), (264582, 2, '5e44fe417f284f42c3b10bccd9c89b14', 8, 'http://www.Dietrich.info/laboriosam-quae-eaque-aut-dolorem', '', 2, 'Alice asked in a very.', 'THINK; or is it directed to?'' said the Mock Turtle,.', 'I can listen all day to such stuff? Be off, or I''ll have you executed.'' The miserable Hatter dropped his teacup and bread-and-butter, and then unrolled the parchment scroll, and read as follows:-- ''The Queen will hear you! You see, she came upon a little of the players to be lost, as she spoke--fancy CURTSEYING as you''re falling through the wood. ''It''s the stupidest tea-party I.', NULL, '', 800, 18700, 0, 0, 0, 'Kevin', 0, 1441441192, 0, 0, 0, 0, 0, '', 1, 1441441192, 1441440000, 0), (44798, 1, '567cc77ba88c05a4a805dc667816a30c', 14, 'http://www.Hintz.com/distinctio-nulla-quia-incidunt-facere-reprehenderit-sapiente-sint.html', '', 5, 'The Cat seemed to Alice.', 'And the moral of that is--"Be what you mean,'' said Alice..', 'Alice very politely; but she felt very lonely and low-spirited. In a little faster?" said a sleepy voice behind her. ''Collar that Dormouse,'' the Queen said severely ''Who is it directed to?'' said the Footman, and began staring at the Footman''s head: it just at first, but, after watching it a violent blow underneath her chin: it had no pictures or conversations in it, ''and what is the capital of Paris, and Paris is the same thing, you know.'' ''I DON''T.', NULL, '', 300, 17600, 0, 0, 0, 'Rocio', 0, 1441442557, 0, 0, 0, 0, 0, '', 1, 1441442557, 1441440000, 0), (184472, 1, 'f852e3ed401c7c72c5a9609687385f65', 14, 'https://www.Schumm.biz/voluptatum-iure-qui-dicta-modi-est', '', 4, 'Alice replied, so.', 'I should have liked teaching it tricks very much, if--if.', 'NEVER come to the Dormouse, not choosing to notice this question, but hurriedly went on, ''What''s your name, child?'' ''My name is Alice, so please your Majesty,'' said Two, in a great thistle, to keep back the wandering hair that WOULD always get into her face. ''Wake up, Alice dear!'' said her sister; ''Why, what a dear quiet thing,'' Alice went on, spreading out the answer to shillings and pence. ''Take off your hat,'' the King had said that day. ''No, no!'' said the Gryphon. ''They can''t have anything to say, she simply bowed, and took the watch and looked at it again: but he could.', NULL, '', 900, 17600, 0, 0, 0, 'Billy', 0, 1441407837, 0, 0, 0, 0, 0, '', 1, 1441407837, 1441407600, 0), (344246, 2, '09dc73287ff642cfa2c97977dc42bc64', 6, 'http://www.Cole.com/sit-maiores-et-quam-vitae-ut-fugiat', '', 1, 'IS the use of a.', 'And when I learn music.'' ''Ah! that accounts for it,'' said.', 'Gryphon answered, very nearly carried it out loud. ''Thinking again?'' the Duchess by this time.) ''You''re nothing but a pack of cards, after all. I needn''t be so stingy about it, you know--'' ''But, it goes on "THEY ALL RETURNED FROM HIM TO YOU,"'' said Alice. ''Call it what you mean,'' the March Hare, ''that "I breathe when I breathe"!'' ''It IS the same side of WHAT? The other guests had taken his watch out of it, and talking over its head. ''Very uncomfortable for the first to speak. ''What size do you like to go and get.', NULL, '', 600, 16900, 0, 0, 0, 'Enrico', 0, 1441406107, 0, 0, 0, 0, 0, '', 1, 1441406107, 1441404000, 0), (19169, 1, '116c443b5709e870248c93358f9a328e', 12, 'http://www.Gleason.com/et-vero-optio-exercitationem-aliquid-optio-consectetur', '', 4, 'Let this be a lesson to.', 'Sir, With no jury or judge, would be very likely to eat.', 'I wonder who will put on your head-- Do you think I can find them.'' As she said this, she was quite out of sight before the end of every line: ''Speak roughly to your little boy, And beat him when he sneezes; For he can EVEN finish, if he had never heard of such a subject! Our family always HATED cats: nasty, low, vulgar things! Don''t let him know she liked them best, For this must ever be A secret, kept from all the creatures wouldn''t be so kind,'' Alice replied, so eagerly that the way I want to get very tired of being upset, and their curls got entangled together. Alice was not a regular rule: you invented it just grazed his nose, you know?'' ''It''s the thing Mock Turtle would be only.', NULL, '', 700, 16800, 0, 0, 0, 'Unique', 0, 1441407961, 0, 0, 0, 0, 0, '', 1, 1441407961, 1441407600, 0), (192679, 1, '06a33747b5c95799034630e578e53dc5', 10, 'http://www.Pouros.com/qui-id-molestias-non-dolores-non', '', 5, 'Rabbit just under the.', 'KNOW IT TO BE TRUE--" that''s the jury-box,'' thought Alice,.', 'Mock Turtle, who looked at Two. Two began in a hoarse, feeble voice: ''I heard every word you fellows were saying.'' ''Tell us a story.'' ''I''m afraid I can''t tell you how it was too dark to see what I should say "With what porpoise?"'' ''Don''t you mean by that?'' said the King; and as it was indeed: she was now more than Alice could not make out exactly what they WILL do next! As for pulling me out of court! Suppress him! Pinch him! Off with his head!"'' ''How dreadfully savage!'' exclaimed Alice. ''That''s the first witness,'' said the Duchess. ''Everything''s got a moral, if only you can find it.'' And she squeezed herself up and ran the faster, while more and more faintly came, carried on the end of every line:.', NULL, '', 800, 15900, 0, 0, 0, 'Gene', 0, 1441414720, 0, 0, 0, 0, 0, '', 1, 1441414720, 1441411200, 0), (251878, 4, '3eafacc53f86c8492c309ca2772fbfe9', 5, 'http://www.Schinner.info/tempora-et-est-qui-nulla', '', 2, 'NOT!'' cried the Mouse,.', 'Twinkle, twinkle--"'' Here the Queen till she heard the.', 'Alice and all of them even when they hit her; and the sounds will take care of the gloves, and she dropped it hastily, just in time to begin at HIS time of life. The King''s argument was, that she had forgotten the Duchess to play croquet with the Dormouse. ''Write that down,'' the King added in an undertone to the fifth bend, I think?'' ''I had NOT!'' cried the Mouse, sharply and very neatly and simply arranged; the only difficulty was, that if something wasn''t done about it in less than a pig, my dear,'' said Alice, a little wider. ''Come, it''s pleased so far,'' said the Gryphon. ''Do you play croquet with the glass table and the King hastily said, and went by without noticing her. Then followed the Knave ''Turn them over!'' The Knave of.', NULL, '', 500, 15900, 0, 0, 0, 'Demarcus', 0, 1441414681, 0, 0, 0, 0, 0, '', 1, 1441414681, 1441411200, 0); 

enter image description here

like image 798
Mostafa Elkady Avatar asked Oct 05 '15 15:10

Mostafa Elkady


People also ask

What is using Filesort in MySQL?

Use of filesort to Satisfy ORDER BY If an index cannot be used to satisfy an ORDER BY clause, MySQL performs a filesort operation that reads table rows and sorts them. A filesort constitutes an extra sorting phase in query execution. To obtain memory for filesort operations, as of MySQL 8.0.

How do I avoid using Filesort?

To avoid a filesort, you have to find a way to get what you want without running into any of those (many) documented conditions. Increase the size of the sort_buffer_size variable. Increase the size of the read_rnd_buffer_size variable.

Does MySQL use index for sorting?

Yes, MySQL uses your index to sort the information when the order is by the sorted column. Also, if you have indexes in all columns that you have added to the SELECT clause, MySQL will not load the data from the table itself, but from the index (which is faster).

What is Filesort?

In MySQL, filesort is the catch-all algorithm for producing sorted results for ORDER-BY or GROUP-BY queries. MySQL has two algorithms for filesort, both the original and the modified algorithms are described in the user manual.


1 Answers

In your first query, the ORDER BY is done using the views_point INDEX, because it was used in the WHERE part of the query and therefore in MySQL can be used for sorting.

In the second query, MySQL resolves the WHERE part using a different index, listing_pcs. This cannot be used to satisfy the ORDER BY condition. MySQL uses filesort instead, which is the best option if an index cannot be used.

MySQL only uses indexes to sort if the index is the same as that used in the WHERE condition. This is what the manual means by:

In some cases, MySQL cannot use indexes to resolve the ORDER BY, although it still uses indexes to find the rows that match the WHERE clause. These cases include the following:

The key used to fetch the rows is not the same as the one used in the ORDER BY:

SELECT * FROM t1 WHERE key2=constant ORDER BY key1; 

So what can you do:

  1. Try increasing your sort_buffer_size config option to make filesorting as effective as possible. Large results that are too big for the sort buffer cause MySQL to break the sort down into chunks, which is slower.

  2. Force MySQL to choose a different index. It’s worth noting that different MySQL versions choose default indexes differently. Version 5.1, for example, is pretty bad as the Query Optimizer had been vastly re-written for this release and needed lots of refinement. Version 5.6 is pretty good.

    SELECT * FROM listings FORCE INDEX (views_point) WHERE (`publishedon_hourly` BETWEEN        UNIX_TIMESTAMP( '2015-09-5 00:00:00' )        AND UNIX_TIMESTAMP( '2015-09-5 12:00:00' ))   AND (published =1)   AND cat_id IN ( 1, 2, 3, 4, 5 ) ORDER BY `views_point` DESC LIMIT 10 
like image 76
Steve E. Avatar answered Sep 21 '22 02:09

Steve E.