How to retrieve only a part of entire dataset (similar to LIMIT in MySQL)?


To retrieve first n rows in a query, use the FIRST clause:

select FIRST 10 *
from employee
order by last_name;

To get the last n records, invert the ORDER BY clause:

select FIRST 10 *
from employee
order by last_name DESC;

Please note that using the FIRST clause without ORDER BY doesn't make much sense as relational database systems don't have a concept of row number. Unless you want 'any 10 records', you should not rely on the order of records if you don't use ORDER BY, as it may change after backup and restore.

If you wish to get a set of records that is not at the start of dataset, for example, you wish to get N records from record X to record X+N, use the skip clause to skip the first X records:

select FIRST 10 SKIP 20 *
from employee
order by last_name;

Also, please note that NULLs always get at the end of dataset, as they are unknown values. If you wish, you can use NULLS FIRST clause to have them at the beginning when doing the descending sort (or whatever combination you prefer).

Firebird 2 introduces a similar ROWS clause that is prefered as it is compliant with SQL standard, can be used with UNION and any type of subquery.

select *
from employee
order by last_name
rows 20 to 30;


Do you find this FAQ incorrect or incomplete? Please e-mail us what needs to be changed. To ensure quality, each change is checked by our editors (and often tested on live Firebird databases), before it enters the main FAQ database. If you desire so, the changes will be credited to your name. To learn more, visit our add content page.



All contents are copyright © 2007-2024 FirebirdFAQ.org unless otherwise stated in the text.


Links   Firebird   News   FlameRobin   Powered by FB: Home Inventory   Euchre  
Add content   About  

Categories
 Newbies
 SQL
 Installation and setup
 Backup and restore
 Performance
 Security
 Connectivity and API
 HOWTOs
 Errors and error codes
 Miscellaneous