Java ResultSet
A Java ResultSet (java.sql.ResultSet) holds the rows returned by a SQL query and lets your program read them one at a time. It works like a cursor: it points at one row, you read that row's columns, then you move to the next row.
Every JDBC query ends with a ResultSet, so knowing how to read it well is essential. In this lesson you will loop through rows, read columns by name and by index, handle NULL values, read dates as LocalDate, inspect columns with ResultSetMetaData, move freely through a scrollable ResultSet, change data through an updatable one, and map rows into Java records for a grade report.
How the Java ResultSet Cursor Works
When a query returns, the cursor sits before the first row. Each call to next() moves it forward one row and returns true, or returns false when there are no more rows.
id | name | marks
cursor -> (before first row)
next() 1 | Asha | 88 <- true
next() 2 | Ravi | 72 <- true
next() 3 | Meena | 92 <- true
next() (after last row) <- false, loop ends
Example: Looping Through Rows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSetLoop {
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "");
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(30), marks INT)");
statement.executeUpdate("INSERT INTO students VALUES (1, 'Asha', 88), (2, 'Ravi', 72), (3, 'Meena', 92)");
try (ResultSet rows = statement.executeQuery("SELECT id, name, marks FROM students ORDER BY id")) {
int rowCount = 0;
while (rows.next()) {
int id = rows.getInt("id");
String name = rows.getString("name");
int marks = rows.getInt("marks");
System.out.println(id + ". " + name + " scored " + marks);
rowCount++;
}
System.out.println("Rows read: " + rowCount);
}
}
}
}
Output:
1. Asha scored 88
2. Ravi scored 72
3. Meena scored 92
Rows read: 3
How it works:
while (rows.next())is the standard loop. It runs once per row and stops by itself after the last one.- Inside the loop, the getter methods read columns of the current row only.
- Calling a getter before the first
next()throwsSQLException, because the cursor is not on a row yet. - The
ResultSetis closed by try-with-resources. Closing it frees database resources such as server-side cursors.
Reading Columns: Getter Methods
Each column is read with a getXxx() method that matches the Java type you want. You can identify the column by its label (name) or by its index, counting from 1.
| Method | Returns | Typical SQL type |
|---|---|---|
getString(col) | String | VARCHAR, CHAR, TEXT (works on most types) |
getInt(col) / getLong(col) | int / long | INT / BIGINT |
getDouble(col) | double | DOUBLE, FLOAT |
getBigDecimal(col) | BigDecimal | DECIMAL, NUMERIC |
getBoolean(col) | boolean | BOOLEAN, BIT |
getObject(col, LocalDate.class) | LocalDate | DATE |
getObject(col, LocalDateTime.class) | LocalDateTime | TIMESTAMP |
getObject(col, Integer.class) | Integer or null | any numeric column that may be NULL |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GetterMethods {
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "");
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(30), marks INT)");
statement.executeUpdate("INSERT INTO students VALUES (1, 'Asha', 88)");
try (ResultSet row = statement.executeQuery("SELECT name, marks FROM students WHERE id = 1")) {
row.next();
System.out.println("getString(1): " + row.getString(1));
System.out.println("getString(\"name\"): " + row.getString("name"));
System.out.println("getInt(\"marks\"): " + row.getInt("marks"));
System.out.println("getDouble(\"marks\"): " + row.getDouble("marks"));
System.out.println("getString(\"marks\"): " + row.getString("marks"));
System.out.println("findColumn(\"marks\"): " + row.findColumn("marks"));
}
}
}
}
Output:
getString(1): Asha
getString("name"): Asha
getInt("marks"): 88
getDouble("marks"): 88.0
getString("marks"): 88
findColumn("marks"): 2
How it works:
- Index
1means the first column in the SELECT list, which isname, not the first column of the table. - Labels are case-insensitive, so
"name","NAME"and"Name"all work. - The driver converts where it can: an
INTcolumn can be read asdoubleor asString. Converting text such as"Asha"to a number fails withSQLException. findColumn("marks")returns the index of a label. It is handy in tight loops, where reading by index is slightly faster than looking up the name every time.
Note: When a query uses an alias, such as
SELECT COUNT(*) AS total, read the column by the alias:getInt("total"). Without an alias, use the index:getInt(1).
Handling NULL Values in a ResultSet
Primitive getters such as getInt() cannot return null, so they return 0 (or false) for SQL NULL. That makes "zero" and "missing" look the same. There are two ways to tell them apart.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class NullValues {
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "");
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(30), marks INT)");
statement.executeUpdate("INSERT INTO students VALUES (1, 'Asha', 88), (2, 'Ravi', NULL), (3, 'Meena', 0)");
try (ResultSet rows = statement.executeQuery("SELECT name, marks FROM students ORDER BY id")) {
while (rows.next()) {
String name = rows.getString("name");
int marks = rows.getInt("marks");
boolean wasNull = rows.wasNull(); // check right after the getter
Integer boxedMarks = rows.getObject("marks", Integer.class);
System.out.println(name + ": getInt=" + marks + ", wasNull=" + wasNull + ", getObject=" + boxedMarks);
}
}
}
}
}
Output:
Asha: getInt=88, wasNull=false, getObject=88
Ravi: getInt=0, wasNull=true, getObject=null
Meena: getInt=0, wasNull=false, getObject=0
How it works:
- Ravi has no marks (
NULL) and Meena scored0.getInt()returns0for both. wasNull()reports whether the last column read wasNULL. It must be called immediately after the getter, before reading another column.getObject("marks", Integer.class)returns a boxedInteger, which isnullfor SQLNULL. This is usually the clearest choice for nullable columns.getString()andgetBigDecimal()already returnnullfor SQLNULL, so they need no extra check.
Reading Dates and Times as java.time Objects
Modern drivers return DATE and TIMESTAMP columns directly as java.time classes through getObject(column, Class).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class DateColumns {
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:events", "sa", "");
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE events (title VARCHAR(40), event_date DATE, starts_at TIMESTAMP)");
statement.executeUpdate("INSERT INTO events VALUES ('Java Workshop', DATE '2026-12-05', TIMESTAMP '2026-12-05 10:30:00')");
try (ResultSet row = statement.executeQuery("SELECT title, event_date, starts_at FROM events")) {
row.next();
LocalDate eventDate = row.getObject("event_date", LocalDate.class);
LocalDateTime startsAt = row.getObject("starts_at", LocalDateTime.class);
System.out.println(row.getString("title") + " on " + eventDate);
System.out.println("Day of week: " + eventDate.getDayOfWeek());
System.out.println("Starts at: " + startsAt.toLocalTime());
}
}
}
}
Output:
Java Workshop on 2026-12-05
Day of week: SATURDAY
Starts at: 10:30
How it works:
getObject(..., LocalDate.class)returns aLocalDate, so all the date methods from the Java Date and Time section are available immediately.LocalDateTime.toLocalTime()keeps only the time part.LocalTimeprints10:30because the seconds are zero.- This replaces the older
getDate()andgetTimestamp()methods, which return the legacyjava.sql.Dateandjava.sql.Timestamptypes.
Inspecting Columns with ResultSetMetaData
getMetaData() describes the result itself: how many columns it has, their labels and their SQL types. Generic tools such as report printers and CSV exporters use it to handle any query.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.JDBCType;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class MetaDataExample {
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "");
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(30), marks INT, joined DATE)");
try (ResultSet rows = statement.executeQuery("SELECT id, name AS student_name, marks, joined FROM students")) {
ResultSetMetaData meta = rows.getMetaData();
int columnCount = meta.getColumnCount();
System.out.println("Columns: " + columnCount);
for (int i = 1; i <= columnCount; i++) {
String label = meta.getColumnLabel(i);
String type = JDBCType.valueOf(meta.getColumnType(i)).getName();
System.out.println(" " + i + ". " + label + " : " + type);
}
}
}
}
}
Output:
Columns: 4
1. ID : INTEGER
2. STUDENT_NAME : VARCHAR
3. MARKS : INTEGER
4. JOINED : DATE
How it works:
- Metadata is available even when the query returns no rows, because it describes the shape of the result, not its data.
getColumnLabel()returns the alias when there is one (STUDENT_NAME), otherwise the column name. H2 stores unquoted names in upper case, which is why the labels are upper case.getColumnType()returns anintconstant fromjava.sql.Types.JDBCType.valueOf()turns it into a readable name.
| ResultSetMetaData method | Returns |
|---|---|
getColumnCount() | Number of columns |
getColumnLabel(i) | Alias or name, used by getXxx("label") |
getColumnType(i) | SQL type as a java.sql.Types constant |
getColumnTypeName(i) | Database-specific type name |
isNullable(i) | columnNoNulls, columnNullable or columnNullableUnknown |
getTableName(i) | Table the column came from (may be empty for expressions) |
Scrollable ResultSet: Moving in Any Direction
By default a ResultSet is forward-only: you can only call next(). If you create the statement with a scrollable type, you can jump to any row and move backwards too.
| ResultSet type | Movement | Sees changes made by others after the query? |
|---|---|---|
TYPE_FORWARD_ONLY (default) | next() only | Driver-specific |
TYPE_SCROLL_INSENSITIVE | Any direction | No, it shows a snapshot |
TYPE_SCROLL_SENSITIVE | Any direction | Yes, where the driver supports it |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.StringJoiner;
public class ScrollableResultSet {
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "");
Statement setup = connection.createStatement()) {
setup.executeUpdate("CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(30))");
setup.executeUpdate("INSERT INTO students VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meena'), (4, 'Kavin'), (5, 'Divya')");
try (Statement scrollable = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rows = scrollable.executeQuery("SELECT name FROM students ORDER BY id")) {
rows.last();
System.out.println("Total rows: " + rows.getRow());
rows.first();
System.out.println("first(): " + rows.getString("name"));
rows.absolute(3);
System.out.println("absolute(3): " + rows.getString("name"));
rows.previous();
System.out.println("previous(): " + rows.getString("name"));
rows.relative(2);
System.out.println("relative(2): " + rows.getString("name"));
rows.absolute(-1);
System.out.println("absolute(-1): " + rows.getString("name"));
StringJoiner reversed = new StringJoiner(", ");
rows.afterLast();
while (rows.previous()) {
reversed.add(rows.getString("name"));
}
System.out.println("Reverse order: " + reversed);
}
}
}
}
Output:
Total rows: 5
first(): Asha
absolute(3): Meena
previous(): Ravi
relative(2): Kavin
absolute(-1): Divya
Reverse order: Divya, Kavin, Meena, Ravi, Asha
How it works:
last()followed bygetRow()is a quick way to count rows, becausegetRow()returns the current row number.absolute(3)jumps to row 3. Negative numbers count from the end, soabsolute(-1)is the last row.relative(2)moves two rows forward from the current position (row 2 to row 4).afterLast()puts the cursor past the end, so awhile (rows.previous())loop reads every row backwards.
Note: A scrollable
ResultSetmay hold the whole result in memory. For large results, use the default forward-only type and let the database do sorting and counting withORDER BYandCOUNT(*).
Updatable ResultSet: Changing Rows While Reading
With CONCUR_UPDATABLE, you can update, delete and insert rows through the ResultSet. The driver turns these calls into SQL for you.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UpdatableResultSet {
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "");
Statement setup = connection.createStatement()) {
setup.executeUpdate("CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(30), marks INT)");
setup.executeUpdate("INSERT INTO students VALUES (1, 'Asha', 88), (2, 'Ravi', 72), (3, 'Meena', 92), (4, 'Kavin', 60)");
try (Statement editable = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rows = editable.executeQuery("SELECT id, name, marks FROM students")) {
while (rows.next()) {
String name = rows.getString("name");
int marks = rows.getInt("marks");
if (name.equals("Kavin")) {
rows.deleteRow(); // remove this student
} else if (marks < 75) {
rows.updateInt("marks", marks + 5); // change the value in the ResultSet
rows.updateRow(); // write the change to the database
}
}
rows.moveToInsertRow(); // a special buffer row for new data
rows.updateInt("id", 6);
rows.updateString("name", "Divya");
rows.updateInt("marks", 95);
rows.insertRow();
rows.moveToCurrentRow();
}
try (ResultSet check = setup.executeQuery("SELECT id, name, marks FROM students ORDER BY id")) {
while (check.next()) {
System.out.println(check.getInt("id") + " " + check.getString("name") + " " + check.getInt("marks"));
}
}
}
}
}
Output:
1 Asha 88
2 Ravi 77
3 Meena 92
6 Divya 95
How it works:
updateInt()changes the value only inside theResultSet. Nothing reaches the database untilupdateRow()is called.deleteRow()deletes the current row from the table.moveToInsertRow()moves to an empty buffer row. After filling every column,insertRow()inserts it, andmoveToCurrentRow()returns to where the cursor was.
Note: Updatable result sets work only for simple queries on one table that include the primary key, and driver support varies. In most applications, plain
UPDATE,DELETEandINSERTstatements run through a Java PreparedStatement are clearer and more portable.
Real-World Example: Mapping Rows to Records for a Grade Report
Applications rarely pass a ResultSet around. Instead, they read each row into a Java object right away, close the ResultSet, and work with a plain List. A record is ideal for this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GradeReport {
record Student(int id, String name, Integer marks) { }
static List<Student> loadStudents(Connection connection, String className) throws SQLException {
String sql = "SELECT id, name, marks FROM students WHERE class_name = ? ORDER BY id";
List<Student> students = new ArrayList<>();
try (PreparedStatement query = connection.prepareStatement(sql)) {
query.setString(1, className);
query.setFetchSize(100); // hint: fetch up to 100 rows per network round trip
try (ResultSet rows = query.executeQuery()) {
while (rows.next()) {
students.add(new Student(
rows.getInt("id"),
rows.getString("name"),
rows.getObject("marks", Integer.class))); // null when absent
}
}
}
return students;
}
static String grade(int marks) {
if (marks >= 90) return "A";
if (marks >= 80) return "B";
if (marks >= 70) return "C";
if (marks >= 60) return "D";
return "F";
}
public static void main(String[] args) throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "");
Statement setup = connection.createStatement()) {
setup.executeUpdate("CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(30), class_name VARCHAR(10), marks INT)");
setup.executeUpdate("""
INSERT INTO students VALUES
(1, 'Asha', '10-A', 88), (2, 'Ravi', '10-A', 72), (3, 'Meena', '10-A', 92),
(4, 'Kavin', '10-A', NULL), (5, 'Divya', '10-A', 64), (6, 'Arun', '10-B', 70)""");
List<Student> students = loadStudents(connection, "10-A");
System.out.println("Report card for class 10-A");
for (Student student : students) {
if (student.marks() == null) {
System.out.println(" " + student.id() + ". " + student.name() + ": absent");
} else {
System.out.println(" " + student.id() + ". " + student.name() + ": "
+ student.marks() + " (" + grade(student.marks()) + ")");
}
}
List<Integer> presentMarks = students.stream()
.map(Student::marks)
.filter(Objects::nonNull)
.toList();
double average = presentMarks.stream().mapToInt(Integer::intValue).average().orElse(0);
Student topStudent = students.stream()
.filter(student -> student.marks() != null)
.max(Comparator.comparing(Student::marks))
.orElseThrow();
Map<String, Long> gradeCounts = presentMarks.stream()
.collect(Collectors.groupingBy(GradeReport::grade, TreeMap::new, Collectors.counting()));
System.out.printf("Present: %d of %d%n", presentMarks.size(), students.size());
System.out.printf("Class average: %.1f%n", average);
System.out.println("Top student: " + topStudent.name() + " (" + topStudent.marks() + ")");
System.out.println("Grade counts: " + gradeCounts);
}
}
}
Output:
Report card for class 10-A
1. Asha: 88 (B)
2. Ravi: 72 (C)
3. Meena: 92 (A)
4. Kavin: absent
5. Divya: 64 (D)
Present: 4 of 5
Class average: 79.0
Top student: Meena (92)
Grade counts: {A=1, B=1, C=1, D=1}
How it works:
- Read, map, close.
loadStudents()turns each row into aStudentrecord and closes theResultSetbefore returning. The rest of the program never touches JDBC. - Parameters keep the query safe. The class name is bound with
setString(), so only class 10-A is loaded and Arun from 10-B is left out. - Nullable columns become
Integer.getObject("marks", Integer.class)storesnullfor Kavin, who was absent. UsinggetInt()would have recorded a misleading0and pulled the average down. - Fetch size is a performance hint.
setFetchSize(100)asks the driver to bring rows in groups of 100. It does not limit the result; it only reduces round trips for large queries. - Statistics come from the list. The average is
(88 + 72 + 92 + 64) / 4 = 79.0. The top student and the grade counts use the Stream API on the mapped records, andTreeMapkeeps the grades in alphabetical order.
Now that you can write and read data, the next lesson combines everything into complete create, read, update and delete operations: Java JDBC CRUD. For the basics of opening the connection used here, see Java JDBC Basics.