Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Monday, 19 February 2024

Limit Function in DB2

In IBM DB2, you can use the FETCH FIRST clause to limit the number of rows returned by a query. Here's how you can use it with an example:


Suppose you have a table called employees with columns employee_id, first_name, and last_name, and you want to retrieve the first 5 employees ordered by employee_id:

SELECT *

FROM employees

ORDER BY employee_id

FETCH FIRST 5 ROWS ONLY;


In this query:

- SELECT * selects all columns from the employees table.

- FROM employees specifies the table from which to retrieve the data.

- ORDER BY employee_id ensures that the results are sorted by the employee_id column.

- FETCH FIRST 5 ROWS ONLY restricts the result set to only include the first 5 rows.


This query will return the first 5 rows from the employees table, sorted by employee_id.

You can also use the OFFSET clause to skip a certain number of rows before retrieving the specified number of rows. For example, to skip the first 10 rows and retrieve the next 5:

SELECT *

FROM employees

ORDER BY employee_id

OFFSET 10 ROWS

FETCH FIRST 5 ROWS ONLY;


This query will skip the first 10 rows and return the next 5 rows from the employees table, sorted by employee_id.

Using FETCH FIRST with OFFSET allows you to paginate through large result sets efficiently.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.