Introduction to databases and persistence
A Transaction is a group of database actions that are treated as one single job.
Imagine you are transferring 00 from Alice to Bob. This requires two steps:
What happens if the power goes out after step 1 but before step 2? Alice loses money, and Bob gets nothing. The money vanishes.
To prevent this, databases use transactions. You wrap both steps in a transaction block. If any part fails, the database Rolls Back (undoes) everything to the start. If everything works, it Commits (saves) the changes.
Relational databases follow 4 rules called ACID:
-- SQLite Transaction Syntax
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';
COMMIT; -- Save changes
-- OR
-- ROLLBACK; -- Undo changes if something went wrong
An Index is a tool that helps the database find data faster.
<aside> 💡
In an old library, if you wanted a book, you wouldn't walk shelf by shelf looking at every book spine. That is slow (a "Full Table Scan"). You would go to the Card Catalog. You look up the Author alphabetically, find the card, and it tells you exactly where the book is.
A database index works the same way. It creates a sorted list for a specific column (like last_name) so it can find the row instantly.
</aside>
Best Practice: Index columns that you use often in WHERE clauses (like id, email, or foreign keys).
-- Create an index on the email column
CREATE INDEX idx_students_email ON students(email);
A View is like a "saved query". It looks like a table, but it doesn't store data itself.
If you often run a complex join to get a "Class Roster", you can save it as a View.
CREATE VIEW class_roster AS
SELECT students.first_name, classes.title
FROM students
JOIN enrollments ON students.id = enrollments.student_id
JOIN classes ON enrollments.class_id = classes.id;
-- Now you can query it like a simple table
SELECT * FROM class_roster;
Sometimes a query is slow, and you don't know why. SQL databases allow you to ask "How are you going to run this?".
In SQLite, you put EXPLAIN QUERY PLAN before your query.
EXPLAIN QUERY PLAN SELECT * FROM students WHERE email = '[email protected]';
Output Meaning:
SCAN TABLE students: It is reading every single row (Slow!).SEARCH TABLE students USING INDEX: It is using the index you created (Fast!).In the SQLite CLI, you can turn on the timer to see exactly how long queries take.
.timer on
SELECT * FROM students;
-- Output: Run Time: real 0.000 user 0.000 sys 0.000
The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0

Found a mistake or have a suggestion? Let us know in the feedback form.