Db2 LIMIT

Summary: in this tutorial, you will learn how to use the db2 LIMIT clause to limit the number of rows returned by a query.

Introduction to Db2 LIMIT clause

The LIMIT clause allows you to limit the number of rows returned by the query. The LIMIT clause is an extension of the SELECT statement that has the following syntax:

SELECT select_list FROM table_name ORDER BY sort_expression LIMIT n [OFFSET m];
Code language: SQL (Structured Query Language) (sql)

In this syntax:

  • n is the number of rows to be returned.
  • m is the number of rows to skip before returning the n rows.

Another shorter version of LIMIT clause is as follows:

LIMIT m, n;
Code language: SQL (Structured Query Language) (sql)

This syntax means skipping m rows and returning the next n rows from the result set.

A table may store rows in an unspecified order. If you don’t use the ORDER BY clause with the LIMIT clause, the returned rows are also unspecified. Therefore, it is a good practice to always use the ORDER BY clause with the LIMIT clause.

Db2 LIMIT clause examples

We will use the books table from the sample database for the demonstration.

1) Db2 LIMIT OFFSET examples

The following query returns all rows from the books table sorted by titles:

SELECT title, rating FROM books ORDER BY title;
Code language: SQL (Structured Query Language) (sql)
Db2 LIMIT example

To get the first 10 books, you add the LIMIT clause to the above statement:

SELECT title, rating FROM books ORDER BY title LIMIT 10;
Code language: SQL (Structured Query Language) (sql)
Db2 LIMIT top 10 books example

To skip the first 5 books and return the next 10 books, you use the LIMIT OFFSET clause as follows:

SELECT title, rating FROM books ORDER BY title LIMIT 10 OFFSET 5;
Code language: SQL (Structured Query Language) (sql)
Db2 LIMIT OFFSET example

Or in a shorter version:

SELECT title, rating FROM books ORDER BY title LIMIT 5, 10;
Code language: SQL (Structured Query Language) (sql)

2) Using Db2 LIMIT to get top-N rows

The LIMIT clause is useful to get the top-N report e.g., top 10 books that have the highest rating and top 20 books that have the highest number of pages.

This example uses the LIMIT clause to get the top 10 books that have the highest ratings:

SELECT title, rating FROM books ORDER BY rating DESC LIMIT 10;
Code language: SQL (Structured Query Language) (sql)
Db2 LIMIT top 10 books by ratings

In this example:

  • First, sort the books by rating from high to low using the ORDER BY clause
  • Second, pick the first 10 rows from the sorted result set using the LIMIT clause.

In this tutorial, you have learned how to use the Db2 LIMIT clause to restrict the number of rows returned by a query.

Was this tutorial helpful ?