Queries and Transactions
How you talk to a database with SQL, what happens inside when a query or a commit runs, how the database recovers from a crash, and the ACID properties that make it trustworthy.
From parts to action
The previous lesson showed what a database is made of. This one puts those parts to work: how you talk to the database with SQL, what happens inside when a query or a commit runs, and the guarantees, called ACID, that make databases trustworthy with money and records.
The SQL language
SQL (Structured Query Language) is the standard language for working with relational databases. It's declarative: you describe the result you want, and the database works out how to get it. That's the optimizer's job, covered in the next section.
SQL commands fall into four groups:
- DDL (Data Definition Language)
- Creates, changes, and removes the structure: tables, indexes, views, and users. Also includes
TRUNCATE, which quickly empties a table. - DML (Data Manipulation Language)
- Reads and changes the data inside tables. Some references put
SELECTin its own group, DQL (Data Query Language). - DCL (Data Control Language)
- Gives and takes away permissions.
- TCL (Transaction Control Language)
- Groups changes into transactions, then saves them for good or undoes them.
Every platform adds its own variations to standard SQL. Oracle's procedural language, for example, is PL/SQL. The SQL Language lesson covers the command groups and dialects in more depth.
What happens when a query runs
- Connect. The application contacts the listener on port 1521 and asks for a database service, for example
sqlplus kofi@//dbserver:1521/salespdb. The listener hands the connection to a new server process, and Oracle checks the username and password. - Parse. Oracle checks that the SQL is written correctly, that the tables and columns exist, and that the user has permission to use them. It then looks in the shared pool for the same statement. If it finds it, it reuses the existing plan (a soft parse). If not, it has to build a new one (a hard parse), which takes much more work.
- Optimize. On a hard parse, the optimizer considers different ways to run the query, such as a full table scan or an index, and picks the one it estimates is cheapest. It bases its estimates on statistics about the data, such as how many rows each table has. The chosen approach is the execution plan.
- Execute. Oracle follows the plan. It looks for each block it needs in the buffer cache first. If the block isn't there, it reads it from the data files into the cache.
- Return rows. The results are sent back to the application, a batch at a time. This is called fetching.
What happens when you commit
Say Kofi's balance changes from 500 to 400. Here's what happens when the application runs an UPDATE and then COMMIT:
- Change the block in memory. The server process reads the block holding Kofi's row into the buffer cache, if it isn't there already. It saves the old value, 500, in an undo segment, then changes the row to 400. The block is now dirty: newer in memory than on disk.
- Record the change. A redo record describing the change, including the undo, goes into the redo log buffer.
- Commit. On
COMMIT, the log writer (LGWR) writes the redo log buffer to the online redo log on disk. As soon as that write finishes, Oracle tells the application the commit succeeded. - Write the data later. The database writer (DBWn) writes dirty blocks to the data files later, in batches. A checkpoint makes sure all changes up to a certain point are in the data files, which limits how much redo needs replaying after a crash.
Why not write the data files right away? Adding to the end of the redo log is a single, fast, sequential write, while updating data files means scattered writes all over the disk. Write-ahead logging lets commits finish quickly, and it's still safe.
After a crash, the data files may be missing recent committed changes, or may contain changes that were never committed. When the instance restarts, SMON runs instance recovery automatically. First it rolls forward, replaying the redo to reapply every change. Then it rolls back, using undo to remove the changes that were never committed. This is why the redo logs are so important to protect.
The ACID properties
A transaction is a group of changes that belong together. Relational databases guarantee four properties for every transaction, known as ACID:
Take a bank transfer: Kofi sends 100 to Ama. That's one transaction with two changes:
UPDATE accounts SET balance = balance - 100 WHERE owner = 'Kofi';
UPDATE accounts SET balance = balance + 100 WHERE owner = 'Ama';
COMMIT;
| Property | What it guarantees in the transfer | How Oracle delivers it |
|---|---|---|
| Atomicity | If the server crashes after the first update, Kofi doesn't lose 100 that Ama never receives. Both updates happen, or neither does. | Undo lets Oracle roll back an unfinished transaction, including during instance recovery. |
| Consistency | The transfer can't break the rules, such as leaving Kofi with a negative balance. | Constraints such as primary keys, foreign keys, and CHECK rules reject changes that break them. |
| Isolation | Someone running a report mid-transfer never sees the 100 missing from both accounts, or in both at once. | Read consistency: each query sees data as it was when the query started, rebuilt from undo when needed. |
| Durability | Once the app says "Transfer complete", the transfer survives even if the server loses power a second later. | LGWR writes the redo to disk before the commit is confirmed. |
Isolation in practice
Perfect isolation would make every transaction wait for the others, which is slow, so databases offer isolation levels that trade some isolation for speed. Oracle's default is read committed: each query sees only data that was committed before it started. The stricter serializable level is there when you need it.
Because Oracle rebuilds older versions of data from undo, readers never wait for writers, and writers never wait for readers. Writers changing the same row do wait for each other.
Key takeaways
- SQL commands fall into DDL, DML, DCL, and TCL. The SQL module covers each in depth.
- A query is parsed, optimized, and executed, reading from the buffer cache when it can. Repeated queries reuse their plan from the shared pool.
- A commit is safe once LGWR has written its redo to disk; the data files catch up later. After a crash, Oracle rolls forward with redo, then rolls back with undo.
- ACID (atomicity, consistency, isolation, durability) is what makes relational databases trustworthy for transactions.
- In Oracle, readers never wait for writers, because older versions of data are rebuilt from undo.