next up previous contents index
Next: Cursors Up: Controlling Results Previous: Controlling Results

   
LIMIT

The LIMIT and OFFSET clauses of SELECT allow the user to specify which rows to return. For example, suppose customer has 1,000 rows with customer_id values ranging from 1 to 1,000. Figure [*] shows queries using LIMIT and LIMIT...OFFSET.  

        test=> SELECT customer_id FROM customer ORDER BY customer_id LIMIT 3;
         customer_id 
        -------------
                   1
                   2
                   3
        (3 rows) 
         
        test=> SELECT customer_id FROM customer ORDER BY customer_id LIMIT 3 OFFSET 997;
         customer_id 
        -------------
                 998
                 999
                1000
        (3 rows)
 

The first query sorts the table by customer_id and uses LIMIT to return the first three rows. The second query is similar, except that it skips to the 997th row before returning three rows.

Notice that each query uses ORDER BY . Although this clause is not required, LIMIT without ORDER BY returns random rows from the query, which would be useless.

LIMIT improves performance by reducing the number of rows returned to the client. If an index  matches the ORDER BY, sometimes LIMIT can even produce results without executing the entire query.   


Bruce Momjian
2001-05-09