What is atomicity in databases? Provide an example.
sobes.tech AI
Answer from AI
Atomicity in databases is a property of a transaction that guarantees that all operations within the transaction are executed as a single unit: either all succeed or, in case of an error, all are rolled back, leaving the system in a consistent state.
Example: when transferring money between accounts, the amount must be deducted from one account and credited to another. If the deduction succeeds but the credit does not, the data will be inconsistent. Thanks to atomicity, both operations will either be executed together or not at all.
Example in Node.js using a transaction (for example, with PostgreSQL and the pg library):
const { Client } = require('pg');
async function transferFunds(client, fromAccount, toAccount, amount) {
try {
await client.query('BEGIN');
await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, fromAccount]);
await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, toAccount]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
}
}
Here, if one of the balance update operations fails, the transaction will be rolled back, and the database will remain in its original state.