PDA

View Full Version : Limiting Results in sorted query


_underdog
06-20-2002, 01:14 PM
Hi all! I am a java web programmer, but I use mySQL as my backend database. Thought maybe someone here could give me some suggestions.

I have a java webapp that allows users to query a database table and get results back in an html table. My query looks something like this:

SELECT [columnNames]
FROM [tableName]
WHERE [some conditions (specified by the user)]
ORDERBY [columnX (also specified by the user)], id

If the user does not limit their search criteria the results can get large and it can take a while to run the query.

I only really need the first 50 records because I display 50 at a time. Is there any way I can limit my results returned by the server and still maintain my sorting?

imported_Gryphon
06-20-2002, 01:26 PM
LIMIT 0,50

This will show the first 50, 0 is the starting row, 50 is how many.

_underdog
06-20-2002, 02:34 PM
Thought about using limit but then I saw this in the mySQL documentation:

<quote>If you use LIMIT # with ORDER BY, MySQL will end the sorting as soon as it has found
the First # lines instead of sorting the whole table.</quote>

If I use limit will it just select the first 50 rows and sort them or does it order them and then just return the first 50?

imported_Gryphon
06-20-2002, 02:37 PM
Hmm, I have no trouble using it, my whole tables always get sorted. I use limit last though, it might not work if LIMIT comes before ORDER BY, I have never tried it.

_underdog
06-20-2002, 05:26 PM
Hey thanks for the help. I think I was taking that quote out of context. It was in the section on how mySQL optimizes queries. I think what it was actually saying was that it orders the # requested and then it stops and does not order the rest of the entries in the table to save time.

imported_Gryphon
06-20-2002, 05:28 PM
no problemo ;)