Scrollable and Updatable Result Sets in JDBC
Request scrollable and updatable result sets with type and concurrency settings, move the cursor with previous, absolute, relative, first and last, edit, insert and delete rows through the result set, check what the driver really granted, and know when SQL or pagination queries are better.
kvi5hnuCode Sprout team member9 min readOn this page
By default, a ResultSet is a forward-only, read-only cursor: you call next() until the rows run out, and you can only read. That's the most efficient mode and what you need almost always. JDBC can also give you result sets that move in both directions and jump to any row, and result sets through which you can change the database. This article covers both, and also when not to use them.
Requesting a result set type
You choose the capabilities when you create the statement:
Statement stat = conn.createStatement(type, concurrency);
PreparedStatement ps = conn.prepareStatement(sql, type, concurrency);
| Constant | Meaning |
|---|---|
ResultSet.TYPE_FORWARD_ONLY | only next() (default) |
ResultSet.TYPE_SCROLL_INSENSITIVE | scrollable, and doesn't see changes other transactions make after the query |
ResultSet.TYPE_SCROLL_SENSITIVE | scrollable, and may reflect later changes in the database |
ResultSet.CONCUR_READ_ONLY | can't be used to change the database (default) |
ResultSet.CONCUR_UPDATABLE | changes made through the result set are written to the database |
There's an optional third argument, holdability: HOLD_CURSORS_OVER_COMMIT keeps result sets open after a commit, while CLOSE_CURSORS_AT_COMMIT closes them. The default depends on the driver, and conn.getHoldability() tells you.
Drivers support these modes to different degrees. Few support TYPE_SCROLL_SENSITIVE properly (H2 doesn't). Most implement scrolling by reading all rows into memory, so scrolling through a million-row result can exhaust memory. DatabaseMetaData.supportsResultSetType and supportsResultSetConcurrency tell you what is available.
If a driver can't provide what you asked for, the JDBC specification says it should give you something lesser and add an SQLWarning to the connection. In practice, not every driver adds the warning. Check rs.getType() and rs.getConcurrency() before relying on a capability. A scrolling or update method called on a result set that doesn't support it throws an SQLException.
Scrolling
On a scrollable result set, the cursor can move freely:
| Method | Moves to |
|---|---|
next(), previous() | the next or previous row |
first(), last() | the first or last row |
beforeFirst(), afterLast() | the positions before the first or after the last row |
absolute(n) | row n, counting from 1. Negative values count from the end, so absolute(-1) is the last row |
relative(n) | n rows forward, or backward if n is negative |
The movement methods return true if the cursor ended up on a row. Moving past either end leaves the cursor before the first or after the last row and returns false. getRow() returns the current row number, or 0 when the cursor isn't on a row. isFirst(), isLast(), isBeforeFirst() and isAfterLast() test the position. A well-known trick is rs.last(); int count = rs.getRow(); to count the rows. But a SELECT COUNT(*) is cheaper when the rows aren't needed anyway.
Updating through a result set
With CONCUR_UPDATABLE, you can change the data you're looking at:
- Update a row: call
updateXxx(column, value)for each column you want to change, thenupdateRow()to write the row to the database. Moving to another row without callingupdateRow()discards the changes, andcancelRowUpdates()discards them explicitly. Column numbers refer to the result set's columns, not the table's. - Insert a row:
moveToInsertRow()moves to a special insert row, a staging area. Set columns withupdateXxx, callinsertRow(), thenmoveToCurrentRow()to return to where you were. Columns you don't set are NULL or get their default value, so a NOT NULL column without a default makes the insert fail. Where the new row appears in the result set depends on the driver. - Delete a row:
deleteRow()removes the current row from the database immediately.
Whether a query's result can be updated depends on the query. Typically it must select from a single table and include its primary key, without grouping, aggregates or DISTINCT. A join can be updatable in some drivers. rowUpdated(), rowInserted() and rowDeleted() report changes, if the driver can detect them (DatabaseMetaData.ownUpdatesAreVisible and its relatives tell you).
Pagination
Showing "page 3 of the results" with a scrollable result set (absolute((page - 1) * size + 1)) only works for small results, because the driver usually fetches every row first. Let the database do the work:
- Offset pagination:
ORDER BY name OFFSET ? ROWS FETCH NEXT ? ROWS ONLY(standard SQL), orLIMIT ? OFFSET ?. It is simple, but the database still has to skip all the earlier rows, so late pages get slow. - Keyset (seek) pagination: remember the last row of the current page and continue after it:
WHERE (name, id) > (?, ?) ORDER BY name, id FETCH FIRST 20 ROWS ONLY. With an index, every page is equally fast, and rows inserted meanwhile don't shift the pages.
Trying it with H2
This program asks the driver which modes it supports, scrolls through five products, and shows that previous() fails on a forward-only result set. It then lowers prices, deletes a row, cancels an edit and inserts a row through an updatable result set, and fails to insert a row without its NOT NULL column. Finally it shows that an aggregate query isn't updatable:
import java.math.BigDecimal;
import java.sql.*;
public class Scrolling {
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:shop")) {
try (Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40) NOT NULL, supplier VARCHAR(10), price DECIMAL(8,2))");
stat.executeUpdate("""
INSERT INTO products VALUES (1, 'Hammer', 'ACME', 12.50), (2, 'Oak shelf', 'NORD', 89.90),
(3, 'Pine stool', 'NORD', 35.00), (4, 'Desk lamp', 'SOLA', 42.00), (5, 'Saw', 'ACME', 19.00)""");
}
DatabaseMetaData meta = conn.getMetaData();
System.out.println("scroll-insensitive supported: " + meta.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)
+ ", scroll-sensitive: " + meta.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)
+ ", updatable: " + meta.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE));
System.out.println("--- scrolling ---");
try (Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stat.executeQuery("SELECT id, name FROM products ORDER BY id")) {
rs.last();
System.out.println("rows: " + rs.getRow() + ", last is " + rs.getString("name"));
rs.absolute(2);
System.out.println("absolute(2): " + rs.getString("name"));
rs.relative(2);
System.out.println("relative(2): " + rs.getString("name") + " at row " + rs.getRow());
rs.previous();
System.out.println("previous(): " + rs.getString("name"));
rs.absolute(-1);
System.out.println("absolute(-1): " + rs.getString("name"));
System.out.println("relative(10) -> " + rs.relative(10) + ", isAfterLast " + rs.isAfterLast() + ", getRow " + rs.getRow());
rs.afterLast();
System.out.print("backwards:");
while (rs.previous()) System.out.print(" " + rs.getString("name"));
System.out.println();
}
try (Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT name FROM products")) {
rs.next();
rs.previous();
} catch (SQLException e) {
System.out.println("previous() on a forward-only result set: " + e.getSQLState());
}
System.out.println("--- updating through the result set ---");
try (Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stat.executeQuery("SELECT id, name, supplier, price FROM products ORDER BY id")) {
System.out.println("type " + (rs.getType() == ResultSet.TYPE_SCROLL_INSENSITIVE ? "SCROLL_INSENSITIVE" : rs.getType())
+ ", concurrency " + (rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE ? "UPDATABLE" : "READ_ONLY"));
while (rs.next()) {
if (rs.getString("supplier").equals("NORD")) { // some condition evaluated in Java
BigDecimal price = rs.getBigDecimal("price");
rs.updateBigDecimal("price", price.multiply(new BigDecimal("0.9")).setScale(2, java.math.RoundingMode.HALF_EVEN));
rs.updateRow(); // send the change
} else if (rs.getString("name").equals("Saw")) {
rs.deleteRow();
} else if (rs.getString("name").equals("Hammer")) {
rs.updateString("name", "Claw hammer");
rs.cancelRowUpdates(); // changed my mind
}
}
rs.moveToInsertRow();
rs.updateInt("id", 6);
rs.updateString("name", "Tape measure");
rs.updateString("supplier", "ACME");
rs.updateBigDecimal("price", new BigDecimal("7.25"));
rs.insertRow();
rs.moveToCurrentRow();
rs.moveToInsertRow();
rs.updateInt("id", 7);
try { rs.insertRow(); } catch (SQLException e) { System.out.println("insert without NOT NULL name: " + e.getSQLState()); }
}
try (Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT * FROM products ORDER BY id")) {
while (rs.next()) System.out.println(" " + rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getBigDecimal(4));
}
System.out.println("--- a query that can't be updated ---");
try (Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stat.executeQuery("SELECT supplier, COUNT(*) FROM products GROUP BY supplier")) {
System.out.println("concurrency " + (rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE ? "UPDATABLE" : "READ_ONLY")
+ ", warning: " + (conn.getWarnings() == null ? "none" : conn.getWarnings().getMessage()));
rs.next();
rs.updateInt(2, 99);
rs.updateRow();
} catch (SQLException e) {
System.out.println("update failed: " + e.getSQLState());
}
System.out.println("holdability: " + (conn.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT ? "HOLD_CURSORS_OVER_COMMIT" : "CLOSE_CURSORS_AT_COMMIT"));
}
}
}
Output with H2 2.3:
scroll-insensitive supported: true, scroll-sensitive: false, updatable: true
--- scrolling ---
rows: 5, last is Saw
absolute(2): Oak shelf
relative(2): Desk lamp at row 4
previous(): Pine stool
absolute(-1): Saw
relative(10) -> false, isAfterLast true, getRow 0
backwards: Saw Desk lamp Pine stool Oak shelf Hammer
previous() on a forward-only result set: 90128
--- updating through the result set ---
type SCROLL_INSENSITIVE, concurrency UPDATABLE
insert without NOT NULL name: 23502
1 Hammer ACME 12.50
2 Oak shelf NORD 80.91
3 Pine stool NORD 31.50
4 Desk lamp SOLA 42.00
6 Tape measure ACME 7.25
--- a query that can't be updated ---
concurrency READ_ONLY, warning: none
update failed: 90127
holdability: HOLD_CURSORS_OVER_COMMIT
H2 quietly returned a read-only result set for the GROUP BY query without adding a warning, which is why checking getConcurrency() matters. Its error codes 90128 and 90127 are H2-specific SQLStates for "result set not scrollable" and "result set not updatable". The cancelled rename left "Hammer" unchanged, and "Saw" is gone.
The program
The runnable demo uses a CachedRowSet (article 63), which is always scrollable and updatable because it holds its rows in memory. It walks the cursor with the scrolling methods and shows a page of three rows. It then lowers the prices above 30, deletes one row and inserts another, and finally lists every row with its state. setShowDeleted(true) includes rows marked as deleted in the listing. A row set records changes and writes them to a database only when acceptChanges is called. The JDK's row set implementation departs from the ResultSet rules in some corner cases (for example, negative absolute positions), so this demo sticks to the common operations.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.*;
import java.util.*;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.*;
public class Solution {
static CachedRowSet products() throws SQLException {
CachedRowSet rs = RowSetProvider.newFactory().createCachedRowSet();
RowSetMetaData meta = new RowSetMetaDataImpl();
meta.setColumnCount(3);
String[] names = { "ID", "NAME", "PRICE" };
int[] types = { Types.INTEGER, Types.VARCHAR, Types.DECIMAL };
for (int i = 0; i < 3; i++) {
meta.setColumnName(i + 1, names[i]);
meta.setColumnLabel(i + 1, names[i]);
meta.setColumnType(i + 1, types[i]);
}
rs.setMetaData(meta);
String[] products = { "Hammer", "Oak shelf", "Pine stool", "Desk lamp", "Saw", "Tape measure", "Chisel" };
String[] prices = { "12.50", "89.90", "35.00", "42.00", "19.00", "7.25", "15.80" };
for (int i = 0; i < products.length; i++) {
rs.moveToInsertRow();
rs.updateInt(1, i + 1);
rs.updateString(2, products[i]);
rs.updateBigDecimal(3, new BigDecimal(prices[i]));
rs.insertRow();
}
rs.moveToCurrentRow();
rs.beforeFirst();
while (rs.next()) rs.setOriginalRow(); // treat these rows as loaded, not as new
rs.beforeFirst();
return rs;
}
static String here(ResultSet rs) throws SQLException {
if (rs.isBeforeFirst()) return "before first";
if (rs.isAfterLast()) return "after last";
return "row " + rs.getRow() + " = " + rs.getString("NAME") + (rs.isFirst() ? " (first)" : "") + (rs.isLast() ? " (last)" : "");
}
public static void main(String[] args) throws SQLException {
try (CachedRowSet rs = products()) {
System.out.println("type scrollable: " + (rs.getType() != ResultSet.TYPE_FORWARD_ONLY)
+ ", updatable: " + (rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE));
System.out.println("--- moving the cursor ---");
System.out.println("start: " + here(rs));
rs.first(); System.out.println("first(): " + here(rs));
rs.relative(3); System.out.println("relative(3): " + here(rs));
rs.previous(); System.out.println("previous(): " + here(rs));
rs.absolute(5); System.out.println("absolute(5): " + here(rs));
rs.last(); System.out.println("last(): " + here(rs) + " -> " + rs.getRow() + " rows");
boolean moved = rs.relative(5);
System.out.println("relative(5): " + here(rs) + ", returned " + moved);
rs.beforeFirst(); System.out.println("beforeFirst(): " + here(rs));
System.out.println("--- showing page 2 with 3 rows per page ---");
int page = 2, size = 3;
if (rs.absolute((page - 1) * size + 1)) {
int shown = 0;
do { System.out.println(" " + rs.getInt("ID") + " " + rs.getString("NAME")); }
while (++shown < size && rs.next());
}
System.out.println("--- editing rows ---");
rs.beforeFirst();
while (rs.next()) {
BigDecimal price = rs.getBigDecimal("PRICE");
if (price.compareTo(new BigDecimal("30")) > 0) {
rs.updateBigDecimal("PRICE", price.multiply(new BigDecimal("0.9")).setScale(2, RoundingMode.HALF_EVEN));
rs.updateRow();
} else if (rs.getString("NAME").equals("Saw")) {
rs.deleteRow();
}
}
rs.moveToInsertRow();
rs.updateInt("ID", 8);
rs.updateString("NAME", "Spirit level");
rs.updateBigDecimal("PRICE", new BigDecimal("24.00"));
rs.insertRow();
rs.moveToCurrentRow();
rs.setShowDeleted(true); // also list rows marked for deletion
rs.beforeFirst();
while (rs.next()) {
String state = rs.rowDeleted() ? "deleted" : rs.rowInserted() ? "inserted" : rs.rowUpdated() ? "updated" : "";
System.out.printf(" %d %-12s %6s %s%n", rs.getInt("ID"), rs.getString("NAME"), rs.getBigDecimal("PRICE"), state);
}
rs.setShowDeleted(false);
}
}
}
type scrollable: true, updatable: true
--- moving the cursor ---
start: before first
first(): row 1 = Hammer (first)
relative(3): row 4 = Desk lamp
previous(): row 3 = Pine stool
absolute(5): row 5 = Saw
last(): row 7 = Chisel (last) -> 7 rows
relative(5): after last, returned false
beforeFirst(): before first
--- showing page 2 with 3 rows per page ---
4 Desk lamp
5 Saw
6 Tape measure
--- editing rows ---
1 Hammer 12.50
2 Oak shelf 80.91 updated
3 Pine stool 31.50 updated
4 Desk lamp 37.80 updated
5 Saw 19.00 deleted
6 Tape measure 7.25
7 Chisel 15.80
8 Spirit level 24.00 inserted
Common questions
How do I implement pagination correctly?
In SQL: ORDER BY a unique key and use OFFSET ? ROWS FETCH NEXT ? ROWS ONLY (or LIMIT/OFFSET). For deep pages, "keyset" pagination (WHERE id > ? ORDER BY id FETCH FIRST 20 ROWS ONLY, passing the last ID seen) stays fast because the database doesn't skip rows.
Is TYPE_SCROLL_INSENSITIVE safe for large results?
Usually not: most drivers load every row into memory to support it. Use forward-only cursors with a fetch size for large results.
Why does rs.updateRow() throw "not updatable"?
The statement wasn't created with CONCUR_UPDATABLE, the driver silently downgraded it, or the query isn't updatable (joins, aggregates, no primary key). Check rs.getConcurrency().
What does holdability matter for?
For code that commits while iterating, for example processing a long result in chunks and committing every 1,000 rows. With CLOSE_CURSORS_AT_COMMIT, the result set closes at the first commit. Request HOLD_CURSORS_OVER_COMMIT if the driver supports it, or restructure with keyset pagination.
Should a web application keep a result set open between requests? No. A result set holds a connection, and the user may never come back. Read a page, close everything, and query again for the next page.
API reference
| API | Purpose |
|---|---|
createStatement(type, concurrency[, holdability]), prepareStatement(sql, type, concurrency) | request a result set mode |
TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE | scrolling modes |
CONCUR_READ_ONLY, CONCUR_UPDATABLE | update modes |
HOLD_CURSORS_OVER_COMMIT, CLOSE_CURSORS_AT_COMMIT | holdability |
ResultSet.getType(), getConcurrency(), getHoldability() | what you actually got |
previous, first, last, beforeFirst, afterLast, absolute, relative | move the cursor |
getRow, isFirst, isLast, isBeforeFirst, isAfterLast | cursor position |
updateXxx, updateRow, cancelRowUpdates | change the current row |
moveToInsertRow, insertRow, moveToCurrentRow | insert a row |
deleteRow, rowUpdated, rowInserted, rowDeleted | delete rows and detect changes |
DatabaseMetaData.supportsResultSetType, supportsResultSetConcurrency | driver capabilities |
Summary
- Pass a type and a concurrency to
createStatementorprepareStatementto get scrollable or updatable result sets. CheckgetType()andgetConcurrency(), because drivers may grant less than you asked for. - Scrollable result sets support
previous,absolute,relative,first,lastand position tests. Most drivers implement them by buffering all rows. - Updatable result sets change the database through
updateXxxplusupdateRow, the insert row withinsertRow, anddeleteRow. Usually only single-table queries with a key are updatable. - For program-driven changes, SQL statements are much faster. For pagination, use
OFFSET/FETCHor keyset queries instead of scrolling.
Practice Questions
You call rs.previous() and get an SQLException, although you can read rows fine with next(). Why?
The statement was created with the default type, TYPE_FORWARD_ONLY. Create it with conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY) or the matching prepareStatement overload, and check rs.getType() in case the driver can't provide scrolling for that query.
You change a column with rs.updateString("name", "New") and then call rs.next(). Is the database changed?
No. The updateXxx methods only change the result set's copy of the row. Without updateRow(), moving to another row discards the change. Call rs.updateRow() before moving on.
Why does an updatable query SELECT supplier, COUNT(*) FROM products GROUP BY supplier come back read-only?
Each result row summarizes several table rows, so there's no single table row that an update could be written to. Drivers only make results updatable when every result row maps to exactly one row of one table, which normally requires selecting from a single table, including its primary key, and using no grouping, aggregates or DISTINCT.
A web page shows 20 orders per page out of 2 million. Why is rs.absolute(page * 20 + 1) on a scrollable result set a bad idea, and what is better?
Most drivers implement scrolling by fetching all rows into memory, so every page view would load 2 million rows. Let the database return just the page: ... ORDER BY placed DESC, id DESC OFFSET ? ROWS FETCH NEXT 20 ROWS ONLY, or with keyset pagination, WHERE (placed, id) < (?, ?) ORDER BY placed DESC, id DESC FETCH FIRST 20 ROWS ONLY using the last row of the previous page.
How can you find out the number of rows in a scrollable result set, and when should you not do it that way?
rs.last(); int count = rs.getRow(); rs.beforeFirst();. If you don't need the rows themselves, or the result is large, run SELECT COUNT(*) ... with the same conditions instead. It lets the database count without sending any rows.
Previous: LOBs, SQL Escapes, Multiple Results and Generated Keys in JDBC
Next: JDBC Row Sets: CachedRowSet, WebRowSet, FilteredRowSet and JoinRowSet
Related reading
- LOBs, SQL Escapes, Multiple Results and Generated Keys in JDBC
- Prepared Statements in JDBC: Parameters, Reuse and Preventing SQL Injection
- Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
- Connecting to a Database with JDBC: URLs, Drivers, DriverManager and DataSource
- JDBC Design and SQL Basics: How Java Talks to Databases

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.