Ever wanted to select specific rows from a dataset? Well InterBase has some very cool features in the SQL syntax that allows you to do just that!
Adding the ROWS command to the end of your SQL statement (as per the example below) will return a specific number of records. For examples, to fetch the first 10 records just add rows 10.
Select * from MyTable rows 10;
When you want to get the next 10 records you can use the extended syntax with the “to” command.
Select * from MyTable rows 11 to 20;
The second query can obviously be used to fetch records 1 to 10 as well and is very useful when combined with a parameterised query to allow restful paging of data sets.
Fetching Page Headers
Now, say you wanted to get the first record of every page of data, you can also easily do this by adding an additional optional parameter “by” for example
Select * from MyTable rows 1 to 100 by 10;
The above statement would return records 1, 11, 21, 31 etc… for the total records up to 100th record.
You can also skip records to return by a percentage of the dataset result size by simply adding “PERCENT” to the end of the above statement.
Select * from MyTable rows 1 to 100 by 7 PERCENT;
Getting the top 10
But what if you want to use ROWS to get the top 10? Well, you can easily select 10 records, but what if the 11th and 12th record have the same value as the 10th? They should be returned as well, but how?
InterBase supports this easily by adding “WITH TIES”. To use “WITH TIES” you also need to include an “ORDER BY” clause to indicate what field to measure the ties on. For example, to get the top 10 sales people by a field storing the sales_booked, you could run the following statement.
Select * from salespeople order by sales_booked desc rows 10 with ties;
This will include the top 10 and also anyone with sales_booked matching the 10th record.
Getting the first 10 percent
Following on, the first 10% of records can be returned by using the following syntax.
Select * from salespeople rows 10 percent;
While getting 10% of records is a nice feature, combining this with the “ORDER BY” and “WITH TIES” makes a very easy way to select the top 10% of sales people (for example) rather than the top 10.
There are some very cool features in the InterBase language for defining the specific size and scope of data to return that lend itself nicely to a range of useful implementations around statistics and restful data service development.
For more fun details on the InterBase language, check out the language reference guide on http://docs.embarcadero.com/products/interbase