6.1.1. FIRST, SKIP

Used for

Retrieving a slice of rows from an ordered set

Available in

DSQL, PSQL

Syntax

  1. SELECT
  2. [FIRST <m>] [SKIP <n>]
  3. FROM ...
  4. ...
  5. <m>, <n> ::=
  6. <integer-literal>
  7. | <query-parameter>
  8. | (<integer-expression>)
Table 62. Arguments for the FIRST and SKIP Clauses
ArgumentDescription

integer-literal

Integer literal

query-parameter

Query parameter place-holder. ? in DSQL and :paramname in PSQL

integer-expression

Expression returning an integer value

FIRST and SKIP are non-standard syntax

FIRST and SKIP are Firebird-specific, non-SQL-compliant keywords. You are advised to use the ROWS syntax wherever possible.

Description

FIRST limits the output of a query to the first m rows. SKIP will suppress the given n rows before starting to return output.

FIRST and SKIP are both optional. When used together as in “FIRST *m* SKIP *n*”, the n topmost rows of the output set are discarded and the first m rows of the rest of the set are returned.

Characteristics of FIRST and SKIP

  • Any argument to FIRST and SKIP that is not an integer literal or an SQL parameter must be enclosed in parentheses. This implies that a subquery expression must be enclosed in two pairs of parentheses.

  • SKIP 0 is allowed but totally pointless.

  • FIRST 0 is also allowed and returns an empty set.

  • Negative SKIP and/or FIRST values result in an error.

  • If a SKIP lands past the end of the dataset, an empty set is returned.

  • If the number of rows in the dataset (or the remainder left after a SKIP) is less than the value of the m argument supplied for FIRST, that smaller number of rows is returned. These are valid results, not error conditions.

An error occurs when you use FIRST in subqueries. This query

  1. DELETE FROM MYTABLE
  2. WHERE ID IN (SELECT FIRST 10 ID FROM MYTABLE)

will delete all records from the table. The subquery retrieves 10 rows each time, deletes them and the operation is repeated until the table is empty. Keep it in mind! Or, better, use the ROWS clause in the DELETE statement.

Examples of FIRST/SKIP

The following query will return the first 10 names from the People table:

  1. select first 10 id, name from People
  2. order by name asc

The following query will return everything but the first 10 names:

  1. select skip 10 id, name from People
  2. order by name asc

And this one returns the last 10 rows. Notice the double parentheses:

  1. select skip ((select count(*) - 10 from People))
  2. id, name from People
  3. order by name asc

This query returns rows 81 to 100 of the People table:

  1. select first 20 skip 80 id, name from People
  2. order by name asc

See also

ROWS