Skip to content
Advertisement

UPDATE with RETURNING: Not able to retrieve ResultSet

I’ve tested the following UPDATE-RETURNING statement in my PostgreSQL client, and it correctly updates and returns the updated rows.

However, in Java, I’m not able to retrieve the ResultSet. statement.execute() and statement.getMoreResults() always return false and statement.getResultSet() returns null, always.

Am I missing something here?

PreparedStatement statement = this.prepareStatement(
    "WITH temp AS (" +
    "    SELECT id" +
    "    FROM mytable " +
    "    LIMIT 5 "
    ") " +
    "UPDATE mytable " +
    "SET updated = NOW() " +
    "FROM temp " +
    "WHERE temp.id = mytable.id " +
    "RETURNING mytable.data"
);

boolean hasResult = statement.execute();

if (!hasResult) {
    hasResult = statement.getMoreResults();
    // hasResult is still false
    // statement.getResultSet() still returns null
} else {
    // statement.getUpdateCount() returns the correct count of updated rows
}

Advertisement

Answer

Well, I wasn’t really able to solve this properly. However, I ended up using a workaround by wrapping the whole SQL request with a SELECT statement:

PreparedStatement statement = this.prepareStatement(
    "WITH results AS (" +
        "WITH temp AS (" +
        "    SELECT id" +
        "    FROM mytable " +
        "    LIMIT 5 "
        ") " +
        "UPDATE mytable " +
        "SET updated = NOW() " +
        "FROM temp " +
        "WHERE temp.id = mytable.id " +
        "RETURNING mytable.data" +
    ") " +
    "SELECT * FROM results"
);

ResultSet result = statement.executeQuery();

while (result.next()) {
    // Work with result
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement