Junior — Middle
Can you explain the principle of random access to data in a database and its features?
sobes.tech AI
Answer from AI
Random access to data in a database means the ability to directly access any data element without the need to sequentially traverse all previous elements.
Features:
- Allows quick reading or modification of data by key or index.
- Used in indexed structures, such as B-trees, hash tables.
- Unlike sequential access, random access is efficient for operations that retrieve data based on specific criteria.
For example, when working with a database, you can quickly retrieve a record by its primary key without reading all records:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
user = cursor.fetchone()
Here, the query uses an index on the id field, providing random access to the required record.