How to check if resultset has one row or more with JDBC?
-
This is indeed something that is missing in JDBC, reason for this is that not all database system support getting the size of the resultset in advance (because results aren't prefetched). Unfortunately this means you can not easily use those features in databases that do support it, such as MySQL. – Thirler Apr 07 '10 at 11:25
-
possible duplicate of [Java ResultSet how to check if there are any results](http://stackoverflow.com/questions/867194/java-resultset-how-to-check-if-there-are-any-results) – rogerdpack Oct 06 '14 at 12:17
7 Answers
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
boolean isMoreThanOneRow = rs.first() && rs.next();
You didn't ask this one, but you may need it:
boolean isEmpty = ! rs.first();
Normally, we don't need the row count because we use a WHILE loop to iterate through the result set instead of a FOR loop:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
// retrieve and print the values for the current row
int i = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f);
}
However, in some cases, you might want to window the results, and you need the record count ahead of time to display to the user something like Row 1 to 10 of 100
. You can do a separate query with SELECT COUNT(*)
first, to get the record count, but note that the count is only approximate, since rows can be added or removed between the time it takes to execute the two queries.
Sample from ResultSet Overview

- 53,009
- 9
- 91
- 143
-
the isMoreThanOneRow give me the error, The requested operation is not supported on forward only result sets. – Vodo-Siosk Baas Feb 18 '16 at 21:49
-
@Vodo-SioskBaas, you need to do that right after the `executeQuery` statement, so that the `first()` doesn't need to rewind or change your cursor so that it can rewind. – Marcus Adams Feb 21 '16 at 17:36
There are many options, and since you don't provide more context the only thing left is to guess. My answers are sorted by complexity and performance ascending order.
- Just run
select count(1) FROM ...
and get the answer. You'd have to run another query that actually selects and returns the data. - Iterate with
rs.next()
and count until you're happy. Then if you still need the actual data re-run same query. - If your driver supports backwards iteration, go for
rs.next()
couple of times and then rewind back withrs.previous()
.

- 26,463
- 15
- 97
- 154
-
2If your driver doesn't support backwards iteration, `first()` usually works to start over. – Marcus Adams Apr 07 '10 at 11:18
You don't need JDBC for this. The normal idiom is to collect all results in a collection and make use of the collection methods, such as List#size()
.
List<Item> items = itemDAO.list();
if (items.isEmpty()) {
// It is empty!
if (items.size() == 1) {
// It has only one row!
} else {
// It has more than one row!
}
where the list()
method look like something:
public List<Item> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Item> items = new ArrayList<Item>();
try {
connection = database.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(SQL_LIST);
while (resultSet.next()) {
Item item = new Item();
item.setId(resultSet.getLong("id"));
item.setName(resultSet.getString("name"));
// ...
items.add(item);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return items;
}

- 1,082,665
- 372
- 3,610
- 3,555
-
This doesn't scale very well. What if the result set has millions of rows? – mindas Apr 07 '10 at 12:05
-
@mindas: It would then already make no sense to `SELECT * FROM table` them. You need `SELECT COUNT(*) FROM table` then. JDBC is simply not the right tool for this particular purpose and that's exactly the reason a fictive `ResultSet#size()` method doesn't exist in JDBC. – BalusC Apr 07 '10 at 12:16
-
Original question have never said it is doing `SELECT * FROM table` neither I have suggested that. Original question hasn't got an assumption that all data is actually necessary, too. – mindas Apr 07 '10 at 12:41
-
@mindas: Either way, there's still no reason to do this using JDBC. Either use SQL to select the rowcount, or use collection methods to get the result size. – BalusC Apr 07 '10 at 12:54
If you want to make sure that there is exactly one row, you can ensure that the first row is the last:
ResultSet rs = stmt.executeQuery("SELECT a FROM Table1 WHERE b=10");
if (rs.isBeforeFirst() && rs.next() && rs.isFirst() && rs.isLast()) {
// Logic for where there's exactly 1 row
Long valA = rs.getLong("a");
// ...
}
else {
// More that one row or 0 rows returned.
// ..
}

- 1,247
- 4
- 15
- 33
-
This will not work since `rs.next()` will already skip to the next resultSet and it will give you the wrong data. I tested it on the join clause and it cuts out one element – amer Jun 03 '21 at 08:34
My no-brainer suggestion: Fetch the first result row, and then try to fetch the next. If the attempt is successful, you have more than one row.
If there is more than one row and you want to process that data, you'll need to either cache the stuff from the first row, or use a scrollable result set so you can seek back to the top before going through the results.
You can also ask SQL directly for this information by doing a SELECT COUNT(*)
on the rest of your query; the result will be 0, 1 or more depending on how many rows the rest of the query would return. That's pretty easy to implement but involves two queries to the DB, assuming you're going to want to read and process the actual query next.

- 66,391
- 18
- 125
- 167
This implementation allows you to check for whether result of the query is empty or not at the cost of duplicating some lines.
ResultSet result = stmt.executeQuery("SELECT * FROM Table");
if(result.next()) {
// Duplicate the code which should be pasted inside while
System.out.println(result.getInt(1));
System.out.println(result.getString(2));
while(result.next()){
System.out.println(result.getInt(1));
System.out.println(result.getString(2));
}
}else{
System.out.println("Query result is empty");
}
Drawbacks:
- In this implementation a portion of the code will be duplicated.
- You cannot know how many lines are present in the result.

- 953
- 12
- 26
Get the Row Count using ResultSetMetaData
class.
From your code u can create ResultSetMetaData
like :
ResultSetMetaData rsmd = resultSet.getMetaData(); //get ResultSetMetaData
rsmd.getColumnCount(); // get row count from resultsetmetadata
-
1-1 ResultSetMetaData has nothing to do with row count.. rsmd.getColumnCount() gives you the number of columns of your resultset – bluish Nov 18 '11 at 09:07