docs.roxen.comBack to normal mode
DocsRoxenWebServer 4.0TutorialsDatabase Tutorial
Copyright © 2006, Roxen Internet Software
Suggestions, comments & compliments
manuals@roxen.com

Limiting

It is sometimes useful not to retrieve all the rows in a query.

You can do it using SQL or (in Pike) you can do it by simply not using some of the results you fetch.

Doing it in SQL has some advantages, for instance it will reduce the load on your SQL server, your Pike application and your internal network. On the other side, the syntax for performing such an operation is not part of the SQL standard, and so every server adds its own extensions to perform this operation.

We will introduce the MySQL syntax here. For other systems, consult your server's of choice SQL reference manual.

MySQL offers limiting via an extension of the SELECT syntax, which gets changed like this:


SELECT <columns> FROM <tables> [WHERE <condition>] [ORDER BY <columns>]
       [LIMIT [offset,]howmany>]

offset and howmany are two numbers. When returning rows, MySQL will skip the first offset, and only return howmany.

Fetch the 20th to 30th countries with their associated codes (sorted by country name) with the 'LIMIT' syntax, in RXML:


<sqltable border=1 host="mysql://user:password@localhost/sample"
  query="select name,code from ids order by name limit 20,10">

...or with Pike, using the query() function and result selection:

object db;
array(mapping(string:mixed)) result;
db=Sql.sql("mysql://user:password@localhost/sample");
result=db->query("select name,code from ids order by name");
if (sizeof(result)>20)
    result=result[20..];
else
    result=({});
if (sizeof(result)>10)
    result=result[..10];
foreach(result,mapping m) {
    write(m->name+"\t"+m->code+"\n");
}

The two sizeof()-based conditionals are needed because when slicing arrays, we need to make sure that valid indexes are used, and that the required semantics are respected.

With Pike, using the big_query() function and result selection:

object(Sql.sql) db;
object(Sql.sql_result) result;
int j;
db=Sql.sql("mysql://user:password@localhost/sample");
result=db->big_query("select name,code from ids order by name");
for(j=0;j<19 && result->fetch_row();j++)
    ; //empty body, it's all done in the condition
for(j=0;j<11;j++) {
    array row;
    if (!(row=result->fetch_row()))
        break;
    write (row[0]+"\t"+row[1]+"\n"); //row[0] is the name, row[1] is the code
}