Solved

Problems with large MySQL table using ORDER BY and LIMIT

Posted on 2010-09-23
3
580 Views
Last Modified: 2013-12-16
I have a MySQL table that is pretty huge. There are 21 columns and (at this point) about 3 million rows. The interface I'm writing in C# to display data from this table will obviously need the ability to break results into pages. The way I was going to do this was using LIMIT. All results would be sorted by date. So the query for the first page would look like this:

   SELECT * FROM BigTable ORDER BY ItemDate ASC LIMIT 0,250;

This takes forever though, because before it applies the limit it goes through and orders the entire table by the date field. So I'm not really sure how to speed this up and make it work efficiently. Any recommendations?
0
Comment
Question by:elorc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 45

Accepted Solution

by:
Kent Olsen earned 500 total points
ID: 33746540
Hi elorc,

There are a couple of ways.  :)

Is there an Identity column on the table?  That's an easy solution.

Is the ItemDate column indexed?  Assuming so, try the code below.


Kent

SELECT *
FROM
(
  SELECT ItemDate 
  FROM BigTable 
  ORDER BY ItemDate ASC 
  LIMIT 0,250
) t0
LEFT JOIN BigTable
  ON t0.ItemDate = BigTable.ItemDate;

Open in new window

0
 
LVL 1

Author Closing Comment

by:elorc
ID: 33747852
That makes a ridiculous difference. Thank you.
0
 
LVL 45

Expert Comment

by:Kent Olsen
ID: 33747938
Hi elorc,

Just so you know how this works, MySQL recognizes that there is an index on the ItemDate column and grabs the first 250 dates from the index instead of reading the table.

It then joins only those 250 rows from the table.



Kent
0

Featured Post

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the adminiā€¦

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question