0

Is possible to merge my following queries into one? I'm using mysql as my database.

String qry = "SELECT id FROM customers WHERE completed=false AND server=?";
ps = connection.prepareStatement(qry);
ps.setString(1,getServerId());
rs = ps.executeQuery();
final Set<Long> ids = new HashSet<>();
while (rs.next()) {
    ids.add(rs.getLong(1));
}
qry = "";
for (long l : ids) {
     qry += "UPDATE customers SET completed=true WHERE id = "+l+"; ";
}

... execute query, close streams, and do some application logic with ids from database...

1 Answer 1

2

You can just

UPDATE customers SET completed=true WHERE completed=false AND server=?

Edit: You provided the information saying you need to actually use the Ids. Select normally then build a string in the format MySql understands as a "list", it will certainly be faster than multiple update queries and will cost less bytes to send over the network. Here is the snippet:

String qry = "SELECT id FROM customers WHERE completed=false AND server=?";
ps = connection.prepareStatement(qry);
ps.setString(1,getServerId());
rs = ps.executeQuery();
final Set<Long> ids = new HashSet<>();
while (rs.next()) {
    ids.add(rs.getLong(1));
}
qry = "";
if(ids.size()>0) {
    StringBuilder idsAsString = new StringBuilder();
    for(int i = 0; i < ids.size(); i++) {
        idsAsString.append(ids.get(i));
        if(i < ids.size()-1)
            idsAsString.append(",");
    }
    qry = "UPDATE customers SET completed=true WHERE id IN ("+idsAsString+"); ";
}

instead of building multiple UPDATE statements in a for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

well i need to do some application logic with ids, i need select statement in the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.