A3.3.3 · Database programming
A3.3.3 · 数据库编程
Updating data in a database
更新数据库中的数据
A plant nursery takes a delivery, drops its prices, and discontinues a line. Nothing about the table's design changes, only the rows inside it, and SQL has exactly three statements for that.
一家苗圃收了一批货,降了价,又停产了一个品种。表的设计没有任何改变,变的只是里面的行,而 SQL 恰好有三条语句来做这件事。
Explainer
讲解
A3.3.1 split SQL into DDL (statements that define the structure) and DML (statements that work with the data inside it). SELECT, from A3.3.2, is the DML statement that only reads. This statement is about the three DML statements that actually change what is stored.
A3.3.1 把 SQL 分成了 DDL(定义结构的语句)和 DML(处理其中数据的语句)。来自 A3.3.2 的 SELECT 是只读取的 DML 语句。这条陈述讲的是真正改变所存储内容的三条 DML 语句。
An update query is any DML statement that changes the contents of a table rather than just reading them. There are three: INSERT INTO adds new records, UPDATE ... SET modifies existing records, and DELETE removes records.
更新查询是指任何改变表内容、而不只是读取内容的 DML 语句。一共有三条:INSERT INTO 添加新记录,UPDATE ... SET 修改已有的记录,DELETE 删除记录。
None of them touch the table's structure. The columns, data types and keys defined by DDL stay exactly as they were, only the rows change.
它们都不会触碰表的结构。由 DDL 定义的列、数据类型和键保持原样,变的只有行。
The three statements
三条语句
| Statement | 语句 | What it does | 作用 | Example | 示例 |
|---|---|---|---|---|---|
| INSERT INTO | Adds one new record. The value list must line up with the field list, in the same order. | 添加一条新记录。值列表必须与字段列表一一对应,顺序也相同。 | INSERT INTO Seedling (SeedlingID, SpeciesName, TrayCode, StockCount, Price) VALUES ("S5", "Sea Holly", "T-11", 60, 6.00); | ||
| UPDATE ... SET | Changes values in records that already exist. SET names each field and its new value; WHERE decides which rows are affected. | 修改已经存在的记录中的值。SET 指明每个字段及其新值;WHERE 决定哪些行受到影响。 | UPDATE Seedling SET Price = 3.00 WHERE SeedlingID = "S3"; | ||
| DELETE | Removes whole records. The row disappears; individual fields cannot be deleted this way. | 删除整条记录。这一行消失;不能用这种方式删除单个字段。 | DELETE FROM Seedling WHERE StockCount = 0; |
WHERE is what limits the damage. UPDATE and DELETE apply to every row that matches the condition. If the condition is left out entirely, every row in the table matches.
WHERE 决定了破坏的范围。UPDATE 和 DELETE 作用于每一个满足条件的行。如果完全省略条件,表中的每一行都满足。
DELETE FROM Seedling; is valid SQL. It empties the table. UPDATE Seedling SET Price = 3.00; is also valid, and it reprices every product in the nursery. Neither one produces an error message first.
DELETE FROM Seedling; 是合法的 SQL。它会清空整张表。UPDATE Seedling SET Price = 3.00; 也是合法的,它会给苗圃里的每件商品重新定价。两者都不会先产生任何错误提示。
Worked example
例题讲解
SEEDLING: one table, three updates
SEEDLING:一张表,三种更新
A small nursery keeps one table of what is currently growing. Click through and watch each statement change it.
一家小苗圃用一张表记录目前在培育的东西。点击查看每条语句如何改变它。
Explainer
讲解
Why updating an indexed column costs more
为什么更新有索引的列代价更高
Every statement above looks like a single operation. On an indexed column, it is not.
上面的每条语句看起来都是单一操作。在有索引的列上,就不是了。
An index is a separate, sorted structure the database keeps alongside a table so that searches on one particular column do not have to scan every row. The nursery's staff search by species name constantly, so SpeciesName is indexed.
索引(index)是数据库在表旁边保存的一个单独的、有序的结构,使得针对某一列的搜索不必扫描每一行。苗圃员工经常按品种名称搜索,所以 SpeciesName 上建了索引。
The index is a second copy of that column's values, held in order, each pointing back at the row it came from. It is a real object stored on disk, not a setting.
索引是该列的值的第二份副本,按顺序存放,每个值都指回它来自的那一行。它是存储在磁盘上的真实对象,而不是一个设置。
What an update actually does to the index
更新实际上对索引做了什么
Follow the same nursery table, this time watching the index rather than the rows.
还是同一张苗圃的表,这次观察的是索引,而不是行。
Fragmentation is what a heavily updated index turns into: the entries are still in the right order, but they are spread across far more space than they need, with a gap left behind wherever an old entry was removed. The index still gives correct answers, it just takes more reads to get them, so the very queries it was created to speed up start slowing down.
碎片化(fragmentation)是被大量更新的索引最终变成的样子:条目的顺序仍然正确,但分散在比需要大得多的空间里,每个旧条目被删除的地方都留下了空隙。索引仍然给出正确的答案,只是需要更多的读取次数,所以它本来用来加速的那些查询反而开始变慢。
How this is managed in practice
实际中如何管理
Batch the updates. Applying two hundred price changes as one operation makes the index do its maintenance work once, instead of two hundred separate times.
批量更新。把两百次价格改动作为一次操作应用,索引只需要做一次维护工作,而不是两百次。
Rebuild or reorganize the index regularly. Reorganizing tidies the existing index in place; rebuilding discards it and constructs a fresh, compact one. Either way the fragmentation left behind by heavy modification is cleared out, which is why this is scheduled after any significant bulk change.
定期重建或重组索引。重组是在原地整理现有的索引;重建则是丢弃它,构建一个全新的、紧凑的索引。无论哪种,大量修改留下的碎片都会被清除,这就是为什么要在任何大规模批量修改之后安排这件事。
Use partial or filtered indexes. Index only the rows that are actually searched, for example just the species still in stock. A smaller index means less to maintain on every write.
使用部分索引或过滤索引。只对真正被搜索的行建立索引,比如只针对仍有库存的品种。更小的索引意味着每次写入时需要维护的内容更少。
There is a second cost that is easy to miss. While the index is being updated, the rows involved can be locked, so other transactions that need those records have to wait. A slow write does not only slow itself down, it holds up everything queued behind it.
还有第二种容易被忽略的成本。在索引被更新期间,相关的行可能被锁定,所以需要这些记录的其他事务就得等待。一次缓慢的写入不只是拖慢它自己,还会拖住排在它后面的所有操作。
Try it yourself
动手试试
Change the data yourself
自己改数据
A live copy of the SEEDLING table. Your INSERT, UPDATE and DELETE statements really do change it, and it stays changed until you reset it. That includes the mistakes. SELECT works here too, so you can check the damage before undoing it.
SEEDLING 表的一个实时副本。你的 INSERT、UPDATE 和 DELETE 语句确实会改变它,而且在你重置之前它会一直保持改变,包括你犯的错误。这里 SELECT 也能用,所以你可以在撤销之前先检查损失。
4 rows
Run the last chip. "Forget the WHERE" is the mistake the warning card near the top of this page describes, and it is much more convincing to watch every price in the nursery become 3.00 than to be told it would. Nothing asks you to confirm, and nothing warns you first, which is exactly the point. Then reset the tables and try DELETE FROM Seedling; on its own.
运行最后一个芯片按钮。"忘了 WHERE"正是本页顶部警告卡片所描述的错误,亲眼看着苗圃里每一件商品的价格都变成 3.00,比听别人说它会这样要有说服力得多。没有任何东西让你确认,也没有任何东西事先警告你,这正是重点。然后重置表,单独试试 DELETE FROM Seedling;。
Check your understanding
检查你的理解
SEEDLING has an index on SpeciesName. Which statement forces the database to do extra write work inside the index itself?
SEEDLING 在 SpeciesName 上有索引。哪条语句会迫使数据库在索引内部做额外的写入工作?
Common mistake
常见错误
A3.3.3A3.3.3 的这一常见模式RecurringThe command term here is explain, which needs a mechanism, not a claim. Answers about indexed columns often stop at "it slows the update down" and stop there. That sentence states the effect and never says what the database is doing extra, so it cannot be given the marks reserved for the reason.
反复出现这里的指令词是 explain,它需要的是机制,而不是一个断言。关于有索引的列的答案常常止于"这会让更新变慢"。这句话陈述了影响,却从没说数据库额外做了什么,所以拿不到专门留给理由的分数。
What a weak answer looks like: "Updating an indexed column is slower because indexes make updates take longer." This restates the question. No mechanism, no marks beyond the first.
较弱的答案是这样的:"更新有索引的列更慢,因为索引会让更新花更长时间。"这只是把问题重述了一遍。没有机制,除了第一分之外没有别的分。
What it should say: "The row is written, and then the index must be maintained too: the old entry is removed and a new one inserted in sorted position. Repeated modification leaves the index fragmented, so it is rebuilt or reorganized to restore performance." One sentence for the extra work, one for the consequence.
应该这样写:"这一行被写入,然后索引也必须被维护:旧条目被删除,新条目被插入到排序后的正确位置。反复修改会让索引碎片化,所以要重建或重组它来恢复性能。"一句说明额外的工作,一句说明后果。
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[2]Construct an SQL statement that adds a new seedling record to the SEEDLING table.
[2]构建一条 SQL 语句,向 SEEDLING 表中添加一条新的苗木记录。
Marking points
评分要点
- INSERT INTO SEEDLING naming the columns.
- VALUES (...) giving one value per column in the same order, with the primary key present and unique.
- INSERT INTO SEEDLING,写出各列名。
- VALUES (...) 按相同顺序为每列给一个值,主键存在且唯一。
[3]Explain what would happen if the WHERE clause were omitted from an UPDATE statement.
[3]解释如果 UPDATE 语句中省略了 WHERE 子句会发生什么。
Marking points
评分要点
- With no WHERE clause the UPDATE applies to every row in the table.
- Every record would get the new value, overwriting the real data.
- The change is hard to reverse without a backup, so a SELECT with the intended WHERE should be run first.
- 没有 WHERE 子句,UPDATE 会作用于表中每一行。
- 每条记录都会得到新值,覆盖掉真实数据。
- 没有备份很难撤销,所以应先用打算使用的 WHERE 跑一个 SELECT。
[5]Explain the performance implications of frequently updating an indexed column, and outline one way a database administrator can reduce them.
[5]解释频繁更新有索引的列对性能的影响,并概述数据库管理员可以降低这种影响的一种方法。
Marking points
评分要点
- Every update to an indexed column must also update the index, so writes are slower than on an unindexed column.
- Frequent updates can also fragment the index, degrading later reads.
- The DBA can index only columns that are frequently searched, batch the updates, or rebuild or reorganise the index periodically.
- Another option is to remove the index if its read benefit is smaller than its write cost.
- 对带索引列的每次更新还必须更新索引,所以写入比无索引列慢。
- 频繁更新还会使索引碎片化,降低之后的读取性能。
- 数据库管理员可以只对经常被搜索的列建索引、批量执行更新,或定期重建或重整索引。
- 另一种选择是,如果索引的读取收益小于写入代价,就删除它。
Flashcards
闪卡
Active recall for this statement's key terms.
针对本条陈述关键术语的主动回忆。
Keep this statement's practice with you
把本条陈述的练习带在身边
Free account: unlock every revision question and flashcard for A3.3.3, and every other IB CS 2027 statement.
免费账号:解锁 A3.3.3 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。