Sobes.tech
Junior — Middle

Have you used the SELECT FOR UPDATE command to lock rows when working with a database?

sobes.tech AI

Answer from AI

Yes, the SELECT FOR UPDATE command is used to lock selected rows in the database to prevent them from being modified by other transactions until the current one is completed. This is useful when implementing logic that requires guaranteeing that data does not change between reading and subsequent updating.

Example of usage in Java with JDBC:

String sql = "SELECT * FROM accounts WHERE id = ? FOR UPDATE";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
    ps.setInt(1, accountId);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
        // Work with data
    }
    // After all operations, the transaction commit will release the lock
}

It is important that SELECT FOR UPDATE is executed within a transaction for the lock to be effective.